Test Failed
Pull Request — master (#31)
by Keoghan
04:32 queued 01:26
created

ImageSetRepository::getImageRepository()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 10
ccs 5
cts 6
cp 0.8333
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3.0416
1
<?php
2
3
namespace App\Support\Images;
4
5
use App\Support\Contracts\ImageSetRepository as ImageSetRepositoryContract;
6
use Symfony\Component\Finder\Finder;
7
use Symfony\Component\Finder\SplFileInfo;
8
9
class ImageSetRepository implements ImageSetRepositoryContract
10
{
11
    protected $locations = [];
12
13
    /**
14
     * ImageSetRepository constructor.
15
     * Accepts a set of locations, or a singular one.
16
     *
17
     * @param $location
18
     */
19 65
    public function __construct($location)
20
    {
21 65
        $this->addLocation($location);
22 65
    }
23
24
    /**
25
     * Add a location for the where we may find docker files.
26
     *
27
     * @param $location
28
     *
29
     * @return ImageSetRepository
30
     */
31 65
    public function addLocation($location)
32
    {
33 65
        if (!is_array($location)) {
34 3
            $location = [$location];
35
        }
36
37 65
        $this->locations = array_unique(array_merge($this->locations, $location));
38
39 65
        return $this;
40
    }
41
42
    /**
43
     * Get an image repository using the most recently added locations first.
44
     *
45
     * @param $imageSetName
46
     *
47
     * @throws \Exception
48
     *
49
     * @return ImageRepository
50
     */
51 2
    public function getImageRepository($imageSetName)
52
    {
53 2
        foreach (array_reverse($this->locations) as $location) {
54 2
            $path = $location.'/'.$imageSetName;
55 2
            if (is_dir($path)) {
56 2
                return new ImageRepository($path, $imageSetName);
57
            }
58
        }
59
60
        throw new \Exception("Image Set {$imageSetName} not located.");
61
    }
62
63
    /**
64
     * Return a list of the available ImageSets.
65
     *
66
     * @return \Illuminate\Support\Collection
67
     */
68 1
    public function availableImageSets()
69
    {
70 1
        return collect($this->locations)
71
            ->flatMap(function ($location) {
72
                try {
73 1
                    return iterator_to_array(
74 1
                        Finder::create()->in($location)->depth(1)->directories()
75
                    );
76
                } catch (\InvalidArgumentException $e) {
77
                    return;
78
                }
79 1
            })->filter()
80
            ->map(function (SplFileInfo $directory) {
81 1
                return $directory->getRelativePathname();
82 1
            })->unique();
83
    }
84
}
85