SuiteTicket.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of the overtrue/wechat.
  4. *
  5. * (c) overtrue <i@overtrue.me>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace EasyWeChat\OpenWork\SuiteAuth;
  11. use EasyWeChat\Kernel\Exceptions\RuntimeException;
  12. use EasyWeChat\Kernel\Traits\InteractsWithCache;
  13. use EasyWeChat\OpenWork\Application;
  14. /**
  15. * SuiteTicket.
  16. *
  17. * @author xiaomin <keacefull@gmail.com>
  18. */
  19. class SuiteTicket
  20. {
  21. use InteractsWithCache;
  22. /**
  23. * @var Application
  24. */
  25. protected $app;
  26. /**
  27. * SuiteTicket constructor.
  28. *
  29. * @param Application $app
  30. */
  31. public function __construct(Application $app)
  32. {
  33. $this->app = $app;
  34. }
  35. /**
  36. * @param string $ticket
  37. *
  38. * @return $this
  39. *
  40. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  41. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  42. * @throws \Psr\SimpleCache\InvalidArgumentException
  43. */
  44. public function setTicket(string $ticket)
  45. {
  46. $this->getCache()->set($this->getCacheKey(), $ticket, 1800);
  47. if (!$this->getCache()->has($this->getCacheKey())) {
  48. throw new RuntimeException('Failed to cache suite ticket.');
  49. }
  50. return $this;
  51. }
  52. /**
  53. * @return string
  54. *
  55. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  56. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  57. * @throws \Psr\SimpleCache\InvalidArgumentException
  58. */
  59. public function getTicket(): string
  60. {
  61. if ($cached = $this->getCache()->get($this->getCacheKey())) {
  62. return $cached;
  63. }
  64. throw new RuntimeException('Credential "suite_ticket" does not exist in cache.');
  65. }
  66. /**
  67. * @return string
  68. */
  69. protected function getCacheKey(): string
  70. {
  71. return 'easywechat.open_work.suite_ticket.'.$this->app['config']['suite_id'];
  72. }
  73. }