1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- <?php
- /*
- * This file is part of the overtrue/wechat.
- *
- * (c) overtrue <i@overtrue.me>
- *
- * This source file is subject to the MIT license that is bundled
- * with this source code in the file LICENSE.
- */
- namespace App\Libs\TikTok\Kernel\Traits;
- use App\Libs\TikTok\Kernel\Exceptions\InvalidArgumentException;
- use App\Libs\TikTok\Kernel\ServiceContainer;
- use Psr\Cache\CacheItemPoolInterface;
- use Psr\SimpleCache\CacheInterface as SimpleCacheInterface;
- use Symfony\Component\Cache\Adapter\FilesystemAdapter;
- use Symfony\Component\Cache\Psr16Cache;
- /**
- * Trait InteractsWithCache.
- *
- * @author overtrue <i@overtrue.me>
- */
- trait InteractsWithCache {
- /**
- * @var SimpleCacheInterface
- */
- protected $cache;
- /**
- * Get cache instance.
- *
- * @return SimpleCacheInterface
- *
- * @throws InvalidArgumentException
- */
- public function getCache(): SimpleCacheInterface {
- if ($this->cache) {
- return $this->cache;
- }
- if (property_exists($this, 'app') && $this->app instanceof ServiceContainer && isset($this->app['cache'])) {
- $this->setCache($this->app['cache']);
- // Fix PHPStan error
- assert($this->cache instanceof SimpleCacheInterface);
- return $this->cache;
- }
- return $this->cache = $this->createDefaultCache();
- }
- /**
- * Set cache instance.
- *
- * @param SimpleCacheInterface|CacheItemPoolInterface $cache
- *
- * @return $this
- *
- * @throws InvalidArgumentException
- */
- public function setCache($cache) {
- if (empty(\array_intersect([SimpleCacheInterface::class, CacheItemPoolInterface::class], \class_implements($cache)))) {
- throw new InvalidArgumentException(\sprintf('The cache instance must implements %s or %s interface.', SimpleCacheInterface::class, CacheItemPoolInterface::class));
- }
- if ($cache instanceof CacheItemPoolInterface) {
- if (!$this->isSymfony43OrHigher()) {
- throw new InvalidArgumentException(sprintf('The cache instance must implements %s', SimpleCacheInterface::class));
- }
- $cache = new Psr16Cache($cache);
- }
- $this->cache = $cache;
- return $this;
- }
- /**
- * @return SimpleCacheInterface
- */
- protected function createDefaultCache() {
- return new Psr16Cache(new FilesystemAdapter('EasyTiktok', 1500));
- }
- /**
- * @return bool
- */
- protected function isSymfony43OrHigher(): bool {
- return \class_exists('Symfony\Component\Cache\Psr16Cache');
- }
- }
|