Completed
Push — master ( 7ea984...92b282 )
by n
02:25
created

MiddlewareResolver::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 4
Ratio 100 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 4
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace N1215\Jugoya\Resolver;
4
5
use Interop\Http\ServerMiddleware\MiddlewareInterface;
6
use N1215\Jugoya\Wrapper\CallableMiddleware;
7
use Psr\Container\ContainerInterface;
8
use Psr\Container\NotFoundExceptionInterface;
9
use Psr\Container\ContainerExceptionInterface;
10
11 View Code Duplication
class MiddlewareResolver implements MiddlewareResolverInterface
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
12
{
13
14
    /**
15
     * @var ContainerInterface
16
     */
17
    protected $container;
18
19
    /**
20
     * @param ContainerInterface $container
21
     */
22 11
    public function __construct(ContainerInterface $container)
23
    {
24 11
        $this->container = $container;
25 11
    }
26
27
    /**
28
     * @param string|callable|MiddlewareInterface $ref
29
     * @return MiddlewareInterface
30
     * @throws UnresolvedException
31
     */
32 10
    public function resolve($ref)
33
    {
34 10
        if ($ref instanceof MiddlewareInterface) {
35 4
            return $ref;
36
        }
37
38 9
        if (is_callable($ref)) {
39 4
            return new CallableMiddleware($ref);
40
        }
41
42 8
        if (!is_string($ref)) {
43 1
            throw new \InvalidArgumentException("Argument 1 \$ref must be one of an instance of MiddlewareInterface, a callable or string.");
44
        }
45
46
        try {
47 7
            $entry = $this->container->get($ref);
48 7
        } catch (NotFoundExceptionInterface $e) {
49 1
            throw new UnresolvedException('Could not found an entry from the container.', 0, $e);
50 1
        } catch (ContainerExceptionInterface $e) {
51 1
            throw new UnresolvedException('Something wrong with the container.', 0, $e);
52
        }
53
54 5
        if (!$entry instanceof MiddlewareInterface) {
55 1
            $type = is_object($entry) ? get_class($entry) : gettype($entry);
56 1
            throw new UnresolvedException("Expected container returns an instance of MiddlewareInterface, {$type} given.");
57
        }
58
59 4
        return $entry;
60
    }
61
}
62