Passed
Pull Request — master (#3)
by Harry
03:37 queued 01:14
created

TablePopulator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of graze/sprout.
4
 *
5
 * Copyright (c) 2017 Nature Delivered Ltd. <https://www.graze.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license https://github.com/graze/sprout/blob/master/LICENSE.md
11
 * @link    https://github.com/graze/sprout
12
 */
13
14
namespace Graze\Sprout\Parser;
15
16
use League\Flysystem\AdapterInterface;
17
use SplFileInfo;
18
19
class TablePopulator
20
{
21
    /** @var AdapterInterface */
22
    private $filesystem;
23
24
    /**
25
     * SchemaParser constructor.
26
     *
27
     * @param AdapterInterface $filesystem
28
     */
29 4
    public function __construct(AdapterInterface $filesystem)
30
    {
31 4
        $this->filesystem = $filesystem;
32 4
    }
33
34
    /**
35
     * @param ParsedSchema $parsedSchema
36
     *
37
     * @return ParsedSchema|null
38
     */
39 4
    public function populateTables(ParsedSchema $parsedSchema)
40
    {
41 4
        if (count($parsedSchema->getTables()) === 0) {
42 3
            if ($this->filesystem->has($parsedSchema->getPath()) === false) {
43 1
                return null;
44
            }
45
46
            // find existing tables
47 2
            $files = $this->filesystem->listContents($parsedSchema->getPath());
48 2
            $files = array_values(array_filter(
49 2
                $files,
50 2
                function (SplFileInfo $file) {
51
                    // ignore empty file names (`.bla`) files
52 1
                    return ($file->getBasename('.' . $file->getExtension()) !== '');
53 2
                }
54
            ));
55
56
            // sort by file size, largest first
57 2
            usort(
58 2
                $files,
59 2
                function (SplFileInfo $a, SplFileInfo $b) {
60 1
                    $left = $a->getSize();
61 1
                    $right = $b->getSize();
62 1
                    return ($left == $right) ? 0 : (($left > $right) ? -1 : 1);
63 2
                }
64
            );
65
66
            // remove the file extensions to get the table names
67 2
            $parsedSchema->setTables(array_map(
68 2
                function (SplFileInfo $file) {
69 1
                    return $file->getBasename('.' . $file->getExtension());
70 2
                },
71 2
                $files
72
            ));
73
        }
74
75 3
        if (count($parsedSchema->getTables()) === 0) {
76 1
            return null;
77
        }
78
79 2
        return $parsedSchema;
80
    }
81
}
82