-
Notifications
You must be signed in to change notification settings - Fork 1
/
__init__.py
1525 lines (1011 loc) · 43.5 KB
/
__init__.py
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
# -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <[email protected]>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
from __future__ import absolute_import;
import re;
from pymfony.component.system import ClassLoader;
from pymfony.component.system import Object;
from pymfony.component.system import Tool;
from pymfony.component.system import SourceFileLoader;
from pymfony.component.system.oop import abstract;
from pymfony.component.system.reflection import ReflectionObject;
from pymfony.component.system.types import OrderedDict;
from pymfony.component.system.types import Array;
from pymfony.component.config.resource import FileResource;
from pymfony.component.config.resource import ResourceInterface;
from pymfony.component.dependency.interface import ScopeInterface;
from pymfony.component.dependency.interface import ContainerInterface;
from pymfony.component.dependency.interface import IntrospectableContainerInterface;
from pymfony.component.dependency.interface import ContainerAwareInterface;
from pymfony.component.dependency.interface import TaggedContainerInterface;
from pymfony.component.dependency.interface import ExtensionInterface;
from pymfony.component.dependency.interface import CompilerPassInterface;
from pymfony.component.dependency.definition import Alias;
from pymfony.component.dependency.definition import Definition;
from pymfony.component.dependency.definition import Reference;
from pymfony.component.dependency.exception import BadMethodCallException;
from pymfony.component.dependency.exception import ServiceNotFoundException;
from pymfony.component.dependency.exception import InvalidArgumentException;
from pymfony.component.dependency.exception import LogicException;
from pymfony.component.dependency.exception import RuntimeException;
from pymfony.component.dependency.exception import ServiceCircularReferenceException
from pymfony.component.dependency.parameterbag import ParameterBag;
from pymfony.component.dependency.parameterbag import ParameterBagInterface;
from pymfony.component.dependency.parameterbag import FrozenParameterBag;
from pymfony.component.dependency.compiler import PassConfig;
from pymfony.component.dependency.compiler import Compiler;
"""
"""
class Scope(ScopeInterface):
"""Scope class.
@author: Johannes M. Schmitt <[email protected]>
@api:
"""
def __init__(self, name, parentName = ContainerInterface.SCOPE_CONTAINER):
"""
@api:
"""
self.__name = None;
self.__parentName = None;
self.__name = name;
self.__parentName = parentName;
def getName(self):
"""
@api:
"""
return self.__name;
def getParentName(self):
"""
@api:
"""
return self.__parentName;
@abstract
class ContainerAware(ContainerAwareInterface):
def __init__(self):
self._container = None;
def setContainer(self, container = None):
assert isinstance(container, (ContainerInterface, type(None)));
self._container = container;
class Container(IntrospectableContainerInterface):
"""Container is a dependency injection container.
It gives access to object instances (services).
Services and parameters are simple key/pair stores.
Parameter and service keys are case insensitive.
A service id can contain lowercased letters, digits, underscores, and dots.
Underscores are used to separate words, and dots to group services
under namespaces:
<ul>
<li>request</li>
<li>mysql_session_storage</li>
<li>symfony.mysql_session_storage</li>
</ul>
A service can also be defined by creating a method named
getXXXService(), where XXX is the camelized version of the id:
<ul>
<li>request -> getRequestService()</li>
<li>mysql_session_storage -> getMysqlSessionStorageService()</li>
<li>symfony.mysql_session_storage -> getSymfony_MysqlSessionStorageService()</li>
</ul>
The container can have three possible behaviors when a service does not exist:
* EXCEPTION_ON_INVALID_REFERENCE: Throws an exception (the default)
* None_ON_INVALID_REFERENCE: Returns None
* IGNORE_ON_INVALID_REFERENCE: Ignores the wrapping command asking for the reference
(for instance, ignore a setter if the service does not exist):
@author: Fabien Potencier <[email protected]>
@author: Johannes M. Schmitt <[email protected]>
@api:
"""
def __init__(self, parameterBag=None):
"""Constructor.
@param: ParameterBagInterface parameterBag A ParameterBagInterface instance
@api
"""
self._services = dict();
self._scopes = dict();
self._scopeChildren = dict();
self._scopedServices = dict();
self._scopeStacks = dict();
self._parameterBag = None;
self._loading = dict();
if parameterBag is None:
self._parameterBag = ParameterBag();
else:
assert isinstance(parameterBag, ParameterBagInterface);
self._parameterBag = parameterBag;
self.set('service_container', self);
def compile(self):
"""Compiles the container.
This method does two things:
Parameter values are resolved;
The parameter bag is frozen.
@api:
"""
self._parameterBag.resolve();
self._parameterBag = FrozenParameterBag(self._parameterBag.all());
def isFrozen(self):
"""Returns True if the container parameter bag are frozen.:
@return: Boolean True if the container parameter bag are frozen, False otherwise
@api:
"""
return isinstance(self._parameterBag, FrozenParameterBag);
def getParameterBag(self):
"""Gets the service container parameter bag.
@return: ParameterBagInterface A ParameterBagInterface instance
@api
"""
return self._parameterBag;
def getParameter(self, name):
"""Gets a parameter.
@param: string name The parameter name
@return mixed The parameter value
@raise InvalidArgumentException if the parameter is not defined:
@api
"""
return self._parameterBag.get(name);
def hasParameter(self, name):
"""Checks if a parameter exists.:
@param: string name The parameter name
@return Boolean The presence of parameter in container
@api
"""
return self._parameterBag.has(name);
def setParameter(self, name, value):
"""Sets a parameter.
@param: string name The parameter name
@param mixed value The parameter value
@api
"""
self._parameterBag.set(name, value);
def set(self, identifier, service, scope = ContainerInterface.SCOPE_CONTAINER):
"""Sets a service.
@param: string identifier The service identifier:
@param object service The service instance
@param string scope The scope of the service
@raise RuntimeException When trying to set a service in an inactive scope
@raise InvalidArgumentException When trying to set a service in the prototype scope
@api
"""
if (self.SCOPE_PROTOTYPE == scope) :
raise InvalidArgumentException(
'You cannot set service "{0}" of scope "prototype".'
''.format(identifier)
);
identifier = self._formatIdentifier(identifier);
if (self.SCOPE_CONTAINER != scope) :
if not scope in self._scopedServices :
raise RuntimeException(
'You cannot set service "{0}" of inactive scope.'
''.format(identifier)
);
self._scopedServices[scope][identifier] = service;
self._services[identifier] = service;
def has(self, identifier):
"""Returns True if the given service is defined.:
@param: string id The service identifier:
@return Boolean True if the service is defined, False otherwise:
@api
"""
identifier = self._formatIdentifier(identifier);
method = 'get'+self.camelize(identifier)+'Service';
return identifier in self._services.keys() or (hasattr(self, method) and isinstance(getattr(self, method), type(self.has)));
def get(self, identifier, invalidBehavior = ContainerInterface.EXCEPTION_ON_INVALID_REFERENCE):
"""Gets a service.
If a service is defined both through a set() method and
with a getidService() method, the former has always precedence.
@param: string id The service identifier:
@param integer invalidBehavior The behavior when the service does not exist
@return object The associated service
@raise InvalidArgumentException if the service is not defined:
@raise ServiceCircularReferenceException When a circular reference is detected
@raise ServiceNotFoundException When the service is not defined
@see Reference
@api
"""
identifier = self._formatIdentifier(identifier);
if identifier in self._services.keys():
return self._services[identifier];
if identifier in self._loading.keys():
raise ServiceCircularReferenceException(identifier, list(self._loading.keys()));
method = 'get'+self.camelize(identifier)+'Service';
if (hasattr(self, method) and isinstance(getattr(self, method), type(self.get))):
self._loading[identifier] = True;
try:
service = getattr(self, method)();
except Exception as e:
self._loading.pop(identifier, None);
self._services.pop(identifier, None);
raise e;
self._loading.pop(identifier, None);
return service;
if (self.EXCEPTION_ON_INVALID_REFERENCE == invalidBehavior) :
raise ServiceNotFoundException(identifier);
def initialized(self, identifier):
"""Returns True if the given service has actually been initialized:
@param: string id The service identifier:
@return Boolean True if service has already been initialized, False otherwise:
"""
identifier = self._formatIdentifier(identifier);
return identifier in self._services;
def getServiceIds(self):
"""Gets all service ids.
@return: list An array of all defined service ids
"""
ids = list();
r = ReflectionObject(self);
for method in r.getMethods():
match = re.search('^get(.+)Service$', method.getName());
if match :
ids.append(self.underscore(match.group(1)));
return Array.uniq(ids + list(self._services.keys()));
def enterScope(self, name):
"""This is called when you enter a scope
@param: string name
@raise RuntimeException When the parent scope is inactive
@raise InvalidArgumentException When the scope does not exist
@api
"""
if name not in self._scopes :
raise InvalidArgumentException(
'The scope "{0}" does not exist.'.format(name)
);
if self.SCOPE_CONTAINER != self._scopes[name] and self._scopes[name] not in self._scopedServices :
raise RuntimeException(
'The parent scope "{0}" must be active when entering this '
'scope.'.format(self._scopes[name])
);
# check if a scope of this name is already active, if so we need to
# remove all services of this scope, and those of any of its child
# scopes from the global services map
if name in self._scopedServices :
services = OrderedDict();
services[0] = self._services;
services[name] = self._scopedServices[name];
self._scopedServices.pop(name, None);
for child in self._scopeChildren[name]:
if child in self._scopedServices:
services[child] = self._scopedServices[child];
self._scopedServices.pop(child, None);
# update global map
self._services = Array.diffKey(*services.values());
services.pop(0);
# add stack entry for this scope so we can restore the removed services later
if name not in self._scopeStacks :
self._scopeStacks[name] = list();
self._scopeStacks[name].append(services);
self._scopedServices[name] = dict();
def leaveScope(self, name):
"""This is called to leave the current scope, and move back to the parent
scope.
@param: string name The name of the scope to leave
@raise InvalidArgumentException if the scope is not active:
@api
"""
if name not in self._scopedServices :
raise InvalidArgumentException(
'The scope "{0}" is not active.'.format(name)
);
# remove all services of this scope, or any of its child scopes from
# the global service map
services = [self._services, self._scopedServices[name]];
self._scopedServices.pop(name, None);
for child in self._scopeChildren[name]:
if child not in self._scopedServices :
continue;
services.append(self._scopedServices[child]);
self._scopedServices.pop(child, None);
self._services = Array.diffKey(*services);
# check if we need to restore services of a previous scope of this type:
if name in self._scopeStacks and self._scopeStacks[name] :
services = self._scopeStacks[name].pop();
self._scopedServices.update(services);
for scopeServices in services.values():
self._services.update(scopeServices);
def addScope(self, scope):
"""Adds a scope to the container.
@param: ScopeInterface scope
@raise InvalidArgumentException
@api
"""
assert isinstance(scope, ScopeInterface);
name = scope.getName();
parentScope = scope.getParentName();
if (self.SCOPE_CONTAINER == name or self.SCOPE_PROTOTYPE == name) :
raise InvalidArgumentException(
'The scope "{0}" is reserved.'.format(name)
);
if name in self._scopes :
raise InvalidArgumentException(
'A scope with name "{0}" already exists.'.format(name)
);
if self.SCOPE_CONTAINER != parentScope and parentScope not in self._scopes :
raise InvalidArgumentException(
'The parent scope "{0}" does not exist, or is invalid.'
''.format(parentScope)
);
self._scopes[name] = parentScope;
self._scopeChildren[name] = list();
# normalize the child relations
while (parentScope != self.SCOPE_CONTAINER):
self._scopeChildren[parentScope].append(name);
parentScope = self._scopes[parentScope];
def hasScope(self, name):
"""Returns whether this container has a certain scope
@param: string name The name of the scope
@return Boolean
@api
"""
return name in self._scopes;
def isScopeActive(self, name):
"""Returns whether this scope is currently active
This does not actually check if the passed scope actually exists.:
@param: string name
@return Boolean
@api
"""
return name in self._scopedServices;
@classmethod
def camelize(self, identifier):
"""Camelizes a string.
@param: string identifier A string to camelize
@return string The camelized string
"""
def callback(match):
if '.' == match.group(1):
return '_'+str(match.group(2)).upper();
else:
return ''+str(match.group(2)).upper();
return re.sub('(^|_|\.)+(.)', callback, identifier);
@classmethod
def underscore(cls, identifier):
"""A string to underscore.
@param identifier: string The string to underscore
@return: string The underscored string
"""
value = str(identifier);
# value = value.replace("_", ".");
patterns = [
r"([A-Z]+)([A-Z][a-z])",
r"([a-z\d])([A-Z])",
]
repls = [
'\\1_\\2',
'\\1_\\2',
];
for i in range(len(patterns)):
value = re.sub(patterns[i], repls[i], value);
return value.lower();
def _formatIdentifier(self, identifier):
return str(identifier).lower();
class ContainerBuilder(Container, TaggedContainerInterface):
"""ContainerBuilder is a DI container that provides an API to easily describe services.
@author: Fabien Potencier <[email protected]>
@api
"""
def __init__(self, parameterBag=None):
"""Sets the track resources flag.
If you are not using the loaders and therefore don't want
to depend on the Config component, set this flag to False.
@param: Boolean track True if you want to track resources, False otherwise:
"""
self.__trackResources = True;
self.__resources = [];
self.__definitions = dict();
self.__extensions = dict();
self.__extensionsByNs = dict();
self.__extensionConfigs = dict();
self.__aliases = dict();
self.__compiler = None;
Container.__init__(self, parameterBag=parameterBag);
def setResourceTracking(self, track):
"""Sets the track resources flag.
If you are not using the loaders and therefore don't want
to depend on the Config component, set this flag to False.
@param: Boolean track True if you want to track resources, False otherwise:
"""
self.__trackResources = bool(track);
def isTrackingResources(self):
"""Checks if resources are tracked.:
@return: Boolean True if resources are tracked, False otherwise:
"""
return self.__trackResources;
def registerExtension(self, extension):
"""Registers an extension.
@param: ExtensionInterface extension An extension instance
@api
"""
assert isinstance(extension, ExtensionInterface);
self.__extensions[extension.getAlias()] = extension;
if extension.getNamespace():
self.__extensionsByNs[extension.getNamespace()] = extension;
def getExtension(self, name):
"""Returns an extension by alias or namespace.
@param: string name An alias or a namespace
@return ExtensionInterface An extension instance
@raise LogicException if the extension is not registered:
@api
"""
if name in self.__extensions:
return self.__extensions[name];
if name in self.__extensionsByNs:
return self.__extensionsByNs[name];
raise LogicException(
'Container extension "{0}" is not registered'.format(name)
);
def getExtensions(self):
"""Returns all registered extensions.
@return: ExtensionInterface[] An array of ExtensionInterface
@api
"""
return self.__extensions;
def hasExtension(self, name):
"""Checks if we have an extension.:
@param: string name The name of the extension
@return Boolean If the extension exists
@api
"""
return name in self.__extensions or name in self.__extensionsByNs;
def getResources(self):
"""Returns an array of resources loaded to build this configuration.
@return: ResourceInterface[] An array of resources
@api
"""
return Array.uniq(self.__resources, str);
def addResource(self, resource):
"""Adds a resource for this configuration.
@param: ResourceInterface resource A resource instance
@return ContainerBuilder The current instance
@api
"""
assert isinstance(resource, ResourceInterface);
if not self.__trackResources or not str(resource):
return self;
self.__resources.append(resource);
return self;
def setResources(self, resources):
"""Sets the resources for this configuration.
@param: ResourceInterface[] resources An array of resources
@return ContainerBuilder The current instance
@api
"""
assert isinstance(resources, list);
if ( not self.__trackResources) :
return self;
self.__resources = resources;
return self;
def addObjectResource(self, objectResource):
"""Adds the object class hierarchy(, as resources.):
@param: object object An object instance
@return ContainerBuilder The current instance
@api
"""
assert isinstance(objectResource, Object);
if not self.__trackResources:
return self;
parent = ReflectionObject(objectResource);
while parent:
self.addResource(FileResource(parent.getFileName()));
parent = parent.getParentClass();
return self;
def loadFromExtension(self, extension, values = None):
"""Loads the configuration for an extension.
@param: string extension The extension alias or namespace
@param array values An array of values that customizes the extension
@return ContainerBuilder The current instance
@raise BadMethodCallException When this ContainerBuilder is frozen
@raise LogicException if the container is frozen:
@api
"""
if values is None:
values = dict();
if self.isFrozen():
raise BadMethodCallException(
'Cannot load from an extension on a frozen container.'
);
namespace = self.getExtension(extension).getAlias();
if namespace not in self.__extensionConfigs:
self.__extensionConfigs[namespace] = list();
self.__extensionConfigs[namespace].append(values);
return self;
def addCompilerPass(self, cpass,
cType=PassConfig.TYPE_BEFORE_OPTIMIZATION):
"""Adds a compiler pass.
@param: CompilerPassInterface cpass A compiler pass
@param string cType The type of compiler pass
@return ContainerBuilder The current instance
@api
"""
assert isinstance(cpass, CompilerPassInterface);
if self.__compiler is None:
self.__compiler = Compiler();
self.__compiler.addPass(cpass, cType);
self.addObjectResource(cpass);
return self;
def getCompilerPassConfig(self):
"""Returns the compiler pass config which can then be modified.:
@return: PassConfig The compiler pass config
@api
"""
if self.__compiler is None:
self.__compiler = Compiler();
return self.__compiler.getPassConfig();
def getCompiler(self):
"""Returns the compiler.
@return: Compiler The compiler
@api
"""
if self.__compiler is None:
self.__compiler = Compiler();
return self.__compiler;
def getScopes(self):
"""Returns all Scopes.
@return: dict A dict of scopes
@api
"""
return self._scopes;
def getScopeChildren(self):
"""Returns all Scope children.
@return: dict A dict of scope children.
@api
"""
return self._scopeChildren;
def set(self, identifier, service, scope = ContainerInterface.SCOPE_CONTAINER):
"""Sets a service.
@param: string id The service identifier:
@param object service The service instance
@param string scope The scope
@raise BadMethodCallException When this ContainerBuilder is frozen
@api
"""
identifier = self._formatIdentifier(identifier);
if self.isFrozen():
# setting a synthetic service on a frozen container is alright
if identifier not in self.__definitions or not self.__definitions[identifier].isSynthetic():
raise BadMethodCallException('Setting service "{0}" on a frozen container is not allowed.'.format(identifier));
self.__definitions.pop(identifier, None);
self.__aliases.pop(identifier, None);
Container.set(self, identifier, service, scope);
def removeDefinition(self, identifier):
"""Removes a service definition.
@param: string id The service identifier:
@api
"""
identifier = self._formatIdentifier(identifier);
self.__definitions.pop(identifier, None);
def has(self, identifier):
"""Returns True if the given service is defined.:
@param: string id The service identifier:
@return Boolean True if the service is defined, False otherwise:
@api
"""
identifier = self._formatIdentifier(identifier);
return identifier in self.__definitions\
or identifier in self.__aliases\
or Container.has(self, identifier);
def get(self, identifier, invalidBehavior = ContainerInterface.EXCEPTION_ON_INVALID_REFERENCE):
"""Gets a service.
@param: string id The service identifier:
@param integer invalidBehavior The behavior when the service does not exist
@return object The associated service
@raise InvalidArgumentException if the service is not defined:
@raise LogicException if the service has a circular reference to itself:
@see Reference
@api
"""
identifier = self._formatIdentifier(identifier);
try:
return Container.get(self, identifier, ContainerInterface.EXCEPTION_ON_INVALID_REFERENCE);
except InvalidArgumentException as e:
if identifier in self._loading:
raise LogicException(
'The service "{0}" has a circular reference to itself.'
''.format(identifier), 0, e
);
if not self.hasDefinition(identifier) \
and identifier in self.__aliases:
return self.get(self.__aliases[identifier]);
try:
definition = self.getDefinition(identifier);
except InvalidArgumentException as e:
if (ContainerInterface.EXCEPTION_ON_INVALID_REFERENCE != invalidBehavior):
return None;
raise e;
self._loading[identifier] = True;
try:
service = self.__createService(definition, identifier);
except Exception as e:
self._loading.pop(identifier, None);
raise e;
self._loading.pop(identifier, None);
return service;
def merge(self, container):
"""Merges a ContainerBuilder with the current ContainerBuilder configuration.
Service definitions overrides the current defined ones.
But for parameters, they are overridden by the current ones. It allows
the parameters passed to the container constructor to have precedence
over the loaded ones.
container = ContainerBuilder(array('foo' => 'bar'));
loader = LoaderXXX(container);
loader.load('resource_name');
container.register('foo', stdClass());
In the above example, even if the loaded resource defines a foo:
parameter, the value will still be 'bar' as defined in the ContainerBuilder
constructor.
@param: ContainerBuilder container The ContainerBuilder instance to merge.
@raise BadMethodCallException When this ContainerBuilder is frozen
@api
"""
assert isinstance(container, ContainerBuilder);
if self.isFrozen():
raise BadMethodCallException(
'Cannot merge on a frozen container.'
);
self.addDefinitions(container.getDefinitions());
self.addAliases(container.getAliases());
self.getParameterBag().add(container.getParameterBag().all());
if self.__trackResources:
for resource in container.getResources():
self.addResource(resource);
for name in self.__extensions.keys():
if name not in self.__extensionConfigs:
self.__extensionConfigs[name] = list();
if container.getExtensionConfig(name):
self.__extensionConfigs[name] = \
list(self.__extensionConfigs[name]) +\
list(container.getExtensionConfig[name]);
def getExtensionConfig(self, name):
"""Returns the configuration array for the given extension.