Completed
Push — feature/middleware ( 864c18 )
by Romain
03:21
created

AbstractMiddleware::getSignalObject()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 8.7624
c 0
b 0
f 0
cc 5
eloc 10
nc 6
nop 2
1
<?php
2
/*
3
 * 2017 Romain CANON <[email protected]>
4
 *
5
 * This file is part of the TYPO3 FormZ project.
6
 * It is free software; you can redistribute it and/or modify it
7
 * under the terms of the GNU General Public License, either
8
 * version 3 of the License, or any later version.
9
 *
10
 * For the full copyright and license information, see:
11
 * http://www.gnu.org/licenses/gpl-3.0.html
12
 */
13
14
namespace Romm\Formz\Middleware\Item;
15
16
use Romm\ConfigurationObject\Service\Items\DataPreProcessor\DataPreProcessor;
17
use Romm\ConfigurationObject\Service\Items\DataPreProcessor\DataPreProcessorInterface;
18
use Romm\Formz\Exceptions\InvalidArgumentValueException;
19
use Romm\Formz\Exceptions\InvalidEntryException;
20
use Romm\Formz\Exceptions\MissingArgumentException;
21
use Romm\Formz\Exceptions\SignalNotFoundException;
22
use Romm\Formz\Form\Definition\Step\Step\Step;
23
use Romm\Formz\Form\FormObject\FormObject;
24
use Romm\Formz\Middleware\MiddlewareInterface;
25
use Romm\Formz\Middleware\Option\AbstractOptionDefinition;
26
use Romm\Formz\Middleware\Processor\MiddlewareProcessor;
27
use Romm\Formz\Middleware\Request\Exception\StopPropagationException;
28
use Romm\Formz\Middleware\Request\Forward;
29
use Romm\Formz\Middleware\Request\Redirect;
30
use Romm\Formz\Middleware\Signal\After;
31
use Romm\Formz\Middleware\Signal\Before;
32
use Romm\Formz\Middleware\Signal\MiddlewareSignal;
33
use Romm\Formz\Middleware\Signal\SendsMiddlewareSignal;
34
use Romm\Formz\Middleware\Signal\SignalObject;
35
use TYPO3\CMS\Extbase\Mvc\Controller\Arguments;
36
use TYPO3\CMS\Extbase\Mvc\Web\Request;
37
38
/**
39
 * Abstract class that must be extended by middlewares.
40
 *
41
 * Child middleware must implement their own signals.
42
 */
43
abstract class AbstractMiddleware implements MiddlewareInterface, DataPreProcessorInterface
44
{
45
    /**
46
     * @var MiddlewareProcessor
47
     */
48
    private $processor;
49
50
    /**
51
     * This is the default option class, this property can be overridden in
52
     * child classes to be mapped to another option definition.
53
     *
54
     * @var \Romm\Formz\Middleware\Option\DefaultOptionDefinition
55
     */
56
    protected $options;
57
58
    /**
59
     * Can be overridden in child class with custom priority value.
60
     *
61
     * The higher the priority is, the earlier the middleware is called.
62
     *
63
     * Note that you can also override the method `getPriority()` for advanced
64
     * priority calculation.
65
     *
66
     * @var int
67
     */
68
    protected $priority = 0;
69
70
    /**
71
     * @param AbstractOptionDefinition $options
72
     */
73
    final public function __construct(AbstractOptionDefinition $options)
74
    {
75
        $this->options = $options;
0 ignored issues
show
Documentation Bug introduced by
$options is of type object<Romm\Formz\Middle...stractOptionDefinition>, but the property $options was declared to be of type object<Romm\Formz\Middle...efaultOptionDefinition>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
76
    }
77
78
    /**
79
     * Abstraction for processing the middleware initialization.
80
     *
81
     * For own initialization, @see initializeMiddleware()
82
     */
83
    final public function initialize()
84
    {
85
        $this->initializeMiddleware();
86
    }
87
88
    /**
89
     * You can override this method in your child class to initialize your
90
     * middleware correctly.
91
     */
92
    protected function initializeMiddleware()
93
    {
94
    }
95
96
    /**
97
     * @see \Romm\Formz\Middleware\Signal\SendsMiddlewareSignal::beforeSignal()
98
     *
99
     * @param string $signal
100
     * @return SignalObject
101
     */
102
    final public function beforeSignal($signal = null)
103
    {
104
        return $this->getSignalObject($signal, Before::class);
105
    }
106
107
    /**
108
     * @see \Romm\Formz\Middleware\Signal\SendsMiddlewareSignal::afterSignal()
109
     *
110
     * @param string $signal
111
     * @return SignalObject
112
     */
113
    final public function afterSignal($signal = null)
114
    {
115
        return $this->getSignalObject($signal, After::class);
116
    }
117
118
    /**
119
     * @return AbstractOptionDefinition
120
     */
121
    public function getOptions()
122
    {
123
        return $this->options;
124
    }
125
126
    /**
127
     * Returns a new forward dispatcher, on which you can add options by calling
128
     * its fluent methods.
129
     *
130
     * You must call the method `dispatch()` to actually dispatch the forward
131
     * signal.
132
     *
133
     * @return Forward
134
     */
135
    final protected function forward()
136
    {
137
        return new Forward($this->getRequest());
138
    }
139
140
    /**
141
     * Returns a new redirect dispatcher, on which you can add options by
142
     * calling its fluent methods.
143
     *
144
     * You must call the method `dispatch()` to actually dispatch the redirect
145
     * signal.
146
     *
147
     * @return Redirect
148
     */
149
    final protected function redirect()
150
    {
151
        return new Redirect($this->getRequest());
152
    }
153
154
    /**
155
     * Will stop the propagation of middlewares: the next middlewares wont be
156
     * processed.
157
     *
158
     * Use with caution!
159
     */
160
    final protected function stopPropagation()
161
    {
162
        throw new StopPropagationException;
163
    }
164
165
    /**
166
     * @return FormObject
167
     */
168
    final protected function getFormObject()
169
    {
170
        return $this->processor->getFormObject();
171
    }
172
173
    /**
174
     * @return Request
175
     */
176
    final protected function getRequest()
177
    {
178
        return $this->processor->getRequest();
179
    }
180
181
    /**
182
     * @return Arguments
183
     */
184
    final protected function getRequestArguments()
185
    {
186
        return $this->processor->getRequestArguments();
187
    }
188
189
    /**
190
     * @return array
191
     */
192
    final protected function getSettings()
193
    {
194
        return $this->processor->getSettings();
195
    }
196
197
    /**
198
     * @return Step|null
199
     */
200
    final protected function getCurrentStep()
201
    {
202
        $request = ($this->getFormObject()->formWasSubmitted())
203
            ? $this->getRequest()->getReferringRequest()
204
            : $this->getRequest();
205
206
        return $this->getFormObject()->fetchCurrentStep($request)->getCurrentStep();
207
    }
208
209
    /**
210
     * @return int
211
     */
212
    public function getPriority()
213
    {
214
        return (int)$this->priority;
215
    }
216
217
    /**
218
     * @param MiddlewareProcessor $middlewareProcessor
219
     */
220
    final public function bindMiddlewareProcessor(MiddlewareProcessor $middlewareProcessor)
221
    {
222
        $this->processor = $middlewareProcessor;
223
    }
224
225
    /**
226
     * Returns the name of the signal on which this middleware is bound.
227
     *
228
     * @return string
229
     * @throws SignalNotFoundException
230
     */
231
    final public function getBoundSignalName()
232
    {
233
        $interfaces = class_implements($this);
234
235
        foreach ($interfaces as $interface) {
236
            if (in_array(MiddlewareSignal::class, class_implements($interface))) {
237
                return $interface;
238
            }
239
        }
240
241
        throw SignalNotFoundException::signalNotFoundInMiddleware($this);
242
    }
243
244
    /**
245
     * Will inject empty options if no option has been defined at all.
246
     *
247
     * @param DataPreProcessor $processor
248
     */
249
    public static function dataPreProcessor(DataPreProcessor $processor)
250
    {
251
        $data = $processor->getData();
252
253
        if (false === isset($data['options'])) {
254
            $data['options'] = [];
255
        }
256
257
        $processor->setData($data);
258
    }
259
260
    /**
261
     * @param string $signal
262
     * @param string $type
263
     * @return SignalObject
264
     * @throws InvalidArgumentValueException
265
     * @throws InvalidEntryException
266
     * @throws MissingArgumentException
267
     */
268
    private function getSignalObject($signal, $type)
269
    {
270
        if (false === $this instanceof SendsMiddlewareSignal) {
271
            throw InvalidEntryException::middlewareNotSendingSignals($this);
272
        }
273
274
        /** @var SendsMiddlewareSignal $this */
275
        if (null === $signal) {
276
            if (count($this->getAllowedSignals()) > 1) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Romm\Formz\Middleware\Item\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Item\AbstractMiddleware: Romm\Formz\Middleware\It...our\BehaviourMiddleware, Romm\Formz\Middleware\It...FormInjectionMiddleware, Romm\Formz\Middleware\It...ormValidationMiddleware, Romm\Formz\Middleware\It...tenceFetchingMiddleware. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
277
                throw MissingArgumentException::signalNameArgumentMissing($this);
0 ignored issues
show
Documentation introduced by
$this is of type this<Romm\Formz\Middlewa...tem\AbstractMiddleware>, but the function expects a object<Romm\Formz\Middle...\SendsMiddlewareSignal>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
278
            }
279
280
            $signal = reset($this->getAllowedSignals());
0 ignored issues
show
Bug introduced by
$this->getAllowedSignals() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Romm\Formz\Middleware\Item\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Item\AbstractMiddleware: Romm\Formz\Middleware\It...our\BehaviourMiddleware, Romm\Formz\Middleware\It...FormInjectionMiddleware, Romm\Formz\Middleware\It...ormValidationMiddleware, Romm\Formz\Middleware\It...tenceFetchingMiddleware. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
281
        }
282
283
        if (false === in_array($signal, $this->getAllowedSignals())) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Romm\Formz\Middleware\Item\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Item\AbstractMiddleware: Romm\Formz\Middleware\It...our\BehaviourMiddleware, Romm\Formz\Middleware\It...FormInjectionMiddleware, Romm\Formz\Middleware\It...ormValidationMiddleware, Romm\Formz\Middleware\It...tenceFetchingMiddleware. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
284
            throw InvalidArgumentValueException::signalNotAllowed($this);
0 ignored issues
show
Documentation introduced by
$this is of type this<Romm\Formz\Middlewa...tem\AbstractMiddleware>, but the function expects a object<Romm\Formz\Middle...\SendsMiddlewareSignal>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
285
        }
286
287
        return new SignalObject($this->processor, $signal, $type);
288
    }
289
290
    /**
291
     * @return array
292
     */
293
    public function __sleep()
294
    {
295
        return ['options'];
296
    }
297
}
298