Passed
Pull Request — master (#34)
by Anatoly
02:23
created

CollectableFileLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php declare(strict_types=1);
2
3
/**
4
 * It's free open-source software released under the MIT License.
5
 *
6
 * @author Anatoly Fenric <[email protected]>
7
 * @copyright Copyright (c) 2018, Anatoly Fenric
8
 * @license https://github.com/sunrise-php/http-router/blob/master/LICENSE
9
 * @link https://github.com/sunrise-php/http-router
10
 */
11
12
namespace Sunrise\Http\Router\Loader;
13
14
/**
15
 * Import classes
16
 */
17
use Sunrise\Http\Router\ExceptionFactory;
18
use Sunrise\Http\Router\RouteCollectionFactory;
19
use Sunrise\Http\Router\RouteCollectionFactoryInterface;
20
use Sunrise\Http\Router\RouteCollectionInterface;
21
use Sunrise\Http\Router\RouteCollector;
22
use Sunrise\Http\Router\RouteFactory;
23
use Sunrise\Http\Router\RouteFactoryInterface;
24
25
/**
26
 * Import functions
27
 */
28
use function is_file;
29
30
/**
31
 * CollectableFileLoader
32
 */
33
class CollectableFileLoader implements LoaderInterface
34
{
35
36
    /**
37
     * @var string[]
38
     */
39
    private $resources = [];
40
41
    /**
42
     * @var RouteCollectionFactoryInterface
43
     */
44
    private $collectionFactory;
45
46
    /**
47
     * @var RouteFactoryInterface
48
     */
49
    private $routeFactory;
50
51
    /**
52
     * @param null|RouteCollectionFactoryInterface $collectionFactory
53
     * @param null|RouteFactoryInterface $routeFactory
54
     */
55 3
    public function __construct(
56
        RouteCollectionFactoryInterface $collectionFactory = null,
57
        RouteFactoryInterface $routeFactory = null
58
    ) {
59 3
        $this->collectionFactory = $collectionFactory ?? new RouteCollectionFactory();
60 3
        $this->routeFactory = $routeFactory ?? new RouteFactory();
61 3
    }
62
63
    /**
64
     * {@inheritDoc}
65
     */
66 2
    public function attach($resource) : void
67
    {
68 2
        if (!is_file($resource)) {
69 1
            throw (new ExceptionFactory)->invalidLoadResourceForFile($resource);
70
        }
71
72 1
        $this->resources[] = $resource;
73 1
    }
74
75
    /**
76
     * {@inheritDoc}
77
     */
78 1
    public function load() : RouteCollectionInterface
79
    {
80 1
        $collect = new RouteCollector(
81 1
            $this->collectionFactory,
82 1
            $this->routeFactory
83
        );
84
85 1
        foreach ($this->resources as $resource) {
86
            (function () use ($resource) {
87 1
                require $resource;
88 1
            })->call($collect);
89
        }
90
91 1
        return $collect->getCollection();
92
    }
93
}
94