Completed
Push — master ( 305296...60efc6 )
by Carsten
03:28 queued 01:50
created

YamlFileParserCallable::__invoke()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 33
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 16
cts 16
cp 1
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 17
nc 3
nop 2
crap 3
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 11
    public function __construct( Finder $finder, $default_yaml_flags = 0, LoggerInterface $logger = null)
37
    {
38 11
        $this->finder = $finder;
39 11
        $this->default_yaml_flags = $default_yaml_flags;
40 11
        $this->logger = $logger ?: new NullLogger;
41 11
    }
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 6
    public function __invoke( $yaml_file, $yaml_flags = null )
50
    {
51 6
        $finder = clone $this->finder;
52 6
        $finder = $finder->files()->name( $yaml_file );
53
54
        // If there's no such file
55 6
        if (!iterator_count($finder)):
56 2
            $this->logger->debug("Could not find YAML file", [
57
                'file' => $yaml_file
58 2
            ]);
59 2
            return null;
60
        endif;
61
62
        // Reset finder instance
63 4
        $iterator = $finder->getIterator();
64 4
        $iterator->rewind();
65
66
        // Retrieve first item
67 4
        $file = $iterator->current();
68 4
        $yaml_content = $file->getContents();
69
70
        // How to parse
71 4
        $flags = is_integer($yaml_flags) ? $yaml_flags : $this->default_yaml_flags;
72
73
        // Some info
74 4
        $this->logger->info("Parse YAML file " . $file->getFilename(), [
75 4
            'file' => $file->getPathname(),
76
            'flags' => $flags
77 4
        ]);
78
79
        // Parse and return
80 4
        return Yaml::parse($yaml_content, $flags);
81
    }
82
}
83