Passed
Push — master ( 6bd0a6...8635a1 )
by Enjoys
01:43
created

Parse   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 21
c 2
b 0
f 0
dl 0
loc 69
ccs 20
cts 20
cp 1
rs 10
wmc 9

6 Methods

Rating   Name   Duplication   Size   Complexity  
A parse() 0 12 3
A addConfigSource() 0 3 1
A setLogger() 0 3 1
A __construct() 0 3 1
A applyValueHandlers() 0 8 2
A parseFile() 0 4 1
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
    protected LoggerInterface $logger;
23
24
    private array $valueHandlers = [
25
        EnvValueHandler::class,
26
        DefinedConstantsValueHandler::class
27
    ];
28
29 23
    public function __construct()
30
    {
31 23
        $this->logger = new NullLogger();
32
    }
33
34 15
    public function setLogger(LoggerInterface $logger)
35
    {
36 15
        $this->logger = $logger;
37
    }
38
39 22
    public function addConfigSource(string $source): void
40
    {
41 22
        $this->configSource = $source;
42
    }
43
44
    /**
45
     * @return array|false|null
46
     */
47 23
    public function parse()
48
    {
49 23
        if (is_null($this->configSource)) {
50 1
            $this->logger->notice('Add data for parsing');
51 1
            return null;
52
        }
53
54 22
        if (!is_file($this->configSource)) {
55 17
            return $this->parseString($this->applyValueHandlers($this->configSource));
56
        }
57
58 5
        return $this->parseFile($this->configSource);
59
    }
60
61 22
    private function applyValueHandlers(string $data): string
62
    {
63
        /** @var class-string<ValueHandlerInterface> $valueHandler */
64 22
        foreach ($this->valueHandlers as $valueHandler) {
65 22
            $data = (new $valueHandler())->handle($data);
66
        }
67
      //  var_dump($data);
68 22
        return $data;
69
    }
70
71
    /**
72
     * @param string $filename
73
     * @return array|null|false
74
     */
75 5
    private function parseFile(string $filename)
76
    {
77 5
        $data = file_get_contents($filename);
78 5
        return $this->parseString($this->applyValueHandlers($data));
79
    }
80
81
    /**
82
     * @param string $input
83
     * @return array|null|false
84
     */
85
    abstract protected function parseString(string $input);
86
87
88
}
89