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

JsonParser::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Brendt\Stitcher\Parser;
4
5
use Brendt\Stitcher\Config;
6
use Brendt\Stitcher\Exception\ParserException;
7
use Brendt\Stitcher\Factory\ParserFactory;
8
use Symfony\Component\Finder\Finder;
9
use Symfony\Component\Finder\SplFileInfo;
10
11
/**
12
 * The JsonParser take a path to one or more JSON files, and parses the content into an array.
13
 */
14
class JsonParser extends AbstractArrayParser
15
{
16
    /**
17
     * @var string
18
     */
19
    private $srcDir;
20
21
    /**
22
     * JsonParser constructor.
23
     *
24
     * @param ParserFactory $parserFactory
25
     * @param string        $srcDir
26
     */
27
    public function __construct(ParserFactory $parserFactory, string $srcDir) {
28
        parent::__construct($parserFactory);
29
30
        $this->srcDir = $srcDir;
31
    }
32
33
    /**
34
     * @param string $path
35
     *
36
     * @return array
37
     * @throws ParserException
38
     */
39
    public function parse($path = '*.json') {
40
        if (!strpos($path, '.json')) {
41
            $path .= '.json';
42
        }
43
44
        $data = [];
45
        /** @var SplFileInfo[] $files */
46
        $files = Finder::create()->files()->in($this->srcDir)->path($path);
47
48
        foreach ($files as $file) {
49
            $parsed = json_decode($file->getContents(), true);
50
51
            if (json_last_error() > 0 && $error = json_last_error_msg()) {
52
                throw new ParserException("{$file->getRelativePathname()}: {$error}");
53
            }
54
55 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...
56
                $id = str_replace(".{$file->getExtension()}", '', $file->getFilename());
57
                $parsed = ['entries' => [$id => $parsed]];
58
            }
59
60
            $data += $parsed['entries'];
61
        }
62
63
        $data = $this->parseArrayData($data);
64
65
        return $data;
66
    }
67
68
}
69