Validate   A
last analyzed

Complexity

Total Complexity 35

Size/Duplication

Total Lines 116
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 67
dl 0
loc 116
rs 9.6
c 0
b 0
f 0
wmc 35

2 Methods

Rating   Name   Duplication   Size   Complexity  
A onInject() 0 3 1
F onMethodInject() 0 98 34
1
<?php
2
namespace WebStream\Annotation\Attributes;
3
4
use WebStream\Annotation\Base\Annotation;
5
use WebStream\Annotation\Base\IAnnotatable;
6
use WebStream\Annotation\Base\IMethod;
7
use WebStream\Annotation\Attributes\Ext\ValidateRule\IValidate;
8
use WebStream\ClassLoader\ClassLoader;
9
use WebStream\Container\Container;
10
use WebStream\Exception\Extend\AnnotationException;
11
use WebStream\Exception\Extend\InvalidRequestException;
12
use WebStream\Exception\Extend\ValidateException;
13
14
/**
15
 * Validate
16
 * @author Ryuichi TANAKA.
17
 * @since 2015/03/30
18
 * @version 0.4
19
 *
20
 * @Annotation
21
 * @Target("METHOD")
22
 */
23
class Validate extends Annotation implements IMethod
24
{
25
    /**
26
     * @var array<string> 注入アノテーション情報
27
     */
28
    private $injectAnnotation;
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function onInject(array $injectAnnotation)
34
    {
35
        $this->injectAnnotation = $injectAnnotation;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function onMethodInject(IAnnotatable $instance, \ReflectionMethod $method, Container $container)
42
    {
43
        $key = $this->injectAnnotation['key'];
44
        $rule = $this->injectAnnotation['rule'];
45
        $method = array_key_exists('method', $this->injectAnnotation) ?
46
            $this->injectAnnotation['method'] : "get";
47
48
        if ($method !== null && !array_key_exists($method, array_flip(["get", "post", "put", "delete"]))) {
49
            throw new ValidateException("Invalid method attribute is specified: " . $method);
50
        }
51
52
        // パラメータの有無にかかわらずルール定義が間違っている場合はエラー
53
        if (preg_match('/^([a-zA-Z]{1}[a-zA-Z0-9_]{1,})(?:$|\[(.+?)\]$)/', $rule, $matches)) {
54
            $className = ucfirst(preg_replace_callback('/_([a-zA-Z])/', function ($matches) {
55
                return ucfirst($matches[1]);
56
            }, $matches[1]));
57
            $classpath = null;
58
            $classLoader = new ClassLoader($container->applicationInfo->applicationRoot);
0 ignored issues
show
Bug Best Practice introduced by
The property applicationInfo does not exist on WebStream\Container\Container. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug introduced by
The property applicationRoot does not exist on string.
Loading history...
59
            $classLoader->inject('logger', $container->logger);
0 ignored issues
show
Bug Best Practice introduced by
The property logger does not exist on WebStream\Container\Container. Since you implemented __get, consider adding a @property annotation.
Loading history...
60
            $ignoreDir = $container->applicationInfo->externalLibraryRoot;
0 ignored issues
show
Bug introduced by
The property externalLibraryRoot does not exist on string.
Loading history...
61
            $fileName = $className . '.php';
62
            $isLoaded = $classLoader->import($fileName, function ($filepath) use ($ignoreDir) {
63
                if ($ignoreDir === null || $ignoreDir === "") {
64
                    return true;
65
                }
66
                $pos = strpos($filepath, $ignoreDir);
67
                return $pos === false || $pos !== 0;
68
            });
69
70
            // デフォルトバリデーションルールのパス
71
            if (!$isLoaded) {
72
                $loadList = $classLoader->load($className);
73
                $loadListWithoutIgnorePathList = [];
74
                foreach ($loadList as $path) {
75
                    $pos = strpos($path, $ignoreDir);
76
                    if ($pos === false || $pos !== 0) {
77
                        $loadListWithoutIgnorePathList[] = $path;
78
                    }
79
                }
80
81
                // バリデーションルールのクラス名が複数指定されている場合は適用判断不可能なのでエラー
82
                if (count($loadListWithoutIgnorePathList) >= 2) {
83
                    $errorMsg = "Class load failed because the same class name has been identified: " . $className . "";
84
                    throw new ValidateException($errorMsg);
85
                }
86
87
                if (count($loadListWithoutIgnorePathList) === 0) {
88
                    $errorMsg = "Invalid Validate class: " . $className . "";
89
                    throw new ValidateException($errorMsg);
90
                }
91
            }
92
93
            $namespaces = $classLoader->getNamespaces($fileName);
94
            foreach ($namespaces as $namespace) {
95
                if (strpos(IValidate::class, $namespace) === 0) {
96
                    $classpath = $namespace . "\\" . $className;
97
                }
98
            }
99
100
            if (!class_exists($classpath)) {
101
                $errorMsg = "Invalid Validate class's classpath: " . $classpath;
102
                throw new AnnotationException($errorMsg);
103
            }
104
105
            $validateInstance = new $classpath();
106
            $params = null;
107
            if ($container->request->requestMethod === 'GET') {
0 ignored issues
show
Bug Best Practice introduced by
The property request does not exist on WebStream\Container\Container. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug introduced by
The property requestMethod does not exist on string.
Loading history...
108
                if ($method === null || "get" === mb_strtolower($method)) {
109
                    $params = $container->request->get;
0 ignored issues
show
Bug introduced by
The property get does not exist on string.
Loading history...
110
                }
111
            } elseif ($container->request->requestMethod === 'POST') {
112
                if ($method === null || "post" === mb_strtolower($method)) {
113
                    $params = $container->request->post;
0 ignored issues
show
Bug introduced by
The property post does not exist on string.
Loading history...
114
                }
115
            } elseif ($container->request->requestMethod === 'PUT') {
116
                if ($method === null || "put" === mb_strtolower($method)) {
117
                    $params = $container->request->put;
0 ignored issues
show
Bug introduced by
The property put does not exist on string.
Loading history...
118
                }
119
            } elseif ($container->request->requestMethod === 'DELETE') {
120
                if ($method === null || "delete" === mb_strtolower($method)) {
121
                    $params = $container->request->delete;
0 ignored issues
show
Bug introduced by
The property delete does not exist on string.
Loading history...
122
                }
123
            } else {
124
                $errorMsg = "Unsupported method is specified: " . $method;
125
                throw new InvalidRequestException($errorMsg);
126
            }
127
128
            // パラメータの指定なしの場合、value=null
129
            // パラメータの指定ありあつ値の指定なしの場合、value=""
130
            $value = is_array($params) && array_key_exists($key, $params) ? $params[$key] : null;
131
132
            if (!$validateInstance->isValid($value, $rule)) {
133
                $errorMsg = "Validation rule error. Rule is '$rule', value is " . ($value === null || $value === '' ? "empty" : "'${value}'");
134
                throw new ValidateException($errorMsg);
135
            }
136
        } else {
137
            $errorMsg = "Invalid validation rule definition: " . $rule;
138
            throw new ValidateException($errorMsg);
139
        }
140
    }
141
}
142