Build inheritance form errors

@param FormInterface $form
@return array
433175
protected function getErrorsFromForm(FormInterface $form)
    {
        $errors = [];
        /** @var FormError $error */

        if($form->getErrors()->count() === 0 && $form->isRoot() && !$form->isValid()){
            $errors["_self"] = "Empty post data";
        }

        foreach ($form->getErrors() as $error) {
            $key = $error->getOrigin()->getName();
            $errors[($form->isRoot()) ? "_self" : $key] = $error->getMessage();
        }

        foreach ($form->all() as $childForm) {
            if ($childForm instanceof FormInterface) {
                if ($childErrors = $this->getErrorsFromForm($childForm)) {
                    unset($errors["_self"]);
                    $errors = array_merge_recursive($errors, $childErrors);
                }
            }
        }

        return $errors;
    }
1349379
protected function getValidationData(Form $form)
    {
        // If parent has metadata
        $parent = $form->getParent();
        if ($parent && null !== $parent->getConfig()->getDataClass()) {
            $classMetadata = $metadata = $this->getMetadataFor($parent->getConfig()->getDataClass());
            if ($classMetadata->hasPropertyMetadata($form->getName())) {
                $metadata = $classMetadata->getPropertyMetadata($form->getName());
                /** @var PropertyMetadata $item */
                foreach ($metadata as $item) {
                    $this->composeValidationData(
                        $parentData,
                        $item->getConstraints(),
                        $getters = !empty($item->getters) ? (array)$item->getters : array()
                    );
                }
            }
        }
        // If has own metadata
        if (null !== $form->getConfig()->getDataClass()) {
            $metadata = $this->getMetadataFor($form->getConfig()->getDataClass());
            $this->composeValidationData(
                $ownData,
                $metadata->getConstraints(),
                $getters = !empty($metadata->getters) ? (array)$metadata->getters : array()
            );
        }
        // If has constraints in a form element
        $this->composeValidationData(
            $formData,
            (array)$form->getConfig()->getOption('constraints'),
            array()
        );

        $result = array();
        $groups = $this->getValidationGroups($form);

        if (!empty($parentData)) {
            $parentData['groups'] = $this->getValidationGroups($parent);
            $result['parent']     = $parentData;
        }
        if (!empty($ownData)) {
            $ownData['groups'] = $groups;
            $result['entity']  = $ownData;
        }
        if (!empty($formData)) {
            $formData['groups'] = $groups;
            $result['form']     = $formData;
        }

        return $result;
    }
432120
protected function getAllErrors(FormInterface $form)
    {
        $errors = $form->getErrors();
        $children = $form->all();
        if (!count($errors) && !count($children)) {
            return null;
        }

        $section = [
            'field' => $form->getName()
        ];

        if (count($errors)) {
            $section['errors'] = array_map(
                function (FormError $error) {
                    return [
                        'message' => $error->getMessage(),
                        'parameters' => $error->getMessageParameters()
                    ];
                },
                iterator_to_array($form->getErrors())
            );
        }

        if (count($children)) {
            $section['children'] = array_values(
                array_filter(
                    array_map(
                        function (FormInterface $field) {
                            return $this->getAllErrors($field);
                        },
                        $form->all()
                    )
                )
            );

            if (!count($errors) && !count($section['children'])) {
                return null;
            }
        }

        return $section;
    }
577825
private function validateForm(array $form): array
    {
        $resolver = new OptionsResolver();
        $resolver->setRequired([
            'url',
        ]);
        $resolver->setDefaults([
            'method' => 'POST',
            'encType' => 'application/x-www-form-urlencoded',
            'url_options' => [],
        ]);
        $resolver->setAllowedTypes('url', ['string']);
        $resolver->setAllowedTypes('url_options', ['array']);
        $resolver->setAllowedTypes('method', ['string']);
        $resolver->setAllowedTypes('encType', ['string']);
        $resolver->setAllowedValues('encType', ['application/x-www-form-urlencoded', 'text/plain', 'multipart/form-data']);
        $resolver->setAllowedValues('method', ['POST', 'GET']);

        $form = $resolver->resolve($form);

        if (! empty($form['url_options']))
        {
            foreach($form['url_options'] as $q=>$w)
            {
                $method = 'get' . ucfirst($w);
                $found = false;
                if (method_exists($this->getTemplateManager()->getEntity(), $method))
                {
                    $form['url'] = str_replace($q, $this->getTemplateManager()->getEntity()->$method(), $form['url']);
                    $found = true;
                }
                $method = 'is' . ucfirst($w);
                if (method_exists($this->getTemplateManager()->getEntity(), $method) && ! $found)
                {
                    $form['url'] = str_replace($q, $this->getTemplateManager()->getEntity()->$method(), $form['url']);
                    $found = true;
                }
                if (! $found)
                    trigger_error(sprintf('The form url does not have an option %s in the entity %s.', $w, get_class($this->getTemplateManager()->getEntity())), E_USER_ERROR);
            }
        }

        return $form;
    }
566760
public function getFormErrors(FormView $formView)
    {
        $formViews = array();
        foreach ($this->types as $name => $type) {
            $formViews[] = $formView[$name];
        }

        $formHelper = $this->getFormHelper();

        return $formHelper->getRecursiveErrorMessages($formViews);
    }
643454
protected function createInstance(
        InputInterface $input,
        OutputInterface $output,
        Form $form = null
    ) {
        if (!isset($form)) {
            $form = new Form();
        }

        return $form
            ->setInput($input)
            ->setOutput($output)
            ->setHelperSet($this->getHelperSet());
    }
446167
private function addChildErrors (FormInterface $form, string $fieldPrefix, string $translationDomain, array &$allErrors) : void
    {
        foreach ($form->all() as $children)
        {
            $childErrors = $children->getErrors();
            $fieldName = \ltrim("{$fieldPrefix}{$children->getName()}");

            if (0 < \count($childErrors))
            {
                $allErrors[$fieldName] = \array_map(
                    function (FormError $error) use ($translationDomain)
                    {
                        return $this->translator->trans($error->getMessage(), [], $translationDomain);
                    },
                    \iterator_to_array($childErrors)
                );
            }

            $this->addChildErrors($children, "{$fieldName}_", $translationDomain, $allErrors);
        }
    }
1145249
public function getFormErrors(FormView $formView)
    {
        $errors = parent::getFormErrors($formView);

        $formHelper = $this->getFormHelper();

        if (isset($formView['pagepartadmin_' . $this->pagePartAdmin->getContext()])) {
            $errors = array_merge($errors, $formHelper->getRecursiveErrorMessages($formView['pagepartadmin_' . $this->pagePartAdmin->getContext()]));
        }

        return $errors;
    }
425540
public function getFlattenErrors(FormInterface $form = null, $subForm = false)
    {
        $form    = $form ?: $this->form;
        $flatten = [];

        foreach ($form->getErrors() as $error) {
            if ($subForm) {
                $flatten[] = $error->getMessage();
            } else {
                $path = $error->getCause()->getPropertyPath();

                if (!array_key_exists($path, $flatten)) {
                    $flatten[$path] = [$error->getMessage()];
                    continue;
                }

                $flatten[$path][] = $error->getMessage();
            }
        }

        $subForm = true;
        foreach ($form->all() as $key => $child) {
            $childErrors = $this->getFlattenErrors($child, $subForm);

            if (!empty($childErrors)) {
                $flatten[$key] = $childErrors;
            }
        }

        return $flatten;
    }
1262076
public function render(FormInterface $form)
    {
        if (method_exists($form, 'prepare')) {
            $form->prepare();
        }

        $formContent = '';

        foreach ($form as $element) {
            if ($element instanceof FieldsetInterface) {
                $formContent.= $this->getView()->bootstrapFormCollection($element);
            } else {
                $formContent.= $this->getView()->bootstrapFormRow($element);
            }
        }

        return $this->openTag($form) . $formContent . $this->closeTag();
    }
1015187
private function getLocale(FormInterface $form)
    {
        if (null === $form->getParent()) {
            return null;
        }

        $entity = $form->getParent()->getData();

        if (!is_object($entity)) {
            return null;
        }

        $class = ClassUtils::getClass($entity);

        if (!$this->translatableManager->isTranslation($class)) {
            return null;
        }

        return $this->propertyAccessor->getValue($entity, $this->translatableManager->getTranslationLocaleProperty());
    }
155518
public function login(?FormInterface $form = null)
    {
        if (!$form) {
            throw new \RuntimeException('This provider require a form');
        }

        $url = $this->config['login']['url'] ?? null;
        if ($this->router->getRouteCollection()->get($url)) {
            $url = $this->router->generate($url, [], Router::ABSOLUTE_URL);
        }

        $opts = [
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_HTTPHEADER => [],
        ];

        $paramsIn = $this->config['login']['parameters_in'] ?? 'form';
        if ('header' === $paramsIn) {
            $opts[CURLOPT_HEADER] = true;
            $headers = [];
            foreach ($form->getData() as $key => $value) {
                $headers[] = sprintf('%s: %s', $key, $value);
            }
            $opts[CURLOPT_HTTPHEADER] = array_merge(["Accept: application/json"], $headers);
        } elseif ('query' === $paramsIn) {
            $url .= '?'.http_build_query($form->getData(), null, '&');
        } else {
            $opts[CURLOPT_POSTFIELDS] = http_build_query($form->getData(), null, '&');
            $opts[CURLOPT_POST] = true;
        }

        $opts[CURLOPT_URL] = $url;

        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $result = curl_exec($ch);

        // Split the HTTP response into header and body.
        try {
            list($headers, $body) = explode("\r\n\r\n", $result);
            $headers = explode("\r\n", $headers);
        } catch (\ErrorException $exception) {
            throw new AuthenticationFailedException('Authentication Failed');
        }

        // We catch HTTP/1.1 4xx or HTTP/1.1 5xx error response.
        if (strpos($headers[0], 'HTTP/1.1 4') !== false || strpos($headers[0], 'HTTP/1.1 5') !== false) {
            $result = [
                'code' => 0,
                'message' => '',
            ];

            if (preg_match('/^HTTP\/1.1 ([0-9]{3,3}) (.*)$/', $headers[0], $matches)) {
                $result['code'] = $matches[1];
                $result['message'] = $matches[2];
            }

            // In case retrun with WWW-Authenticate replace the description.
            foreach ($headers as $header) {
                if (preg_match("/^WWW-Authenticate:.*error='(.*)'/", $header, $matches)) {
                    $result['message'] = $matches[1];
                }
            }

            throw new AuthenticationFailedException($result['message'] ?: 'Authentication Failed', $result['code'] ?: 401);
        }

        $tokenPath = $this->config['login']['response_token_path'] ?? 'token';
        $token = $body;

        if ($tokenPath) {
            $token = search($tokenPath, @json_decode($body));
        }

        if (!$token) {
            throw new AuthenticationFailedException('Authentication Failed');
        }

        $this->session->set(self::SESSION_PATH, $token);
    }
1227684
protected function findConstraints(FormInterface $form)
    {
        $constraints = new ConstraintCollection();

        // Find constraints configured with the form
        $formConstraints = $form->getConfig()->getOption('constraints');
        if (!empty($formConstraints)) {
            if (is_array($formConstraints)) {
                $constraints->addCollection(
                    new ConstraintCollection($formConstraints)
                );
            } else {
                $constraints->add($formConstraints);
            }
        }

        // Find constraints bound by data
        if ($form->getConfig()->getMapped()) {
            $constraints->addCollection(
                $this->constraintFinder->find($form)
            );
        }

        return $constraints;
    }
1044075
public function transform(FormInterface $form)
    {
        $formView = $form->createView();

        $question = new AlwaysReturnKeyOfChoiceQuestion($this->questionFrom($form), $formView->vars['choices'], $this->defaultValueFrom($form));

        if ($form->getConfig()->getOption('multiple')) {
            $question->setMultiselect(true);
        }

        return $question;
    }
228109
protected function attemptLogin(Request $request, FormInterface $form)
    {
        return $this->guard()->attempt(
            [
                $this->username() => $form->repository()->getFieldByName($this->username())->getValue(),
                'password' => $form->repository()->getFieldByName('password')->getValue()
            ],
            $request->filled($this->remember())
        );
    }
768650
public function getValidationErrors()
    {
        $fields = $this->getFields();
        if (!$fields) {
            return [];
        }

        $result = [];
        foreach ($fields as $field) {
            if ($field instanceof AbstractFormField) {
                if (!$field->isValid()) {
                    $result = array_merge($result, $field->getErrorMessages());
                }
            }
        }

        return $result;
    }
1234750
public function addReferrerToForm(FormInterface $form): void
    {
        $request = $this->get('request_stack')->getCurrentRequest();
        $form->add('http-referrer', HiddenType::class, [
            'mapped' => false,
            'data' => $request->headers->get('referer'),
        ]);
    }