<?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  2020 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 */

namespace Sso\BackendBundle\Form\Filter\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Lexik\Bundle\FormFilterBundle\Event\GetFilterConditionEvent;

/**
 * Class ApplicationRelationFilterSubscriber
 *
 * @copyright  2020 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 * @package Sso\BackendBundle\Form\Filter\EventSubscriber
 */
class ApplicationRelationFilterSubscriber implements EventSubscriberInterface
{
    /**
     * Prepare query for application relation filter in choices
     *
     * @param GetFilterConditionEvent $event
     */
    public function filterApplicationRelation(GetFilterConditionEvent $event)
    {
        $expr = $event->getFilterQuery()->getExpr();
        $values = $event->getValues();

        if ('' !== $values['value'] && null !== $values['value']) {
            $paramName = str_replace('.', '_', $event->getField());

            $event->setCondition(
                $expr->eq($event->getField(), ':' . $paramName),
                array($paramName => $values['value'])
            );
        }
    }

    /**
     * @inheritDoc
     */
    public static function getSubscribedEvents()
    {
        return array(
            'lexik_form_filter.apply.orm.filter_application_relation' => array('filterApplicationRelation'),
            'lexik_form_filter.apply.dbal.filter_application_relation' => array('filterApplicationRelation'),
        );
    }
}
