|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types = 1); |
| 4 | + |
| 5 | +namespace Ock\ReflectorAwareAttributes; |
| 6 | + |
| 7 | +/** |
| 8 | + * Static methods to be called from attribute constructors. |
| 9 | + */ |
| 10 | +class AttributeConstructor { |
| 11 | + |
| 12 | + /** |
| 13 | + * Reflector that an attribute is attached to. |
| 14 | + */ |
| 15 | + private static \ReflectionClass|\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty|\ReflectionClassConstant|null $reflector = null; |
| 16 | + |
| 17 | + /** |
| 18 | + * @template TReturn |
| 19 | + * |
| 20 | + * @param \Closure(): TReturn $callback |
| 21 | + * @param \ReflectionClass|\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty|\ReflectionClassConstant $reflector |
| 22 | + * |
| 23 | + * @return TReturn |
| 24 | + */ |
| 25 | + public static function callWithReflector( |
| 26 | + \Closure $callback, |
| 27 | + \ReflectionClass|\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty|\ReflectionClassConstant $reflector, |
| 28 | + ): mixed { |
| 29 | + try { |
| 30 | + self::$reflector = $reflector; |
| 31 | + return $callback(); |
| 32 | + } |
| 33 | + finally { |
| 34 | + self::$reflector = null; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Gets the reflector the current attribute is attached to. |
| 40 | + * |
| 41 | + * This should only be called from an attribute constructor that was invoked |
| 42 | + * with ::newAttributeInstance() above. |
| 43 | + * |
| 44 | + * @throws \LogicException |
| 45 | + * The method is called at the wrong time. |
| 46 | + */ |
| 47 | + public static function getReflector(): \ReflectionClass|\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty|\ReflectionClassConstant { |
| 48 | + if (self::$reflector === null) { |
| 49 | + throw new \LogicException("This method can only be called from an attribute constructor, and only when the attribute is instantiated using the 'ock/reflector-aware-attributes' package."); |
| 50 | + } |
| 51 | + return self::$reflector; |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Gets the reflector the current attribute is attached to, or NULL. |
| 56 | + * |
| 57 | + * This should only be called from an attribute constructor that was invoked |
| 58 | + * with ::newAttributeInstance() above. |
| 59 | + */ |
| 60 | + public static function getReflectorIfSet(): \ReflectionClass|\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty|\ReflectionClassConstant|null { |
| 61 | + return self::$reflector; |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments