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

ContainerTrait   B

Complexity

Total Complexity 53

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 53
c 1
b 0
f 1
lcom 1
cbo 0
dl 0
loc 55
rs 7.4757

2 Methods

Rating   Name   Duplication   Size   Complexity  
A from() 0 7 1
B getFromContainer() 0 18 5

How to fix   Complexity   

Complex Class

Complex classes like ContainerTrait often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ContainerTrait, and based on these observations, apply Extract Interface, too.

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