Completed
Push — feature/middleware ( aef20d...bf156f )
by Romain
02:16
created

AbstractMiddleware   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 251
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 10

Importance

Changes 0
Metric Value
wmc 26
lcom 3
cbo 10
dl 0
loc 251
rs 10
c 0
b 0
f 0

19 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A initialize() 0 4 1
A initializeMiddleware() 0 3 1
A beforeSignal() 0 4 1
A afterSignal() 0 4 1
A getOptions() 0 4 1
A getOptionsClassName() 0 4 1
A forward() 0 4 1
A redirect() 0 4 1
A getFormObject() 0 4 1
A getRequest() 0 4 1
A getRequestArguments() 0 4 1
A getPriority() 0 4 1
A bindMiddlewareProcessor() 0 4 1
A getBoundSignalName() 0 12 3
A dataPreProcessor() 0 10 2
B getSignalObject() 0 24 5
A __sleep() 0 4 1
A injectReflectionService() 0 4 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\Element;
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\FormObject\FormObject;
23
use Romm\Formz\Middleware\Element\MiddlewareInterface;
24
use Romm\Formz\Middleware\MiddlewareFactory;
25
use Romm\Formz\Middleware\Option\OptionDefinitionInterface;
26
use Romm\Formz\Middleware\Processor\MiddlewareProcessor;
27
use Romm\Formz\Middleware\Request\Forward;
28
use Romm\Formz\Middleware\Request\Redirect;
29
use Romm\Formz\Middleware\Signal\After;
30
use Romm\Formz\Middleware\Signal\Before;
31
use Romm\Formz\Middleware\Signal\MiddlewareSignalInterface;
32
use Romm\Formz\Middleware\Signal\SendsMiddlewareSignal;
33
use Romm\Formz\Middleware\Signal\SignalObject;
34
use TYPO3\CMS\Core\Utility\GeneralUtility;
35
use TYPO3\CMS\Extbase\Mvc\Controller\Arguments;
36
use TYPO3\CMS\Extbase\Mvc\Web\Request;
37
use TYPO3\CMS\Extbase\Reflection\ReflectionService;
38
39
/**
40
 * Abstract class that must be extended by middlewares.
41
 *
42
 * Child middleware must implement their own signals.
43
 */
44
abstract class AbstractMiddleware implements MiddlewareInterface, DataPreProcessorInterface
45
{
46
    /**
47
     * @var MiddlewareProcessor
48
     */
49
    private $processor;
50
51
    /**
52
     * This is the default option class, this property can be overridden in
53
     * children classes to be mapped to another option definition.
54
     *
55
     * @var \Romm\Formz\Middleware\Option\DefaultOptionDefinition
56
     */
57
    protected $options;
58
59
    /**
60
     * Can be overridden in child class with custom priority value.
61
     *
62
     * The higher the priority is, the earlier the middleware is called.
63
     *
64
     * Note that you can also override the method `getPriority()` for advanced
65
     * priority calculation.
66
     *
67
     * @var int
68
     */
69
    protected $priority = 0;
70
71
    /**
72
     * @var ReflectionService
73
     */
74
    protected $reflectionService;
75
76
    /**
77
     * @param OptionDefinitionInterface $options
78
     */
79
    final public function __construct(OptionDefinitionInterface $options)
80
    {
81
        $this->options = $options;
0 ignored issues
show
Documentation Bug introduced by
$options is of type object<Romm\Formz\Middle...ionDefinitionInterface>, 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...
82
    }
83
84
    /**
85
     * Abstraction for processing the middleware initialization.
86
     *
87
     * For own initialization, @see initializeMiddleware()
88
     */
89
    final public function initialize()
90
    {
91
        $this->initializeMiddleware();
92
    }
93
94
    /**
95
     * You can override this method in your child class to initialize your
96
     * middleware correctly.
97
     */
98
    protected function initializeMiddleware()
99
    {
100
    }
101
102
    /**
103
     * @see \Romm\Formz\Middleware\Signal\SendsMiddlewareSignal::beforeSignal()
104
     *
105
     * @param string $signal
106
     * @return SignalObject
107
     */
108
    final public function beforeSignal($signal = null)
109
    {
110
        return $this->getSignalObject($signal, Before::class);
111
    }
112
113
    /**
114
     * @see \Romm\Formz\Middleware\Signal\SendsMiddlewareSignal::afterSignal()
115
     *
116
     * @param string $signal
117
     * @return SignalObject
118
     */
119
    final public function afterSignal($signal = null)
120
    {
121
        return $this->getSignalObject($signal, After::class);
122
    }
123
124
    /**
125
     * @return OptionDefinitionInterface
126
     */
127
    public function getOptions()
128
    {
129
        return $this->options;
130
    }
131
132
    /**
133
     * @return string
134
     */
135
    public static function getOptionsClassName()
136
    {
137
        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...
138
    }
139
140
    /**
141
     * Returns a new forward dispatcher, on which you can add options by calling
142
     * its fluent methods.
143
     *
144
     * You must call the method `dispatch()` to actually dispatch the forward
145
     * signal.
146
     *
147
     * @return Forward
148
     */
149
    final protected function forward()
150
    {
151
        return new Forward($this->getRequest());
152
    }
153
154
    /**
155
     * Returns a new redirect dispatcher, on which you can add options by
156
     * calling its fluent methods.
157
     *
158
     * You must call the method `dispatch()` to actually dispatch the redirect
159
     * signal.
160
     *
161
     * @return Redirect
162
     */
163
    final protected function redirect()
164
    {
165
        return new Redirect($this->getRequest());
166
    }
167
168
    /**
169
     * @return FormObject
170
     */
171
    final protected function getFormObject()
172
    {
173
        return $this->processor->getFormObject();
174
    }
175
176
    /**
177
     * @return Request
178
     */
179
    final protected function getRequest()
180
    {
181
        return $this->processor->getRequest();
182
    }
183
184
    /**
185
     * @return Arguments
186
     */
187
    final protected function getRequestArguments()
188
    {
189
        return $this->processor->getRequestArguments();
190
    }
191
192
    /**
193
     * @return int
194
     */
195
    public function getPriority()
196
    {
197
        return (int)$this->priority;
198
    }
199
200
    /**
201
     * @param MiddlewareProcessor $middlewareProcessor
202
     */
203
    final public function bindMiddlewareProcessor(MiddlewareProcessor $middlewareProcessor)
204
    {
205
        $this->processor = $middlewareProcessor;
206
    }
207
208
    /**
209
     * Returns the name of the signal on which this middleware is bound.
210
     *
211
     * @return string
212
     * @throws SignalNotFoundException
213
     */
214
    final public function getBoundSignalName()
215
    {
216
        $interfaces = class_implements($this);
217
218
        foreach ($interfaces as $interface) {
219
            if (in_array(MiddlewareSignalInterface::class, class_implements($interface))) {
220
                return $interface;
221
            }
222
        }
223
224
        throw SignalNotFoundException::signalNotFoundInMiddleware($this);
225
    }
226
227
    /**
228
     * Will inject empty options if no option has been defined at all.
229
     *
230
     * @param DataPreProcessor $processor
231
     */
232
    public static function dataPreProcessor(DataPreProcessor $processor)
233
    {
234
        $data = $processor->getData();
235
236
        if (false === isset($data['options'])) {
237
            $data['options'] = [];
238
        }
239
240
        $processor->setData($data);
241
    }
242
243
    /**
244
     * Returns a signal object, that will be used to dispatch a signal coming
245
     * from this middleware.
246
     *
247
     * @param string $signal
248
     * @param string $type
249
     * @return SignalObject
250
     * @throws InvalidArgumentValueException
251
     * @throws InvalidEntryException
252
     * @throws MissingArgumentException
253
     */
254
    private function getSignalObject($signal, $type)
255
    {
256
        if (false === $this instanceof SendsMiddlewareSignal) {
257
            throw InvalidEntryException::middlewareNotSendingSignals($this);
258
        }
259
260
        /** @var SendsMiddlewareSignal $this */
261
        if (null === $signal) {
262
            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\Element\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Element\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...
263
                throw MissingArgumentException::signalNameArgumentMissing($this);
0 ignored issues
show
Documentation introduced by
$this is of type this<Romm\Formz\Middlewa...ent\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...
264
            }
265
266
            $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\Element\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Element\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...
267
        }
268
269
        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\Element\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Element\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...
270
            throw InvalidArgumentValueException::signalNotAllowed($this);
0 ignored issues
show
Documentation introduced by
$this is of type this<Romm\Formz\Middlewa...ent\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...
271
        }
272
273
        /** @var SignalObject $signalObject */
274
        $signalObject = GeneralUtility::makeInstance(SignalObject::class, $this->processor, $signal, $type);
275
276
        return $signalObject;
277
    }
278
279
    /**
280
     * @return array
281
     */
282
    public function __sleep()
283
    {
284
        return ['options'];
285
    }
286
287
    /**
288
     * @param ReflectionService $reflectionService
289
     */
290
    public function injectReflectionService(ReflectionService $reflectionService)
291
    {
292
        $this->reflectionService = $reflectionService;
293
    }
294
}
295