addExtension example

protected function setUp(): void
    {
        parent::setUp();

        $loader = new FilesystemLoader([
            __DIR__.'/../../Resources/views/Form',
            __DIR__.'/Fixtures/templates/form',
        ]);

        $environment = new Environment($loader['strict_variables' => true]);
        $environment->addExtension(new TranslationExtension(new StubTranslator()));
        $environment->addGlobal('global', '');
        $environment->addExtension(new FormExtension());

        $rendererEngine = new TwigRendererEngine([
            'form_table_layout.html.twig',
            'custom_widgets.html.twig',
        ]$environment);
        $this->renderer = new FormRenderer($rendererEngine$this->createMock(CsrfTokenManagerInterface::class));
        $this->registerTwigRuntimeLoader($environment$this->renderer);
    }

    
 JsonResponse {
        $documentTypes = $request->request->all('documentTypes');
        if (\count($documentTypes) > 0) {
            $skipSentDocuments = (bool) $request->request->get('skipSentDocuments', false);
            $documentIds = $this->getDocumentIds('order', $orderId$documentTypes$skipSentDocuments);
        } else {
            $documentIds = $request->request->all('documentIds');
        }

        $mediaIds = $request->request->all('mediaIds');

        $context->addExtension(
            MailSendSubscriberConfig::MAIL_CONFIG_EXTENSION,
            new MailSendSubscriberConfig(
                $request->request->get('sendMail', true) === false,
                $documentIds,
                $mediaIds
            )
        );

        $toPlace = $this->orderService->orderStateTransition(
            $orderId,
            $transition,
            

  public function testEscaping($template$expected) {
    $loader = new FilesystemLoader();
    $twig = new Environment($loader[
      'debug' => TRUE,
      'cache' => FALSE,
      'autoescape' => 'html',
      'optimizations' => 0,
    ]);
    $twig->addExtension($this->systemUnderTest);

    $name = '__string_template_test__';
    $nodes = $twig->parse($twig->tokenize(new Source($template$name)));

    $this->assertSame($expected$nodes->getNode('body')
      ->getNode(0)
      ->getNode('expr') instanceof FilterExpression);
  }

  /** * Provides tests data for testEscaping. * * @return array * An array of test data each containing of a twig template string and * a boolean expecting whether the path will be safe. */
'auto_reload' => null,
            'optimizations' => -1,
        ]$options);

        $this->debug = (bool) $options['debug'];
        $this->setCharset($options['charset'] ?? 'UTF-8');
        $this->autoReload = null === $options['auto_reload'] ? $this->debug : (bool) $options['auto_reload'];
        $this->strictVariables = (bool) $options['strict_variables'];
        $this->setCache($options['cache']);
        $this->extensionSet = new ExtensionSet();

        $this->addExtension(new CoreExtension());
        $this->addExtension(new EscaperExtension($options['autoescape']));
        $this->addExtension(new OptimizerExtension($options['optimizations']));
    }

    /** * Enables debugging mode. */
    public function enableDebug()
    {
        $this->debug = true;
        $this->updateOptionsHash();
    }
if (!\array_key_exists($element->getUniqueIdentifier()$search)) {
                continue;
            }

            $data = $search[$element->getUniqueIdentifier()];
            unset($data['id']);

            if (empty($data)) {
                continue;
            }

            $element->addExtension('search', new ArrayEntity($data));
        }

        $result = new EntitySearchResult($this->definition->getEntityName()$ids->getTotal()$entities$aggregations$criteria$context);
        $result->addState(...$ids->getStates());

        $event = new EntitySearchResultLoadedEvent($this->definition, $result);
        $this->eventDispatcher->dispatch($event$event->getName());

        return $result;
    }
}
static::assertInstanceOf(LineItem::class$lineItem);
        $collection = $lineItem->getExtensionOfType(OrderConverter::ORIGINAL_DOWNLOADS, OrderLineItemDownloadCollection::class);
        static::assertInstanceOf(OrderLineItemDownloadCollection::class$collection);
        static::assertEquals(1, $collection->count());

        $cart = $this->getCart();
        $cart->getLineItems()->clear();
        $lineItemA = (new LineItem('line-item-label-1', 'line-item-label-1', Uuid::randomHex()))
            ->setPrice(new CalculatedPrice(1, 1, new CalculatedTaxCollection()new TaxRuleCollection()))
            ->setLabel('line-item-label-1')
            ->setStates([State::IS_DOWNLOAD]);
        $lineItemA->addExtension(OrderConverter::ORIGINAL_DOWNLOADS, $collection);
        $lineItemB = (new LineItem('line-item-label-2', 'line-item-label-2', Uuid::randomHex()))
            ->setPrice(new CalculatedPrice(1, 1, new CalculatedTaxCollection()new TaxRuleCollection()))
            ->setLabel('line-item-label-2')
            ->setStates([State::IS_DOWNLOAD]);
        $cart->add($lineItemA);
        $cart->add($lineItemB);

        $order = $this->orderConverter->convertToOrder($cart$this->getSalesChannelContext(true)new OrderConversionContext());

        static::assertArrayHasKey('lineItems', $order);
        static::assertIsArray($order['lineItems']);
        
return $remapped;
    }

    /** * @param EntitySearchResult<ProductCollection> $entities * @param array<string> $mapping */
    private function addExtensions(IdSearchResult $ids, EntitySearchResult $entities, array $mapping): void
    {
        foreach ($ids->getExtensions() as $name => $extension) {
            $entities->addExtension($name$extension);
        }

        /** @var string $id */
        foreach ($ids->getIds() as $id) {
            if (!isset($mapping[$id])) {
                continue;
            }

            // current id was mapped to another variant             if (!$entities->has($mapping[$id])) {
                continue;
            }
$persister = new CartPersister($connection$eventDispatcher$cartSerializationCleaner, false);

        $cart = new Cart('existing');

        $persister->save($cart, Generator::createSalesChannelContext());
    }

    public function testEmptyCartWithManualShippingCostsExtensionIsSaved(): void
    {
        $cart = new Cart('existing');
        $cart->addExtension(
            DeliveryProcessor::MANUAL_SHIPPING_COSTS,
            new CalculatedPrice(
                20.0,
                20.0,
                new CalculatedTaxCollection(),
                new TaxRuleCollection()
            )
        );

        $this->getContainer()->get(CartPersister::class)
            ->save($cart$this->getSalesChannelContext($cart->getToken()));

        
/** * @internal * * @covers \Shopware\Core\Framework\Adapter\Twig\Filter\ReplaceRecursiveFilter */
class ReplaceRecursiveFilterTest extends TestCase
{
    public function testReplace(): void
    {
        $env = new Environment(new ArrayLoader(['test' => '{{ {"berries": ["blueberry"]}|replace_recursive({"berries": ["strawberry", "blackberry"]})|json_encode|raw }}']));
        $env->addExtension(new ReplaceRecursiveFilter());

        static::assertSame('{"berries":["strawberry","blackberry"]}', $env->render('test'));
    }
}
Profiler::trace('cart::delivery::process', function D) use ($data$original$toCalculate$context$behavior): void {
            if ($behavior->hasPermission(self::SKIP_DELIVERY_PRICE_RECALCULATION)) {
                $deliveries = $original->getDeliveries();
                $firstDelivery = $deliveries->first();
                if ($firstDelivery === null) {
                    return;
                }

                // Stored original edit shipping cost                 $manualShippingCosts = $toCalculate->getExtension(self::MANUAL_SHIPPING_COSTS) ?? $firstDelivery->getShippingCosts();

                $toCalculate->addExtension(self::MANUAL_SHIPPING_COSTS, $manualShippingCosts);

                if ($manualShippingCosts instanceof CalculatedPrice) {
                    $firstDelivery->setShippingCosts($manualShippingCosts);
                }

                $this->deliveryCalculator->calculate($data$toCalculate$deliveries$context);

                $toCalculate->setDeliveries($deliveries);

                return;
            }

            
// Compute the derivative URI scheme. Derivatives created from writable         // source stream wrappers will inherit the scheme. Derivatives created         // from read-only stream wrappers will fall-back to the default scheme.         $scheme = $is_writable ? $source_scheme : $default_scheme;
      }
    }
    else {
      $path = $uri;
      $source_scheme = $scheme = $default_scheme;
    }
    return "$scheme://styles/{$this->id()}/$source_scheme/{$this->addExtension($path)}";
  }

  /** * {@inheritdoc} */
  public function buildUrl($path$clean_urls = NULL) {
    /** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
    $stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');

    $uri = $stream_wrapper_manager->normalizeUri($this->buildUri($path));

    
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Twig\Extension\ExpressionExtension;
use Twig\Environment;
use Twig\Loader\ArrayLoader;

class ExpressionExtensionTest extends TestCase
{
    public function testExpressionCreation()
    {
        $template = "{{ expression('1 == 1') }}";
        $twig = new Environment(new ArrayLoader(['template' => $template])['debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0]);
        $twig->addExtension(new ExpressionExtension());

        $output = $twig->render('template');
        $this->assertEquals('1 == 1', $output);
    }
}
/** @var ProductSortingCollection $sortings */
        $sortings = $criteria->getExtension('sortings') ?? new ProductSortingCollection();
        $sortings->merge($this->getAvailableSortings($request$context->getContext()));

        $currentSorting = $this->getCurrentSorting($sortings$request);

        $criteria->addSorting(
            ...$currentSorting->createDalSorting()
        );

        $criteria->addExtension('sortings', $sortings);
    }

    public function process(Request $request, ProductListingResult $result, SalesChannelContext $context): void
    {
        /** @var ProductSortingCollection $sortings */
        $sortings = $result->getCriteria()->getExtension('sortings');
        $currentSortingKey = $this->getCurrentSorting($sortings$request)->getKey();

        $result->setSorting($currentSortingKey);

        $result->setAvailableSortings($sortings);
    }


        if (isset($data['quantity'])) {
            $lineItem->setQuantity((int) $data['quantity']);
        }

        if (isset($data['priceDefinition']) && !$context->hasPermission(ProductCartProcessor::ALLOW_PRODUCT_PRICE_OVERWRITES)) {
            throw CartException::insufficientPermission();
        }

        if (isset($data['priceDefinition'])) {
            $lineItem->addExtension(ProductCartProcessor::CUSTOM_PRICE, new ArrayEntity());
            $lineItem->setPriceDefinition($this->priceDefinitionFactory->factory($context->getContext()$data['priceDefinition']$data['type']));
        }
    }
}
$processor = new SortingListingProcessor(
            new StaticSystemConfigService([
                'core.listing.defaultSorting' => 'foo',
            ]),
            new StaticEntityRepository([
                $sortings,
            ])
        );

        $result = new ProductListingResult('foo', 1, new ProductCollection(), null, new Criteria(), Context::createDefaultContext());
        $result->getCriteria()->addExtension('sortings', $sortings);

        $processor->process(
            new Request(['order' => 'foo']),
            $result,
            $this->createMock(SalesChannelContext::class)
        );

        static::assertEquals('foo', $result->getSorting());
    }

    /** * @dataProvider unknownSortingProvider */
Home | Imprint | This part of the site doesn't use cookies.