Passed
Push — master ( 676110...9cfebc )
by Daniel
02:12
created

ConfigurationLoader::loadRaw()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 10
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Dandelion\Configuration;
6
7
use Dandelion\Exception\InvalidTypeException;
8
use Dandelion\Exception\IOException;
9
use Dandelion\Filesystem\FilesystemInterface;
10
use Symfony\Component\Serializer\SerializerInterface;
11
12
use function is_object;
13
14
class ConfigurationLoader implements ConfigurationLoaderInterface
15
{
16
    /**
17
     * @var \Dandelion\Configuration\ConfigurationFinderInterface
18
     */
19
    protected $configurationFinder;
20
21
    /**
22
     * @var \Dandelion\Filesystem\FilesystemInterface
23
     */
24
    protected $filesystem;
25
26
    /**
27
     * @var \Symfony\Component\Serializer\SerializerInterface
28
     */
29
    protected $serializer;
30
31
    /**
32
     * @param \Dandelion\Configuration\ConfigurationFinderInterface $configurationFinder
33
     * @param \Dandelion\Filesystem\FilesystemInterface $filesystem
34
     * @param \Symfony\Component\Serializer\SerializerInterface $serializer
35
     */
36
    public function __construct(
37
        ConfigurationFinderInterface $configurationFinder,
38
        FilesystemInterface $filesystem,
39
        SerializerInterface $serializer
40
    ) {
41
        $this->configurationFinder = $configurationFinder;
42
        $this->filesystem = $filesystem;
43
        $this->serializer = $serializer;
44
    }
45
46
    /**
47
     * @return \Dandelion\Configuration\Configuration
48
     *
49
     * @throws \Dandelion\Exception\InvalidTypeException
50
     * @throws \Dandelion\Exception\IOException
51
     */
52
    public function load(): Configuration
53
    {
54
        $configurationFileContent = $this->loadRaw();
55
56
        $configuration = $this->serializer->deserialize(
57
            $configurationFileContent,
58
            Configuration::class,
59
            'json'
60
        );
61
62
        if (!is_object($configuration) || !($configuration instanceof Configuration)) {
63
            throw new InvalidTypeException('Invalid type of deserialized data.');
64
        }
65
66
        return $configuration;
67
    }
68
69
    /**
70
     * @return string
71
     *
72
     * @throws \Dandelion\Exception\IOException
73
     */
74
    public function loadRaw(): string
75
    {
76
        $configurationFile = $this->configurationFinder->find();
77
        $realPathToConfigurationFile = $configurationFile->getRealPath();
78
79
        if ($realPathToConfigurationFile === false) {
80
            throw new IOException('Configuration file does not exists.');
81
        }
82
83
        return $this->filesystem->readFile($realPathToConfigurationFile);
84
    }
85
}
86