Passed
Push — master ( c423ac...6bd0a6 )
by Enjoys
10:06
created

Parse::applyValueHandlers()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 8
rs 10
ccs 0
cts 0
cp 0
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Enjoys\Config;
6
7
use Enjoys\Config\ValueHandler\DefinedConstantsValueHandler;
8
use Enjoys\Config\ValueHandler\EnvValueHandler;
9
use Enjoys\Traits\Options;
10
use Psr\Log\LoggerInterface;
11
use Psr\Log\NullLogger;
12
13
/**
14
 * Description of Parse
15
 * @author Enjoys
16
 */
17
abstract class Parse implements ParseInterface
18
{
19
    use Options;
20
21
    private ?string $configSource = null;
22 22
    protected LoggerInterface $logger;
23
24 22
    private array $valueHandlers = [
25
        EnvValueHandler::class,
26
        DefinedConstantsValueHandler::class
27 14
    ];
28
29 14
    public function __construct()
30
    {
31
        $this->logger = new NullLogger();
32 21
    }
33
34 21
    public function setLogger(LoggerInterface $logger)
35
    {
36
        $this->logger = $logger;
37
    }
38
39
    public function addConfigSource(string $source): void
40 22
    {
41
        $this->configSource = $source;
42 22
    }
43 1
44 1
    /**
45
     * @return array|false|null
46
     */
47 21
    public function parse()
48 16
    {
49
        if (is_null($this->configSource)) {
50
            $this->logger->notice('Add data for parsing');
51 5
            return null;
52
        }
53
54
        if (!is_file($this->configSource)) {
55
            return $this->parseString($this->applyValueHandlers($this->configSource));
56
        }
57
58
        return $this->parseFile($this->configSource);
59
    }
60
61
    /**
62
     * @param string $data
63
     * @return string
64
     */
65
    private function applyValueHandlers($data)
66
    {
67
        /** @var class-string<ValueHandlerInterface> $valueHandler */
68
        foreach ($this->valueHandlers as $valueHandler) {
69
            $data = (new $valueHandler())->handle($data);
70
        }
71
      //  var_dump($data);
72
        return $data;
73
    }
74
75
    /**
76
     * @param string $filename
77
     * @return array|null|false
78
     */
79
    private function parseFile(string $filename)
80
    {
81
        $data = file_get_contents($filename);
82
        return $this->parseString($this->applyValueHandlers($data));
83
    }
84
85
    /**
86
     * @param string $input
87
     * @return array|null|false
88
     */
89
    abstract protected function parseString(string $input);
90
91
92
}
93