Completed
Pull Request — 3.x (#6220)
by Vincent
03:15
created

AdminSearchBlockService::__construct()   C

Complexity

Conditions 10
Paths 7

Size

Total Lines 67

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 67
rs 6.8533
c 0
b 0
f 0
cc 10
nc 7
nop 4

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Block;
15
16
use Sonata\AdminBundle\Admin\AdminInterface;
17
use Sonata\AdminBundle\Admin\Pool;
18
use Sonata\AdminBundle\Search\SearchHandler;
19
use Sonata\BlockBundle\Block\BlockContextInterface;
20
use Sonata\BlockBundle\Block\Service\AbstractBlockService;
21
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
22
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
23
use Symfony\Component\HttpFoundation\Response;
24
use Symfony\Component\OptionsResolver\OptionsResolver;
25
use Twig\Environment;
26
27
/**
28
 * @final since sonata-project/admin-bundle 3.52
29
 *
30
 * @author Thomas Rabaix <[email protected]>
31
 */
32
class AdminSearchBlockService extends AbstractBlockService
33
{
34
    /**
35
     * @var Pool
36
     */
37
    protected $pool;
38
39
    /**
40
     * @var SearchHandler
41
     */
42
    protected $searchHandler;
43
44
    /**
45
     * NEXT_MAJOR: Change signature for (Environment $twig, Pool $pool, SearchHandler $searchHandler).
46
     *
47
     * @param Environment|string        $twigOrName
48
     * @param Pool|EngineInterface|null $poolOrTemplating
49
     * @param SearchHandler|Pool        $searchHandlerOrPool
50
     */
51
    public function __construct($twigOrName, ?object $poolOrTemplating, object $searchHandlerOrPool, ?SearchHandler $searchHandler = null)
52
    {
53
        if ($poolOrTemplating instanceof Pool) {
54
            if (!$twigOrName instanceof Environment) {
55
                throw new \TypeError(sprintf(
0 ignored issues
show
Unused Code introduced by
The call to TypeError::__construct() has too many arguments starting with sprintf('Argument 1 pass... \gettype($twigOrName)).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
56
                    'Argument 1 passed to %s() must be an instance of %s, %s given.',
57
                    __METHOD__,
58
                    Environment::class,
59
                    \is_object($twigOrName) ? 'instance of '.\get_class($twigOrName) : \gettype($twigOrName)
60
                ));
61
            }
62
63
            if (!$searchHandlerOrPool instanceof SearchHandler) {
64
                throw new \TypeError(sprintf(
0 ignored issues
show
Unused Code introduced by
The call to TypeError::__construct() has too many arguments starting with sprintf('Argument 3 pass...get_class($twigOrName)).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
65
                    'Argument 3 passed to %s() must be an instance of %s, instance of %s given.',
66
                    __METHOD__,
67
                    SearchHandler::class,
68
                    \get_class($twigOrName)
69
                ));
70
            }
71
72
            parent::__construct($twigOrName);
73
74
            $this->pool = $poolOrTemplating;
75
            $this->searchHandler = $searchHandlerOrPool;
76
        } elseif (null === $poolOrTemplating || $poolOrTemplating instanceof EngineInterface) {
77
            @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
78
                'Passing %s as argument 2 to %s() is deprecated since sonata-project/admin-bundle 3.x'
79
                .' and will throw a \TypeError in version 4.0. You must pass an instance of %s instead.',
80
                null === $poolOrTemplating ? 'null' : EngineInterface::class,
81
                __METHOD__,
82
                Pool::class
83
            ), E_USER_DEPRECATED);
84
85
            if (!$searchHandlerOrPool instanceof Pool) {
86
                throw new \TypeError(sprintf(
0 ignored issues
show
Unused Code introduced by
The call to TypeError::__construct() has too many arguments starting with sprintf('Argument 2 pass...get_class($twigOrName)).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
87
                    'Argument 2 passed to %s() must be an instance of %s, instance of %s given.',
88
                    __METHOD__,
89
                    Pool::class,
90
                    \get_class($twigOrName)
91
                ));
92
            }
93
94
            if (null === $searchHandler) {
95
                throw new \TypeError(sprintf(
0 ignored issues
show
Unused Code introduced by
The call to TypeError::__construct() has too many arguments starting with sprintf('Passing null as...h\SearchHandler::class).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
96
                    'Passing null as argument 3 to %s() is not allowed when %s is passed as argument 2.'
97
                    .' You must pass an instance of %s instead.',
98
                    __METHOD__,
99
                    EngineInterface::class,
100
                    SearchHandler::class
101
                ));
102
            }
103
104
            parent::__construct($twigOrName, $poolOrTemplating);
105
106
            $this->pool = $searchHandlerOrPool;
107
            $this->searchHandler = $searchHandler;
108
        } else {
109
            throw new \TypeError(sprintf(
0 ignored issues
show
Unused Code introduced by
The call to TypeError::__construct() has too many arguments starting with sprintf('Argument 2 pass...ass($poolOrTemplating)).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
110
                'Argument 2 passed to %s() must be either null or an instance of %s or preferably %s, instance of %s given.',
111
                __METHOD__,
112
                EngineInterface::class,
113
                Pool::class,
114
                \get_class($poolOrTemplating)
115
            ));
116
        }
117
    }
118
119
    public function execute(BlockContextInterface $blockContext, ?Response $response = null)
120
    {
121
        try {
122
            $admin = $this->pool->getAdminByAdminCode($blockContext->getSetting('admin_code'));
123
        } catch (ServiceNotFoundException $e) {
124
            throw new \RuntimeException('Unable to find the Admin instance', $e->getCode(), $e);
125
        }
126
127
        if (!$admin instanceof AdminInterface) {
128
            throw new \RuntimeException('The requested service is not an Admin instance');
129
        }
130
131
        $admin->checkAccess('list');
132
133
        $pager = $this->searchHandler->search(
134
            $admin,
135
            $blockContext->getSetting('query'),
136
            $blockContext->getSetting('page'),
137
            $blockContext->getSetting('per_page')
138
        );
139
140
        if (false === $pager) {
141
            $response = $response ?: new Response();
142
143
            return $response->setContent('')->setStatusCode(204);
144
        }
145
146
        return $this->renderPrivateResponse($admin->getTemplate('search_result_block'), [
0 ignored issues
show
Deprecated Code introduced by
The method Sonata\AdminBundle\Admin...nterface::getTemplate() has been deprecated with message: since sonata-project/admin-bundle 3.35. To be removed in 4.0. Use TemplateRegistry services instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
147
            'block' => $blockContext->getBlock(),
148
            'settings' => $blockContext->getSettings(),
149
            'admin_pool' => $this->pool,
150
            'pager' => $pager,
151
            'admin' => $admin,
152
        ], $response);
153
    }
154
155
    public function getName()
156
    {
157
        return 'Admin Search Result';
158
    }
159
160
    public function configureSettings(OptionsResolver $resolver)
161
    {
162
        $resolver
163
            ->setDefaults([
164
                'admin_code' => '',
165
                'query' => '',
166
                'page' => 0,
167
                'per_page' => 10,
168
                'icon' => '<i class="fa fa-list"></i>',
169
            ])
170
            ->setRequired('admin_code')
171
            ->setAllowedTypes('admin_code', ['string']);
172
    }
173
}
174