/usr/share/php/Nette/DI/ContainerBuilder.php is in php-nette 2.4-20160731-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | <?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\DI;
use Nette;
use Nette\PhpGenerator\Helpers as PhpHelpers;
use Nette\Utils\Strings;
use Nette\Utils\Validators;
use ReflectionClass;
/**
* Container builder.
*/
class ContainerBuilder
{
use Nette\SmartObject;
const THIS_SERVICE = 'self',
THIS_CONTAINER = 'container';
/** @var array */
public $parameters = [];
/** @var ServiceDefinition[] */
private $definitions = [];
/** @var array of alias => service */
private $aliases = [];
/** @var array for auto-wiring */
private $classList = [];
/** @var bool */
private $classListNeedsRefresh = TRUE;
/** @var string[] of classes excluded from auto-wiring */
private $excludedClasses = [];
/** @var array */
private $dependencies = [];
/** @var string */
private $currentService;
/**
* Adds new service definition.
* @param string
* @return ServiceDefinition
*/
public function addDefinition($name, ServiceDefinition $definition = NULL)
{
$this->classListNeedsRefresh = TRUE;
if (!is_string($name) || !$name) { // builder is not ready for falsy names such as '0'
throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($name)));
}
$name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
if (isset($this->definitions[$name])) {
throw new Nette\InvalidStateException("Service '$name' has already been added.");
}
if (!$definition) {
$definition = new ServiceDefinition;
}
$definition->setNotifier(function () {
$this->classListNeedsRefresh = TRUE;
});
return $this->definitions[$name] = $definition;
}
/**
* Removes the specified service definition.
* @param string
* @return void
*/
public function removeDefinition($name)
{
$this->classListNeedsRefresh = TRUE;
$name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
unset($this->definitions[$name]);
}
/**
* Gets the service definition.
* @param string
* @return ServiceDefinition
*/
public function getDefinition($name)
{
$service = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
if (!isset($this->definitions[$service])) {
throw new MissingServiceException("Service '$name' not found.");
}
return $this->definitions[$service];
}
/**
* Gets all service definitions.
* @return ServiceDefinition[]
*/
public function getDefinitions()
{
return $this->definitions;
}
/**
* Does the service definition or alias exist?
* @param string
* @return bool
*/
public function hasDefinition($name)
{
$name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
return isset($this->definitions[$name]);
}
/**
* @param string
* @param string
*/
public function addAlias($alias, $service)
{
if (!is_string($alias) || !$alias) { // builder is not ready for falsy names such as '0'
throw new Nette\InvalidArgumentException(sprintf('Alias name must be a non-empty string, %s given.', gettype($alias)));
} elseif (!is_string($service) || !$service) { // builder is not ready for falsy names such as '0'
throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($service)));
} elseif (isset($this->aliases[$alias])) {
throw new Nette\InvalidStateException("Alias '$alias' has already been added.");
} elseif (isset($this->definitions[$alias])) {
throw new Nette\InvalidStateException("Service '$alias' has already been added.");
}
$this->aliases[$alias] = $service;
}
/**
* Removes the specified alias.
* @return void
*/
public function removeAlias($alias)
{
unset($this->aliases[$alias]);
}
/**
* Gets all service aliases.
* @return array
*/
public function getAliases()
{
return $this->aliases;
}
/**
* @param string[]
* @return self
*/
public function addExcludedClasses(array $classes)
{
foreach ($classes as $class) {
if (class_exists($class) || interface_exists($class)) {
self::checkCase($class);
$this->excludedClasses += class_parents($class) + class_implements($class) + [$class => $class];
}
}
return $this;
}
/**
* @deprecated
*/
public function setClassName($name)
{
trigger_error(__METHOD__ . ' has been deprecated', E_USER_DEPRECATED);
return $this;
}
/**
* @deprecated
*/
public function getClassName()
{
trigger_error(__METHOD__ . ' has been deprecated', E_USER_DEPRECATED);
}
/********************* class resolving ****************d*g**/
/**
* Resolves service name by type.
* @param string class or interface
* @return string|NULL service name or NULL
* @throws ServiceCreationException
*/
public function getByType($class)
{
$class = ltrim($class, '\\');
if ($this->currentService !== NULL
&& is_a($this->definitions[$this->currentService]->getClass(), $class, TRUE)
) {
return $this->currentService;
}
$classes = $this->getClassList();
if (empty($classes[$class][TRUE])) {
self::checkCase($class);
return;
} elseif (count($classes[$class][TRUE]) === 1) {
return $classes[$class][TRUE][0];
} else {
$list = $classes[$class][TRUE];
$hint = count($list) === 2 && ($tmp = strpos($list[0], '.') xor strpos($list[1], '.'))
? '. If you want to overwrite service ' . $list[$tmp ? 0 : 1] . ', give it proper name.'
: '';
throw new ServiceCreationException("Multiple services of type $class found: " . implode(', ', $list) . $hint);
}
}
/**
* Gets the service names and definitions of the specified type.
* @param string
* @return ServiceDefinition[]
*/
public function findByType($class)
{
$class = ltrim($class, '\\');
self::checkCase($class);
$found = [];
$classes = $this->getClassList();
if (!empty($classes[$class])) {
foreach (array_merge(...array_values($classes[$class])) as $name) {
$found[$name] = $this->definitions[$name];
}
}
return $found;
}
/**
* Gets the service objects of the specified tag.
* @param string
* @return array of [service name => tag attributes]
*/
public function findByTag($tag)
{
$found = [];
foreach ($this->definitions as $name => $def) {
if (($tmp = $def->getTag($tag)) !== NULL) {
$found[$name] = $tmp;
}
}
return $found;
}
/**
* @internal
*/
public function getClassList()
{
if ($this->classList !== FALSE && $this->classListNeedsRefresh) {
$this->prepareClassList();
$this->classListNeedsRefresh = FALSE;
}
return $this->classList ?: [];
}
/**
* Generates $dependencies, $classes and normalizes class names.
* @return array
* @internal
*/
public function prepareClassList()
{
unset($this->definitions[self::THIS_CONTAINER]);
$this->addDefinition(self::THIS_CONTAINER)->setClass(Container::class);
$this->classList = FALSE;
foreach ($this->definitions as $name => $def) {
// prepare generated factories
if ($def->getImplement()) {
$this->resolveImplement($def, $name);
}
if ($def->isDynamic()) {
if (!$def->getClass()) {
throw new ServiceCreationException("Class is missing in definition of service '$name'.");
}
$def->setFactory(NULL);
continue;
}
// complete class-factory pairs
if (!$def->getEntity()) {
if (!$def->getClass()) {
throw new ServiceCreationException("Class and factory are missing in definition of service '$name'.");
}
$def->setFactory($def->getClass(), ($factory = $def->getFactory()) ? $factory->arguments : []);
}
// auto-disable autowiring for aliases
if (($alias = $this->getServiceName($def->getFactory()->getEntity())) &&
(!$def->getImplement() || (!Strings::contains($alias, '\\') && $this->definitions[$alias]->getImplement()))
) {
$def->setAutowired(FALSE);
}
}
// resolve and check classes
foreach ($this->definitions as $name => $def) {
$this->resolveServiceClass($name);
}
// build auto-wiring list
$this->classList = $preferred = [];
foreach ($this->definitions as $name => $def) {
if ($class = $def->getImplement() ?: $def->getClass()) {
$defAutowired = $def->getAutowired();
if (is_array($defAutowired)) {
foreach ($defAutowired as $k => $aclass) {
if ($aclass === self::THIS_SERVICE) {
$defAutowired[$k] = $class;
} elseif (!is_a($class, $aclass, TRUE)) {
throw new ServiceCreationException("Incompatible class $aclass in autowiring definition of service '$name'.");
}
}
}
foreach (class_parents($class) + class_implements($class) + [$class] as $parent) {
$autowired = $defAutowired && empty($this->excludedClasses[$parent]);
if ($autowired && is_array($defAutowired)) {
$autowired = FALSE;
foreach ($defAutowired as $aclass) {
if (is_a($parent, $aclass, TRUE)) {
if (empty($preferred[$parent]) && isset($this->classList[$parent][TRUE])) {
$this->classList[$parent][FALSE] = array_merge(...$this->classList[$parent]);
$this->classList[$parent][TRUE] = [];
}
$preferred[$parent] = $autowired = TRUE;
break;
}
}
} elseif (isset($preferred[$parent])) {
$autowired = FALSE;
}
$this->classList[$parent][$autowired][] = (string) $name;
}
}
}
}
private function resolveImplement(ServiceDefinition $def, $name)
{
$interface = $def->getImplement();
if (!interface_exists($interface)) {
throw new ServiceCreationException("Interface $interface used in service '$name' not found.");
}
self::checkCase($interface);
$rc = new ReflectionClass($interface);
$this->addDependency($rc);
$method = $rc->hasMethod('create')
? $rc->getMethod('create')
: ($rc->hasMethod('get') ? $rc->getMethod('get') : NULL);
if (count($rc->getMethods()) !== 1 || !$method || $method->isStatic()) {
throw new ServiceCreationException("Interface $interface used in service '$name' must have just one non-static method create() or get().");
}
$def->setImplementMode($methodName = $rc->hasMethod('create') ? $def::IMPLEMENT_MODE_CREATE : $def::IMPLEMENT_MODE_GET);
if (!$def->getClass() && !$def->getEntity()) {
$returnType = PhpReflection::getReturnType($method);
if (!$returnType) {
throw new ServiceCreationException("Method $interface::$methodName() used in service '$name' has no @return annotation.");
} elseif (!class_exists($returnType)) {
throw new ServiceCreationException("Check a @return annotation of the $interface::$methodName() method used in service '$name', class '$returnType' cannot be found.");
}
$def->setClass($returnType);
}
if ($methodName === 'get') {
if ($method->getParameters()) {
throw new ServiceCreationException("Method $interface::get() used in service '$name' must have no arguments.");
}
if (!$def->getEntity()) {
$def->setFactory('@\\' . ltrim($def->getClass(), '\\'));
} elseif (!$this->getServiceName($def->getFactory()->getEntity())) {
throw new ServiceCreationException("Invalid factory in service '$name' definition.");
}
}
if (!$def->parameters) {
$ctorParams = [];
if (!$def->getEntity()) {
$def->setFactory($def->getClass(), $def->getFactory() ? $def->getFactory()->arguments : []);
}
if (($class = $this->resolveEntityClass($def->getFactory(), [$name => 1]))
&& ($ctor = (new ReflectionClass($class))->getConstructor())
) {
foreach ($ctor->getParameters() as $param) {
$ctorParams[$param->getName()] = $param;
}
}
foreach ($method->getParameters() as $param) {
$hint = PhpReflection::getParameterType($param);
if (isset($ctorParams[$param->getName()])) {
$arg = $ctorParams[$param->getName()];
if ($hint !== PhpReflection::getParameterType($arg)) {
throw new ServiceCreationException("Type hint for \${$param->getName()} in $interface::$methodName() doesn't match type hint in $class constructor.");
}
$def->getFactory()->arguments[$arg->getPosition()] = self::literal('$' . $arg->getName());
} elseif (!$def->getSetup()) {
$hint = Nette\Utils\ObjectMixin::getSuggestion(array_keys($ctorParams), $param->getName());
throw new ServiceCreationException("Unused parameter \${$param->getName()} when implementing method $interface::$methodName()" . ($hint ? ", did you mean \${$hint}?" : '.'));
}
$paramDef = $hint . ' ' . $param->getName();
if ($param->isDefaultValueAvailable()) {
$def->parameters[$paramDef] = $param->getDefaultValue();
} else {
$def->parameters[] = $paramDef;
}
}
}
}
/** @return string|NULL */
private function resolveServiceClass($name, $recursive = [])
{
if (isset($recursive[$name])) {
throw new ServiceCreationException(sprintf('Circular reference detected for services: %s.', implode(', ', array_keys($recursive))));
}
$recursive[$name] = TRUE;
$def = $this->definitions[$name];
$factoryClass = $def->getFactory() ? $this->resolveEntityClass($def->getFactory()->getEntity(), $recursive) : NULL; // call always to check entities
if ($class = $def->getClass() ?: $factoryClass) {
if (!class_exists($class) && !interface_exists($class)) {
throw new ServiceCreationException("Class or interface '$class' used in service '$name' not found.");
}
self::checkCase($class);
$def->setClass($class);
if (count($recursive) === 1) {
$this->addDependency(new ReflectionClass($factoryClass ?: $class));
}
} elseif ($def->getAutowired()) {
throw new ServiceCreationException("Unknown type of service '$name', declare return type of factory method (for PHP 5 use annotation @return)");
}
return $class;
}
/** @return string|NULL */
private function resolveEntityClass($entity, $recursive = [])
{
$entity = $this->normalizeEntity($entity instanceof Statement ? $entity->getEntity() : $entity);
$serviceName = current(array_slice(array_keys($recursive), -1));
if (is_array($entity)) {
if (($service = $this->getServiceName($entity[0])) || $entity[0] instanceof Statement) {
$entity[0] = $this->resolveEntityClass($entity[0], $recursive);
if (!$entity[0]) {
return;
} elseif (isset($this->definitions[$service]) && $this->definitions[$service]->getImplement()) { // @Implement::create
return $entity[1] === 'create' ? $this->resolveServiceClass($service, $recursive) : NULL;
}
}
try {
$reflection = Nette\Utils\Callback::toReflection($entity[0] === '' ? $entity[1] : $entity);
$refClass = $reflection instanceof \ReflectionMethod ? $reflection->getDeclaringClass() : NULL;
} catch (\ReflectionException $e) {
}
if (isset($e) || ($refClass && (!$reflection->isPublic()
|| ($refClass->isTrait() && !$reflection->isStatic())
))) {
throw new ServiceCreationException(sprintf("Method %s() used in service '%s' is not callable.", Nette\Utils\Callback::toString($entity), $serviceName));
}
$this->addDependency($reflection);
$type = PhpReflection::getReturnType($reflection);
if ($type && !class_exists($type) && !interface_exists($type)) {
throw new ServiceCreationException(sprintf("Class or interface '%s' not found. Is return type of %s() used in service '%s' correct?", $type, Nette\Utils\Callback::toString($entity), $serviceName));
}
return $type;
} elseif ($service = $this->getServiceName($entity)) { // alias or factory
if (Strings::contains($service, '\\')) { // @\Class
return ltrim($service, '\\');
}
return $this->definitions[$service]->getImplement()
?: $this->definitions[$service]->getClass()
?: $this->resolveServiceClass($service, $recursive);
} elseif (is_string($entity)) { // class
if (!class_exists($entity)) {
throw new ServiceCreationException("Class $entity used in service '$serviceName' not found.");
}
return ltrim($entity, '\\');
}
}
/**
* @return void
*/
public function complete()
{
$this->prepareClassList();
foreach ($this->definitions as $name => $def) {
if ($def->isDynamic()) {
continue;
}
$this->currentService = NULL;
$entity = $def->getFactory()->getEntity();
$serviceRef = $this->getServiceName($entity);
$factory = $serviceRef && !$def->getFactory()->arguments && !$def->getSetup() && $def->getImplementMode() !== $def::IMPLEMENT_MODE_CREATE
? new Statement(['@' . self::THIS_CONTAINER, 'getService'], [$serviceRef])
: $def->getFactory();
try {
$def->setFactory($this->completeStatement($factory));
$this->classListNeedsRefresh = FALSE;
$this->currentService = $name;
$setups = $def->getSetup();
foreach ($setups as & $setup) {
if (is_string($setup->getEntity()) && strpbrk($setup->getEntity(), ':@?\\') === FALSE) { // auto-prepend @self
$setup = new Statement(['@' . $name, $setup->getEntity()], $setup->arguments);
}
$setup = $this->completeStatement($setup);
}
$def->setSetup($setups);
} catch (\Exception $e) {
throw new ServiceCreationException("Service '$name': " . $e->getMessage(), 0, $e);
} finally {
$this->currentService = NULL;
}
}
}
/**
* @return Statement
*/
public function completeStatement(Statement $statement)
{
$entity = $this->normalizeEntity($statement->getEntity());
$arguments = $statement->arguments;
if (is_string($entity) && Strings::contains($entity, '?')) { // PHP literal
} elseif ($service = $this->getServiceName($entity)) { // factory calling
$params = [];
foreach ($this->definitions[$service]->parameters as $k => $v) {
$params[] = preg_replace('#\w+\z#', '\$$0', (is_int($k) ? $v : $k)) . (is_int($k) ? '' : ' = ' . PhpHelpers::dump($v));
}
$rm = new \ReflectionFunction(create_function(implode(', ', $params), ''));
$arguments = Helpers::autowireArguments($rm, $arguments, $this);
$entity = '@' . $service;
} elseif ($entity === 'not') { // operator
} elseif (is_string($entity)) { // class name
if (!class_exists($entity)) {
throw new ServiceCreationException("Class $entity not found.");
} elseif ((new ReflectionClass($entity))->isAbstract()) {
throw new ServiceCreationException("Class $entity is abstract.");
} elseif (($rm = (new ReflectionClass($entity))->getConstructor()) !== NULL && !$rm->isPublic()) {
$visibility = $rm->isProtected() ? 'protected' : 'private';
throw new ServiceCreationException("Class $entity has $visibility constructor.");
} elseif ($constructor = (new ReflectionClass($entity))->getConstructor()) {
$this->addDependency($constructor);
$arguments = Helpers::autowireArguments($constructor, $arguments, $this);
} elseif ($arguments) {
throw new ServiceCreationException("Unable to pass arguments, class $entity has no constructor.");
}
} elseif (!Nette\Utils\Arrays::isList($entity) || count($entity) !== 2) {
throw new ServiceCreationException(sprintf('Expected class, method or property, %s given.', PhpHelpers::dump($entity)));
} elseif (!preg_match('#^\$?' . PhpHelpers::PHP_IDENT . '(\[\])?\z#', $entity[1])) {
throw new ServiceCreationException("Expected function, method or property name, '$entity[1]' given.");
} elseif ($entity[0] === '') { // globalFunc
if (!Nette\Utils\Arrays::isList($arguments)) {
throw new ServiceCreationException("Unable to pass specified arguments to $entity[0].");
} elseif (!function_exists($entity[1])) {
throw new ServiceCreationException("Function $entity[1] doesn't exist.");
}
$rf = new \ReflectionFunction($entity[1]);
$this->addDependency($rf);
$arguments = Helpers::autowireArguments($rf, $arguments, $this);
} else {
if ($entity[0] instanceof Statement) {
$entity[0] = $this->completeStatement($entity[0]);
} elseif ($service = $this->getServiceName($entity[0])) { // service method
$entity[0] = '@' . $service;
}
if ($entity[1][0] === '$') { // property getter, setter or appender
Validators::assert($arguments, 'list:0..1', "setup arguments for '" . Nette\Utils\Callback::toString($entity) . "'");
if (!$arguments && substr($entity[1], -2) === '[]') {
throw new ServiceCreationException("Missing argument for $entity[1].");
}
} else {
$class = empty($service) || $entity[1] === 'create'
? $this->resolveEntityClass($entity[0])
: $this->definitions[$service]->getClass();
$arguments = $this->autowireArguments($class, $entity[1], $arguments);
}
}
array_walk_recursive($arguments, function (& $val) {
if ($val instanceof Statement) {
$val = $this->completeStatement($val);
} elseif ($val === $this) {
trigger_error("Replace object ContainerBuilder in Statement arguments with '@container'.", E_USER_DEPRECATED);
$val = self::literal('$this');
} elseif ($val instanceof ServiceDefinition) {
$val = '@' . current(array_keys($this->getDefinitions(), $val, TRUE));
} elseif (is_string($val) && strlen($val) > 1 && $val[0] === '@' && $val[1] !== '@') {
$pair = explode('::', $val, 2);
$name = $this->getServiceName($pair[0]);
if (!isset($pair[1])) { // @service
$val = '@' . $name;
} elseif (preg_match('#^[A-Z][A-Z0-9_]*\z#', $pair[1], $m)) { // @service::CONSTANT
$val = self::literal($this->getDefinition($name)->getClass() . '::' . $pair[1]);
} else { // @service::property
$val = new Statement(['@' . $name, '$' . $pair[1]]);
}
}
});
return new Statement($entity, $arguments);
}
private function checkCase($class)
{
if ((class_exists($class) || interface_exists($class)) && $class !== ($name = (new ReflectionClass($class))->getName())) {
throw new ServiceCreationException("Case mismatch on class name '$class', correct name is '$name'.");
}
}
/**
* Adds item to the list of dependencies.
* @param ReflectionClass|\ReflectionFunctionAbstract|string
* @return self
* @internal
*/
public function addDependency($dep)
{
$this->dependencies[] = $dep;
return $this;
}
/**
* Returns the list of dependencies.
* @return array
*/
public function getDependencies()
{
return $this->dependencies;
}
/**
* Expands %placeholders% in strings.
* @return mixed
* @deprecated
*/
public function expand($value)
{
return Helpers::expand($value, $this->parameters);
}
/**
* @return Nette\PhpGenerator\PhpLiteral
*/
public static function literal($phpCode)
{
return new Nette\PhpGenerator\PhpLiteral($phpCode);
}
/** @internal */
public function normalizeEntity($entity)
{
if (is_string($entity) && Strings::contains($entity, '::') && !Strings::contains($entity, '?')) { // Class::method -> [Class, method]
$entity = explode('::', $entity);
}
if (is_array($entity) && $entity[0] instanceof ServiceDefinition) { // [ServiceDefinition, ...] -> [@serviceName, ...]
$entity[0] = '@' . current(array_keys($this->definitions, $entity[0], TRUE));
} elseif ($entity instanceof ServiceDefinition) { // ServiceDefinition -> @serviceName
$entity = '@' . current(array_keys($this->definitions, $entity, TRUE));
} elseif (is_array($entity) && $entity[0] === $this) { // [$this, ...] -> [@container, ...]
trigger_error("Replace object ContainerBuilder in Statement entity with '@container'.", E_USER_DEPRECATED);
$entity[0] = '@' . self::THIS_CONTAINER;
}
return $entity; // Class, @service, [Class, member], [@service, member], [, globalFunc], Statement
}
/**
* Converts @service or @\Class -> service name and checks its existence.
* @return string of FALSE, if argument is not service name
* @internal
*/
public function getServiceName($arg)
{
if (!is_string($arg) || !preg_match('#^@[\w\\\\.][^:]*\z#', $arg)) {
return FALSE;
}
$service = substr($arg, 1);
if ($service === self::THIS_SERVICE) {
$service = $this->currentService;
}
if (Strings::contains($service, '\\')) {
if ($this->classList === FALSE) { // may be disabled by prepareClassList
return $service;
}
$res = $this->getByType($service);
if (!$res) {
throw new ServiceCreationException("Reference to missing service of type $service.");
}
return $res;
}
$service = isset($this->aliases[$service]) ? $this->aliases[$service] : $service;
if (!isset($this->definitions[$service])) {
throw new ServiceCreationException("Reference to missing service '$service'.");
}
return $service;
}
/**
* Creates a list of arguments using autowiring.
* @return array
* @internal
*/
public function autowireArguments($class, $method, array $arguments)
{
$rc = new ReflectionClass($class);
if (!$rc->hasMethod($method)) {
if (!Nette\Utils\Arrays::isList($arguments)) {
throw new ServiceCreationException("Unable to pass specified arguments to $class::$method().");
}
return $arguments;
}
$rm = $rc->getMethod($method);
if (!$rm->isPublic()) {
throw new ServiceCreationException("$class::$method() is not callable.");
}
$this->addDependency($rm);
return Helpers::autowireArguments($rm, $arguments, $this);
}
/** @deprecated */
public function generateClasses($className = 'Container', $parentName = NULL)
{
trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
return (new PhpGenerator($this))->generate($className);
}
/** @deprecated */
public function formatStatement(Statement $statement)
{
trigger_error(__METHOD__ . ' is deprecated', E_USER_DEPRECATED);
return (new PhpGenerator($this))->formatStatement($statement);
}
/** @deprecated */
public function formatPhp($statement, $args)
{
array_walk_recursive($args, function (& $val) {
if ($val instanceof Statement) {
$val = $this->completeStatement($val);
} elseif ($val === $this) {
trigger_error("Replace object ContainerBuilder in Statement arguments with '@container'.", E_USER_DEPRECATED);
$val = self::literal('$this');
} elseif ($val instanceof ServiceDefinition) {
$val = '@' . current(array_keys($this->getDefinitions(), $val, TRUE));
}
});
return (new PhpGenerator($this))->formatPhp($statement, $args);
}
}
|