<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\CoreBundle\Shared\Twig\Extensions;

use Symfony\Component\Form\FormView;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class FormExtension extends AbstractExtension
{
    public function getFunctions(): array
    {
        return [
            new TwigFunction('form_errors_count', $this->countErrors(...), ['is_safe' => ['html']]),
        ];
    }

    public function countErrors(FormView $field): int
    {
        $count = \count($field->vars['errors'] ?? []);

        foreach ($field as $child) {
            $count += $this->countErrors($child);
        }

        return $count;
    }
}
