This repository has been archived by the owner on Feb 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 89
/
ServiceManager.php
1267 lines (1116 loc) · 38.4 KB
/
ServiceManager.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
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\ServiceManager;
class ServiceManager implements ServiceLocatorInterface
{
/**@#+
* Constants
*/
const SCOPE_PARENT = 'parent';
const SCOPE_CHILD = 'child';
/**@#-*/
/**
* Lookup for canonicalized names.
*
* @var array
*/
protected $canonicalNames = [];
/**
* @var bool
*/
protected $allowOverride = false;
/**
* @var array
*/
protected $invokableClasses = [];
/**
* @var string|callable|\Closure|FactoryInterface[]
*/
protected $factories = [];
/**
* @var AbstractFactoryInterface[]
*/
protected $abstractFactories = [];
/**
* @var array[]
*/
protected $delegators = [];
/**
* @var array
*/
protected $pendingAbstractFactoryRequests = [];
/**
* @var integer
*/
protected $nestedContextCounter = -1;
/**
* @var array
*/
protected $nestedContext = [];
/**
* @var array
*/
protected $shared = [];
/**
* Registered services and cached values
*
* @var array
*/
protected $instances = [];
/**
* @var array
*/
protected $aliases = [];
/**
* @var array
*/
protected $initializers = [];
/**
* @var ServiceManager[]
*/
protected $peeringServiceManagers = [];
/**
* Whether or not to share by default
*
* @var bool
*/
protected $shareByDefault = true;
/**
* @var bool
*/
protected $retrieveFromPeeringManagerFirst = false;
/**
* @var bool Track whether not to throw exceptions during create()
*/
protected $throwExceptionInCreate = true;
/**
* @var array map of characters to be replaced through strtr
*/
protected $canonicalNamesReplacements = ['-' => '', '_' => '', ' ' => '', '\\' => '', '/' => ''];
/**
* @var ServiceLocatorInterface
*/
protected $serviceManagerCaller;
/**
* Constructor
*
* @param ConfigInterface $config
*/
public function __construct(ConfigInterface $config = null)
{
if ($config) {
$config->configureServiceManager($this);
}
}
/**
* Set allow override
*
* @param $allowOverride
* @return ServiceManager
*/
public function setAllowOverride($allowOverride)
{
$this->allowOverride = (bool) $allowOverride;
return $this;
}
/**
* Get allow override
*
* @return bool
*/
public function getAllowOverride()
{
return $this->allowOverride;
}
/**
* Set flag indicating whether services are shared by default
*
* @param bool $shareByDefault
* @return ServiceManager
* @throws Exception\RuntimeException if allowOverride is false
*/
public function setShareByDefault($shareByDefault)
{
if ($this->allowOverride === false) {
throw new Exception\RuntimeException(sprintf(
'%s: cannot alter default shared service setting; container is marked immutable (allow_override is false)',
get_class($this) . '::' . __FUNCTION__
));
}
$this->shareByDefault = (bool) $shareByDefault;
return $this;
}
/**
* Are services shared by default?
*
* @return bool
*/
public function shareByDefault()
{
return $this->shareByDefault;
}
/**
* Set throw exceptions in create
*
* @param bool $throwExceptionInCreate
* @return ServiceManager
*/
public function setThrowExceptionInCreate($throwExceptionInCreate)
{
$this->throwExceptionInCreate = $throwExceptionInCreate;
return $this;
}
/**
* Get throw exceptions in create
*
* @return bool
*/
public function getThrowExceptionInCreate()
{
return $this->throwExceptionInCreate;
}
/**
* Set flag indicating whether to pull from peering manager before attempting creation
*
* @param bool $retrieveFromPeeringManagerFirst
* @return ServiceManager
*/
public function setRetrieveFromPeeringManagerFirst($retrieveFromPeeringManagerFirst = true)
{
$this->retrieveFromPeeringManagerFirst = (bool) $retrieveFromPeeringManagerFirst;
return $this;
}
/**
* Should we retrieve from the peering manager prior to attempting to create a service?
*
* @return bool
*/
public function retrieveFromPeeringManagerFirst()
{
return $this->retrieveFromPeeringManagerFirst;
}
/**
* Set invokable class
*
* @param string $name
* @param string $invokableClass
* @param bool $shared
* @return ServiceManager
* @throws Exception\InvalidServiceNameException
*/
public function setInvokableClass($name, $invokableClass, $shared = null)
{
$cName = $this->canonicalizeName($name);
if ($this->has([$cName, $name], false)) {
if ($this->allowOverride === false) {
throw new Exception\InvalidServiceNameException(sprintf(
'A service by the name or alias "%s" already exists and cannot be overridden; please use an alternate name',
$name
));
}
$this->unregisterService($cName);
}
if ($shared === null) {
$shared = $this->shareByDefault;
}
$this->invokableClasses[$cName] = $invokableClass;
$this->shared[$cName] = (bool) $shared;
return $this;
}
/**
* Set factory
*
* @param string $name
* @param string|FactoryInterface|callable $factory
* @param bool $shared
* @return ServiceManager
* @throws Exception\InvalidArgumentException
* @throws Exception\InvalidServiceNameException
*/
public function setFactory($name, $factory, $shared = null)
{
$cName = $this->canonicalizeName($name);
if (!($factory instanceof FactoryInterface || is_string($factory) || is_callable($factory))) {
throw new Exception\InvalidArgumentException(sprintf(
'Provided factory must be the class name of a factory, callable or an instance of "%s".',
FactoryInterface::class
));
}
if ($this->has([$cName, $name], false)) {
if ($this->allowOverride === false) {
throw new Exception\InvalidServiceNameException(sprintf(
'A service by the name or alias "%s" already exists and cannot be overridden, please use an alternate name',
$name
));
}
$this->unregisterService($cName);
}
if ($shared === null) {
$shared = $this->shareByDefault;
}
$this->factories[$cName] = $factory;
$this->shared[$cName] = (bool) $shared;
return $this;
}
/**
* Add abstract factory
*
* @param AbstractFactoryInterface|string $factory
* @param bool $topOfStack
* @return ServiceManager
* @throws Exception\InvalidArgumentException if the abstract factory is invalid
*/
public function addAbstractFactory($factory, $topOfStack = true)
{
if (!$factory instanceof AbstractFactoryInterface && is_string($factory)) {
$factory = new $factory();
}
if (!$factory instanceof AbstractFactoryInterface) {
throw new Exception\InvalidArgumentException(
'Provided abstract factory must be the class name of an abstract'
. ' factory or an instance of an AbstractFactoryInterface.'
);
}
if ($topOfStack) {
array_unshift($this->abstractFactories, $factory);
} else {
array_push($this->abstractFactories, $factory);
}
return $this;
}
/**
* Sets the given service name as to be handled by a delegator factory
*
* @param string $serviceName name of the service being the delegate
* @param string $delegatorFactoryName name of the service being the delegator factory
*
* @return ServiceManager
*/
public function addDelegator($serviceName, $delegatorFactoryName)
{
$cName = $this->canonicalizeName($serviceName);
if (!isset($this->delegators[$cName])) {
$this->delegators[$cName] = [];
}
$this->delegators[$cName][] = $delegatorFactoryName;
return $this;
}
/**
* Add initializer
*
* @param callable|InitializerInterface $initializer
* @param bool $topOfStack
* @return ServiceManager
* @throws Exception\InvalidArgumentException
*/
public function addInitializer($initializer, $topOfStack = true)
{
if (!($initializer instanceof InitializerInterface || is_callable($initializer))) {
if (is_string($initializer)) {
$initializer = new $initializer;
}
if (!($initializer instanceof InitializerInterface || is_callable($initializer))) {
throw new Exception\InvalidArgumentException('$initializer should be callable.');
}
}
if ($topOfStack) {
array_unshift($this->initializers, $initializer);
} else {
array_push($this->initializers, $initializer);
}
return $this;
}
/**
* Register a service with the locator
*
* @param string $name
* @param mixed $service
* @return ServiceManager
* @throws Exception\InvalidServiceNameException
*/
public function setService($name, $service)
{
$cName = $this->canonicalizeName($name);
if ($this->has($cName, false)) {
if ($this->allowOverride === false) {
throw new Exception\InvalidServiceNameException(sprintf(
'%s: A service by the name "%s" or alias already exists and cannot be overridden, please use an alternate name.',
get_class($this) . '::' . __FUNCTION__,
$name
));
}
$this->unregisterService($cName);
}
$this->instances[$cName] = $service;
return $this;
}
/**
* @param string $name
* @param bool $isShared
* @return ServiceManager
* @throws Exception\ServiceNotFoundException
*/
public function setShared($name, $isShared)
{
$cName = $this->canonicalizeName($name);
if (!isset($this->invokableClasses[$cName])
&& !isset($this->factories[$cName])
&& !$this->canCreateFromAbstractFactory($cName, $name)
) {
throw new Exception\ServiceNotFoundException(sprintf(
'%s: A service by the name "%s" was not found and could not be marked as shared',
get_class($this) . '::' . __FUNCTION__,
$name
));
}
$this->shared[$cName] = (bool) $isShared;
return $this;
}
/**
* @param string $name
* @return bool
* @throws Exception\ServiceNotFoundException
*/
public function isShared($name)
{
$cName = $this->canonicalizeName($name);
if (!$this->has($name)) {
throw new Exception\ServiceNotFoundException(sprintf(
'%s: A service by the name "%s" was not found',
get_class($this) . '::' . __FUNCTION__,
$name
));
}
if (!isset($this->shared[$cName])) {
return $this->shareByDefault();
}
return $this->shared[$cName];
}
/**
* Resolve the alias for the given canonical name
*
* @param string $cName The canonical name to resolve
* @return string The resolved canonical name
*/
protected function resolveAlias($cName)
{
$stack = [];
while ($this->hasAlias($cName)) {
if (isset($stack[$cName])) {
throw new Exception\CircularReferenceException(sprintf(
'Circular alias reference: %s -> %s',
implode(' -> ', $stack),
$cName
));
}
$stack[$cName] = $cName;
$cName = $this->aliases[$this->canonicalizeName($cName)];
}
return $cName;
}
/**
* Retrieve a registered instance
*
* @param string $name
* @param bool $usePeeringServiceManagers
* @throws Exception\ServiceNotFoundException
* @return object|array
*/
public function get($name, $usePeeringServiceManagers = true)
{
// inlined code from ServiceManager::canonicalizeName for performance
if (isset($this->canonicalNames[$name])) {
$cName = $this->canonicalNames[$name];
} else {
$cName = $this->canonicalizeName($name);
}
$isAlias = false;
if ($this->hasAlias($cName)) {
$isAlias = true;
$name = $this->resolveAlias($cName);
$cName = $this->canonicalizeName($name);
}
$instance = null;
if ($usePeeringServiceManagers && $this->retrieveFromPeeringManagerFirst) {
$instance = $this->retrieveFromPeeringManager($name);
if (null !== $instance) {
return $instance;
}
}
if (isset($this->instances[$cName])) {
return $this->instances[$cName];
}
if (!$instance) {
$this->checkNestedContextStart($cName);
if (isset($this->invokableClasses[$cName])
|| isset($this->factories[$cName])
|| isset($this->aliases[$cName])
|| $this->canCreateFromAbstractFactory($cName, $name)
) {
$instance = $this->create([$cName, $name]);
} elseif ($isAlias && $this->canCreateFromAbstractFactory($name, $cName)) {
/*
* case of an alias leading to an abstract factory :
* 'my-alias' => 'my-abstract-defined-service'
* $name = 'my-alias'
* $cName = 'my-abstract-defined-service'
*/
$instance = $this->create([$name, $cName]);
} elseif ($usePeeringServiceManagers && !$this->retrieveFromPeeringManagerFirst) {
$instance = $this->retrieveFromPeeringManager($name);
}
$this->checkNestedContextStop();
}
// Still no instance? raise an exception
if ($instance === null) {
$this->checkNestedContextStop(true);
if ($isAlias) {
throw new Exception\ServiceNotFoundException(sprintf(
'An alias "%s" was requested but no service could be found.',
$name
));
}
throw new Exception\ServiceNotFoundException(sprintf(
'%s was unable to fetch or create an instance for %s',
get_class($this) . '::' . __FUNCTION__,
$name
));
}
if (($this->shareByDefault && !isset($this->shared[$cName]))
|| (isset($this->shared[$cName]) && $this->shared[$cName] === true)
) {
$this->instances[$cName] = $instance;
}
return $instance;
}
/**
* Create an instance of the requested service
*
* @param string|array $name
*
* @return bool|object
*/
public function create($name)
{
if (is_array($name)) {
list($cName, $rName) = $name;
} else {
$rName = $name;
// inlined code from ServiceManager::canonicalizeName for performance
if (isset($this->canonicalNames[$rName])) {
$cName = $this->canonicalNames[$name];
} else {
$cName = $this->canonicalizeName($name);
}
}
if (isset($this->delegators[$cName])) {
return $this->createDelegatorFromFactory($cName, $rName);
}
return $this->doCreate($rName, $cName);
}
/**
* Creates a callback that uses a delegator to create a service
*
* @param DelegatorFactoryInterface|callable $delegatorFactory the delegator factory
* @param string $rName requested service name
* @param string $cName canonical service name
* @param callable $creationCallback callback for instantiating the real service
*
* @return callable
*/
private function createDelegatorCallback($delegatorFactory, $rName, $cName, $creationCallback)
{
return function () use ($delegatorFactory, $rName, $cName, $creationCallback) {
return $delegatorFactory instanceof DelegatorFactoryInterface
? $delegatorFactory->createDelegatorWithName($this, $cName, $rName, $creationCallback)
: $delegatorFactory($this, $cName, $rName, $creationCallback);
};
}
/**
* Actually creates the service
*
* @param string $rName real service name
* @param string $cName canonicalized service name
*
* @return bool|mixed|null|object
* @throws Exception\ServiceNotFoundException
*
*/
protected function doCreate($rName, $cName)
{
$instance = null;
if (isset($this->factories[$cName])) {
$instance = $this->createFromFactory($cName, $rName);
}
if ($instance === null && isset($this->invokableClasses[$cName])) {
$instance = $this->createFromInvokable($cName, $rName);
}
$this->checkNestedContextStart($cName);
if ($instance === null && $this->canCreateFromAbstractFactory($cName, $rName)) {
$instance = $this->createFromAbstractFactory($cName, $rName);
}
$this->checkNestedContextStop();
if ($instance === null && $this->throwExceptionInCreate) {
$this->checkNestedContextStop(true);
throw new Exception\ServiceNotFoundException(sprintf(
'No valid instance was found for %s%s',
$cName,
($rName ? '(alias: ' . $rName . ')' : '')
));
}
// Do not call initializers if we do not have an instance
if ($instance === null) {
return $instance;
}
foreach ($this->initializers as $initializer) {
if ($initializer instanceof InitializerInterface) {
$initializer->initialize($instance, $this);
} else {
call_user_func($initializer, $instance, $this);
}
}
return $instance;
}
/**
* Determine if we can create an instance.
* Proxies to has()
*
* @param string|array $name
* @param bool $checkAbstractFactories
* @return bool
* @deprecated this method is being deprecated as of zendframework 2.3, and may be removed in future major versions
*/
public function canCreate($name, $checkAbstractFactories = true)
{
trigger_error(sprintf('%s is deprecated; please use %s::has', __METHOD__, __CLASS__), E_USER_DEPRECATED);
return $this->has($name, $checkAbstractFactories, false);
}
/**
* Determine if an instance exists.
*
* @param string|array $name An array argument accepts exactly two values.
* Example: array('canonicalName', 'requestName')
* @param bool $checkAbstractFactories
* @param bool $usePeeringServiceManagers
* @return bool
*/
public function has($name, $checkAbstractFactories = true, $usePeeringServiceManagers = true)
{
if (is_string($name)) {
$rName = $name;
// inlined code from ServiceManager::canonicalizeName for performance
if (isset($this->canonicalNames[$rName])) {
$cName = $this->canonicalNames[$rName];
} else {
$cName = $this->canonicalizeName($name);
}
} elseif (is_array($name) && count($name) >= 2) {
list($cName, $rName) = $name;
} else {
return false;
}
if (isset($this->invokableClasses[$cName])
|| isset($this->factories[$cName])
|| isset($this->aliases[$cName])
|| isset($this->instances[$cName])
|| ($checkAbstractFactories && $this->canCreateFromAbstractFactory($cName, $rName))
) {
return true;
}
if ($usePeeringServiceManagers) {
$caller = $this->serviceManagerCaller;
foreach ($this->peeringServiceManagers as $peeringServiceManager) {
// ignore peering service manager if they are the same instance
if ($caller === $peeringServiceManager) {
continue;
}
$peeringServiceManager->serviceManagerCaller = $this;
if ($peeringServiceManager->has($name)) {
$peeringServiceManager->serviceManagerCaller = null;
return true;
}
$peeringServiceManager->serviceManagerCaller = null;
}
}
return false;
}
/**
* Determine if we can create an instance from an abstract factory.
*
* @param string $cName
* @param string $rName
* @return bool
*/
public function canCreateFromAbstractFactory($cName, $rName)
{
if (array_key_exists($cName, $this->nestedContext)) {
$context = $this->nestedContext[$cName];
if ($context === false) {
return false;
} elseif (is_object($context)) {
return !isset($this->pendingAbstractFactoryRequests[get_class($context).$cName]);
}
}
$this->checkNestedContextStart($cName);
// check abstract factories
$result = false;
$this->nestedContext[$cName] = false;
foreach ($this->abstractFactories as $abstractFactory) {
$pendingKey = get_class($abstractFactory).$cName;
if (isset($this->pendingAbstractFactoryRequests[$pendingKey])) {
$result = false;
break;
}
if ($abstractFactory->canCreateServiceWithName($this, $cName, $rName)) {
$this->nestedContext[$cName] = $abstractFactory;
$result = true;
break;
}
}
$this->checkNestedContextStop();
return $result;
}
/**
* Ensure the alias definition will not result in a circular reference
*
* @param string $alias
* @param string $nameOrAlias
* @throws Exception\CircularReferenceException
* @return self
*/
protected function checkForCircularAliasReference($alias, $nameOrAlias)
{
$aliases = $this->aliases;
$aliases[$alias] = $this->canonicalizeName($nameOrAlias);
$stack = [];
while (isset($aliases[$alias])) {
if (isset($stack[$alias])) {
throw new Exception\CircularReferenceException(sprintf(
'The alias definition "%s" : "%s" results in a circular reference: "%s" -> "%s"',
$alias,
$nameOrAlias,
implode('" -> "', $stack),
$alias
));
}
$stack[$alias] = $alias;
$alias = $this->canonicalizeName($aliases[$alias]);
}
return $this;
}
/**
* @param string $alias
* @param string $nameOrAlias
* @return ServiceManager
* @throws Exception\ServiceNotFoundException
* @throws Exception\InvalidServiceNameException
*/
public function setAlias($alias, $nameOrAlias)
{
if (!is_string($alias) || !is_string($nameOrAlias)) {
throw new Exception\InvalidServiceNameException('Service or alias names must be strings.');
}
$cAlias = $this->canonicalizeName($alias);
if ($alias == '' || $nameOrAlias == '') {
throw new Exception\InvalidServiceNameException('Invalid service name alias');
}
if ($this->allowOverride === false && $this->has([$cAlias, $alias], false)) {
throw new Exception\InvalidServiceNameException(sprintf(
'An alias by the name "%s" or "%s" already exists',
$cAlias,
$alias
));
}
if ($this->hasAlias($alias)) {
$this->checkForCircularAliasReference($cAlias, $nameOrAlias);
}
$this->aliases[$cAlias] = $nameOrAlias;
return $this;
}
/**
* Determine if we have an alias
*
* @param string $alias
* @return bool
*/
public function hasAlias($alias)
{
return isset($this->aliases[$this->canonicalizeName($alias)]);
}
/**
* Create scoped service manager
*
* @param string $peering
* @return ServiceManager
*/
public function createScopedServiceManager($peering = self::SCOPE_PARENT)
{
$scopedServiceManager = new ServiceManager();
if ($peering == self::SCOPE_PARENT) {
$scopedServiceManager->peeringServiceManagers[] = $this;
}
if ($peering == self::SCOPE_CHILD) {
$this->peeringServiceManagers[] = $scopedServiceManager;
}
return $scopedServiceManager;
}
/**
* Add a peering relationship
*
* @param ServiceManager $manager
* @param string $peering
* @return ServiceManager
*/
public function addPeeringServiceManager(ServiceManager $manager, $peering = self::SCOPE_PARENT)
{
if ($peering == self::SCOPE_PARENT) {
$this->peeringServiceManagers[] = $manager;
}
if ($peering == self::SCOPE_CHILD) {
$manager->peeringServiceManagers[] = $this;
}
return $this;
}
/**
* Canonicalize name
*
* @param string $name
* @return string
*/
protected function canonicalizeName($name)
{
if (isset($this->canonicalNames[$name])) {
return $this->canonicalNames[$name];
}
// this is just for performance instead of using str_replace
return $this->canonicalNames[$name] = strtolower(strtr($name, $this->canonicalNamesReplacements));
}
/**
* Create service via callback
*
* @param callable $callable
* @param string $cName
* @param string $rName
* @throws Exception\ServiceNotCreatedException
* @throws Exception\ServiceNotFoundException
* @throws Exception\CircularDependencyFoundException
* @return object
*/
protected function createServiceViaCallback($callable, $cName, $rName)
{
static $circularDependencyResolver = [];
$depKey = spl_object_hash($this) . '-' . $cName;
if (isset($circularDependencyResolver[$depKey])) {
$circularDependencyResolver = [];
throw new Exception\CircularDependencyFoundException('Circular dependency for LazyServiceLoader was found for instance ' . $rName);
}
try {
$circularDependencyResolver[$depKey] = true;
$instance = call_user_func($callable, $this, $cName, $rName);
unset($circularDependencyResolver[$depKey]);
} catch (Exception\ServiceNotFoundException $e) {
unset($circularDependencyResolver[$depKey]);
throw $e;
} catch (\Exception $e) {
unset($circularDependencyResolver[$depKey]);
throw new Exception\ServiceNotCreatedException(
sprintf('An exception was raised while creating "%s"; no instance returned', $rName),
(int)$e->getCode(),
$e
);
}
if ($instance === null) {
throw new Exception\ServiceNotCreatedException('The factory was called but did not return an instance.');
}
return $instance;
}
/**
* Retrieve a keyed list of all registered services. Handy for debugging!
*
* @return array
*/
public function getRegisteredServices()
{
return [
'invokableClasses' => array_keys($this->invokableClasses),
'factories' => array_keys($this->factories),
'aliases' => array_keys($this->aliases),
'instances' => array_keys($this->instances),
];
}
/**
* Retrieve a keyed list of all canonical names. Handy for debugging!
*
* @return array
*/
public function getCanonicalNames()
{
return $this->canonicalNames;
}
/**
* Allows to override the canonical names lookup map with predefined
* values.
*
* @param array $canonicalNames
* @return ServiceManager
*/
public function setCanonicalNames($canonicalNames)
{
$this->canonicalNames = $canonicalNames;
return $this;
}
/**
* Attempt to retrieve an instance via a peering manager
*
* @param string $name
* @return mixed
*/
protected function retrieveFromPeeringManager($name)
{