-
Notifications
You must be signed in to change notification settings - Fork 132
/
ReflectionClass.php
1317 lines (1171 loc) · 38.1 KB
/
ReflectionClass.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Roave\BetterReflection\Reflection;
use Roave\BetterReflection\NodeCompiler\CompileNodeToValue;
use Roave\BetterReflection\NodeCompiler\CompilerContext;
use Roave\BetterReflection\Reflection\Exception\NotAClassReflection;
use Roave\BetterReflection\Reflection\Exception\NotAnInterfaceReflection;
use Roave\BetterReflection\Reflection\Exception\NotAnObject;
use Roave\BetterReflection\Reflector\ClassReflector;
use Roave\BetterReflection\Reflector\Reflector;
use Roave\BetterReflection\SourceLocator\Located\LocatedSource;
use Roave\BetterReflection\TypesFinder\FindTypeFromAst;
use phpDocumentor\Reflection\Types\Object_;
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Namespace_ as NamespaceNode;
use PhpParser\Node\Stmt\ClassLike as ClassLikeNode;
use PhpParser\Node\Stmt\Class_ as ClassNode;
use PhpParser\Node\Stmt\Trait_ as TraitNode;
use PhpParser\Node\Stmt\Interface_ as InterfaceNode;
use PhpParser\Node\Stmt\ClassConst as ConstNode;
use PhpParser\Node\Stmt\Property as PropertyNode;
use PhpParser\Node\Stmt\TraitUse;
class ReflectionClass implements Reflection, \Reflector
{
/**
* @var Reflector
*/
private $reflector;
/**
* @var NamespaceNode
*/
private $declaringNamespace;
/**
* @var LocatedSource
*/
private $locatedSource;
/**
* @var ClassLikeNode
*/
private $node;
/**
* @var mixed[]|null
*/
private $cachedConstants;
/**
* @var ReflectionProperty[]|null
*/
private $cachedProperties;
/**
* @var ReflectionMethod[]|null
*/
private $cachedMethods;
private function __construct()
{
}
/**
* Create a reflection and return the string representation of a named class
*
* @param string $className
* @return string
*/
public static function export(?string $className) : string
{
if (null === $className) {
throw new \InvalidArgumentException('Class name must be provided');
}
$reflection = self::createFromName($className);
return $reflection->__toString();
}
/**
* Get a string representation of this reflection
*
* @todo Refactor this
* @see https://github.com/Roave/BetterReflection/issues/94
*
* @return string
*/
public function __toString() : string
{
$isObject = $this instanceof ReflectionObject;
$format = "%s [ <user> class %s%s%s ] {\n";
$format .= " @@ %s %d-%d\n\n";
$format .= " - Constants [%d] {%s\n }\n\n";
$format .= " - Static properties [%d] {%s\n }\n\n";
$format .= " - Static methods [%d] {%s\n }\n\n";
$format .= " - Properties [%d] {%s\n }\n\n";
$format .= ($isObject ? " - Dynamic properties [%d] {%s\n }\n\n" : '%s%s');
$format .= " - Methods [%d] {%s\n }\n";
$format .= "}\n";
$staticProperties = array_filter($this->getProperties(), function (ReflectionProperty $property) {
return $property->isStatic();
});
$staticMethods = array_filter($this->getMethods(), function (ReflectionMethod $method) {
return $method->isStatic();
});
$defaultProperties = array_filter($this->getProperties(), function (ReflectionProperty $property) {
return !$property->isStatic() && $property->isDefault();
});
$dynamicProperties = array_filter($this->getProperties(), function (ReflectionProperty $property) {
return !$property->isStatic() && !$property->isDefault();
});
$methods = array_filter($this->getMethods(), function (ReflectionMethod $method) {
return !$method->isStatic();
});
$buildString = function (array $items, $indentLevel = 4) {
if (!count($items)) {
return '';
}
$indent = "\n" . str_repeat(' ', $indentLevel);
return $indent . implode($indent, explode("\n", implode("\n", $items)));
};
$buildConstants = function (array $items, $indentLevel = 4) {
$str = '';
foreach ($items as $name => $value) {
$str .= "\n" . str_repeat(' ', $indentLevel);
$str .= sprintf(
'Constant [ %s %s ] { %s }',
gettype($value),
$name,
$value
);
}
return $str;
};
$interfaceNames = $this->getInterfaceNames();
$str = sprintf(
$format,
($isObject ? 'Object of class' : 'Class'),
$this->getName(),
null !== $this->getParentClass() ? (' extends ' . $this->getParentClass()->getName()) : '',
count($interfaceNames) ? (' implements ' . implode(', ', $interfaceNames)) : '',
$this->getFileName(),
$this->getStartLine(),
$this->getEndLine(),
count($this->getConstants()),
$buildConstants($this->getConstants()),
count($staticProperties),
$buildString($staticProperties),
count($staticMethods),
$buildString($staticMethods),
count($defaultProperties),
$buildString($defaultProperties),
$isObject ? count($dynamicProperties) : '',
$isObject ? $buildString($dynamicProperties) : '',
count($methods),
$buildString($methods)
);
return $str;
}
/**
* Create a ReflectionClass by name, using default reflectors etc.
*
* @param string $className
* @return ReflectionClass
*/
public static function createFromName(string $className)
{
return ClassReflector::buildDefaultReflector()->reflect($className);
}
/**
* Create a ReflectionClass from an instance, using default reflectors etc.
*
* This is simply a helper method that calls ReflectionObject::createFromInstance().
*
* @see ReflectionObject::createFromInstance
* @param object $instance
* @return ReflectionClass
* @throws \InvalidArgumentException
*/
public static function createFromInstance($instance)
{
if (! is_object($instance)) {
throw new \InvalidArgumentException('Instance must be an instance of an object');
}
return ReflectionObject::createFromInstance($instance);
}
/**
* Create from a Class Node.
*
* @param Reflector $reflector
* @param ClassLikeNode $node
* @param LocatedSource $locatedSource
* @param NamespaceNode|null $namespace optional - if omitted, we assume it is global namespaced class
*
* @return ReflectionClass
*/
public static function createFromNode(
Reflector $reflector,
ClassLikeNode $node,
LocatedSource $locatedSource,
NamespaceNode $namespace = null
) {
$class = new self();
$class->reflector = $reflector;
$class->locatedSource = $locatedSource;
$class->node = $node;
if (null !== $namespace) {
$class->declaringNamespace = $namespace;
}
return $class;
}
/**
* Get the "short" name of the class (e.g. for A\B\Foo, this will return
* "Foo").
*
* @return string
*/
public function getShortName() : string
{
return $this->node->name;
}
/**
* Get the "full" name of the class (e.g. for A\B\Foo, this will return
* "A\B\Foo").
*
* @return string
*/
public function getName() : string
{
if (!$this->inNamespace()) {
return $this->getShortName();
}
return $this->getNamespaceName() . '\\' . $this->getShortName();
}
/**
* Get the "namespace" name of the class (e.g. for A\B\Foo, this will
* return "A\B").
*
* @return string
*/
public function getNamespaceName() : string
{
if (!$this->inNamespace()) {
return '';
}
return implode('\\', $this->declaringNamespace->name->parts);
}
/**
* Decide if this class is part of a namespace. Returns false if the class
* is in the global namespace or does not have a specified namespace.
*
* @return bool
*/
public function inNamespace() : bool
{
return null !== $this->declaringNamespace
&& null !== $this->declaringNamespace->name;
}
/**
* Construct a flat list of methods that are available. This will search up
* all parent classes/traits/interfaces/current scope for methods.
*
* @return ReflectionMethod[]
*/
private function scanMethods() : array
{
// merging together methods from interfaces, parent class, traits, current class (in this precise order)
/* @var $inheritedMethods \ReflectionMethod[] */
$inheritedMethods = array_merge(
array_merge(
[],
...array_map(
function (ReflectionClass $ancestor) {
return $ancestor->getMethods();
},
array_values(array_merge(
$this->getInterfaces(),
array_filter([$this->getParentClass()]),
$this->getTraits()
))
)
),
array_map(
function (ClassMethod $methodNode) {
return ReflectionMethod::createFromNode($this->reflector, $methodNode, $this);
},
$this->node->getMethods()
)
);
$methodsByName = [];
foreach ($inheritedMethods as $inheritedMethod) {
$methodsByName[$inheritedMethod->getName()] = $inheritedMethod;
}
return $methodsByName;
}
/**
* @return ReflectionMethod[] indexed by method name
*/
private function getMethodsIndexedByName() : array
{
if (! isset($this->cachedMethods)) {
$this->cachedMethods = $this->scanMethods();
}
return $this->cachedMethods;
}
/**
* Fetch an array of all methods for this class.
*
* @param int|null $filter
* Filter the results to include only methods with certain attributes. Defaults
* to no filtering.
* Any combination of \ReflectionMethod::IS_STATIC,
* \ReflectionMethod::IS_PUBLIC,
* \ReflectionMethod::IS_PROTECTED,
* \ReflectionMethod::IS_PRIVATE,
* \ReflectionMethod::IS_ABSTRACT,
* \ReflectionMethod::IS_FINAL.
* For example if $filter = \ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_FINAL
* the only the final public methods will be returned
* @return ReflectionMethod[]
*/
public function getMethods(?int $filter = null) : array
{
if (null === $filter) {
return array_values($this->getMethodsIndexedByName());
}
return array_values(
array_filter(
$this->getMethodsIndexedByName(),
function (ReflectionMethod $method) use ($filter) {
return $filter & $method->getModifiers();
}
)
);
}
/**
* Get only the methods that this class implements (i.e. do not search
* up parent classes etc.)
*
* @param int|null $filter
* @see ReflectionClass::getMethods for the usage of $filter
* @return ReflectionMethod[]
*/
public function getImmediateMethods(?int $filter = null) : array
{
/* @var $methods \ReflectionMethod[] */
$methods = array_map(
function (ClassMethod $methodNode) {
return ReflectionMethod::createFromNode($this->reflector, $methodNode, $this);
},
$this->node->getMethods()
);
$methodsByName = [];
foreach ($methods as $method) {
if (null === $filter || $filter & $method->getModifiers()) {
$methodsByName[$method->getName()] = $method;
}
}
return $methodsByName;
}
/**
* Get a single method with the name $methodName.
*
* @param string $methodName
*
* @return ReflectionMethod
*
* @throws \OutOfBoundsException
*/
public function getMethod(string $methodName) : ReflectionMethod
{
$methods = $this->getMethodsIndexedByName();
if (! isset($methods[$methodName])) {
throw new \OutOfBoundsException('Could not find method: ' . $methodName);
}
return $methods[$methodName];
}
/**
* Does the class have the specified method method?
*
* @param string $methodName
* @return bool
*/
public function hasMethod(string $methodName) : bool
{
try {
$this->getMethod($methodName);
return true;
} catch (\OutOfBoundsException $exception) {
return false;
}
}
/**
* Get an array of the defined constants in this class.
*
* @return mixed[]
*/
public function getConstants() : array
{
if (null !== $this->cachedConstants) {
return $this->cachedConstants;
}
$constants = [];
foreach ($this->node->stmts as $stmt) {
if ($stmt instanceof ConstNode) {
$constName = $stmt->consts[0]->name;
$constValue = (new CompileNodeToValue())->__invoke(
$stmt->consts[0]->value,
new CompilerContext($this->reflector, $this)
);
$constants[$constName] = $constValue;
}
}
$this->cachedConstants = $constants;
return $constants;
}
/**
* Get the value of the specified class constant.
*
* Returns null if not specified.
*
* @param string $name
* @return mixed|null
*/
public function getConstant(string $name)
{
$constants = $this->getConstants();
if (!isset($constants[$name])) {
return null;
}
return $constants[$name];
}
/**
* Does this class have the specified constant?
*
* @param string $name
* @return bool
*/
public function hasConstant(string $name) : bool
{
return null !== $this->getConstant($name);
}
/**
* Get the constructor method for this class.
*
* @return ReflectionMethod
* @throws \OutOfBoundsException
*/
public function getConstructor() : ReflectionMethod
{
return $this->getMethod('__construct');
}
/**
* Get only the properties for this specific class (i.e. do not search
* up parent classes etc.)
*
* @param int|null $filter
* @see ReflectionClass::getProperties() for the usage of filter
* @return ReflectionProperty[]
*/
public function getImmediateProperties(?int $filter = null) : array
{
if (null === $this->cachedProperties) {
$properties = [];
foreach ($this->node->stmts as $stmt) {
if ($stmt instanceof PropertyNode) {
$prop = ReflectionProperty::createFromNode($this->reflector, $stmt, $this);
$properties[$prop->getName()] = $prop;
}
}
$this->cachedProperties = $properties;
}
if (null === $filter) {
return $this->cachedProperties;
}
return array_filter(
$this->cachedProperties,
function (ReflectionProperty $property) use ($filter) {
return $filter & $property->getModifiers();
}
);
}
/**
* Get the properties for this class.
*
* @param int|null $filter
* Filter the results to include only properties with certain attributes. Defaults
* to no filtering.
* Any combination of \ReflectionProperty::IS_STATIC,
* \ReflectionProperty::IS_PUBLIC,
* \ReflectionProperty::IS_PROTECTED,
* \ReflectionProperty::IS_PRIVATE.
* For example if $filter = \ReflectionProperty::IS_STATIC | \ReflectionProperty::IS_PUBLIC
* only the static public properties will be returned
* @return ReflectionProperty[]
*/
public function getProperties(?int $filter = null) : array
{
// merging together properties from parent class, traits, current class (in this precise order)
return array_merge(
array_merge(
[],
...array_map(
function (ReflectionClass $ancestor) use ($filter) {
return array_filter(
$ancestor->getProperties($filter),
function (ReflectionProperty $property) {
return !$property->isPrivate();
}
);
},
array_filter([$this->getParentClass()])
),
...array_map(
function (ReflectionClass $trait) use ($filter) {
return $trait->getProperties($filter);
},
$this->getTraits()
)
),
$this->getImmediateProperties($filter)
);
}
/**
* Get the property called $name.
*
* Returns null if property does not exist.
*
* @param string $name
* @return ReflectionProperty|null
*/
public function getProperty(string $name) : ?ReflectionProperty
{
$properties = $this->getProperties();
if (!isset($properties[$name])) {
return null;
}
return $properties[$name];
}
/**
* Does this class have the specified property?
*
* @param string $name
* @return bool
*/
public function hasProperty(string $name) : bool
{
return null !== $this->getProperty($name);
}
public function getDefaultProperties() : array
{
return array_map(
function (ReflectionProperty $property) {
return $property->getDefaultValue();
},
array_filter($this->getProperties(), function (ReflectionProperty $property) {
return $property->isDefault();
})
);
}
/**
* @return string|null
*/
public function getFileName() : ?string
{
return $this->locatedSource->getFileName();
}
/**
* @return LocatedSource
*/
public function getLocatedSource() : LocatedSource
{
return $this->locatedSource;
}
/**
* Get the line number that this class starts on.
*
* @return int
*/
public function getStartLine() : int
{
return (int)$this->node->getAttribute('startLine', -1);
}
/**
* Get the line number that this class ends on.
*
* @return int
*/
public function getEndLine() : int
{
return (int)$this->node->getAttribute('endLine', -1);
}
/**
* Get the parent class, if it is defined. If this class does not have a
* specified parent class, this will throw an exception.
*
* You may optionally specify a source locator that will be used to locate
* the parent class. If no source locator is given, a default will be used.
*
* @return ReflectionClass|null
*/
public function getParentClass()
{
if (!($this->node instanceof ClassNode) || null === $this->node->extends) {
return null;
}
$objectType = (new FindTypeFromAst())->__invoke($this->node->extends, $this->locatedSource, $this->getNamespaceName());
if (null === $objectType || !($objectType instanceof Object_)) {
return null;
}
// @TODO use actual `ClassReflector` or `FunctionReflector`?
/* @var $parent self */
$parent = $this->reflector->reflect((string)$objectType->getFqsen());
if ($parent->isInterface() || $parent->isTrait()) {
throw NotAClassReflection::fromReflectionClass($parent);
}
return $parent;
}
/**
* @return string
*/
public function getDocComment() : string
{
if (!$this->node->hasAttribute('comments')) {
return '';
}
/* @var \PhpParser\Comment\Doc $comment */
$comment = $this->node->getAttribute('comments')[0];
return $comment->getReformattedText();
}
/**
* Is this an internal class?
*
* @return bool
*/
public function isInternal() : bool
{
return $this->locatedSource->isInternal();
}
/**
* Is this a user-defined function (will always return the opposite of
* whatever isInternal returns).
*
* @return bool
*/
public function isUserDefined() : bool
{
return !$this->isInternal();
}
/**
* Is this class an abstract class.
*
* @return bool
*/
public function isAbstract() : bool
{
return $this->node instanceof ClassNode && $this->node->isAbstract();
}
/**
* Is this class a final class.
*
* @return bool
*/
public function isFinal() : bool
{
return $this->node instanceof ClassNode && $this->node->isFinal();
}
/**
* Get the core-reflection-compatible modifier values.
*
* @return int
*/
public function getModifiers() : int
{
$val = 0;
$val += $this->isAbstract() ? \ReflectionClass::IS_EXPLICIT_ABSTRACT : 0;
$val += $this->isFinal() ? \ReflectionClass::IS_FINAL : 0;
return $val;
}
/**
* Is this reflection a trait?
*
* @return bool
*/
public function isTrait() : bool
{
return $this->node instanceof TraitNode;
}
/**
* Is this reflection an interface?
*
* @return bool
*/
public function isInterface() : bool
{
return $this->node instanceof InterfaceNode;
}
/**
* Get the traits used, if any are defined. If this class does not have any
* defined traits, this will return an empty array.
*
* You may optionally specify a source locator that will be used to locate
* the traits. If no source locator is given, a default will be used.
*
* @return ReflectionClass[]
*/
public function getTraits() : array
{
$traitUsages = array_filter($this->node->stmts, function (Node $node) {
return $node instanceof TraitUse;
});
$traitNameNodes = [];
foreach ($traitUsages as $traitUsage) {
$traitNameNodes = array_merge($traitNameNodes, $traitUsage->traits);
}
return array_map(function (Node\Name $importedTrait) {
return $this->reflectClassForNamedNode($importedTrait);
}, $traitNameNodes);
}
/**
* Given an AST Node\Name, try to resolve the type into a fully qualified
* structural element name (FQSEN).
*
* @param Node\Name $node
* @return string
* @throws \Exception
*/
private function getFqsenFromNamedNode(Node\Name $node) : string
{
$objectType = (new FindTypeFromAst())->__invoke($node, $this->locatedSource, $this->getNamespaceName());
if (null === $objectType || !($objectType instanceof Object_)) {
throw new \Exception('Unable to determine FQSEN for named node');
}
return $objectType->getFqsen()->__toString();
}
/**
* Given an AST Node\Name, create a new ReflectionClass for the element.
* This should work with traits, interfaces and classes alike, as long as
* the FQSEN resolves to something that exists.
*
* You may optionally specify a source locator that will be used to locate
* the traits. If no source locator is given, a default will be used.
*
* @param Node\Name $node
* @return ReflectionClass
*/
private function reflectClassForNamedNode(Node\Name $node) : self
{
// @TODO use actual `ClassReflector` or `FunctionReflector`?
return $this->reflector->reflect($this->getFqsenFromNamedNode($node));
}
/**
* Get the names of the traits used as an array of strings, if any are
* defined. If this class does not have any defined traits, this will
* return an empty array.
*
* You may optionally specify a source locator that will be used to locate
* the traits. If no source locator is given, a default will be used.
*
* @return string[]
*/
public function getTraitNames() : array
{
return array_map(
function (ReflectionClass $trait) {
return $trait->getName();
},
$this->getTraits()
);
}
/**
* Return a list of the aliases used when importing traits for this class.
* The returned array is in key/value pair in this format:.
*
* 'aliasedMethodName' => 'ActualClass::actualMethod'
*
* @example
* // When reflecting a class such as:
* class Foo
* {
* use MyTrait {
* myTraitMethod as myAliasedMethod;
* }
* }
* // This method would return
* // ['myAliasedMethod' => 'MyTrait::myTraitMethod']
*
* @return string[]
*/
public function getTraitAliases() : array
{
$traitUsages = array_filter($this->node->stmts, function (Node $node) {
return $node instanceof TraitUse;
});
$resolvedAliases = [];
/* @var Node\Stmt\TraitUse[] $traitUsages */
foreach ($traitUsages as $traitUsage) {
$traitNames = $traitUsage->traits;
$adaptations = $traitUsage->adaptations;
foreach ($adaptations as $adaptation) {
$usedTrait = $adaptation->trait;
if (null === $usedTrait) {
$usedTrait = $traitNames[0];
}
if (empty($adaptation->newName)) {
continue;
}
$resolvedAliases[$adaptation->newName] = sprintf(
'%s::%s',
ltrim($this->getFqsenFromNamedNode($usedTrait), '\\'),
$adaptation->method
);
}
}
return $resolvedAliases;
}
/**
* Gets the interfaces.
*
* @link http://php.net/manual/en/reflectionclass.getinterfaces.php
*
* @return ReflectionClass[] An associative array of interfaces, with keys as interface names and the array
* values as {@see ReflectionClass} objects.
*/
public function getInterfaces() : array
{
return array_merge(...array_map(
function (self $reflectionClass) {
return $reflectionClass->getCurrentClassImplementedInterfacesIndexedByName();
},
$this->getInheritanceClassHierarchy()
));
}
/**
* Get only the interfaces that this class implements (i.e. do not search
* up parent classes etc.)
*
* @return ReflectionClass[]
*/
public function getImmediateInterfaces() : array
{
return $this->getCurrentClassImplementedInterfacesIndexedByName();
}
/**
* Gets the interface names.
*
* @link http://php.net/manual/en/reflectionclass.getinterfacenames.php
*
* @return string[] A numerical array with interface names as the values.
*/
public function getInterfaceNames() : array
{
return array_values(array_map(
function (self $interface) {
return $interface->getName();
},
$this->getInterfaces()
));
}
/**
* Checks whether the given object is an instance.
*
* @link http://php.net/manual/en/reflectionclass.isinstance.php
*
* @param object $object
*
* @return bool
*
* @throws NotAnObject
*/
public function isInstance($object) : bool
{
if (! is_object($object)) {
throw NotAnObject::fromNonObject($object);
}
$className = $this->getName();
// note: since $object was loaded, we can safely assume that $className is available in the current
// php script execution context
return $object instanceof $className;
}
/**
* Checks whether the given class string is a subclass of this class.
*
* @link http://php.net/manual/en/reflectionclass.isinstance.php
*
* @param string $className
*
* @return bool
*/
public function isSubclassOf(string $className) : bool
{
return in_array(
ltrim($className, '\\'),
array_map(
function (self $reflectionClass) {
return $reflectionClass->getName();
},
array_slice(array_reverse($this->getInheritanceClassHierarchy()), 1)
),
true
);