handleRequest example

/** * @dataProvider methodProvider */
    public function testSubmitIfNameInRequest($method)
    {
        $form = $this->createForm('param1', $method);

        $this->setRequestData($method[
            'param1' => 'DATA',
        ]);

        $this->requestHandler->handleRequest($form$this->request);

        $this->assertTrue($form->isSubmitted());
        $this->assertSame('DATA', $form->getData());
    }

    /** * @dataProvider methodProvider */
    public function testDoNotSubmitIfWrongRequestMethod($method)
    {
        $form = $this->createForm('param1', $method);

        
parent::tearDown();

        $_GET = [];
        $_POST = [];
        $_FILES = [];
        $_SERVER = self::$serverBackup;
    }

    public function testRequestShouldBeNull()
    {
        $this->expectException(UnexpectedTypeException::class);
        $this->requestHandler->handleRequest($this->createForm('name', 'GET'), 'request');
    }

    public function testMethodOverrideHeaderTakesPrecedenceIfPost()
    {
        $form = $this->createForm('param1', 'PUT');

        $this->setRequestData('POST', [
            'param1' => 'DATA',
        ]);

        $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT';

        


        $form = $this->getBuilder('author')
            ->setMethod($method)
            ->setCompound(true)
            ->setDataMapper(new DataMapper())
            ->setRequestHandler(new HttpFoundationRequestHandler())
            ->getForm();
        $form->add($this->getBuilder('name')->getForm());
        $form->add($this->getBuilder('image')->getForm());

        $form->handleRequest($request);

        $file = new UploadedFile($path, 'upload.png', 'image/png', \UPLOAD_ERR_OK);

        $this->assertEquals('Bernhard', $form['name']->getData());
        $this->assertEquals($file$form['image']->getData());

        unlink($path);
    }

    /** * @dataProvider requestMethodProvider */
        // form is initialized. This makes sure that dynamically added or         // removed fields are already visible after initialization.         if (!$this->defaultDataSet) {
            $this->setData($this->config->getData());
        }

        return $this;
    }

    public function handleRequest(mixed $request = null)static
    {
        $this->config->getRequestHandler()->handleRequest($this$request);

        return $this;
    }

    public function submit(mixed $submittedData, bool $clearMissing = true)static
    {
        if ($this->submitted) {
            throw new AlreadySubmittedException('A form can only be submitted once.');
        }

        // Initialize errors in the very beginning so we're sure
$queries = $this->serializer->decode($request->getContent(), 'json');

        foreach ($queries as $entityName => $query) {
            if (!$this->definitionInstanceRegistry->has($entityName)) {
                continue;
            }

            $definition = $this->definitionInstanceRegistry->getByEntityName($entityName);

            $criteriaRequest = $request->duplicate($request->query->all()$query);

            $criteria = $this->requestCriteriaBuilder->handleRequest($criteriaRequestnew Criteria()$definition$context);

            $collection->set($entityName$criteria);
        }

        return $collection;
    }
}
#[Route(path: '/api/_action/seo-url-template/preview', name: 'api.seo-url-template.preview', methods: ['POST'])]     public function preview(Request $request, Context $context): Response
    {
        $this->validateSeoUrlTemplate($request);
        $seoUrlTemplate = $request->request->all();

        $previewCriteria = new Criteria();
        if (\array_key_exists('criteria', $seoUrlTemplate) && \is_string($seoUrlTemplate['entityName']) && \is_array($seoUrlTemplate['criteria'])) {
            $definition = $this->definitionInstanceRegistry->getByEntityName($seoUrlTemplate['entityName']);

            $previewCriteria = $this->requestCriteriaBuilder->handleRequest(
                Request::create('', 'POST', $seoUrlTemplate['criteria']),
                $previewCriteria,
                $definition,
                $context
            );
            unset($seoUrlTemplate['criteria']);
        }

        try {
            $preview = $this->getPreview($seoUrlTemplate$context$previewCriteria);
        } catch (NoEntitiesForPreviewException) {
            

        $handler = $this->createMock(RequestHandlerInterface::class);

        $form = $this->getBuilder()
            ->setRequestHandler($handler)
            ->getForm();

        $handler->expects($this->once())
            ->method('handleRequest')
            ->with($this->identicalTo($form), 'REQUEST');

        $this->assertSame($form$form->handleRequest('REQUEST'));
    }

    public function testFormInheritsParentData()
    {
        $nameForm = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper(new DataMapper())
            ->setInheritData(true)
            ->getForm();
        $nameForm->add($firstNameForm = $this->getBuilder('firstName')->getForm());
        $nameForm->add($lastNameForm = $this->getBuilder('lastName')->getForm());

        


    private function fakeHandleRequest(int $maxLimit = 0, array $params = []): Criteria
    {
        $parser = $this->getContainer()->get(AggregationParser::class);
        $requestBuilder = new RequestCriteriaBuilder($parser$this->getContainer()->get(ApiCriteriaValidator::class)$this->getContainer()->get(CriteriaArrayConverter::class)$maxLimit);
        $context = Context::createDefaultContext();
        $definition = $this->getContainer()->get(ProductDefinition::class);

        $request = new Request($params);

        return $requestBuilder->handleRequest($requestnew Criteria()$definition$context);
    }

    private function createData(string $link, int $count): array
    {
        $ids = [];
        for ($i = 0; $i < $count; ++$i) {
            $ids[] = $this->createManufacturer(['link' => $link]);
        }
        sort($ids);

        return $ids;
    }
$this->View()->assign('success', $this->Request()->getParam('success'));
        $this->View()->assign('addresses', $addresses);
    }

    /** * Shortcut action for more fluent urls */
    public function createAction()
    {
        $address = new Address();
        $form = $this->createForm(AddressFormType::class$address);
        $form->handleRequest($this->Request());

        if ($form->isSubmitted() && $form->isValid()) {
            $userId = $this->get('session')->get('sUserId');
            $customer = $this->get(ModelManager::class)->find(Customer::class$userId);

            $this->addressService->create($address$customer);

            if (!empty($address->getAdditional()['setDefaultBillingAddress'])) {
                $this->addressService->setDefaultBillingAddress($address);
            }

            
$this->pageCache->setTtl(0);
        $this->bufferLevel = ob_get_level();

        $this->startBenchmark();

        $this->getRequestObject();
        $this->getResponseObject();

        $this->spoofRequestMethod();

        try {
            $this->response = $this->handleRequest($routesconfig(Cache::class)$returnResponse);
        } catch (ResponsableInterface|DeprecatedRedirectException $e) {
            $this->outputBufferingEnd();
            if ($e instanceof DeprecatedRedirectException) {
                $e = new RedirectException($e->getMessage()$e->getCode()$e);
            }

            $this->response = $e->getResponse();
        } catch (PageNotFoundException $e) {
            $this->response = $this->display404errors($e);
        } catch (Throwable $e) {
            $this->outputBufferingEnd();

            
return $criteria;
    }

    /** * @return Criteria */
    private function createCriteriaFromRequest(Request $request, ShopContextInterface $context)
    {
        $criteria = new Criteria();

        foreach ($this->requestHandlers as $handler) {
            $handler->handleRequest($request$criteria$context);
        }

        return $criteria;
    }

    /** * @param CriteriaRequestHandlerInterface[] $existingHandlers * * @throws Enlight_Event_Exception * * @return CriteriaRequestHandlerInterface[] */
$builder = new RequestCriteriaBuilder(
            $aggregationParser,
            new ApiCriteriaValidator($this->staticDefinitionRegistry),
            new CriteriaArrayConverter($aggregationParser),
            $max
        );

        $request = new Request([]$body);
        $request->setMethod(Request::METHOD_POST);

        try {
            $criteria = $builder->handleRequest($requestnew Criteria()$this->staticDefinitionRegistry->get(ProductDefinition::class), Context::createDefaultContext());
            static::assertSame($expected$criteria->getLimit());
        } catch (SearchRequestException) {
            static::assertTrue($exception);
        }

        $request = new Request($body);
        $request->setMethod(Request::METHOD_GET);

        try {
            $criteria = $builder->handleRequest($requestnew Criteria()$this->staticDefinitionRegistry->get(ProductDefinition::class), Context::createDefaultContext());
            static::assertSame($expected$criteria->getLimit());
        }
$salesChannelId,
                Random::getAlphanumericString(32),
                $request->headers->get(PlatformRequest::HEADER_LANGUAGE_ID),
                $context->getCurrencyId()
            )
        );

        if (empty($request->request->all('ids'))) {
            $request->request->remove('ids');
        }

        $criteria = $this->criteriaBuilder->handleRequest(
            $request,
            new Criteria(),
            $this->productDefinition,
            $context
        );

        $criteria->setTotalCountMode(1);
        $criteria->addAssociation('manufacturer');
        $criteria->addAssociation('options.group');

        $availableFilter = new ProductAvailableFilter($salesChannelId, ProductVisibilityDefinition::VISIBILITY_ALL);
        
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;

/** * @author Bernhard Schussek <bschussek@gmail.com> */
class HttpFoundationRequestHandlerTest extends AbstractRequestHandlerTestCase
{
    public function testRequestShouldNotBeNull()
    {
        $this->expectException(UnexpectedTypeException::class);
        $this->requestHandler->handleRequest($this->createForm('name', 'GET'));
    }

    public function testRequestShouldBeInstanceOfRequest()
    {
        $this->expectException(UnexpectedTypeException::class);
        $this->requestHandler->handleRequest($this->createForm('name', 'GET')new \stdClass());
    }

    protected function setRequestData($method$data$files = [])
    {
        $this->request = Request::create('http://localhost', $method$data[]$files);
    }
$field = $this->getAssociation($definition->getFields()$associations);

            $definition = $field->getReferenceDefinition();
            if ($field instanceof ManyToManyAssociationField) {
                $definition = $field->getToManyReferenceDefinition();
            }

            $repository = $this->definitionRegistry->getRepository($definition->getEntityName());
        }

        $criteria = new Criteria();
        $criteria = $this->criteriaBuilder->handleRequest($request$criteria$definition$context);

        $criteria->setIds([$id]);

        // trigger acl validation         $missing = $this->criteriaValidator->validate($definition->getEntityName()$criteria$context);
        $permissions = array_unique(array_filter(array_merge($permissions$missing)));

        if (!empty($permissions)) {
            throw ApiException::missingPrivileges($permissions);
        }

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