Completed
Push — master ( c57e71...599f56 )
by Derek Stephen
01:42
created

PlatesStrategy::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 5
crap 1
1
<?php
2
3
namespace Bone\Mvc\Router;
4
5
use Bone\Mvc\Router\Decorator\ExceptionDecorator;
6
use Bone\Mvc\Router\Decorator\NotAllowedDecorator;
7
use Bone\Mvc\Router\Decorator\NotFoundDecorator;
8
use Bone\Mvc\View\PlatesEngine;
9
use Bone\Traits\HasLayoutTrait;
10
use Exception;
11
use League\Route\Http\Exception\{MethodNotAllowedException, NotFoundException};
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Bone\Mvc\Router\NotFoundException.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
12
use League\Route\Route;
13
use League\Route\Strategy\ApplicationStrategy;
14
use League\Route\Strategy\StrategyInterface;
15
use Psr\Http\Message\ResponseInterface;
16
use Psr\Http\Message\ServerRequestInterface;
17
use Psr\Http\Server\MiddlewareInterface;
18
use Laminas\Diactoros\Response;
19
use Laminas\Diactoros\Response\HtmlResponse;
20
use Laminas\Diactoros\Response\JsonResponse;
21
use Laminas\Diactoros\Stream;
22
23
class PlatesStrategy extends ApplicationStrategy implements StrategyInterface
24
{
25
    use HasLayoutTrait;
26
27
    /** @var PlatesEngine $viewEngine */
28
    private $viewEngine;
29
30
    /** @var NotFoundDecorator $notFoundDecorator */
31
    private $notFoundDecorator;
32
33
    /** @var NotAllowedDecorator $notAllowedDecorator */
34
    private $notAllowedDecorator;
35
36
    /** @var ExceptionDecorator $exceptionDecorator */
37
    private $exceptionDecorator;
38
39
    /**
40
     * PlatesStrategy constructor.
41
     * @param PlatesEngine $viewEngine
42
     * @param NotFoundDecorator $notFound
43
     * @param NotAllowedDecorator $notAllowed
44
     * @param string $layout
45
     */
46 9
    public function __construct(PlatesEngine $viewEngine, NotFoundDecorator $notFound, NotAllowedDecorator $notAllowed, string $layout, ExceptionDecorator $exceptionDecorator)
47
    {
48 9
        $this->viewEngine = $viewEngine;
49 9
        $this->notFoundDecorator = $notFound;
50 9
        $this->notAllowedDecorator = $notAllowed;
51 9
        $this->exceptionDecorator = $exceptionDecorator;
52 9
        $this->setLayout($layout);
53 9
    }
54
55
    /**
56
     * Invoke the route callable based on the strategy.
57
     *
58
     * @param \League\Route\Route $route
59
     * @param \Psr\Http\Message\ServerRequestInterface $request
60
     *
61
     * @return \Psr\Http\Message\ResponseInterface
62
     */
63
    public function invokeRouteCallable(Route $route, ServerRequestInterface $request): ResponseInterface
64
    {
65
        try {
66
67
            $response = parent::invokeRouteCallable($route, $request);
68
            $contentType = $response->getHeader('Content-Type');
69
70
            if ($contentType && strstr($contentType[0], 'application/json')) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $contentType of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
71
                return $response;
72
            }
73
74
            $body = ['content' => $response->getBody()->getContents()];
75
            $body = $this->viewEngine->render($this->layout, $body);
76
77
            return $this->getResponseWithBodyAndStatus($response, $body, $response->getStatusCode());
0 ignored issues
show
Compatibility introduced by
$response of type object<Psr\Http\Message\ResponseInterface> is not a sub-type of object<Laminas\Diactoros\Response>. It seems like you assume a concrete implementation of the interface Psr\Http\Message\ResponseInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
78
79
        } catch (Exception $e) {
80
            $body = $this->viewEngine->render('error/error', [
81
                'message' => $e->getMessage(),
82
                'code' => $e->getCode(),
83
                'trace' => $e->getTrace(),
84
            ]);
85
            $body = $this->viewEngine->render($this->layout, [
86
                'content' => $body,
87
            ]);
88
            $status = ($e->getCode() >= 100 && $e->getCode() < 600) ? $e->getCode() : 500;
89
90
            return $this->getResponseWithBodyAndStatus(new HtmlResponse($body), $body, $status);
91
        }
92
93
    }
94
95
    /**
96
     * @param ResponseInterface $response
97
     * @param string $body
98
     * @param int $status
99
     * @return \Psr\Http\Message\MessageInterface|Response
100
     */
101 View Code Duplication
    private function getResponseWithBodyAndStatus(Response $response, string $body, int $status = 200)
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...
102
    {
103
        $stream = new Stream('php://memory', 'r+');
104
        $stream->write($body);
105
        $response = $response->withStatus($status)->withBody($stream);
106
107
        return $response;
108
    }
109
110
    /**
111
     * Get a middleware that will decorate a NotFoundException
112
     *
113
     * @param \League\Route\Http\Exception\NotFoundException $exception
0 ignored issues
show
Bug introduced by
There is no parameter named $exception. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
114
     *
115
     * @return \Psr\Http\Server\MiddlewareInterface
116
     */
117
    public function getNotFoundDecorator(NotFoundException $e): MiddlewareInterface
118
    {
119
        return $this->notFoundDecorator;
120
    }
121
122
    /**
123
     * Get a middleware that will decorate a NotAllowedException
124
     *
125
     * @param \League\Route\Http\Exception\NotFoundException $e
126
     *
127
     * @return \Psr\Http\Server\MiddlewareInterface
128
     */
129
    public function getMethodNotAllowedDecorator(MethodNotAllowedException $e): MiddlewareInterface
130
    {
131
        return $this->notAllowedDecorator;
132
    }
133
134
    /**
135
     * @return MiddlewareInterface
136
     */
137
    public function getExceptionHandler(): MiddlewareInterface
138
    {
139
        return $this->exceptionDecorator;
140
    }
141
}