Passed
Push — master ( 003724...f241d1 )
by Brent
02:47
created

YamlParser::parse()   B

Complexity

Conditions 5
Paths 14

Size

Total Lines 28
Code Lines 16

Duplication

Lines 4
Ratio 14.29 %

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 14
nop 1
dl 4
loc 28
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace Brendt\Stitcher\Parser;
4
5
use Brendt\Stitcher\Exception\ParserException;
6
use Brendt\Stitcher\Factory\ParserFactory;
7
use Symfony\Component\Finder\Finder;
8
use Symfony\Component\Finder\SplFileInfo;
9
use Symfony\Component\Yaml\Exception\ParseException;
10
use Symfony\Component\Yaml\Yaml;
11
use Brendt\Stitcher\Config;
12
13
/**
14
 * The YamlParser take a path to one or more YAML files, and parses the content into an array.
15
 *
16
 * @see \Brendt\Stitcher\Parser\AbstractArrayParser::parseArrayData()
17
 */
18
class YamlParser extends AbstractArrayParser
19
{
20
    /**
21
     * @var string
22
     */
23
    private $srcDir;
24
25
    /**
26
     * JsonParser constructor.
27
     *
28
     * @param ParserFactory $parserFactory
29
     * @param string        $srcDir
30
     */
31
    public function __construct(ParserFactory $parserFactory, string $srcDir) {
32
        parent::__construct($parserFactory);
33
34
        $this->srcDir = $srcDir;
35
    }
36
37
    /**
38
     * @param string $path
39
     *
40
     * @return mixed
41
     * @throws ParserException
42
     */
43
    public function parse($path = '*.yml') {
44
        if (!strpos($path, '.yml')) {
45
            $path .= '.yml';
46
        }
47
48
        /** @var SplFileInfo[] $files */
49
        $files = Finder::create()->files()->in($this->srcDir)->path($path);
50
        $data = [];
51
52
        foreach ($files as $file) {
53
            try {
54
                $parsed = Yaml::parse($file->getContents());
55
56 View Code Duplication
                if (!isset($parsed['entries'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
57
                    $id = str_replace(".{$file->getExtension()}", '', $file->getFilename());
58
                    $parsed = ['entries' => [$id => $parsed]];
59
                }
60
61
                $data += $parsed['entries'];
62
            } catch (ParseException $e) {
63
                throw new ParserException("{$file->getRelativePathname()}: {$e->getMessage()}");
64
            }
65
        }
66
67
        $parsedEntries = $this->parseArrayData($data);
68
69
        return $parsedEntries;
70
    }
71
72
}
73