CallbackFilter::filter()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
cc 3
nc 3
nop 4
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\DoctrineMongoDBAdminBundle\Filter;
15
16
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
17
use Sonata\AdminBundle\Form\Type\Filter\DefaultType;
18
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
19
use Symfony\Component\Form\Extension\Core\Type\TextType;
20
21
class CallbackFilter extends Filter
22
{
23
    /**
24
     * @param string $alias
25
     * @param string $field
26
     * @param string $data
27
     *
28
     * @throws \RuntimeException
29
     */
30
    public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data)
31
    {
32
        if (!\is_callable($this->getOption('callback'))) {
33
            throw new \RuntimeException(sprintf(
34
                'Please provide a valid callback option "filter" for field "%s"',
35
                $this->getName()
36
            ));
37
        }
38
39
        \call_user_func($this->getOption('callback'), $queryBuilder, $alias, $field, $data);
40
41
        if (\is_callable($this->getOption('active_callback'))) {
42
            $this->active = \call_user_func($this->getOption('active_callback'), $data);
43
44
            return;
45
        }
46
47
        $this->active = true;
48
    }
49
50
    /**
51
     * @return array
52
     */
53
    public function getDefaultOptions()
54
    {
55
        return [
56
            'callback' => null,
57
            'active_callback' => static function ($data) {
58
                return isset($data['value']) && $data['value'];
59
            },
60
            'field_type' => TextType::class,
61
            'operator_type' => HiddenType::class,
62
            'operator_options' => [],
63
        ];
64
    }
65
66
    public function getRenderSettings()
67
    {
68
        return [DefaultType::class, [
69
                'field_type' => $this->getFieldType(),
70
                'field_options' => $this->getFieldOptions(),
71
                'operator_type' => $this->getOption('operator_type'),
72
                'operator_options' => $this->getOption('operator_options'),
73
                'label' => $this->getLabel(),
74
        ]];
75
    }
76
}
77