CacheableAspect.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Cache\Aspect;
  12. use Hyperf\Cache\Annotation\Cacheable;
  13. use Hyperf\Cache\AnnotationManager;
  14. use Hyperf\Cache\CacheManager;
  15. use Hyperf\Cache\Driver\KeyCollectorInterface;
  16. use Hyperf\Di\Aop\AbstractAspect;
  17. use Hyperf\Di\Aop\ProceedingJoinPoint;
  18. class CacheableAspect extends AbstractAspect
  19. {
  20. public array $classes = [];
  21. public array $annotations = [
  22. Cacheable::class,
  23. ];
  24. public function __construct(protected CacheManager $manager, protected AnnotationManager $annotationManager)
  25. {
  26. }
  27. public function process(ProceedingJoinPoint $proceedingJoinPoint)
  28. {
  29. $className = $proceedingJoinPoint->className;
  30. $method = $proceedingJoinPoint->methodName;
  31. $arguments = $proceedingJoinPoint->arguments['keys'];
  32. [$key, $ttl, $group, $annotation] = $this->annotationManager->getCacheableValue($className, $method, $arguments);
  33. $driver = $this->manager->getDriver($group);
  34. [$has, $result] = $driver->fetch($key);
  35. if ($has) {
  36. return $result;
  37. }
  38. $result = $proceedingJoinPoint->process();
  39. if (! in_array($result, (array) $annotation->skipCacheResults, true)) {
  40. $driver->set($key, $result, $ttl);
  41. if ($driver instanceof KeyCollectorInterface && $annotation instanceof Cacheable && $annotation->collect) {
  42. $driver->addKey($annotation->prefix . 'MEMBERS', $key);
  43. }
  44. }
  45. return $result;
  46. }
  47. }