Completed
Push — master ( 206c33...9e77c2 )
by Oscar
05:44
created

ContainerTrait::from()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 7
rs 9.4286
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
3
namespace Psr7Middlewares\Utils;
4
5
use Interop\Container\ContainerInterface;
6
use InvalidArgumentException;
7
use RuntimeException;
8
9
/**
10
 * Trait to provide a container to load parameters.
11
 */
12
trait ContainerTrait
13
{
14
    /**
15
     * @var ContainerInterface|null
16
     */
17
    protected $container;
18
19
    /**
20
     * @var string|null
21
     */
22
    protected $containerId;
23
24
    /**
25
     * Load the container and the key used to get the service.
26
     *
27
     * @param ContainerInterface $container
28
     * @param string             $id
29
     *
30
     * @return self
31
     */
32
    public function from(ContainerInterface $container, $id)
33
    {
34
        $this->container = $container;
35
        $this->containerId = $id;
36
37
        return $this;
38
    }
39
40
    /**
41
     * Returns the service from the container.
42
     * 
43
     * @param string $type
44
     * @param bool   $required
45
     *
46
     * @return null|mixed
47
     */
48
    protected function getFromContainer($type = null, $required = true)
49
    {
50
        if (isset($this->container)) {
51
            $item = $this->container->get($this->containerId);
52
53
            if ($type !== null && !is_a($item, $type)) {
54
                throw new InvalidArgumentException("Invalid argument, it's not of type '{$type}'");
55
            }
56
57
            return $item;
58
        }
59
60
        if ($required) {
61
            $class = get_class($this);
62
63
            throw new RuntimeException("Missing required '{$type}' in the middleware '{$class}'");
64
        }
65
    }
66
}
67