<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\BackendBundle\Form;

use Lexik\Bundle\FormFilterBundle\Filter\Form\Type as FilterType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

/**
 * Class WsUserGroupFilterType
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package Sso\BackendBundle\Form
 */
class WsUserGroupFilterType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id', FilterType\TextFilterType::class)
            ->add('lowerName', FilterType\TextFilterType::class, ['label' => 'Name'])
            ->add('description', FilterType\TextFilterType::class)
        ;

        $listener = function (FormEvent $event) {
            // Is data empty?
            if ($this->isEmpty($event->getData())) {
                $event->getForm()->addError(new FormError('Filter empty'));
            }
        };

        $builder->addEventListener(FormEvents::POST_SUBMIT, $listener);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'sso_backendbundle_webserviceusergroupfiltertype';
    }

    /**
     * @param mixed $data
     * @return boolean
     */
    private function isEmpty($data)
    {
        if (is_array($data)) {
            foreach ($data as $value) {
                if (!$this->isEmpty($value)) {
                    return false;
                }
            }
            return true;
        }

        return empty($data);
    }
}
