InteractsWithCache.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 App\Libs\TikTok\Kernel\Traits;
  11. use App\Libs\TikTok\Kernel\Exceptions\InvalidArgumentException;
  12. use App\Libs\TikTok\Kernel\ServiceContainer;
  13. use Psr\Cache\CacheItemPoolInterface;
  14. use Psr\SimpleCache\CacheInterface as SimpleCacheInterface;
  15. use Symfony\Component\Cache\Adapter\FilesystemAdapter;
  16. use Symfony\Component\Cache\Psr16Cache;
  17. /**
  18. * Trait InteractsWithCache.
  19. *
  20. * @author overtrue <i@overtrue.me>
  21. */
  22. trait InteractsWithCache {
  23. /**
  24. * @var SimpleCacheInterface
  25. */
  26. protected $cache;
  27. /**
  28. * Get cache instance.
  29. *
  30. * @return SimpleCacheInterface
  31. *
  32. * @throws InvalidArgumentException
  33. */
  34. public function getCache(): SimpleCacheInterface {
  35. if ($this->cache) {
  36. return $this->cache;
  37. }
  38. if (property_exists($this, 'app') && $this->app instanceof ServiceContainer && isset($this->app['cache'])) {
  39. $this->setCache($this->app['cache']);
  40. // Fix PHPStan error
  41. assert($this->cache instanceof SimpleCacheInterface);
  42. return $this->cache;
  43. }
  44. return $this->cache = $this->createDefaultCache();
  45. }
  46. /**
  47. * Set cache instance.
  48. *
  49. * @param SimpleCacheInterface|CacheItemPoolInterface $cache
  50. *
  51. * @return $this
  52. *
  53. * @throws InvalidArgumentException
  54. */
  55. public function setCache($cache) {
  56. if (empty(\array_intersect([SimpleCacheInterface::class, CacheItemPoolInterface::class], \class_implements($cache)))) {
  57. throw new InvalidArgumentException(\sprintf('The cache instance must implements %s or %s interface.', SimpleCacheInterface::class, CacheItemPoolInterface::class));
  58. }
  59. if ($cache instanceof CacheItemPoolInterface) {
  60. if (!$this->isSymfony43OrHigher()) {
  61. throw new InvalidArgumentException(sprintf('The cache instance must implements %s', SimpleCacheInterface::class));
  62. }
  63. $cache = new Psr16Cache($cache);
  64. }
  65. $this->cache = $cache;
  66. return $this;
  67. }
  68. /**
  69. * @return SimpleCacheInterface
  70. */
  71. protected function createDefaultCache() {
  72. return new Psr16Cache(new FilesystemAdapter('EasyTiktok', 1500));
  73. }
  74. /**
  75. * @return bool
  76. */
  77. protected function isSymfony43OrHigher(): bool {
  78. return \class_exists('Symfony\Component\Cache\Psr16Cache');
  79. }
  80. }