YamlFileParserCallable::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 2
1
<?php
2
namespace Germania\YamlServices;
3
4
use Symfony\Component\Yaml\Yaml;
5
use Symfony\Component\Finder\Finder;
6
use Psr\Log\LoggerInterface;
7
use Psr\Log\NullLogger;
8
9
class YamlFileParserCallable
10
{
11
12
13
    /**
14
     * @var integer
15
     */
16
    public $default_yaml_flags = 0;
17
18
19
    /**
20
     * @var Finder
21
     */
22
    public $finder;
23
24
25
    /**
26
     * @var LoggerInterface
27
     */
28
    public $logger;
29
30
31
    /**
32
     * @param Finder  $finder             Symfony Finder instance
33
     * @param integer $default_yaml_flags Default parsing flags, if needed.
34
     * @param LoggerInterface $logger     Optional PSR3 Logger
35
     */
36 55
    public function __construct( Finder $finder, $default_yaml_flags = 0, LoggerInterface $logger = null)
37
    {
38 55
        $this->finder = $finder;
39 55
        $this->default_yaml_flags = $default_yaml_flags;
40 55
        $this->logger = $logger ?: new NullLogger;
41 55
    }
42
43
44
    /**
45
     * @param  string   $yaml_file    The YAML file to parse
46
     * @param  int|null $yaml_flags   Custom YAML flags
47
     * @return string
48
     */
49 30
    public function __invoke( $yaml_file, $yaml_flags = null )
50
    {
51 30
        $finder = clone $this->finder;
52 30
        $finder = $finder->files()->name( $yaml_file );
53
54
        // If there's no such file
55 30
        if (!iterator_count($finder)):
56 10
            $this->logger->debug("Could not find YAML file", [
57 8
                'file' => $yaml_file
58 2
            ]);
59 10
            return null;
60
        endif;
61
62
        // Reset finder instance
63 20
        $iterator = $finder->getIterator();
64 20
        $iterator->rewind();
65
66
        // Retrieve first item
67 20
        $file = $iterator->current();
68 20
        $yaml_content = $file->getContents();
69
70
        // How to parse
71 20
        $flags = is_integer($yaml_flags) ? $yaml_flags : $this->default_yaml_flags;
72
73
        // Some info
74 20
        $this->logger->info("Parse YAML file " . $file->getFilename(), [
75 20
            'file' => $file->getPathname(),
76 16
            'flags' => $flags
77 4
        ]);
78
79
        // Parse and return
80 20
        return Yaml::parse($yaml_content, $flags);
81
    }
82
}
83