Passed
Branch master (267be1)
by Eugene
03:10
created

defaultValidator()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 6
Bugs 0 Features 0
Metric Value
c 6
b 0
f 0
dl 0
loc 18
ccs 0
cts 12
cp 0
rs 8.8571
cc 6
eloc 11
nc 7
nop 5
crap 42
1
<?php
2
namespace Staticus\Resources\Middlewares;
3
4
use Staticus\Config\ConfigInterface;
5
use Staticus\Diactoros\Response\ResourceDoResponse;
6
use Staticus\Middlewares\MiddlewareAbstract;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Staticus\Exceptions\WrongRequestException;
10
use Staticus\Resources\ResourceDOInterface;
11
use Zend\Diactoros\Response\EmptyResponse;
12
13
abstract class PrepareResourceMiddlewareAbstract extends MiddlewareAbstract
14
{
15
    protected $resourceDO;
16
    /**
17
     * @var Config
18
     */
19
    protected $config;
20
21
    public function __construct(ResourceDOInterface $resourceDO, ConfigInterface $config)
22
    {
23
        $this->resourceDO = $resourceDO;
24
        $this->config = $config;
1 ignored issue
show
Documentation Bug introduced by
It seems like $config of type object<Staticus\Config\ConfigInterface> is incompatible with the declared type object<Staticus\Resources\Middlewares\Config> of property $config.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
25
    }
26
27
    public function __invoke(
28
        ServerRequestInterface $request,
29
        ResponseInterface $response,
30
        callable $next = null
31
    )
32
    {
33
        parent::__invoke($request, $response, $next);
34
        if (!$this->fillResource()) {
35
36
            return new EmptyResponse(404, $response->getHeaders());
37
        }
38
39
        // Pass the resource to the next middleware
40
        $response = new ResourceDoResponse($this->resourceDO, $response->getStatusCode(), $response->getHeaders());
41
42
        return $next($request, $response);
43
    }
44
45
    /**
46
     * @throws WrongRequestException
47
     * @todo: Write separate cleanup rules for each parameter
48
     */
49
    protected function fillResource()
50
    {
51
        $name = static::getParamFromRequest('name', $this->request);
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
52
        $name = $this->cleanup($name);
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
53
        $namespace = dirname($name);
54
        $name = basename($name);
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
55
        $name = $this->defaultValidator('name', $name, false
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
56
            , ResourceDOInterface::NAME_REG_SYMBOLS, $this->config->get('staticus.clean_resource_name'));
57
        $namespace = $this->defaultValidator('namespace', $namespace, true
58
            , ResourceDOInterface::NAMESPACE_REG_SYMBOLS, $this->config->get('staticus.clean_resource_name'));
59
        if (!$this->namespaceValidator($namespace)) {
60
61
            return false;
62
        }
63
        $alt = static::getParamFromRequest('alt', $this->request);
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
64
        $alt = $this->cleanup($alt);
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
65
        $var = static::getParamFromRequest('var', $this->request);
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
66
        $var = $this->cleanup($var);
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
67
        $var = $this->defaultValidator('var', $var, true, '\w\d\-\._');
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
68
        $v = (int)static::getParamFromRequest('v', $this->request);
1 ignored issue
show
Comprehensibility introduced by
Avoid variables with short names like $v. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 6 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
69
        $author = static::getParamFromRequest('author', $this->request);
70
        $author = $this->cleanup($author);
71
72
        $dataDir = $this->config->get('staticus.data_dir');
73
        /**
74
         * You shouldn't check 'recreate' and 'destroy' params here.
75
         * @see \Staticus\Action\StaticMiddlewareAbstract::postAction
76
         * @see \Staticus\Action\StaticMiddlewareAbstract::deleteAction
77
         */
78
        $this->resourceDO
79
            ->reset()
80
            ->setBaseDirectory($dataDir)
81
            ->setNamespace($namespace)
82
            ->setName($name)
83
            ->setNameAlternative($alt)
84
            ->setVariant($var)
85
            ->setVersion($v)
86
            ->setAuthor($author);
87
        if (!$this->resourceDO->getType()) {
88
            $type = static::getParamFromRequest('type', $this->request);
89
            $type = $this->cleanup($type);
90
            $type = $this->defaultValidator('type', $type);
91
            $this->resourceDO->setType($type);
92
        }
93
        $this->fillResourceSpecialFields();
94
95
        return true;
96
    }
97
    abstract protected function fillResourceSpecialFields();
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
98
99
    protected function cleanup($name)
100
    {
101
        $name = preg_replace('/\s+/u', ' ', trim(mb_strtolower(rawurldecode((string)$name), 'UTF-8')));
102
        $name = str_replace(['\\'], '', $name);
103
104
        return $name;
105
    }
106
107
    /**
108
     * @param $name
109
     * @param ServerRequestInterface $request
110
     * @return string
111
     * @todo move this method somethere
112
     */
113
    public static function getParamFromRequest($name, ServerRequestInterface $request)
114
    {
115
        $attribute = $request->getAttribute($name);
116
        if ($attribute) {
117
118
            return $attribute;
119
        }
120
        $paramsGET = $request->getQueryParams();
1 ignored issue
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
121
        $paramsPOST = (array)$request->getParsedBody();
122
123
        $str = isset($paramsPOST[$name])
124
            ? $paramsPOST[$name]
125
            : (
126
                isset($paramsGET[$name])
127
                ? $paramsGET[$name]
128
                : ''
129
            );
130
131
        return $str;
132
    }
133
134
    protected function defaultValidator($name, $value, $canBeEmpty = false, $allowedRegexpSymbols = '\w\d\-_', $replaceDeniedSymbols = false)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 141 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
135
    {
136
        if (!empty($value)) {
137
            if ($replaceDeniedSymbols) {
138
                $value = preg_replace('/\s+/u', ' ', preg_replace('/[^' . $allowedRegexpSymbols . ']+/ui', '', $value));
139
                $value = trim(preg_replace('/\/+/u', '/', $value));
140
            } else {
141
                if (!preg_match('/^[' . $allowedRegexpSymbols . ']+$/ui', $value)) {
142
                    throw new WrongRequestException('Wrong request param "' . $name . '": ' . $value);
143
                }
144
            }
145
        }
146
        if (empty($value) && !$canBeEmpty) {
147
            throw new WrongRequestException('Empty request param "' . $name . '"');
148
        }
149
150
        return $value;
151
    }
152
153
    protected function namespaceValidator($namespace)
154
    {
155
        $allowed = $this->config->get('staticus.namespaces');
156
        if ($namespace && !in_array($namespace, $allowed, true)) {
157
            foreach ($allowed as $item) {
158
                if (false !== strpos($item, '*') && fnmatch($item, $namespace)) {
159
                    // TODO: limitations for nested namespaces
160
161
                    return true;
162
                }
163
            }
164
165
            return false;
166
        }
167
168
        return true;
169
    }
170
}
171