Completed
Push — master ( 46c3a0...a94e83 )
by Grégoire
13s queued 11s
created

src/Filter/FilterFactory.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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\AdminBundle\Filter;
15
16
use Symfony\Component\DependencyInjection\ContainerInterface;
17
18
/**
19
 * @final since sonata-project/admin-bundle 3.52
20
 *
21
 * @author Thomas Rabaix <[email protected]>
22
 */
23
class FilterFactory implements FilterFactoryInterface
24
{
25
    /**
26
     * @var ContainerInterface
27
     */
28
    protected $container;
29
30
    /**
31
     * @var string[]
32
     */
33
    protected $types;
34
35
    /**
36
     * @param string[] $types
37
     */
38
    public function __construct(ContainerInterface $container, array $types = [])
39
    {
40
        $this->container = $container;
41
        $this->types = $types;
42
    }
43
44
    public function create($name, $type, array $options = [])
45
    {
46
        if (!$type) {
47
            throw new \RuntimeException('The type must be defined');
48
        }
49
50
        $id = isset($this->types[$type]) ? $this->types[$type] : false;
51
52
        if ($id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
53
            $filter = $this->container->get($id);
54
        } elseif (class_exists($type)) {
55
            $filter = new $type();
56
        } else {
57
            throw new \RuntimeException(sprintf('No attached service to type named `%s`', $type));
58
        }
59
60
        if (!$filter instanceof FilterInterface) {
61
            throw new \RuntimeException(sprintf('The service `%s` must implement `FilterInterface`', $type));
62
        }
63
64
        $filter->initialize($name, $options);
65
66
        return $filter;
67
    }
68
}
69