1 | <?php |
||
27 | class MagicCallPatch implements ClassPatchInterface |
||
28 | { |
||
29 | private $docBlockFactory; |
||
30 | private $contextFactory; |
||
31 | |||
32 | public function __construct() |
||
37 | |||
38 | /** |
||
39 | * Support any class |
||
40 | * |
||
41 | * @param ClassNode $node |
||
42 | * |
||
43 | * @return boolean |
||
44 | */ |
||
45 | public function supports(ClassNode $node) |
||
49 | |||
50 | /** |
||
51 | * Discover Magical API |
||
52 | * |
||
53 | * @param ClassNode $node |
||
54 | */ |
||
55 | public function apply(ClassNode $node) |
||
56 | { |
||
57 | $parentClass = $node->getParentClass(); |
||
58 | $reflectionClass = new \ReflectionClass($parentClass); |
||
59 | |||
60 | try { |
||
61 | $phpdoc = $this->docBlockFactory->create($reflectionClass, $this->contextFactory->createFromReflector($reflectionClass)); |
||
62 | } catch (\InvalidArgumentException $e) { |
||
63 | // No DocBlock |
||
64 | } |
||
65 | |||
66 | /** |
||
67 | * @var Method[] $tagList |
||
68 | */ |
||
69 | $tagList = isset($phpdoc) ? $phpdoc->getTagsByName('method') : array(); |
||
70 | |||
71 | $interfaces = $reflectionClass->getInterfaces(); |
||
72 | foreach($interfaces as $interface) { |
||
73 | try { |
||
74 | $phpdoc = $this->docBlockFactory->create($interface, $this->contextFactory->createFromReflector($interface)); |
||
75 | $tagList = array_merge($tagList, $phpdoc->getTagsByName('method')); |
||
76 | } catch (\InvalidArgumentException $e) { |
||
77 | // No DocBlock |
||
78 | } |
||
79 | } |
||
80 | |||
81 | foreach($tagList as $tag) { |
||
82 | $methodName = $tag->getMethodName(); |
||
|
|||
83 | |||
84 | if (empty($methodName)) { |
||
85 | continue; |
||
86 | } |
||
87 | |||
88 | if (!$reflectionClass->hasMethod($methodName)) { |
||
89 | $methodNode = new MethodNode($tag->getMethodName()); |
||
90 | $methodNode->setStatic($tag->isStatic()); |
||
91 | |||
92 | $node->addMethod($methodNode); |
||
93 | } |
||
94 | } |
||
95 | } |
||
96 | |||
97 | /** |
||
98 | * Returns patch priority, which determines when patch will be applied. |
||
99 | * |
||
100 | * @return integer Priority number (higher - earlier) |
||
101 | */ |
||
102 | public function getPriority() |
||
106 | } |
||
107 | |||
108 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: