Completed
Push — feature/0.7.0 ( a99e68...b0ec67 )
by Ryuichi
03:46
created

CoreModel::__execute()   F

Complexity

Conditions 34
Paths 222

Size

Total Lines 136
Code Lines 89

Duplication

Lines 0
Ratio 0 %

Importance

Changes 10
Bugs 0 Features 0
Metric Value
cc 34
eloc 89
c 10
b 0
f 0
nc 222
nop 3
dl 0
loc 136
rs 3.8063

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace WebStream\Core;
3
4
use WebStream\DI\Injector;
5
use WebStream\Module\Container;
6
use WebStream\Module\Utility\CommonUtils;
7
use WebStream\Module\Utility\ApplicationUtils;
8
use WebStream\Annotation\Filter;
9
use WebStream\Annotation\Base\IAnnotatable;
10
use WebStream\Database\DatabaseManager;
11
use WebStream\Database\Result;
12
use WebStream\Exception\Extend\DatabaseException;
13
use WebStream\Exception\Extend\MethodNotFoundException;
14
15
/**
16
 * CoreModel
17
 * @author Ryuichi TANAKA.
18
 * @since 2012/09/01
19
 * @version 0.7
20
 */
21
class CoreModel implements CoreInterface, IAnnotatable
22
{
23
    use Injector, CommonUtils, ApplicationUtils;
24
25
    /**
26
     * @var Container コンテナ
27
     */
28
    private $container;
29
30
    /**
31
     * @var DatabaseManager データベースマネージャ
32
     */
33
    private $manager;
34
35
    /**
36
     * @var array<AnnotationContainer> クエリアノテーションリスト
37
     */
38
    private $queryAnnotations;
39
40
    /**
41
     * @var boolean オートコミットフラグ
42
     */
43
    private $isAutoCommit;
44
45
    /**
46
     * @var array<mixed> カスタムアノテーション
47
     */
48
    protected $annotation;
49
50
    /**
51
     * @var LoggerAdapter ロガー
52
     */
53
    protected $logger;
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function __construct(Container $container)
59
    {
60
        $this->logger = $container->logger;
0 ignored issues
show
Documentation introduced by
The property logger does not exist on object<WebStream\Module\Container>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
61
        $this->logger->debug("Model start.");
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function __destruct()
68
    {
69
        $this->logger->debug("Model end.");
70
        $this->__clear();
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     * @Filter(type="initialize")
76
     */
77
    public function __initialize(Container $container)
78
    {
79
        if ($container->connectionContainerList === null) {
0 ignored issues
show
Documentation introduced by
The property connectionContainerList does not exist on object<WebStream\Module\Container>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
80
            $this->logger->warn("Can't use database in Model Layer.");
81
82
            return;
83
        }
84
85
        $this->queryAnnotations = $container->queryAnnotations;
0 ignored issues
show
Documentation introduced by
The property queryAnnotations does not exist on object<WebStream\Module\Container>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
86
        $container->logger = $this->logger;
0 ignored issues
show
Documentation introduced by
The property logger does not exist on object<WebStream\Module\Container>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
87
        $this->manager = new DatabaseManager($container);
88
        $this->isAutoCommit = true;
89
        $this->container = $container;
90
    }
91
92
    /**
93
    * {@inheritdoc}
94
     */
95
    public function __customAnnotation(array $annotation)
96
    {
97
        $this->annotation = $annotation;
98
    }
99
100
    /**
101
     * method missing
102
     * @param string メソッド名
103
     * @param array sql/bindパラメータ
104
     */
105
    final public function __call($method, $arguments)
106
    {
107
        // DBコネクションが取得できなければエラー
108
        $filepath = debug_backtrace()[0]["file"];
109
        if (!$this->manager->loadConnection($filepath)) {
110
            throw new MethodNotFoundException("Undefined method called: $method");
111
        }
112
113
        if ($this->manager->isConnected() === false) {
114
            $this->manager->connect();
115
        }
116
117
        $result = $this->__execute($method, $arguments, $filepath);
118
119
        if ($this->isAutoCommit) {
120
            if (is_int($result) && $result > 0) {
121
                $this->manager->commit();
122
            }
123
            $this->manager->disconnect();
124
        }
125
126
        return $result;
127
    }
128
129
    /**
130
     * DB処理を実行する
131
     * @param string メソッド名
132
     * @param array sql/bindパラメータ
133
     * @param string 現在実行中のクラスのファイルパス
134
     */
135
    final public function __execute($method, $arguments, $filepath)
136
    {
137
        $result = null;
138
139
        try {
140
            if (preg_match('/^(?:select|(?:dele|upda)te|insert)$/', $method)) {
141
                $sql = $arguments[0];
142
                $bind = null;
143
                if (array_key_exists(1, $arguments)) {
144
                    $bind = $arguments[1];
145
                }
146
147
                if (is_string($sql)) {
148
                    if ($method !== 'select' && $this->isAutoCommit) {
149
                        $this->manager->beginTransaction();
150
                    }
151
                    if (is_array($bind)) {
152
                        $result = $this->manager->query($sql, $bind)->{$method}();
153
                    } else {
154
                        $result = $this->manager->query($sql)->{$method}();
155
                    }
156
                } else {
157
                    throw new DatabaseException("Invalid SQL or bind parameters: " . $sql .", " . strval($bind));
158
                }
159
            } else {
160
                $bind = null;
161
                if (array_key_exists(0, $arguments)) {
162
                    $bind = $arguments[0];
163
                }
164
165
                $trace = debug_backtrace();
166
                $modelMethod = null;
167
                for ($i = 0; $i < count($trace); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
168
                    if ($this->inArray($trace[$i]["function"], ["__call", "__execute"])) {
169
                        continue;
170
                    }
171
172
                    if ($trace[$i]["function"] !== null) {
173
                        $modelMethod = $trace[$i]["function"];
174
                        break;
175
                    }
176
                }
177
178
                $namespace = substr($this->getNamespace($filepath), 1);
179
                $queryKey = $namespace . "\\" . basename($filepath, ".php") . "#" . $modelMethod;
180
181
                $query = null;
182
                foreach ($this->queryAnnotations as $queryAnnotation) {
183
                    $queryFunctions = $queryAnnotation->get($queryKey);
184
185
                    if ($queryFunctions === null) {
186
                        continue;
187
                    }
188
189
                    foreach ($queryFunctions as $queryFunction) {
190
                        $xmlObjectList = $queryFunction->fetch();
191
                        foreach ($xmlObjectList as $xmlObject) {
192
                            if ($xmlObject !== null) {
193
                                $xmlElement = $xmlObject->xpath("//mapper[@namespace='$namespace']/*[@id='$method']");
194
195
                                if (!empty($xmlElement)) {
196
                                    $query = ["sql" => trim($xmlElement[0]->__toString()), "method" => $xmlElement[0]->getName()];
197
                                    $entity = $xmlElement[0]->attributes()["entity"];
198
                                    $query["entity"] = $entity !== null ? $entity->__toString() : null;
199
                                    break;
200
                                }
201
                            }
202
                        }
203
                    }
204
                }
205
206
                if ($query === null) {
207
                    throw new DatabaseException("SQL statement can't getting from xml file.");
208
                }
209
210
                $sql = $query["sql"];
211
                $method = $query["method"];
212
                $entityClassPath = $query["entity"];
213
214
                if ($entityClassPath !== null) {
215
                    if (!class_exists($entityClassPath)) {
216
                        throw new DatabaseException("Entity classpath is not found: " . $entityClassPath);
217
                    }
218
219
                    switch ($method) {
220
                        case "select":
221
                            if (is_string($sql)) {
222
                                if (is_array($bind)) {
223
                                    $result = $this->manager->query($sql, $bind)->select()->toEntity($entityClassPath);
224
                                } else {
225
                                    $result = $this->manager->query($sql)->select()->toEntity($entityClassPath);
226
                                }
227
                            } else {
228
                                $errorMessage = "Invalid SQL or bind parameters: " . $sql;
229
                                if (is_array($bind)) {
230
                                    $errorMessage .= ", " . strval($bind);
231
                                }
232
233
                                throw new DatabaseException($errorMessage);
234
                            }
235
236
                            break;
237
                        case "insert":
238
                        case "update":
239
                        case "delete":
240
                            // Not implement
241
                            throw new DatabaseException("Entity mapping is select only.");
242
                    }
243
                } else {
244
                    if (is_string($sql)) {
245
                        if ($method !== 'select' && $this->isAutoCommit) {
246
                            $this->manager->beginTransaction();
247
                        }
248
                        if (is_array($bind)) {
249
                            $result = $this->manager->query($sql, $bind)->{$method}();
250
                        } else {
251
                            $result = $this->manager->query($sql)->{$method}();
252
                        }
253
                    } else {
254
                        $errorMessage = "Invalid SQL or bind parameters: " . $sql;
255
                        if (is_array($bind)) {
256
                            $errorMessage .= ", " . strval($bind);
257
                        }
258
259
                        throw new DatabaseException($errorMessage);
260
                    }
261
                }
262
            }
263
        } catch (DatabaseException $e) {
264
            $this->manager->rollback();
265
            $this->manager->disconnect();
266
            throw $e;
267
        }
268
269
        return $result;
270
    }
271
272
    /**
273
     * トランザクション開始
274
     */
275
    final public function beginTransaction()
276
    {
277
        $filepath = debug_backtrace()[0]["file"];
278
        if (!$this->manager->loadConnection($filepath)) {
279
            throw new MethodNotFoundException("Undefined method called: $method");
280
        }
281
282
        if ($this->manager->isConnected() === false) {
283
            $this->manager->connect();
284
        }
285
286
        $this->manager->beginTransaction();
287
        $this->isAutoCommit = false;
288
    }
289
290
    /**
291
     * コミットする
292
     */
293
    final public function commit()
294
    {
295
        if ($this->isAutoCommit === false) {
296
            $this->manager->commit();
297
        }
298
    }
299
300
    /**
301
     * ロールバックする
302
     */
303
    final public function rollback()
304
    {
305
        $this->manager->rollback();
306
    }
307
}
308