forked from swoft-cloud/swoft-component
/
Container.php
1126 lines (990 loc) 路 28.3 KB
/
Container.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 declare(strict_types=1);
namespace Swoft\Bean;
use function array_keys;
use function class_exists;
use function count;
use function end;
use function is_array;
use function is_string;
use function method_exists;
use ReflectionClass;
use ReflectionException;
use function sprintf;
use function strpos;
use Swoft\Annotation\Exception\AnnotationException;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Contract\ContainerInterface;
use Swoft\Bean\Contract\HandlerInterface;
use Swoft\Bean\Definition\ArgsInjection;
use Swoft\Bean\Definition\MethodInjection;
use Swoft\Bean\Definition\ObjectDefinition;
use Swoft\Bean\Definition\Parser\AnnotationObjParser;
use Swoft\Bean\Definition\Parser\DefinitionObjParser;
use Swoft\Bean\Definition\PropertyInjection;
use Swoft\Bean\Exception\ContainerException;
use Swoft\Stdlib\Helper\ArrayHelper;
use Swoft\Stdlib\Helper\ObjectHelper;
use Swoft\Stdlib\Reflections;
use function ucfirst;
/**
* Class Container
*/
class Container implements ContainerInterface
{
/**
* Init method after create bean
*/
public const INIT_METHOD = 'init';
/**
* Destroy method before destroy bean
*/
public const DESTROY_METHOD = 'destroy';
/**
* Default pool size
*/
public const DEFAULT_POOL_SIZE = 100;
/**
* @var Container
*/
public static $instance;
/**
* All load annotations
*
* @var array
*
* @example
* [
* 'loadNamespace' => [
* 'className' => [
* 'annotation' => [
* new ClassAnnotation(),
* new ClassAnnotation(),
* new ClassAnnotation(),
* ]
* 'reflection' => new ReflectionClass(),
* 'properties' => [
* 'propertyName' => [
* 'annotation' => [
* new PropertyAnnotation(),
* new PropertyAnnotation(),
* new PropertyAnnotation(),
* ]
* 'reflection' => new ReflectionProperty(),
* ]
* ],
* 'methods' => [
* 'methodName' => [
* 'annotation' => [
* new MethodAnnotation(),
* new MethodAnnotation(),
* new MethodAnnotation(),
* ]
* 'reflection' => new ReflectionFunctionAbstract(),
* ]
* ],
* 'pathName' => '/xxx/xx/xx.php'
* ]
* ]
* ]
*/
private $annotations = [];
/**
* Annotation parser
*
* @var array
*
* @example
* [
* 'annotationClassName' => 'annotationParserClassName',
* ]
*/
private $parsers = [];
/**
* All definitions
*
* @var array
*
* @example
* [
* 'name' => [
* 'class' => 'className',
* [
* 'construnctArg',
* '${ref.name}', // config params
* '${beanName}', // object
* ],
* 'propertyValue',
* '${ref.name}',
* '${beanName}',
* '__option' => [
* 'scope' => '...',
* 'alias' => '...',
* ]
* ]
* ]
*/
private $definitions = [];
/**
* All alias
*
* @var array
*
* @example
* [
* 'alias' => 'beanName',
* 'alias' => 'beanName',
* 'alias' => 'beanName'
* ]
*/
private $aliases = [];
/**
* Class all bean names (many instances)
*
* @var array
*
* @example
* [
* 'className' => [
* 'beanName',
* 'beanName',
* 'beanName',
* ]
* ]
*/
private $classNames = [];
/**
* Bean definitions
*
* @var ObjectDefinition[]
*
* @example
* [
* 'beanName' => new ObjectDefinition,
* 'beanName' => new ObjectDefinition,
* 'beanName' => new ObjectDefinition
* ]
*/
private $objectDefinitions = [];
/**
* Request bean definitions
*
* @var ObjectDefinition[]
*
* @example
* [
* 'beanName' => new ObjectDefinition,
* 'beanName' => new ObjectDefinition,
* 'beanName' => new ObjectDefinition
* ]
*/
private $requestDefinitions = [];
/**
* Session bean definitions
*
* @var ObjectDefinition[]
*
* @example
* [
* 'beanName' => new ObjectDefinition,
* 'beanName' => new ObjectDefinition,
* 'beanName' => new ObjectDefinition
* ]
*/
private $sessionDefinitions = [];
/**
* Singleton pool
*
* @var array
*
* @example
* [
* 'beanName' => object,
* 'beanName' => object,
* 'beanName' => object,
* ]
*/
private $singletonPool = [];
/**
* Prototype pool
*
* @var array
*
* @example
* [
* 'beanName' => object,
* 'beanName' => object,
* 'beanName' => object,
* ]
*/
private $prototypePool = [];
/**
* Request pool
*
* @var array
*
* @example
* [
* 'beanName' => object,
* 'beanName' => object,
* 'beanName' => object,
* ]
*/
private $requestPool = [];
/**
* Session pool
*
* @var array
*
* @example
* [
* 'beanName' => object,
* 'beanName' => object,
* 'beanName' => object,
* ]
*/
private $sessionPool = [];
/**
* Bean handler
*
* @var HandlerInterface
*/
private $handler;
/**
* Container constructor.
*/
private function __construct()
{
}
/**
* @return Container
*/
public static function getInstance(): Container
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Init
*
* @throws ContainerException
* @throws ReflectionException
* @throws AnnotationException
*/
public function init(): void
{
// Parse annotations
$this->parseAnnotations();
// Parse definitions
$this->parseDefinitions();
// Init beans
$this->initializeBeans();
}
public function initializeRequest(int $rid): void
{
// /* @var ObjectDefinition $objectDefinition */
// foreach ($this->requestDefinitions as $beanName => $objectDefinition) {
// TODO ...
// }
}
/**
* Get request bean
*
* @param string $name
* @param string $id Usually is coroutine ID
*
* @return object
* @throws ContainerException
* @throws ReflectionException
*/
public function getRequest(string $name, string $id)
{
if (isset($this->requestPool[$id][$name])) {
return $this->requestPool[$id][$name];
}
if (isset($this->aliases[$name])) {
return $this->getRequest($this->aliases[$name], $id);
}
// Class name
$classNames = $this->classNames[$name] ?? [];
if ($classNames) {
$name = end($classNames);
return $this->getRequest($name, $id);
}
if (!isset($this->requestDefinitions[$name])) {
throw new ContainerException(sprintf('Request bean(%s) is not defined', $name));
}
return $this->newBean($name, $id);
}
/**
* Get session bean
*
* @param string $name
* @param string $sid
*
* @return object
* @throws ContainerException
* @throws ReflectionException
*/
public function getSession(string $name, string $sid)
{
if (isset($this->sessionPool[$sid][$name])) {
return $this->sessionPool[$sid][$name];
}
if (isset($this->aliases[$name])) {
return $this->getSession($this->aliases[$name], $sid);
}
// Class name
$classNames = $this->classNames[$name] ?? [];
if ($classNames) {
$name = end($classNames);
return $this->getSession($name, $sid);
}
if (!isset($this->sessionDefinitions[$name])) {
throw new ContainerException(sprintf('Session bean(%s) is not defined', $name));
}
return $this->newBean($name, $sid);
}
/**
* Finds an entry of the container by its identifier and returns it.
*
* @param string $id Bean name Or alias Or class name
*
* When class name will return all of instance for class name
*
* @return object
* @throws ContainerException
* @throws ReflectionException
*/
public function get($id)
{
// It is singleton
if (isset($this->singletonPool[$id])) {
return $this->singletonPool[$id];
}
// Prototype by clone
if (isset($this->prototypePool[$id])) {
return clone $this->prototypePool[$id];
}
// Alias name
$aliasId = $this->aliases[$id] ?? '';
if ($aliasId) {
return $this->get($aliasId);
}
// Class name
$classNames = $this->classNames[$id] ?? [];
if ($classNames) {
$id = end($classNames);
return $this->get($id);
}
// Not defined
if (!isset($this->objectDefinitions[$id])) {
throw new ContainerException(sprintf('The bean of %s is not defined', $id));
}
/* @var ObjectDefinition $objectDefinition */
$objectDefinition = $this->objectDefinitions[$id];
// Prototype
return $this->newBean($objectDefinition->getName());
}
/**
* Many instance of one class
*
* @param string $className
*
* @return array
* @throws ContainerException
* @throws ReflectionException
*/
public function gets(string $className): array
{
$instanceNames = $this->classNames[$className] ?? [];
if (empty($instanceNames)) {
return [];
}
$instances = [];
foreach ($instanceNames as $instanceName) {
$instances[] = self::get($instanceName);
}
return $instances;
}
/**
* Quick get exist singleton
*
* @param string $name
*
* @return object|mixed
* @throws ContainerException
*/
public function getSingleton(string $name)
{
if (isset($this->singletonPool[$name])) {
return $this->singletonPool[$name];
}
if (isset($this->aliases[$name])) {
$name = $this->aliases[$name];
return $this->singletonPool[$name];
}
$classNames = $this->classNames[$name] ?? [];
if ($classNames) {
$name = end($classNames);
return $this->singletonPool[$name];
}
throw new ContainerException(sprintf('The singleton bean "%s" is not defined', $name));
}
/**
* Create object by definition
*
* @param string $name
* @param array $definition
*
* @return object
* @throws ContainerException
* @throws ReflectionException
* @example
* [
* 'class' => 'className',
* [
* 'arg',
* '${bean}',
* '${config.xxx.xxx}'
* ], // Index = 0 is constructor
*
* 'propertyName' => 'propertyValue',
* 'propertyName' => '${bean}',
* 'propertyName' => '${xxx.xxx.xxx}',
* '__option' => [
* 'scope' => Bean::xxx,
* 'alias' => 'aliasName'
* ]
* ]
*
*/
public function create(string $name, array $definition = [])
{
if ($this->has($name)) {
throw new ContainerException('Create ' . $name . ' bean by definition is exist!');
}
// Create bean only by class name
if (empty($definition) && class_exists($name)) {
$definition = [
'class' => $name
];
}
$definitionObjParser = new DefinitionObjParser($definition, [], [], $this->aliases);
[, $objectDefinitions] = $definitionObjParser->parseDefinitions();
$this->objectDefinitions[$name] = $objectDefinitions[$name];
return $this->newBean($name);
}
/**
* Returns true if the container can return an entry for the given identifier.
* Returns false otherwise.
*
* @param string $id Bean name Or alias Or class name
*
* @return bool
*/
public function has($id): bool
{
if (isset($this->singletonPool[$id])) {
return true;
}
if (isset($this->aliases[$id])) {
return true;
}
if (isset($this->classNames[$id])) {
return true;
}
if (isset($this->objectDefinitions[$id])) {
return true;
}
return false;
}
/**
* Quick check has singleton
*
* @param string $name Bean name Or alias
*
* @return bool
*/
public function isSingleton(string $name): bool
{
if (isset($this->aliases[$name])) {
$name = $this->aliases[$name];
}
return isset($this->singletonPool[$name]);
}
/**
* Destroy request bean
*
* @param string $id
*/
public function destroyRequest(string $id): void
{
unset($this->requestPool[$id]);
}
/**
* Destroy session bean
*
* @param string $sid
*/
public function destroySession(string $sid): void
{
unset($this->sessionPool[$sid]);
}
/**
* Add definitions
*
* @param array $definitions
*
* @return void
*/
public function addDefinitions(array $definitions): void
{
$this->definitions = ArrayHelper::merge($this->definitions, $definitions);
}
/**
* Add annotations
*
* @param array $annotations
*
* @return void
*/
public function addAnnotations(array $annotations): void
{
$this->annotations = ArrayHelper::merge($this->annotations, $annotations);
}
/**
* Add annotation parsers
*
* @param array $annotationParsers
*
* @return void
*/
public function addParsers(array $annotationParsers): void
{
$this->parsers = ArrayHelper::merge($this->parsers, $annotationParsers);
}
/**
* Parse annotations
*
* @throws ContainerException
* @throws AnnotationException
*/
private function parseAnnotations(): void
{
$annotationParser = new AnnotationObjParser(
$this->definitions, $this->objectDefinitions, $this->classNames, $this->aliases
);
$annotationData = $annotationParser->parseAnnotations($this->annotations, $this->parsers);
[$this->definitions, $this->objectDefinitions, $this->classNames, $this->aliases] = $annotationData;
}
/**
* Parse definitions
*
* @throws ContainerException
*/
private function parseDefinitions(): void
{
$annotationParser = new DefinitionObjParser(
$this->definitions, $this->objectDefinitions, $this->classNames, $this->aliases
);
// Collect info
$definitionData = $annotationParser->parseDefinitions();
[$this->definitions, $this->objectDefinitions, $this->classNames, $this->aliases] = $definitionData;
}
/**
* @param HandlerInterface $handler
*/
public function setHandler(HandlerInterface $handler): void
{
$this->handler = $handler;
}
/**
* @return array
*/
public function getStats(): array
{
return [
'singleton' => count($this->singletonPool),
'prototype' => count($this->prototypePool),
'definition' => count($this->definitions),
// 'definition' => \count($this->r),
];
}
/**
* Get bean names
*
* @return array
*/
public function getNames(): array
{
return [
'session' => array_keys($this->sessionPool),
'request' => array_keys($this->requestPool),
'singleton' => array_keys($this->singletonPool),
'prototype' => array_keys($this->prototypePool),
'definition' => array_keys($this->definitions),
// 'definition' => \count($this->r),
];
}
/**
* @return array
*/
public function getRequestPool(): array
{
return $this->requestPool;
}
/**
* @return array
*/
public function getSessionPool(): array
{
return $this->sessionPool;
}
/**
* @return array
*/
public function getAliases(): array
{
return $this->aliases;
}
/**
* @return array
*/
public function getClassNames(): array
{
return $this->classNames;
}
/**
* @return ObjectDefinition[]
*/
public function getObjectDefinitions(): array
{
return $this->objectDefinitions;
}
/**
* @return ObjectDefinition[]
*/
public function getRequestDefinitions(): array
{
return $this->requestDefinitions;
}
/**
* @return ObjectDefinition[]
*/
public function getSessionDefinitions(): array
{
return $this->sessionDefinitions;
}
/**
* Initialize beans
*
* @throws ContainerException
* @throws ReflectionException
*/
private function initializeBeans(): void
{
/* @var ObjectDefinition $objectDefinition */
foreach ($this->objectDefinitions as $beanName => $objectDefinition) {
$scope = $objectDefinition->getScope();
// Exclude request
if ($scope === Bean::REQUEST) {
$this->requestDefinitions[$beanName] = $objectDefinition;
unset($this->objectDefinitions[$beanName]);
continue;
}
// Exclude session
if ($scope === Bean::SESSION) {
$this->sessionDefinitions[$beanName] = $objectDefinition;
unset($this->objectDefinitions[$beanName]);
continue;
}
// New bean
$this->newBean($beanName);
}
}
/**
* @param string $beanName
*
* @return ObjectDefinition
* @throws ContainerException
*/
private function getNewObjectDefinition(string $beanName): ObjectDefinition
{
if (isset($this->objectDefinitions[$beanName])) {
return $this->objectDefinitions[$beanName];
}
if (isset($this->requestDefinitions[$beanName])) {
return $this->requestDefinitions[$beanName];
}
if (isset($this->sessionDefinitions[$beanName])) {
return $this->sessionDefinitions[$beanName];
}
$classNames = $this->classNames[$beanName] ?? [];
if (!empty($classNames)) {
$beanName = end($classNames);
return $this->getNewObjectDefinition($beanName);
}
if (isset($this->aliases[$beanName])) {
return $this->getNewObjectDefinition($this->aliases[$beanName]);
}
throw new ContainerException('Bean name of ' . $beanName . ' is not defined!');
}
/**
* @param string $beanName
* @param string $scope
* @param object $object
* @param string $id
*
* @return object
*/
private function setNewBean(string $beanName, string $scope, $object, string $id = '')
{
switch ($scope) {
case Bean::SINGLETON: // Singleton
$this->singletonPool[$beanName] = $object;
break;
case Bean::PROTOTYPE:
$this->prototypePool[$beanName] = $object;
// Clone it
$object = clone $object;
break;
case Bean::REQUEST:
$this->requestPool[$id][$beanName] = $object;
break;
case Bean::SESSION:
$this->sessionPool[$id][$beanName] = $object;
break;
}
return $object;
}
/**
* Initialize beans
*
* @param string $beanName
* @param string $id
*
* @return object
* @throws ReflectionException
* @throws ContainerException
*/
private function newBean(string $beanName, string $id = '')
{
// Get object definition
$objectDefinition = $this->getNewObjectDefinition($beanName);
$scope = $objectDefinition->getScope();
$alias = $objectDefinition->getAlias();
$className = $objectDefinition->getClassName();
// Cache reflection class info
Reflections::cache($className);
// Before initialize bean
$this->beforeInit($beanName, $className, $objectDefinition);
$constructArgs = [];
$constructInject = $objectDefinition->getConstructorInjection();
if ($constructInject !== null) {
$constructArgs = $this->getConstructParams($constructInject, $id);
}
$propertyInjects = $objectDefinition->getPropertyInjections();
// Proxy class
if ($this->handler) {
$className = $this->handler->classProxy($className);
}
$reflectionClass = new ReflectionClass($className);
$reflectObject = $this->newInstance($reflectionClass, $constructArgs);
// Inject properties values
$this->newProperty($reflectObject, $reflectionClass, $propertyInjects, $id);
// Alias
if (!empty($alias)) {
$this->aliases[$alias] = $beanName;
}
// Init method
if ($reflectionClass->hasMethod(self::INIT_METHOD)) {
$reflectObject->{self::INIT_METHOD}();
}
return $this->setNewBean($beanName, $scope, $reflectObject, $id);
}
/**
* Get construct args
*
* @param MethodInjection $methodInjection
* @param string $id
*
* @return array
* @throws ContainerException
* @throws ReflectionException
*/
private function getConstructParams(MethodInjection $methodInjection, string $id = ''): array
{
$methodName = $methodInjection->getMethodName();
if ($methodName !== '__construct') {
throw new ContainerException('ConstructInjection method must be `__construct`');
}
$argInjects = $methodInjection->getParameters();
if (empty($argInjects)) {
return [];
}
$args = [];
/* @var ArgsInjection $arg */
foreach ($argInjects as $argInject) {
// Empty args
$argValue = $argInject->getValue();
if (empty($argValue) || !is_string($argValue)) {
$args[] = $argValue;
continue;
}
$isRef = $argInject->isRef();
if ($isRef) {
$argValue = $this->getRefValue($argValue, $id);
}
$args[] = $argValue;
}
return $args;
}
/**
* New bean instance
*
* @param ReflectionClass $reflectionClass
* @param array $args
*
* @return object
* @throws ContainerException
* @throws ReflectionException
*/
private function newInstance(ReflectionClass $reflectionClass, array $args)
{
if (empty($args) || !$reflectionClass->hasMethod('__construct')) {
return $reflectionClass->newInstance();
}
$reflectMethod = $reflectionClass->getMethod('__construct');
if ($reflectMethod->isPrivate() || $reflectMethod->isProtected()) {
throw new ContainerException('Construct function for bean must be public!');
}
return $reflectionClass->newInstanceArgs($args);
}
/**
* Inject properties into this bean. The properties data from config, annotation
*
* @param object $reflectObject
* @param ReflectionClass $reflectionClass
* @param array $propertyInjects
* @param string $id
*
* @return void
* @throws ContainerException
* @throws ReflectionException
*/
private function newProperty(
$reflectObject,
ReflectionClass $reflectionClass,
array $propertyInjects,
string $id = ''
): void {
// New parent properties
$parentClass = $reflectionClass->getParentClass();