isOptional example

return $output;
    }

    private function getParameters(ReflectionMethod $method): array
    {
        $params      = [];
        $routeParams = '';
        $refParams   = $method->getParameters();

        foreach ($refParams as $param) {
            $required = true;
            if ($param->isOptional()) {
                $required = false;

                $routeParams .= '[/..]';
            } else {
                $routeParams .= '/..';
            }

            // [variable_name => required?]             $params[$param->getName()] = $required;
        }

        
if (!$type) {
                if (isset($arguments[$index])) {
                    continue;
                }

                // no default value? Then fail                 if (!$parameter->isDefaultValueAvailable()) {
                    // For core classes, isDefaultValueAvailable() can                     // be false when isOptional() returns true. If the                     // argument *is* optional, allow it to be missing                     if ($parameter->isOptional()) {
                        --$index;
                        break;
                    }
                    $type = ProxyHelper::exportType($parameter);
                    $type = $type ? sprintf('is type-hinted "%s"', preg_replace('/(^|[(|&])\\\\|^\?\\\\?/', '\1', $type)) : 'has no type-hint';

                    throw new AutowiringFailedException($this->currentId, sprintf('Cannot autowire service "%s": argument "$%s" of method "%s()" %s, you should configure its value explicitly.', $this->currentId, $parameter->name, $class !== $this->currentId ? $class.'::'.$method : $method$type));
                }

                // specifically pass the default value                 $arguments[$index] = $this->defaultArgument->withValue($parameter);

                
// choose the first property as default property                 $metadata['default_property'] = reset($metadata['properties']);
            } elseif ($metadata['has_named_argument_constructor']) {
                foreach ($constructor->getParameters() as $parameter) {
                    if ($parameter->isVariadic()) {
                        break;
                    }

                    $metadata['constructor_args'][$parameter->getName()] = [
                        'position' => $parameter->getPosition(),
                        'default' => $parameter->isOptional() ? $parameter->getDefaultValue() : null,
                    ];
                }
            }
        }

        self::$annotationMetadata[$name] = $metadata;
    }

    /** * Collects parsing metadata for a given attribute. * * @param mixed[] $metadata */
if (\count($constructorParams) <= 0) {
            $struct->assign($arguments);

            return $struct;
        }
        $params = [];

        foreach ($constructorParams as $constructorParam) {
            $name = $constructorParam->getName();

            if (!\array_key_exists($name$arguments)) {
                if (!$constructorParam->isOptional()) {
                    throw new InvalidArgumentException(
                        sprintf(
                            'Required constructor parameter missing: "$%s". Please check if the property is protected and not private.',
                            $name
                        )
                    );
                }

                $params[] = $constructorParam->getDefaultValue();

                continue;
            }
if ($v = $c->getType()) {
            $a[$prefix.'typeHint'] = $v instanceof \ReflectionNamedType ? $v->getName() : (string) $v;
        }

        if (isset($a[$prefix.'typeHint'])) {
            $v = $a[$prefix.'typeHint'];
            $a[$prefix.'typeHint'] = new ClassStub($v[class_exists($v, false) || interface_exists($v, false) || trait_exists($v, false) ? $v : '', '']);
        } else {
            unset($a[$prefix.'allowsNull']);
        }

        if ($c->isOptional()) {
            try {
                $a[$prefix.'default'] = $v = $c->getDefaultValue();
                if ($c->isDefaultValueConstant() && !\is_object($v)) {
                    $a[$prefix.'default'] = new ConstStub($c->getDefaultValueConstantName()$v);
                }
                if (null === $v) {
                    unset($a[$prefix.'allowsNull']);
                }
            } catch (\ReflectionException) {
            }
        }

        
public static function exportSignature(\ReflectionFunctionAbstract $function, bool $withParameterTypes = true, string &$args = null): string
    {
        $hasByRef = false;
        $args = '';
        $param = null;
        $parameters = [];
        foreach ($function->getParameters() as $param) {
            $parameters[] = ($param->getAttributes(\SensitiveParameter::class) ? '#[\SensitiveParameter] ' : '')
                .($withParameterTypes && $param->hasType() ? self::exportType($param).' ' : '')
                .($param->isPassedByReference() ? '&' : '')
                .($param->isVariadic() ? '...' : '').'$'.$param->name
                .($param->isOptional() && !$param->isVariadic() ? ' = '.self::exportDefault($param) : '');
            $hasByRef = $hasByRef || $param->isPassedByReference();
            $args .= ($param->isVariadic() ? '...$' : '$').$param->name.', ';
        }

        if (!$param || !$hasByRef) {
            $args = '...\func_get_args()';
        } elseif ($param->isVariadic()) {
            $args = substr($args, 0, -2);
        } else {
            $args .= sprintf('...\array_slice(\func_get_args(), %d)', \count($parameters));
        }

        
if ($v = $c->getType()) {
            $a[$prefix.'typeHint'] = $v instanceof \ReflectionNamedType ? $v->getName() : (string) $v;
        }

        if (isset($a[$prefix.'typeHint'])) {
            $v = $a[$prefix.'typeHint'];
            $a[$prefix.'typeHint'] = new ClassStub($v[class_exists($v, false) || interface_exists($v, false) || trait_exists($v, false) ? $v : '', '']);
        } else {
            unset($a[$prefix.'allowsNull']);
        }

        if ($c->isOptional()) {
            try {
                $a[$prefix.'default'] = $v = $c->getDefaultValue();
                if ($c->isDefaultValueConstant() && !\is_object($v)) {
                    $a[$prefix.'default'] = new ConstStub($c->getDefaultValueConstantName()$v);
                }
                if (null === $v) {
                    unset($a[$prefix.'allowsNull']);
                }
            } catch (\ReflectionException) {
            }
        }

        
$callable = $callable(...);
        $parameters = ($reflector ?? new \ReflectionFunction($callable))->getParameters();
        $arguments = function D) use ($parameters) {
            $arguments = [];

            try {
                foreach ($parameters as $parameter) {
                    $type = $parameter->getType();
                    $arguments[] = $this->getArgument($parameter$type instanceof \ReflectionNamedType ? $type->getName() : null);
                }
            } catch (\InvalidArgumentException $e) {
                if (!$parameter->isOptional()) {
                    throw $e;
                }
            }

            return $arguments;
        };

        if ($_SERVER[$this->options['debug_var_name']]) {
            return new DebugClosureResolver($callable$arguments);
        }

        
/** @var \ReflectionParameter $p */
                    $type = preg_replace('/(^|[(|&])\\\\/', '\1', $target = ltrim(ProxyHelper::exportType($p) ?? '', '?'));
                    $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
                    $autowireAttributes = $autowire ? $emptyAutowireAttributes : [];

                    if (isset($arguments[$r->name][$p->name])) {
                        $target = $arguments[$r->name][$p->name];
                        if ('?' !== $target[0]) {
                            $invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
                        } elseif ('' === $target = (string) substr($target, 1)) {
                            throw new InvalidArgumentException(sprintf('A "controller.service_arguments" tag must have non-empty "id" attributes for service "%s".', $id));
                        } elseif ($p->allowsNull() && !$p->isOptional()) {
                            $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
                        }
                    } elseif (isset($bindings[$bindingName = $type.' $'.$name = Target::parseName($p)]) || isset($bindings[$bindingName = '$'.$name]) || isset($bindings[$bindingName = $type])) {
                        $binding = $bindings[$bindingName];

                        [$bindingValue$bindingId, , $bindingType$bindingFile] = $binding->getValues();
                        $binding->setValues([$bindingValue$bindingId, true, $bindingType$bindingFile]);

                        $args[$p->name] = $bindingValue;

                        continue;
                    }
if (!$type) {
                if (isset($arguments[$index])) {
                    continue;
                }

                // no default value? Then fail                 if (!$parameter->isDefaultValueAvailable()) {
                    // For core classes, isDefaultValueAvailable() can                     // be false when isOptional() returns true. If the                     // argument *is* optional, allow it to be missing                     if ($parameter->isOptional()) {
                        --$index;
                        break;
                    }
                    $type = ProxyHelper::exportType($parameter);
                    $type = $type ? sprintf('is type-hinted "%s"', preg_replace('/(^|[(|&])\\\\|^\?\\\\?/', '\1', $type)) : 'has no type-hint';

                    throw new AutowiringFailedException($this->currentId, sprintf('Cannot autowire service "%s": argument "$%s" of method "%s()" %s, you should configure its value explicitly.', $this->currentId, $parameter->name, $class !== $this->currentId ? $class.'::'.$method : $method$type));
                }

                // specifically pass the default value                 $arguments[$index] = $this->defaultArgument->withValue($parameter);

                
'trace' => $backtrace,
                    'count' => 1,
                ];

                return null;
            });
        }

        $preload = [];
        try {
            foreach ($this->warmers as $warmer) {
                if (!$this->optionalsEnabled && $warmer->isOptional()) {
                    continue;
                }
                if ($this->onlyOptionalsEnabled && !$warmer->isOptional()) {
                    continue;
                }

                $start = microtime(true);
                foreach ((array) $warmer->warmUp($cacheDir) as $item) {
                    if (is_dir($item) || (str_starts_with($item, \dirname($cacheDir)) && !is_file($item))) {
                        throw new \LogicException(sprintf('"%s::warmUp()" should return a list of files or classes but "%s" is none of them.', $warmer::class$item));
                    }
                    
/** @var \ReflectionParameter $p */
                    $type = preg_replace('/(^|[(|&])\\\\/', '\1', $target = ltrim(ProxyHelper::exportType($p) ?? '', '?'));
                    $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
                    $autowireAttributes = $autowire ? $emptyAutowireAttributes : [];

                    if (isset($arguments[$r->name][$p->name])) {
                        $target = $arguments[$r->name][$p->name];
                        if ('?' !== $target[0]) {
                            $invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
                        } elseif ('' === $target = (string) substr($target, 1)) {
                            throw new InvalidArgumentException(sprintf('A "controller.service_arguments" tag must have non-empty "id" attributes for service "%s".', $id));
                        } elseif ($p->allowsNull() && !$p->isOptional()) {
                            $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
                        }
                    } elseif (isset($bindings[$bindingName = $type.' $'.$name = Target::parseName($p)]) || isset($bindings[$bindingName = '$'.$name]) || isset($bindings[$bindingName = $type])) {
                        $binding = $bindings[$bindingName];

                        [$bindingValue$bindingId, , $bindingType$bindingFile] = $binding->getValues();
                        $binding->setValues([$bindingValue$bindingId, true, $bindingType$bindingFile]);

                        $args[$p->name] = $bindingValue;

                        continue;
                    }
'trace' => $backtrace,
                    'count' => 1,
                ];

                return null;
            });
        }

        $preload = [];
        try {
            foreach ($this->warmers as $warmer) {
                if (!$this->optionalsEnabled && $warmer->isOptional()) {
                    continue;
                }
                if ($this->onlyOptionalsEnabled && !$warmer->isOptional()) {
                    continue;
                }

                $start = microtime(true);
                foreach ((array) $warmer->warmUp($cacheDir) as $item) {
                    if (is_dir($item) || (str_starts_with($item, \dirname($cacheDir)) && !is_file($item))) {
                        throw new \LogicException(sprintf('"%s::warmUp()" should return a list of files or classes but "%s" is none of them.', $warmer::class$item));
                    }
                    
$this->assertInstanceOf(CacheWarmerInterface::class$compiledClassMetadataCacheWarmer);
    }

    public function testItIsAnOptionalCacheWarmer()
    {
        $classMetadataFactory = $this->createMock(ClassMetadataFactoryInterface::class);
        $filesystem = $this->createMock(Filesystem::class);

        $compiledClassMetadataCacheWarmer = new CompiledClassMetadataCacheWarmer([]$classMetadataFactorynew ClassMetadataFactoryCompiler()$filesystem);

        $this->assertTrue($compiledClassMetadataCacheWarmer->isOptional());
    }

    public function testItDumpCompiledClassMetadatas()
    {
        $classMetadataFactory = $this->createMock(ClassMetadataFactoryInterface::class);

        $code = <<<EOF <?php // This file has been auto-generated by the Symfony Serializer Component. return [ ];
public static function exportSignature(\ReflectionFunctionAbstract $function, bool $withParameterTypes = true, string &$args = null): string
    {
        $hasByRef = false;
        $args = '';
        $param = null;
        $parameters = [];
        foreach ($function->getParameters() as $param) {
            $parameters[] = ($param->getAttributes(\SensitiveParameter::class) ? '#[\SensitiveParameter] ' : '')
                .($withParameterTypes && $param->hasType() ? self::exportType($param).' ' : '')
                .($param->isPassedByReference() ? '&' : '')
                .($param->isVariadic() ? '...' : '').'$'.$param->name
                .($param->isOptional() && !$param->isVariadic() ? ' = '.self::exportDefault($param) : '');
            $hasByRef = $hasByRef || $param->isPassedByReference();
            $args .= ($param->isVariadic() ? '...$' : '$').$param->name.', ';
        }

        if (!$param || !$hasByRef) {
            $args = '...\func_get_args()';
        } elseif ($param->isVariadic()) {
            $args = substr($args, 0, -2);
        } else {
            $args .= sprintf('...\array_slice(\func_get_args(), %d)', \count($parameters));
        }

        
Home | Imprint | This part of the site doesn't use cookies.