/**
  * Specific annotation evaluation.
  *
  * @param Request          $request    Request
  * @param Annotation       $annotation Annotation
  * @param ReflectionMethod $method     Method
  *
  * @return FormAnnotationResolver self Object
  */
 public function evaluateAnnotation(Request $request, Annotation $annotation, ReflectionMethod $method)
 {
     /**
      * Annotation is only laoded if is typeof WorkAnnotation
      */
     if ($annotation instanceof AnnotationForm) {
         /**
          * Once loaded Annotation info, we just instanced Service name
          */
         $annotationValue = $annotation->getClass();
         /**
          * Get FormType object given a service name
          */
         $type = class_exists($annotationValue) ? new $annotationValue() : $this->formRegistry->getType($annotationValue)->getInnerType();
         /**
          * Get the parameter name. If not defined, is set as $form
          */
         $parameterName = $annotation->getName() ?: $this->defaultName;
         $parameterClass = $this->getParameterType($method, $parameterName, 'Symfony\\Component\\Form\\FormInterface');
         /**
          * Requiring result with calling getBuiltObject(), set as request
          * attribute desired element
          */
         $request->attributes->set($parameterName, $this->getBuiltObject($request, $this->formFactory, $annotation, $parameterClass, $type));
     }
     return $this;
 }
Ejemplo n.º 2
0
 /**
  * {@inheritdoc}
  */
 public function createBuilderForProperty($class, $property, $data = null, array $options = array())
 {
     if (null === ($guesser = $this->registry->getTypeGuesser())) {
         return $this->createNamedBuilder($property, 'Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType', $data, $options);
     }
     $typeGuess = $guesser->guessType($class, $property);
     $maxLengthGuess = $guesser->guessMaxLength($class, $property);
     $requiredGuess = $guesser->guessRequired($class, $property);
     $patternGuess = $guesser->guessPattern($class, $property);
     $type = $typeGuess ? $typeGuess->getType() : 'Symfony\\Component\\Form\\Extension\\Core\\Type\\TextType';
     $maxLength = $maxLengthGuess ? $maxLengthGuess->getValue() : null;
     $pattern = $patternGuess ? $patternGuess->getValue() : null;
     if (null !== $pattern) {
         $options = array_replace_recursive(array('attr' => array('pattern' => $pattern)), $options);
     }
     if (null !== $maxLength) {
         $options = array_replace_recursive(array('attr' => array('maxlength' => $maxLength)), $options);
     }
     if ($requiredGuess) {
         $options = array_merge(array('required' => $requiredGuess->getValue()), $options);
     }
     // user options may override guessed options
     if ($typeGuess) {
         $options = array_merge($typeGuess->getOptions(), $options);
     }
     return $this->createNamedBuilder($property, $type, $data, $options);
 }
 /**
  * @param array $options
  *
  * @return array
  */
 private function addDefaultOptions(array $options)
 {
     $defaultOptions = [];
     // hack to prevent validation error "The CSRF token is invalid."
     foreach ($this->formRegistry->getExtensions() as $extension) {
         foreach ($extension->getTypeExtensions(FormType::class) as $typeExtension) {
             if ($typeExtension instanceof FormTypeCsrfExtension) {
                 $defaultOptions['csrf_protection'] = false;
             }
         }
     }
     return array_replace($defaultOptions, $options);
 }
Ejemplo n.º 4
0
 function it_builds_prototypes_forms_for_calculators(ServiceRegistryInterface $calculatorRegistry, FormBuilder $builder, FormBuilder $flatRateFormBuilder, Form $flatRateForm, CalculatorInterface $flatRateCalculator, FormBuilder $perUnitFormBuilder, Form $perUnitForm, CalculatorInterface $perUnitRateCalculator, FormRegistryInterface $formRegistry)
 {
     $builder->add(Argument::any(), Argument::cetera())->willReturn($builder);
     $builder->addEventSubscriber(Argument::any())->willReturn($builder);
     $flatRateCalculator->getType()->willReturn('flat_rate');
     $perUnitRateCalculator->getType()->willReturn('per_unit_rate');
     $calculatorRegistry->all()->willReturn(['flat_rate' => $flatRateCalculator, 'per_unit_rate' => $perUnitRateCalculator]);
     $flatRateFormBuilder->getForm()->willReturn($flatRateForm);
     $builder->create('configuration', 'sylius_shipping_calculator_flat_rate')->willReturn($flatRateFormBuilder);
     $perUnitFormBuilder->getForm()->willReturn($perUnitForm);
     $builder->create('configuration', 'sylius_shipping_calculator_per_unit_rate')->willReturn($perUnitFormBuilder);
     $formRegistry->hasType('sylius_shipping_calculator_per_unit_rate')->shouldBeCalled()->willReturn(true);
     $formRegistry->hasType('sylius_shipping_calculator_flat_rate')->shouldBeCalled()->willReturn(true);
     $builder->setAttribute('prototypes', ['calculators' => ['flat_rate' => $flatRateForm, 'per_unit_rate' => $perUnitForm], 'rules' => []])->shouldBeCalled();
     $this->buildForm($builder, []);
 }
Ejemplo n.º 5
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->addEventSubscriber(new BuildShippingMethodFormSubscriber($this->calculatorRegistry, $builder->getFormFactory(), $this->formRegistry))->addEventSubscriber(new AddCodeFormSubscriber())->add('translations', 'sylius_translations', ['type' => 'sylius_shipping_method_translation', 'label' => 'sylius.form.shipping_method.translations'])->add('category', 'sylius_shipping_category_choice', ['required' => false, 'empty_value' => 'sylius.ui.no_requirement', 'label' => 'sylius.form.shipping_method.category'])->add('categoryRequirement', 'choice', ['choices' => ShippingMethod::getCategoryRequirementLabels(), 'multiple' => false, 'expanded' => true, 'label' => 'sylius.form.shipping_method.category_requirement'])->add('calculator', 'sylius_shipping_calculator_choice', ['label' => 'sylius.form.shipping_method.calculator'])->add('enabled', 'checkbox', ['label' => 'sylius.form.locale.enabled']);
     $prototypes = ['rules' => [], 'calculators' => []];
     /** @var RuleCheckerInterface $checker */
     foreach ($this->checkerRegistry->all() as $type => $checker) {
         $prototypes['rules'][$type] = $builder->create('__name__', $checker->getConfigurationFormType())->getForm();
     }
     /** @var CalculatorInterface $calculator */
     foreach ($this->calculatorRegistry->all() as $name => $calculator) {
         $calculatorTypeName = sprintf('sylius_shipping_calculator_%s', $calculator->getType());
         if (!$this->formRegistry->hasType($calculatorTypeName)) {
             continue;
         }
         $prototypes['calculators'][$name] = $builder->create('configuration', $calculatorTypeName)->getForm();
     }
     $builder->setAttribute('prototypes', $prototypes);
 }
Ejemplo n.º 6
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->addEventSubscriber(new BuildShippingMethodFormSubscriber($this->calculatorRegistry, $builder->getFormFactory(), $this->formRegistry))->addEventSubscriber(new AddCodeFormSubscriber())->add('translations', 'a2lix_translationsForms', array('form_type' => 'sylius_shipping_method_translation', 'label' => 'sylius.form.shipping_method.name'))->add('category', 'sylius_shipping_category_choice', array('required' => false, 'label' => 'sylius.form.shipping_method.category'))->add('categoryRequirement', 'choice', array('choices' => ShippingMethod::getCategoryRequirementLabels(), 'multiple' => false, 'expanded' => true, 'label' => 'sylius.form.shipping_method.category_requirement'))->add('calculator', 'sylius_shipping_calculator_choice', array('label' => 'sylius.form.shipping_method.calculator'));
     $prototypes = array();
     $prototypes['rules'] = array();
     foreach ($this->checkerRegistry->all() as $type => $checker) {
         $prototypes['rules'][$type] = $builder->create('__name__', $checker->getConfigurationFormType())->getForm();
     }
     $prototypes['calculators'] = array();
     foreach ($this->calculatorRegistry->all() as $name => $calculator) {
         $calculatorTypeName = sprintf("sylius_shipping_calculator_%s", $calculator->getType());
         if (!$this->formRegistry->hasType($calculatorTypeName)) {
             continue;
         }
         $prototypes['calculators'][$name] = $builder->create('configuration', $calculatorTypeName)->getForm();
     }
     $builder->setAttribute('prototypes', $prototypes);
 }
 /**
  * Add the calculator configuration fields.
  *
  * @param FormInterface $form
  * @param string        $calculatorName
  * @param array         $data
  */
 protected function addConfigurationFields(FormInterface $form, $calculatorName, array $data = [])
 {
     $calculator = $this->calculatorRegistry->get($calculatorName);
     $calculatorTypeName = sprintf('sylius_shipping_calculator_%s', $calculator->getType());
     if (!$this->formRegistry->hasType($calculatorTypeName)) {
         return;
     }
     $configurationField = $this->factory->createNamed('configuration', $calculatorTypeName, $data, ['auto_initialize' => false]);
     $form->add($configurationField);
 }
Ejemplo n.º 8
0
 /**
  * Wraps a type into a ResolvedFormTypeInterface implementation and connects
  * it with its parent type.
  *
  * @param FormTypeInterface $type The type to resolve.
  *
  * @return ResolvedFormTypeInterface The resolved type.
  */
 private function resolveType(FormTypeInterface $type)
 {
     $parentType = $type->getParent();
     if ($parentType instanceof FormTypeInterface) {
         $parentType = $this->resolveType($parentType);
     } elseif (null !== $parentType) {
         $parentType = $this->registry->getType($parentType);
     }
     return $this->resolvedTypeFactory->createResolvedType($type, array(), $parentType);
 }
Ejemplo n.º 9
0
 private function getFormType($formType)
 {
     if (is_string($formType)) {
         if ($this->formRegistry->hasType($formType)) {
             $formType = $this->formRegistry->getType($formType);
         } else {
             $formType = new $formType();
         }
     }
     return $formType;
 }
Ejemplo n.º 10
0
    /**
     * Wraps a type into a ResolvedFormTypeInterface implementation and connects
     * it with its parent type.
     *
     * @param FormTypeInterface $type The type to resolve.
     *
     * @return ResolvedFormTypeInterface The resolved type.
     */
    private function resolveType(FormTypeInterface $type)
    {
        $parentType = $type->getParent();

        if ($parentType instanceof FormTypeInterface) {
            $parentType = $this->resolveType($parentType);
        } elseif (null !== $parentType) {
            $parentType = $this->registry->getType($parentType);
        }

        return $this->resolvedTypeFactory->createResolvedType(
            $type,
            // Type extensions are not supported for unregistered type instances,
            // i.e. type instances that are passed to the FormFactory directly,
            // nor for their parents, if getParent() also returns a type instance.
            array(),
            $parentType
        );
    }
Ejemplo n.º 11
0
 /**
  * Returns a type by name.
  *
  * This methods registers the type extensions from the form extensions.
  *
  * @param string $name The name of the type
  *
  * @return FormTypeInterface The type
  *
  * @throws Exception\FormException if the type can not be retrieved from any extension
  *
  * @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
  *             {@link FormRegistryInterface::getType()} instead.
  */
 public function getType($name)
 {
     return $this->registry->getType($name)->getInnerType();
 }
Ejemplo n.º 12
0
 /**
  * Returns a new ApiDoc instance with more data.
  *
  * @param  ApiDoc $annotation
  * @param  Route $route
  * @param  \ReflectionMethod $method
  * @param DunglasResource $dunglasResource
  * @return ApiDoc
  */
 protected function extractData(ApiDoc $annotation, Route $route, \ReflectionMethod $method, DunglasResource $dunglasResource = null)
 {
     //remove methode OPTIONS
     $methods = $route->getMethods();
     $optionIndex = array_search('OPTIONS', $methods);
     if ($optionIndex !== false) {
         unset($methods[$optionIndex]);
         $route->setMethods($methods);
     }
     if (in_array(strtolower($this->versionApi), $this->nelmioDocStandardVersion)) {
         return parent::extractData($annotation, $route, $method);
     }
     // create a new annotation
     $annotation = clone $annotation;
     $annotation->addTag($this->versionApi, '#ff0000');
     // doc
     $annotation->setDocumentation($this->commentExtractor->getDocCommentText($method));
     // parse annotations
     $this->parseAnnotations($annotation, $route, $method);
     $resource = $route->getDefault('_resource');
     // route
     $annotation->setRoute($route);
     $entityClassInput = $entityClassOutput = null;
     //section
     $annotation->setSection($resource);
     $annotation = $this->addFilters($resource, $annotation, $dunglasResource, $route);
     if (in_array($annotation->getMethod(), ['POST', 'PUT'])) {
         $formName = 'api_v2_' . strtolower($dunglasResource->getShortName());
         if ($hasFormtype = $this->registry->hasType($formName)) {
             $type = $this->registry->getType($formName);
             if ($type instanceof ResolvedFormTypeInterface) {
                 $entityClassInput = get_class($type->getInnerType());
                 $dunglasResource->initValidationGroups($type->getInnerType()->validationGrp);
             }
         }
     }
     if ('GET' === $annotation->getMethod()) {
         $entityClassInput = null;
     }
     if (is_null($annotation->getOutput()) || is_array($annotation->getOutput())) {
         $entityClassOutput = $this->transformerHelper->getEntityClass($resource);
     } else {
         $entityClassOutput = $annotation->getOutput();
     }
     if ('DELETE' === $annotation->getMethod()) {
         $entityClassInput = $entityClassOutput = null;
     }
     // input (populates 'parameters' for the formatters)
     if (null !== ($input = $entityClassInput)) {
         $normalizedInput = $this->normalizeClassParameter($input, $dunglasResource);
         $parameters = $this->getParametersParser($normalizedInput, $resource, $dunglasResource, $annotation);
         if ($hasFormtype && in_array($annotation->getMethod(), ['POST', 'PUT'])) {
             $parameters = $this->processFormParams($formName, $parameters, $dunglasResource);
         }
         $parameters = $this->clearClasses($parameters);
         $parameters = $this->generateHumanReadableTypes($parameters);
         if ($annotation->getMethod() === 'POST') {
             if (isset($parameters['id'])) {
                 unset($parameters['id']);
             }
         }
         if (in_array($annotation->getMethod(), ['PUT', 'PATCH'])) {
             // All parameters are optional with PUT (update)
             array_walk($parameters, function ($val, $key) use(&$parameters) {
                 $parameters[$key]['required'] = false;
             });
         }
         $annotation->setParameters($parameters);
     }
     // output (populates 'response' for the formatters)
     if (null !== ($output = $entityClassOutput)) {
         $normalizedOutput = $this->normalizeClassParameter($output, $dunglasResource);
         if (!is_array($annotation->getOutput())) {
             $response = $this->getParametersParser($normalizedOutput, $resource, $dunglasResource, $annotation, 'Output');
             foreach ($response as $key => $params) {
                 if (isset($response[$key]['children'])) {
                     unset($response[$key]['children']);
                 }
                 if ($response[$key]['actualType'] === 'model') {
                     $response[$key]['dataType'] = 'Integer | ' . $response[$key]['dataType'];
                 }
             }
             $response = $this->clearClasses($response);
             $response = $this->generateHumanReadableTypes($response);
         } else {
             $response = $this->normalizeArrayParameter($annotation->getOutput());
         }
         $annotation->setResponse($response);
         $annotation->setResponseForStatusCode($response, $normalizedOutput, 200);
     }
     if (count($annotation->getResponseMap()) > 0) {
         foreach ($annotation->getResponseMap() as $code => $modelName) {
             if (is_array($modelName)) {
                 continue;
             }
             if ('200' === (string) $code && isset($modelName['type']) && isset($modelName['model'])) {
                 /*
                  * Model was already parsed as the default `output` for this ApiDoc.
                  */
                 continue;
             }
             $normalizedModel = $this->normalizeClassParameter($modelName, $dunglasResource);
             $parameters = array();
             $supportedParsers = array();
             foreach ($this->getParsers($normalizedModel) as $parser) {
                 if ($parser->supports($normalizedModel)) {
                     $supportedParsers[] = $parser;
                     $parameters = $this->mergeParameters($parameters, $parser->parse($normalizedModel));
                 }
             }
             foreach ($supportedParsers as $parser) {
                 if ($parser instanceof PostParserInterface) {
                     $mp = $parser->postParse($normalizedModel, $parameters);
                     $parameters = $this->mergeParameters($parameters, $mp);
                 }
             }
             $parameters = $this->clearClasses($parameters);
             $parameters = $this->generateHumanReadableTypes($parameters);
             $annotation->setResponseForStatusCode($parameters, $normalizedModel, $code);
         }
     }
     return $annotation;
 }