getExtension example

$projectDir = $container->getParameter('kernel.project_dir');
        if ($container->fileExists($dir = $projectDir.'/config/validator', '/^$/')) {
            $this->registerMappingFilesFromDir($dir$fileRecorder);
        }

        $this->registerMappingFilesFromConfig($container$config$fileRecorder);
    }

    private function registerMappingFilesFromDir(string $dir, callable $fileRecorder): void
    {
        foreach (Finder::create()->followLinks()->files()->in($dir)->name('/\.(xml|ya?ml)$/')->sortByName() as $file) {
            $fileRecorder($file->getExtension()$file->getRealPath());
        }
    }

    private function registerMappingFilesFromConfig(ContainerBuilder $container, array $config, callable $fileRecorder): void
    {
        foreach ($config['mapping']['paths'] as $path) {
            if (is_dir($path)) {
                $this->registerMappingFilesFromDir($path$fileRecorder);
                $container->addResource(new DirectoryResource($path, '/^$/'));
            } elseif ($container->fileExists($path, false)) {
                if (!preg_match('/\.(xml|ya?ml)$/', $path$matches)) {
                    
/** * Returns the file extension. * * @return string */
    public function getExtension()
    {
        if (!$this->getMedia() instanceof \Shopware\Models\Media\Media) {
            return '';
        }

        return $this->getMedia()->getExtension();
    }

    /** * Returns the media type. * * @return string */
    public function getType()
    {
        if (!$this->getMedia() instanceof \Shopware\Models\Media\Media) {
            return '';
        }


        $container->compile();
    }

    public function testFirewallWithInvalidUserProvider()
    {
        $this->expectException(InvalidConfigurationException::class);
        $this->expectExceptionMessage('Unable to create definition for "security.user.provider.concrete.my_foo" user provider');
        $container = $this->getRawContainer();

        $extension = $container->getExtension('security');
        $extension->addUserProviderFactory(new DummyProvider());

        $container->loadFromExtension('security', [
            'providers' => [
                'my_foo' => ['foo' => []],
            ],

            'firewalls' => [
                'some_firewall' => [
                    'pattern' => '/.*',
                    'http_basic' => [],
                ],

        ], Context::createDefaultContext());

        $criteria = new Criteria([$productId]);
        $criteria->addAssociation('oneToMany');

        /** @var ProductEntity $product */
        $product = $this->productRepository->search($criteria, Context::createDefaultContext())->get($productId);
        static::assertTrue($product->hasExtension('oneToMany'));

        /** @var EntityCollection<ArrayEntity> $productExtensions */
        $productExtensions = $product->getExtension('oneToMany');
        $productExtensions->sort(static fn (ArrayEntity $a, ArrayEntity $b) => $a->get('name') <=> $b->get('name'));

        static::assertInstanceOf(EntityCollection::class$productExtensions);
        static::assertCount(2, $productExtensions);
        static::assertEquals('test 1', $productExtensions->first()->get('name'));
        static::assertEquals('test 2', $productExtensions->last()->get('name'));
    }

    public function testCanWriteExtensionWithoutExtensionKey(): void
    {
        $productId = Uuid::randomHex();
        

function twig_escape_filter(Environment $env$string$strategy = 'html', $charset = null, $autoescape = false)
{
    if ($autoescape && $string instanceof Markup) {
        return $string;
    }

    if (!\is_string($string)) {
        if (\is_object($string) && method_exists($string, '__toString')) {
            if ($autoescape) {
                $c = \get_class($string);
                $ext = $env->getExtension(EscaperExtension::class);
                if (!isset($ext->safeClasses[$c])) {
                    $ext->safeClasses[$c] = [];
                    foreach (class_parents($string) + class_implements($string) as $class) {
                        if (isset($ext->safeClasses[$class])) {
                            $ext->safeClasses[$c] = array_unique(array_merge($ext->safeClasses[$c]$ext->safeClasses[$class]));
                            foreach ($ext->safeClasses[$class] as $s) {
                                $ext->safeLookup[$s][$c] = true;
                            }
                        }
                    }
                }
                
      // submit, in which case the user has bigger problems.       try {
        // Install the given modules.         $this->moduleInstaller->install(array_keys($this->modules['install']));
      }
      catch (PreExistingConfigException $e) {
        $this->messenger()->addError($this->modulesFailToEnableMessage($this->modules, $e));
        return;
      }
      catch (UnmetDependenciesException $e) {
        $this->messenger()->addError(
          $e->getTranslatedMessage($this->getStringTranslation()$this->modules['install'][$e->getExtension()])
        );
        return;
      }

      // Unset the messenger to make sure that we'll get the service from the       // new container.       $this->messenger = NULL;
      $this->messenger()
        ->addStatus($this->modulesEnabledConfirmationMessage($this->modules['install']));
    }

    
foreach ($files as $file) {
            if ($file === null) {
                return false;
            }

            if ($file->getError() === UPLOAD_ERR_NO_FILE) {
                return true;
            }

            // We know that our mimes list always has the first mime             // start with `image` even when then are multiple accepted types.             $type = Mimes::guessTypeFromExtension($file->getExtension()) ?? '';

            if (mb_strpos($type, 'image') !== 0) {
                return false;
            }
        }

        return true;
    }

    /** * Checks to see if an uploaded file's mime type matches one in the parameter. */
$first = $structs->first();

        static::assertInstanceOf(ArrayEntity::class$first);

        static::assertSame('test', $first->get('name'));

        static::assertSame(Uuid::fromBytesToHex($id)$first->get('id'));
        static::assertSame(Uuid::fromBytesToHex($normal)$first->get('normalFk'));

        static::assertTrue($first->hasExtension(EntityReader::FOREIGN_KEYS));
        /** @var ArrayStruct<string, mixed>|null $foreignKeys */
        $foreignKeys = $first->getExtension(EntityReader::FOREIGN_KEYS);

        static::assertInstanceOf(ArrayStruct::class$foreignKeys);

        static::assertTrue($foreignKeys->has('extendedFk'));
        static::assertSame(Uuid::fromBytesToHex($extended)$foreignKeys->get('extendedFk'));
    }

    public function testCustomFieldHydrationWithoutTranslationWithoutInheritance(): void
    {
        $definition = $this->definitionInstanceRegistry->get(CustomFieldPlainTestDefinition::class);

        


                return $order * strcmp($a->getRealPath() ?: $a->getPathname()$b->getRealPath() ?: $b->getPathname());
            };
        } elseif (self::SORT_BY_ACCESSED_TIME === $sort) {
            $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * ($a->getATime() - $b->getATime());
        } elseif (self::SORT_BY_CHANGED_TIME === $sort) {
            $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * ($a->getCTime() - $b->getCTime());
        } elseif (self::SORT_BY_MODIFIED_TIME === $sort) {
            $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * ($a->getMTime() - $b->getMTime());
        } elseif (self::SORT_BY_EXTENSION === $sort) {
            $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * strnatcmp($a->getExtension()$b->getExtension());
        } elseif (self::SORT_BY_SIZE === $sort) {
            $this->sort = static fn (\SplFileInfo $a, \SplFileInfo $b) => $order * ($a->getSize() - $b->getSize());
        } elseif (self::SORT_BY_NONE === $sort) {
            $this->sort = $order;
        } elseif (\is_callable($sort)) {
            $this->sort = $reverseOrder ? static fn (\SplFileInfo $a, \SplFileInfo $b) => -$sort($a$b) : $sort(...);
        } else {
            throw new \InvalidArgumentException('The SortableIterator takes a PHP callable or a valid built-in sort algorithm as an argument.');
        }
    }

    
$this->expectException(ExpressionErrorException::class);
        $translator = new Translator();
        $translator->registerExtension(new HtmlExtension($translator));
        $translator->cssToXPath('e::first-line');
    }

    public function testGetExtensionNotExistsExtension()
    {
        $this->expectException(ExpressionErrorException::class);
        $translator = new Translator();
        $translator->registerExtension(new HtmlExtension($translator));
        $translator->getExtension('fake');
    }

    public function testAddCombinationNotExistsExtension()
    {
        $this->expectException(ExpressionErrorException::class);
        $translator = new Translator();
        $translator->registerExtension(new HtmlExtension($translator));
        $parser = new Parser();
        $xpath = $parser->parse('*')[0];
        $combinedXpath = $parser->parse('*')[0];
        $translator->addCombination('fake', $xpath$combinedXpath);
    }
public function calculate(CartDataCollection $data, Cart $cart, DeliveryCollection $deliveries, SalesChannelContext $context): void
    {
        foreach ($deliveries as $delivery) {
            $this->calculateDelivery($data$cart$delivery$context);
        }
    }

    private function calculateDelivery(CartDataCollection $data, Cart $cart, Delivery $delivery, SalesChannelContext $context): void
    {
        $costs = null;
        $manualShippingCost = $cart->getExtension(DeliveryProcessor::MANUAL_SHIPPING_COSTS);
        $manualShippingCost = $manualShippingCost instanceof CalculatedPrice ? $manualShippingCost : null;
        if ($delivery->getShippingCosts()->getUnitPrice() > 0 || $manualShippingCost) {
            $costs = $this->calculateShippingCosts(
                $delivery->getShippingMethod(),
                new PriceCollection([
                    new Price(
                        Defaults::CURRENCY,
                        $delivery->getShippingCosts()->getTotalPrice(),
                        $delivery->getShippingCosts()->getTotalPrice(),
                        false
                    ),
                ]),
public function get(string $property)
    {
        if (FieldVisibility::$isInTwigRenderingContext) {
            $this->checkIfPropertyAccessIsAllowed($property);
        }

        if ($this->has($property)) {
            return $this->$property; /* @phpstan-ignore-line */
        }

        if ($this->hasExtension($property)) {
            return $this->getExtension($property);
        }

        /** @var ArrayStruct<string, mixed>|null $extension */
        $extension = $this->getExtension('foreignKeys');
        if ($extension && $extension instanceof ArrayStruct && $extension->has($property)) {
            return $extension->get($property);
        }

        throw new \InvalidArgumentException(
            sprintf('Property %s do not exist in class %s', $propertystatic::class)
        );
    }
'productId' => $this->ids->get('p1'),
                'page' => $page,
            ],
            [
                RepositoryFacadeHookFactory::class,
            ]
        );

        $this->getContainer()->get(ScriptExecutor::class)->execute($hook);

        static::assertTrue($page->hasExtension('myProduct'));
        $product = $page->getExtension('myProduct');
        static::assertInstanceOf(ProductEntity::class$product);
        static::assertEquals($this->ids->get('p1')$product->getId());
    }

    public function testSearchWithFilterIntegration(): void
    {
        $this->ids = new IdsCollection();
        $this->createProducts();

        $this->installApp(__DIR__ . '/_fixtures/apps/pageLoadedExample');

        

    public function setPrefix(string $prefix)
    {
        $this->prefix = $prefix;
    }

    /** * @return void */
    protected function extractTemplate(string $template, MessageCatalogue $catalogue)
    {
        $visitor = $this->twig->getExtension(TranslationExtension::class)->getTranslationNodeVisitor();
        $visitor->enable();

        $this->twig->parse($this->twig->tokenize(new Source($template, '')));

        foreach ($visitor->getMessages() as $message) {
            $catalogue->set(trim($message[0])$this->prefix.trim($message[0])$message[1] ?: $this->defaultDomain);
        }

        $visitor->disable();
    }

    
static::assertEquals('bar', $rendered);
    }

    public function testInitialization(): void
    {
        $templateMock = '{{ testDate|format_date(pattern="HH:mm") }}';
        $testDate = new \DateTimeImmutable('now', new \DateTimeZone('UTC'));
        $context = Context::createDefaultContext();
        $renderedTime = $this->stringTemplateRenderer->render($templateMock['testDate' => $testDate]$context);

        /** @var CoreExtension $coreExtension */
        $coreExtension = $this->twig->getExtension(CoreExtension::class);
        $coreExtension->setTimezone('Europe/Berlin');
        $this->stringTemplateRenderer->initialize();

        $renderedWithTimezone = $this->stringTemplateRenderer->render($templateMock['testDate' => $testDate]$context);

        static::assertNotEquals($renderedTime$renderedWithTimezone);
    }
}
Home | Imprint | This part of the site doesn't use cookies.