ModelStorage   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 1
dl 0
loc 61
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A register() 0 17 3
A has() 0 6 1
A get() 0 6 1
1
<?php declare (strict_types = 1);
2
3
namespace Limoncello\Flute\Models;
4
5
/**
6
 * Copyright 2015-2019 [email protected]
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 * http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
21
use Limoncello\Contracts\Data\ModelSchemaInfoInterface;
22
use Limoncello\Flute\Contracts\Models\ModelStorageInterface;
23
use function get_class;
24
25
/**
26
 * @package Limoncello\Flute
27
 */
28
class ModelStorage implements ModelStorageInterface
29
{
30
    /**
31
     * @var array
32
     */
33
    private $models = [];
34
35
    /**
36
     * @var ModelSchemaInfoInterface
37
     */
38
    private $schemas;
39
40
    /**
41
     * @param ModelSchemaInfoInterface $schemas
42 22
     */
43
    public function __construct(ModelSchemaInfoInterface $schemas)
44 22
    {
45
        $this->schemas = $schemas;
46
    }
47
48
    /**
49
     * @inheritdoc
50 22
     */
51
    public function register($model)
52 22
    {
53
        $registered = null;
54 22
55 22
        if ($model !== null) {
56 22
            $class  = get_class($model);
57 22
            $pkName = $this->schemas->getPrimaryKey($class);
58
            $index  = $model->{$pkName};
59 22
60 22
            $registered = $this->models[$class][$index] ?? null;
61 22
            if ($registered === null) {
62
                $this->models[$class][$index] = $registered = $model;
63
            }
64
        }
65 22
66
        return $registered;
67
    }
68
69
    /**
70
     * @inheritdoc
71 1
     */
72
    public function has(string $class, string $index): bool
73 1
    {
74
        $result = isset($this->models[$class][$index]);
75 1
76
        return $result;
77
    }
78
79
    /**
80
     * @inheritdoc
81 1
     */
82
    public function get(string $class, string $index)
83 1
    {
84
        $result = $this->models[$class][$index];
85 1
86
        return $result;
87
    }
88
}
89