Reader.php 915 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace think\annotation;
  3. use ReflectionAttribute;
  4. use ReflectionClass;
  5. use ReflectionMethod;
  6. class Reader
  7. {
  8. /**
  9. * @template T of object
  10. * @param ReflectionClass|ReflectionMethod $ref
  11. * @param class-string<T> $name
  12. * @return array<T>
  13. */
  14. public function getAnnotations($ref, $name)
  15. {
  16. return array_map(function (ReflectionAttribute $attribute) {
  17. return $attribute->newInstance();
  18. }, $ref->getAttributes($name, ReflectionAttribute::IS_INSTANCEOF));
  19. }
  20. /**
  21. * @template T of object
  22. * @param ReflectionClass|ReflectionMethod $ref
  23. * @param class-string<T> $name
  24. * @return T|null
  25. */
  26. public function getAnnotation($ref, $name)
  27. {
  28. $attributes = $this->getAnnotations($ref, $name);
  29. foreach ($attributes as $attribute) {
  30. return $attribute;
  31. }
  32. return null;
  33. }
  34. }