LocalStorage::fromLocal()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace evelikto\di\storage;
4
use evelikto\di\Bean;
5
use evelikto\di\scope\Scope;
6
7
/** Activates the local (singleton or request) scope. */
8
trait LocalStorage
9
{
10
    /** @var array $storage Holds previously resolved dependencies with singleton scope */
11
    protected $storage = [];
12
13
    /**
14
     * Try to read the requested dependency from the storage
15
     *
16
     * @param   string  $name  Dependency name.
17
     * @return  mixed          Retrieved value or null if not previously stored.
18
     */
19
    protected function fromLocal(string $name) {
20
        return array_key_exists($name, $this->storage) ? $this->storage[$name] : null;
21
    }
22
23
    /**
24
     * Save the dependency to the storage.
25
     *
26
     * @param   Bean    $bean  Dependency to be stored.
27
     * @return  mixed          Stored value from the supplied bean.
28
     */
29
    protected function toLocal(Bean $bean) {
30
        if ($bean->scope !== null || ($bean->value instanceof Scope))
31
            return null;
32
33
        $this->storage[$bean->name] = $bean->value;
34
        foreach ($bean->aliases as $alias)
35
            $this->storage[$alias] = $bean->value;
36
37
        return $bean->value;
38
    }
39
}