ContainerTrait   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 2
dl 0
loc 69
c 0
b 0
f 0
ccs 21
cts 21
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setParameter() 0 4 1
A getParameter() 0 8 2
A setService() 0 8 2
A getService() 0 14 3
1
<?php
2
/**
3
 * This file is part of the Yep package.
4
 * Copyright (c) 2018 Martin Zeman (Zemistr) (http://www.zemistr.eu)
5
 */
6
7
namespace Yep\Container;
8
9
use Yep\Container\Exception\ServiceMustBeAnObjectException;
10
use Yep\Container\Exception\ServiceNotFoundException;
11
12
trait ContainerTrait
13
{
14
    protected $parameters = [];
15
    protected $services = [];
16
17 4
    public function __construct(array $parameters = [])
18
    {
19 4
        $this->parameters = $parameters;
20 4
    }
21
22
    /**
23
     * @param string $key
24
     * @param mixed $value
25
     */
26 1
    public function setParameter($key, $value)
27
    {
28 1
        $this->parameters[$key] = $value;
29 1
    }
30
31
    /**
32
     * @param string $key
33
     * @param mixed $default
34
     * @return mixed
35
     */
36 1
    public function getParameter($key, $default = null)
37
    {
38 1
        if (isset($this->parameters[$key])) {
39 1
            return $this->parameters[$key];
40
        }
41
42 1
        return $default;
43
    }
44
45
    /**
46
     * @param string $name
47
     * @param object $service
48
     * @return mixed
49
     * @throws ServiceMustBeAnObjectException
50
     */
51 3
    public function setService($name, $service)
52
    {
53 3
        if (!is_object($service)) {
54 2
            throw ServiceMustBeAnObjectException::create($service);
55
        }
56
57 1
        return $this->services[$name] = $service;
58
    }
59
60
    /**
61
     * @param string $name
62
     * @return mixed
63
     * @throws ServiceMustBeAnObjectException
64
     * @throws ServiceNotFoundException
65
     */
66 3
    public function getService($name)
67
    {
68 3
        if (isset($this->services[$name])) {
69 1
            return $this->services[$name];
70
        }
71
72 3
        if (!method_exists($this, $name.'Factory')) {
73 1
            throw ServiceNotFoundException::create($name);
74
        }
75
76 2
        $service = $this->{$name.'Factory'}();
77
78 2
        return $this->setService($name, $service);
79
    }
80
}
81