Passed
Push — master ( 5e3deb...621a9a )
by Gerrit
07:56 queued 05:39
created

GenericServiceInvokeController::__invoke()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 9
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 9
loc 9
ccs 4
cts 4
cp 1
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * Copyright (C) 2018 Gerrit Addiks.
4
 * This package (including this file) was released under the terms of the GPL-3.0.
5
 * You should have received a copy of the GNU General Public License along with this program.
6
 * If not, see <http://www.gnu.org/licenses/> or send me a mail so i can send you a copy.
7
 *
8
 * @license GPL-3.0
9
 *
10
 * @author Gerrit Addiks <[email protected]>
11
 */
12
13
namespace Addiks\SymfonyGenerics\Controllers\API;
14
15
use Addiks\SymfonyGenerics\Controllers\ControllerHelperInterface;
16
use Webmozart\Assert\Assert;
17
use Psr\Container\ContainerInterface;
18
use Addiks\SymfonyGenerics\Services\ArgumentCompilerInterface;
19
use Symfony\Component\HttpFoundation\Response;
20
use Symfony\Component\HttpFoundation\Request;
21
use ErrorException;
22
use ReflectionObject;
23
use ReflectionMethod;
24
25
final class GenericServiceInvokeController
26
{
27
28
    /**
29
     * @var ControllerHelperInterface
30
     */
31
    private $controllerHelper;
32
33
    /**
34
     * @var ArgumentCompilerInterface
35
     */
36
    private $argumentCompiler;
37
38
    /**
39
     * @var ContainerInterface
40
     */
41
    private $container;
42
43
    /**
44
     * @var string
45
     */
46
    private $serviceId;
47
48
    /**
49
     * @var string
50
     */
51
    private $method;
52
53
    /**
54
     * @var array
55
     */
56
    private $arguments;
57
58
    /**
59
     * @var string|null
60
     */
61
    private $authorizationAttribute;
62
63
    /**
64
     * @var string|null
65
     */
66
    private $successRedirectRoute;
67
68
    /**
69
     * @var array
70
     */
71
    private $successRedirectArguments;
72
73
    /**
74
     * @var integer
75
     */
76
    private $successRedirectStatus;
77
78
    /**
79
     * @var bool
80
     */
81
    private $sendReturnValueInResponse = false;
82
83
    /**
84
     * @var string
85
     */
86
    private $successFlashMessage;
87
88
    /**
89
     * @var array<string, string>
90
     */
91
    private $successResponseHeader = array();
92
93 9
    public function __construct(
94
        ControllerHelperInterface $controllerHelper,
95
        ArgumentCompilerInterface $argumentCompiler,
96
        ContainerInterface $container,
97
        array $options
98
    ) {
99 9
        Assert::null($this->controllerHelper);
100 9
        Assert::keyExists($options, 'service');
101 8
        Assert::keyExists($options, 'method');
102
103
        /** @var int $defaultRedirectStatus */
104 7
        $defaultRedirectStatus = 303;
105
106 7
        $options = array_merge([
107 7
            'arguments' => [],
108
            'authorization-attributes' => null,
109
            'success-redirect' => null,
110
            'success-redirect-arguments' => [],
111 7
            'success-redirect-status' => $defaultRedirectStatus,
112 7
            'success-flash-message' => "",
113
            'send-return-value-in-response' => false,
114
            'success-response-header' => [],
115 7
        ], $options);
116
117 7
        $this->controllerHelper = $controllerHelper;
118 7
        $this->argumentCompiler = $argumentCompiler;
119 7
        $this->container = $container;
120 7
        $this->serviceId = $options['service'];
121 7
        $this->method = $options['method'];
122 7
        $this->arguments = $options['arguments'];
123 7
        $this->authorizationAttribute = $options['authorization-attributes'];
124 7
        $this->successRedirectRoute = $options['success-redirect'];
125 7
        $this->successRedirectArguments = $options['success-redirect-arguments'];
126 7
        $this->successRedirectStatus = $options['success-redirect-status'];
127 7
        $this->successFlashMessage = $options['success-flash-message'];
128 7
        $this->sendReturnValueInResponse = $options['send-return-value-in-response'];
129 7
        $this->successResponseHeader = $options['success-response-header'];
130 7
    }
131
132 2 View Code Duplication
    public function __invoke(): Response
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
133
    {
134
        /** @var Request $request */
135 2
        $request = $this->controllerHelper->getCurrentRequest();
136
137 2
        Assert::isInstanceOf($request, Request::class, "Cannot use controller outside of request-scope!");
138
139 1
        return $this->callService($request);
140
    }
141
142 5
    public function callService(Request $request): Response
143
    {
144 5
        if (!is_null($this->authorizationAttribute)) {
145 1
            $this->controllerHelper->denyAccessUnlessGranted($this->authorizationAttribute, $request);
146
        }
147
148
        /** @var object|null $service */
149 4
        $service = $this->container->get($this->serviceId);
150
151 4
        if (is_null($service)) {
152 1
            throw new ErrorException(sprintf(
153 1
                "Could not find service '%s'!",
154 1
                $this->serviceId
155
            ));
156
        }
157
158 3
        $reflectionObject = new ReflectionObject($service);
159
160
        /** @var ReflectionMethod $reflectionMethod */
161 3
        $reflectionMethod = $reflectionObject->getMethod($this->method);
162
163
        /** @var array $arguments */
164 3
        $arguments = $this->argumentCompiler->buildCallArguments(
165 3
            $reflectionMethod,
166 3
            $this->arguments
167
        );
168
169
        /** @var mixed $returnValue */
170 3
        $returnValue = $reflectionMethod->invokeArgs($service, $arguments);
171
172 3
        $this->controllerHelper->flushORM();
173
174 3
        if (!empty($this->successFlashMessage)) {
175
            $this->controllerHelper->addFlashMessage($this->successFlashMessage, "success");
176
        }
177
178 3
        if (!empty($this->successRedirectRoute)) {
179
            /** @var array $redirectArguments */
180 1
            $redirectArguments = $this->argumentCompiler->buildArguments($this->successRedirectArguments);
181
182 1
            return $this->controllerHelper->redirectToRoute(
183 1
                $this->successRedirectRoute,
184 1
                $redirectArguments,
185 1
                $this->successRedirectStatus
186
            );
187
        }
188
189
        /** @var Response $response */
190 2
        $response = null;
0 ignored issues
show
Unused Code introduced by
$response is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
191
192 2
        if ($this->sendReturnValueInResponse) {
193
            $response = new Response((string)$returnValue);
194
195
        } else {
196 2
            $response = new Response("Service call completed");
197
        }
198
199 2
        $response->headers->add($this->successResponseHeader);
200
201 2
        return $response;
202
    }
203
204
}
205