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
|
|
|
|
18
|
|
|
class TablePopulator |
19
|
|
|
{ |
20
|
|
|
/** @var AdapterInterface */ |
21
|
|
|
private $filesystem; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* SchemaParser constructor. |
25
|
|
|
* |
26
|
|
|
* @param AdapterInterface $filesystem |
27
|
|
|
*/ |
28
|
4 |
|
public function __construct(AdapterInterface $filesystem) |
29
|
|
|
{ |
30
|
4 |
|
$this->filesystem = $filesystem; |
31
|
4 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param ParsedSchema $parsedSchema |
35
|
|
|
* |
36
|
|
|
* @return ParsedSchema|null |
37
|
|
|
*/ |
38
|
4 |
|
public function populateTables(ParsedSchema $parsedSchema) |
39
|
|
|
{ |
40
|
4 |
|
if (count($parsedSchema->getTables()) === 0) { |
41
|
3 |
|
if ($this->filesystem->has($parsedSchema->getPath()) === false) { |
42
|
1 |
|
return null; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
// find existing tables |
46
|
2 |
|
$files = $this->filesystem->listContents($parsedSchema->getPath()); |
47
|
2 |
|
$files = array_values(array_filter( |
48
|
2 |
|
$files, |
49
|
2 |
|
function (array $file) { |
50
|
|
|
// ignore empty file names (`.bla`) files |
51
|
1 |
|
return (pathinfo($file['path'], PATHINFO_FILENAME) !== ''); |
52
|
2 |
|
} |
53
|
|
|
)); |
54
|
|
|
|
55
|
|
|
// sort by file size, largest first |
56
|
2 |
|
usort( |
57
|
2 |
|
$files, |
58
|
2 |
|
function (array $a, array $b) { |
59
|
1 |
|
return ($a['size'] == $b['size']) ? 0 : (($a['size'] > $b['size']) ? -1 : 1); |
60
|
2 |
|
} |
61
|
|
|
); |
62
|
|
|
|
63
|
|
|
// remove the file extensions to get the table names |
64
|
2 |
|
$parsedSchema->setTables(array_map( |
65
|
2 |
|
function (array $file) { |
66
|
1 |
|
return pathinfo($file['path'], PATHINFO_FILENAME); |
67
|
2 |
|
}, |
68
|
2 |
|
$files |
69
|
|
|
)); |
70
|
|
|
} |
71
|
|
|
|
72
|
3 |
|
if (count($parsedSchema->getTables()) === 0) { |
73
|
1 |
|
return null; |
74
|
|
|
} |
75
|
|
|
|
76
|
2 |
|
return $parsedSchema; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|