Completed
Push — feature/middleware ( 1de75b...c62ef3 )
by Romain
02:16
created

AbstractMiddleware::dataPreProcessor()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 25
rs 8.439
c 1
b 0
f 0
cc 5
eloc 13
nc 16
nop 1
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\Application;
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\Middleware\MiddlewareScopes;
23
use Romm\Formz\Form\FormObject\FormObject;
24
use Romm\Formz\Middleware\MiddlewareInterface;
25
use Romm\Formz\Middleware\MiddlewareFactory;
26
use Romm\Formz\Middleware\Option\OptionInterface;
27
use Romm\Formz\Middleware\Processor\MiddlewareProcessor;
28
use Romm\Formz\Middleware\Request\Forward;
29
use Romm\Formz\Middleware\Request\Redirect;
30
use Romm\Formz\Middleware\Scope\MainScope;
31
use Romm\Formz\Middleware\Signal\After;
32
use Romm\Formz\Middleware\Signal\Before;
33
use Romm\Formz\Middleware\Signal\Element\MiddlewareSignalInterface;
34
use Romm\Formz\Middleware\Signal\SendsSignal;
35
use Romm\Formz\Middleware\Signal\Element\SignalObject;
36
use TYPO3\CMS\Core\Utility\GeneralUtility;
37
use TYPO3\CMS\Extbase\Mvc\Controller\Arguments;
38
use TYPO3\CMS\Extbase\Mvc\Web\Request;
39
use TYPO3\CMS\Extbase\Reflection\ReflectionService;
40
41
/**
42
 * Default abstraction layout that can be extended by middlewares. It contains
43
 * basic implementation needed by a middleware to work properly.
44
 *
45
 * The middleware class must still implement its own signals.
46
 */
47
abstract class AbstractMiddleware implements MiddlewareInterface, DataPreProcessorInterface
48
{
49
    /**
50
     * @var MiddlewareProcessor
51
     */
52
    private $processor;
53
54
    /**
55
     * This is the default option class, this property can be overridden in
56
     * children classes to be mapped to another option definition.
57
     *
58
     * Please note that the full class name of the option must be written.
59
     *
60
     * @var \Romm\Formz\Middleware\Option\DefaultOption
61
     */
62
    protected $options;
63
64
    /**
65
     * @var \Romm\Formz\Form\Definition\Middleware\MiddlewareScopes
66
     */
67
    protected $scopes = [];
68
69
    /**
70
     * @var array
71
     */
72
    protected static $defaultScopesWhiteList = [];
73
74
    /**
75
     * @var array
76
     */
77
    protected static $defaultScopesBlackList = [];
78
79
80
    /**
81
     * Can be overridden in child class with custom priority value.
82
     *
83
     * The higher the priority is, the earlier the middleware is called.
84
     *
85
     * Note that you can also override the method `getPriority()` for advanced
86
     * priority calculation.
87
     *
88
     * @var int
89
     */
90
    protected $priority = 0;
91
92
    /**
93
     * @var ReflectionService
94
     */
95
    protected $reflectionService;
96
97
    /**
98
     * @param OptionInterface  $options
99
     * @param MiddlewareScopes $scopes
100
     */
101
    final public function __construct(OptionInterface $options, MiddlewareScopes $scopes)
102
    {
103
        $this->options = $options;
0 ignored issues
show
Documentation Bug introduced by
$options is of type object<Romm\Formz\Middle...Option\OptionInterface>, but the property $options was declared to be of type object<Romm\Formz\Middle...e\Option\DefaultOption>. 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...
104
        $this->scopes = $scopes;
105
    }
106
107
    /**
108
     * Abstraction for processing the middleware initialization.
109
     *
110
     * For own initialization, @see initializeMiddleware()
111
     */
112
    final public function initialize()
113
    {
114
        $this->initializeMiddleware();
115
    }
116
117
    /**
118
     * You can override this method in your child class to initialize your
119
     * middleware correctly.
120
     */
121
    protected function initializeMiddleware()
122
    {
123
    }
124
125
    /**
126
     * @see \Romm\Formz\Middleware\Signal\SendsSignal::beforeSignal()
127
     *
128
     * @param string $signal
129
     * @return SignalObject
130
     */
131
    final public function beforeSignal($signal = null)
132
    {
133
        return $this->getSignalObject($signal, Before::class);
134
    }
135
136
    /**
137
     * @see \Romm\Formz\Middleware\Signal\SendsSignal::afterSignal()
138
     *
139
     * @param string $signal
140
     * @return SignalObject
141
     */
142
    final public function afterSignal($signal = null)
143
    {
144
        return $this->getSignalObject($signal, After::class);
145
    }
146
147
    /**
148
     * @return OptionInterface
149
     */
150
    public function getOptions()
151
    {
152
        return $this->options;
153
    }
154
155
    /**
156
     * @return string
157
     */
158
    public static function getOptionsClassName()
159
    {
160
        return MiddlewareFactory::get()->getOptionsClassNameFromProperty(self::class);
0 ignored issues
show
Bug introduced by
It seems like getOptionsClassNameFromProperty() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
161
    }
162
163
    /**
164
     * @return MiddlewareScopes
165
     */
166
    public function getScopes()
167
    {
168
        return $this->scopes;
169
    }
170
171
    /**
172
     * Returns a new forward dispatcher, on which you can add options by calling
173
     * its fluent methods.
174
     *
175
     * You must call the method `dispatch()` to actually dispatch the forward
176
     * signal.
177
     *
178
     * @return Forward
179
     */
180
    final protected function forward()
181
    {
182
        return new Forward($this->getRequest(), $this->getFormObject());
183
    }
184
185
    /**
186
     * Returns a new redirect dispatcher, on which you can add options by
187
     * calling its fluent methods.
188
     *
189
     * You must call the method `dispatch()` to actually dispatch the redirect
190
     * signal.
191
     *
192
     * @return Redirect
193
     */
194
    final protected function redirect()
195
    {
196
        return new Redirect($this->getRequest(), $this->getFormObject());
197
    }
198
199
    /**
200
     * @return FormObject
201
     */
202
    final protected function getFormObject()
203
    {
204
        return $this->processor->getFormObject();
205
    }
206
207
    /**
208
     * @return Request
209
     */
210
    final protected function getRequest()
211
    {
212
        return $this->processor->getRequest();
213
    }
214
215
    /**
216
     * @return Arguments
217
     */
218
    final protected function getRequestArguments()
219
    {
220
        return $this->processor->getRequestArguments();
221
    }
222
223
    /**
224
     * @return int
225
     */
226
    public function getPriority()
227
    {
228
        return (int)$this->priority;
229
    }
230
231
    /**
232
     * @param MiddlewareProcessor $middlewareProcessor
233
     */
234
    final public function bindMiddlewareProcessor(MiddlewareProcessor $middlewareProcessor)
235
    {
236
        $this->processor = $middlewareProcessor;
237
    }
238
239
    /**
240
     * Returns the name of the signal on which this middleware is bound.
241
     *
242
     * @return string
243
     * @throws SignalNotFoundException
244
     */
245
    final public function getBoundSignalName()
246
    {
247
        $interfaces = class_implements($this);
248
249
        foreach ($interfaces as $interface) {
250
            if (in_array(MiddlewareSignalInterface::class, class_implements($interface))) {
251
                return $interface;
252
            }
253
        }
254
255
        throw SignalNotFoundException::signalNotFoundInMiddleware($this);
256
    }
257
258
    /**
259
     * Will inject empty options if no option has been defined at all.
260
     *
261
     * @param DataPreProcessor $processor
262
     */
263
    public static function dataPreProcessor(DataPreProcessor $processor)
264
    {
265
        $data = $processor->getData();
266
267
        if (false === isset($data['options'])) {
268
            $data['options'] = [];
269
        }
270
271
        if (false === isset($data['scopes'])) {
272
            $data['scopes'] = [];
273
        }
274
275
        if (false === isset($data['scopes']['whiteList'])) {
276
            $data['scopes']['whiteList'] = [MainScope::class];
277
        }
278
279
        if (false === isset($data['scopes']['blackList'])) {
280
            $data['scopes']['blackList'] = [];
281
        }
282
283
        $data['scopes']['whiteList'] = array_unique(array_merge(static::$defaultScopesWhiteList, $data['scopes']['whiteList']));
284
        $data['scopes']['blackList'] = array_unique(array_merge(static::$defaultScopesBlackList, $data['scopes']['blackList']));
285
286
        $processor->setData($data);
287
    }
288
289
    /**
290
     * Returns a signal object, that will be used to dispatch a signal coming
291
     * from this middleware.
292
     *
293
     * @param string $signal
294
     * @param string $type
295
     * @return SignalObject
296
     * @throws InvalidArgumentValueException
297
     * @throws InvalidEntryException
298
     * @throws MissingArgumentException
299
     */
300
    private function getSignalObject($signal, $type)
301
    {
302
        if (false === $this instanceof SendsSignal) {
303
            throw InvalidEntryException::middlewareNotSendingSignals($this);
304
        }
305
306
        /** @var SendsSignal $this */
307
        if (null === $signal) {
308
            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\Ap...tion\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Ap...tion\AbstractMiddleware: Romm\Formz\Domain\Middle...FormInjectionMiddleware, Romm\Formz\Domain\Middle...ormValidationMiddleware. 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...
309
                throw MissingArgumentException::signalNameArgumentMissing($this);
0 ignored issues
show
Documentation introduced by
$this is of type this<Romm\Formz\Middlewa...ion\AbstractMiddleware>, but the function expects a object<Romm\Formz\Middleware\Signal\SendsSignal>.

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...
310
            }
311
312
            $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\Ap...tion\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Ap...tion\AbstractMiddleware: Romm\Formz\Domain\Middle...FormInjectionMiddleware, Romm\Formz\Domain\Middle...ormValidationMiddleware. 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...
313
        }
314
315
        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\Ap...tion\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Ap...tion\AbstractMiddleware: Romm\Formz\Domain\Middle...FormInjectionMiddleware, Romm\Formz\Domain\Middle...ormValidationMiddleware. 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...
316
            throw InvalidArgumentValueException::signalNotAllowed($this);
0 ignored issues
show
Documentation introduced by
$this is of type this<Romm\Formz\Middlewa...ion\AbstractMiddleware>, but the function expects a object<Romm\Formz\Middleware\Signal\SendsSignal>.

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...
317
        }
318
319
        /** @var SignalObject $signalObject */
320
        $signalObject = GeneralUtility::makeInstance(SignalObject::class, $this->processor, $signal, $type);
321
322
        return $signalObject;
323
    }
324
325
    /**
326
     * @return array
327
     */
328
    public function __sleep()
329
    {
330
        return ['options', 'scopes'];
331
    }
332
333
    /**
334
     * @param ReflectionService $reflectionService
335
     */
336
    public function injectReflectionService(ReflectionService $reflectionService)
337
    {
338
        $this->reflectionService = $reflectionService;
339
    }
340
}
341