Sets a service definition.

@param string     $id         The service identifier
@param Definition $definition A Definition instance

@return Definition the service definition

@throws BadMethodCallException When this ContainerBuilder is compiled
431898
public function setDefinition($id, Definition $definition)
    {
        if ($this->isCompiled()) {
            throw new BadMethodCallException('Adding definition to a compiled container is not allowed');
        }

        $id = $this->normalizeId($id);

        unset($this->aliasDefinitions[$id], $this->removedIds[$id]);

        return $this->definitions[$id] = $definition;
    }
21860
public function setLazy(string $id, Definition $definition, bool $multi = false): self
    {
        return $this->set($id, new Definition\Lazy($definition), $multi);
    }
980179
public function offsetUnset($id)
    {
        if (isset($this->delegates[$id])) {
            throw new \LogicException(sprintf('Service %s has been delegated to symfony, cannot unset.', $id));
        }
        // @codingStandardsIgnoreStart
        @trigger_error(
            'unset service: The pimple based DIC is deprecated, use the symfony DIC in new projects.',
            E_USER_DEPRECATED
        );
        // @codingStandardsIgnoreEnd

        parent::offsetUnset($id);
    }
703781
public function set(string $id, Definition $definition, bool $multi = false): self
    {
        if ($this->isFrozen()) {
            throw new FrozenException();
        }

        if ($this->has($id) && $multi !== $this->isMulti($id)) {
            throw new MixedMultiException($id);
        }

        if ($multi) {
            if (!isset($this->definitions[$id])) {
                $this->definitions[$id] = new Definition\Multi();
            }

            /** @var Definition\Multi $multiDefinition */
            $multiDefinition = $this->definitions[$id];
            $multiDefinition->add($definition);
        } else {
            $this->definitions[$id] = $definition;
        }

        return $this;
    }
213390
private function createServiceConfig($id, array $service)
    {
        $serviceConfig = new ServiceConfig($service);

        if (!$serviceConfig->has($tag = ServiceConfig::FIND_TAG)) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Service "%s" must define at least the "%s" attribute for tag "%s".',
                    $id,
                    $tag,
                    $this->baseTag
                )
            );
        }

        return $serviceConfig;
    }
1097153
private function createLazyDefinition($registry, Definition $definition)
    {
        $lazy = new Definition(LazyRegistry::class, [
            new Reference('service_container'),
            new Reference($registry),
        ]);

        foreach ($definition->getMethodCalls() as $methodCall) {
            if ($methodCall[0] === 'offsetSet') {
                $methodCall[1][1] = (string) $methodCall[1][1];
                $lazy->addMethodCall('setLazy', $methodCall[1]);
            }
        }

        return $lazy;
    }
287555
private function populateAvailableType($id, Definition $definition, $onlyAutowiringTypes)
    {
        // Never use abstract services
        if ($definition->isAbstract()) {
            return;
        }

        foreach ($definition->getAutowiringTypes(false) as $type) {
            $this->definedTypes[$type] = true;
            $this->types[$type] = $id;
            unset($this->ambiguousServiceTypes[$type]);
        }

        if ($onlyAutowiringTypes) {
            return;
        }

        if (preg_match('/^\d+_[^~]++~[._a-zA-Z\d]{7}$/', $id) || $definition->isDeprecated() || !$reflectionClass = $this->container->getReflectionClass($definition->getClass(), false)) {
            return;
        }

        foreach ($reflectionClass->getInterfaces() as $reflectionInterface) {
            $this->set($reflectionInterface->name, $id);
        }

        do {
            $this->set($reflectionClass->name, $id);
        } while ($reflectionClass = $reflectionClass->getParentClass());
    }
949429
public function extend($id, $definition)
    {
        if (!isset($this->extensions[$id])) {
            $this->extensions = [];
        }
        $this->extensions[$id][] = $definition;
    }
699380
private function populateAvailableType(ContainerBuilder $container, string $id, Definition $definition)
    {
        // Never use abstract services
        if ($definition->isAbstract()) {
            return;
        }

        if ('' === $id || '.' === $id[0] || $definition->isDeprecated() || !$reflectionClass = $container->getReflectionClass($definition->getClass(), false)) {
            return;
        }

        foreach ($reflectionClass->getInterfaces() as $reflectionInterface) {
            $this->set($reflectionInterface->name, $id);
        }

        do {
            $this->set($reflectionClass->name, $id);
        } while ($reflectionClass = $reflectionClass->getParentClass());
    }
1198009
public function bind($id, $definition = [], $replace = true)
    {
        $container = Container::$instance;
        if (!$replace && $container->has($id)) {
            throw new InvalidParamException("Can not bind service, service '$id' is already exists.");
        }

        if (is_array($definition) && !isset($definition['class'])) {
            throw new InvalidConfigException("The configuration for the \"$id\" service must contain a \"class\" element.");
        }

        $container->setSingleton($id, $definition);
    }
1014361
private function findAndReplaceTaggedServices($id, array $service, ContainerBuilder $container)
    {
        $serviceConfig = $this->createServiceConfig($id, $service);

        if ($serviceConfig->has(ServiceConfig::CONTAINER)) {
            $replace = $this->getDefinitionsAsContainer($container, $serviceConfig);
        } else {
            $replace = $this->getDefinitionsAsArray($container, $serviceConfig);
        }

        $definition = $container->findDefinition($id);
        $definition->replaceArgument($this->findArgumentToReplace($definition, $serviceConfig), $replace);
    }
1366544
private function checkDefinition($id, array $definition, $file)
    {
        if ($throw = $this->isLoadingInstanceof) {
            $keywords = self::$instanceofKeywords;
        } elseif ($throw = (isset($definition['resource']) || isset($definition['namespace']))) {
            $keywords = self::$prototypeKeywords;
        } else {
            $keywords = self::$serviceKeywords;
        }

        foreach ($definition as $key => $value) {
            if (!isset($keywords[$key])) {
                if ($throw) {
                    throw new InvalidArgumentException(sprintf('The configuration key "%s" is unsupported for definition "%s" in "%s". Allowed configuration keys are "%s".', $key, $id, $file, implode('", "', $keywords)));
                }

                @trigger_error(sprintf('The configuration key "%s" is unsupported for service definition "%s" in "%s". Allowed configuration keys are "%s". The YamlFileLoader object will raise an exception instead in Symfony 4.0 when detecting an unsupported service configuration key.', $key, $id, $file, implode('", "', $keywords)), E_USER_DEPRECATED);
            }
        }
    }
462013
private function replaceBlockName(ContainerBuilder $container, Definition $definition, $id)
    {
        $arguments = $definition->getArguments();

        // Replace empty block id with service id
        if ($this->serviceDefinitionNeedsFirstArgument($definition)) {
            // NEXT_MAJOR: Remove the if block when Symfony 2.8 support will be dropped.
            if (method_exists($definition, 'setArgument')) {
                $definition->setArgument(0, $id);

                return;
            }

            $definition->replaceArgument(0, $id);

            return;
        }

        if ($id !== $arguments[0] && 0 !== strpos(
            (string) $container->getParameterBag()->resolveValue($definition->getClass()),
            'Sonata\\BlockBundle\\Block\\Service\\'
        )) {
            // NEXT_MAJOR: Remove deprecation notice
            @trigger_error(
                sprintf('Using service id %s different from block id %s is deprecated since 3.3 and will be removed in 4.0.', $id, $arguments[0]),
                E_USER_DEPRECATED
            );
        }
    }
32025
public function register($id, $definition, $shared = false)
    {
        if (is_object($definition) && !is_callable($definition)) {
            $this->instances[$id] = $definition;

            return $this;
        }

        $this->components[$id] = $definition;

        if ($shared || isset($this->instances[$id])) {
            $this->instances[$id] = null;
        }

        return $this;
    }
937851
public function bind($id, callable $serviceGenerator)
    {
        $this->callables[(string)$id] = function ($zit) use ($serviceGenerator) {
            static $object;

            if (null === $object) {
                $object = $serviceGenerator($zit);
            }

            return $object;
        };
    }
971877
private function addService($id, Definition $definition)
    {
        $this->definitionVariables = new \SplObjectStorage();
        $this->referenceVariables = array();
        $this->variableCount = 0;

        $return = array();

        if ($definition->isSynthetic()) {
            $return[] = '@throws RuntimeException always since this service is expected to be injected dynamically';
        } elseif ($class = $definition->getClass()) {
            $class = $this->container->resolveEnvPlaceholders($class);
            $return[] = sprintf('@return %s A %s instance', 0 === strpos($class, '%') ? 'object' : '\\'.ltrim($class, '\\'), ltrim($class, '\\'));
        } elseif ($definition->getFactory()) {
            $factory = $definition->getFactory();
            if (is_string($factory)) {
                $return[] = sprintf('@return object An instance returned by %s()', $factory);
            } elseif (is_array($factory) && (is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) {
                if (is_string($factory[0]) || $factory[0] instanceof Reference) {
                    $return[] = sprintf('@return object An instance returned by %s::%s()', (string) $factory[0], $factory[1]);
                } elseif ($factory[0] instanceof Definition) {
                    $return[] = sprintf('@return object An instance returned by %s::%s()', $factory[0]->getClass(), $factory[1]);
                }
            }
        }

        if ($definition->isDeprecated()) {
            if ($return && 0 === strpos($return[count($return) - 1], '@return')) {
                $return[] = '';
            }

            $return[] = sprintf('@deprecated %s', $definition->getDeprecationMessage($id));
        }

        $return = str_replace("\n     * \n", "\n     *\n", implode("\n     * ", $return));
        $return = $this->container->resolveEnvPlaceholders($return);

        $doc = '';
        if ($definition->isShared()) {
            $doc .= <<<'EOF'

     *
     * This service is shared.
     * This method always returns the same instance of the service.
EOF;
        }

        if (!$definition->isPublic()) {
            $doc .= <<<'EOF'

     *
     * This service is private.
     * If you want to be able to request this service from the container directly,
     * make it public, otherwise you might end up with broken code.
EOF;
        }

        if ($definition->isAutowired()) {
            $doc = <<<EOF

     *
     * This service is autowired.
EOF;
        }

        if ($definition->isLazy()) {
            $lazyInitialization = '$lazyLoad = true';
            $lazyInitializationDoc = "\n     * @param bool    \$lazyLoad whether to try lazy-loading the service with a proxy\n     *";
        } else {
            $lazyInitialization = '';
            $lazyInitializationDoc = '';
        }

        // with proxies, for 5.3.3 compatibility, the getter must be public to be accessible to the initializer
        $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition);
        $visibility = $isProxyCandidate ? 'public' : 'protected';
        $methodName = $this->generateMethodName($id);
        $code = <<<EOF

    /*{$this->docStar}
     * Gets the '$id' service.$doc
     *$lazyInitializationDoc
     * $return
     */
    {$visibility} function {$methodName}($lazyInitialization)
    {

EOF;

        $code .= $isProxyCandidate ? $this->getProxyDumper()->getProxyFactoryCode($definition, $id, $methodName) : '';

        if ($definition->isSynthetic()) {
            $code .= sprintf("        throw new RuntimeException('You have requested a synthetic service (\"%s\"). The DIC does not know how to construct this service.');\n    }\n", $id);
        } else {
            if ($definition->isDeprecated()) {
                $code .= sprintf("        @trigger_error(%s, E_USER_DEPRECATED);\n\n", $this->export($definition->getDeprecationMessage($id)));
            }

            $code .=
                $this->addServiceInclude($id, $definition).
                $this->addServiceLocalTempVariables($id, $definition).
                $this->addServiceInlinedDefinitions($id, $definition).
                $this->addServiceInstance($id, $definition).
                $this->addServiceInlinedDefinitionsSetup($id, $definition).
                $this->addServiceProperties($id, $definition).
                $this->addServiceMethodCalls($id, $definition).
                $this->addServiceConfigurator($id, $definition).
                $this->addServiceReturn($id, $definition)
            ;
        }

        $this->definitionVariables = null;
        $this->referenceVariables = null;

        return $code;
    }
731890
public function set(string $id, $service)
    {
        if ($this->frozen) {
            throw new FrozenContainerException(
                "The container is frozen and is not possible to define the new service \"{$id}\"."
            );
        }

        $this->definitions[$id] = $service;

        // clean alias and internal cache
        unset($this->services[$id]);
        unset($this->aliases[$id]);

        return $this;
    }