Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame^] | 1 | <?php |
| 2 | |
| 3 | namespace Carbon\PHPStan; |
| 4 | |
| 5 | use Carbon\CarbonInterface; |
| 6 | use ReflectionClass; |
| 7 | use ReflectionException; |
| 8 | |
| 9 | final class MacroScanner |
| 10 | { |
| 11 | /** |
| 12 | * Return true if the given pair class-method is a Carbon macro. |
| 13 | * |
| 14 | * @param string $className |
| 15 | * @phpstan-param class-string $className |
| 16 | * |
| 17 | * @param string $methodName |
| 18 | * |
| 19 | * @return bool |
| 20 | */ |
| 21 | public function hasMethod(string $className, string $methodName): bool |
| 22 | { |
| 23 | return is_a($className, CarbonInterface::class, true) && |
| 24 | \is_callable([$className, 'hasMacro']) && |
| 25 | $className::hasMacro($methodName); |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * Return the Macro for a given pair class-method. |
| 30 | * |
| 31 | * @param string $className |
| 32 | * @phpstan-param class-string $className |
| 33 | * |
| 34 | * @param string $methodName |
| 35 | * |
| 36 | * @throws ReflectionException |
| 37 | * |
| 38 | * @return Macro |
| 39 | */ |
| 40 | public function getMethod(string $className, string $methodName): Macro |
| 41 | { |
| 42 | $reflectionClass = new ReflectionClass($className); |
| 43 | $property = $reflectionClass->getProperty('globalMacros'); |
| 44 | |
| 45 | $property->setAccessible(true); |
| 46 | $macro = $property->getValue()[$methodName]; |
| 47 | |
| 48 | return new Macro( |
| 49 | $className, |
| 50 | $methodName, |
| 51 | $macro |
| 52 | ); |
| 53 | } |
| 54 | } |