1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yarak\DB\Seeders; |
4
|
|
|
|
5
|
|
|
use Yarak\Config\Config; |
6
|
|
|
use Yarak\Output\Output; |
7
|
|
|
use Yarak\Exceptions\FileNotFound; |
8
|
|
|
|
9
|
|
|
class SeedRunner |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* If true, seeders have been required. |
13
|
|
|
* |
14
|
|
|
* @var bool |
15
|
|
|
*/ |
16
|
|
|
protected $loaded = false; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Output strategy. |
20
|
|
|
* |
21
|
|
|
* @var Output |
22
|
|
|
*/ |
23
|
|
|
protected $output; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Construct. |
27
|
|
|
* |
28
|
|
|
* @param Output $output |
29
|
|
|
*/ |
30
|
|
|
public function __construct(Output $output) |
31
|
|
|
{ |
32
|
|
|
$this->output = $output; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Run the given seeder class. |
37
|
|
|
* |
38
|
|
|
* @param string $class |
39
|
|
|
*/ |
40
|
|
|
public function run($class) |
41
|
|
|
{ |
42
|
|
|
$config = Config::getInstance(); |
43
|
|
|
|
44
|
|
|
$this->loadSeeders($config); |
45
|
|
|
|
46
|
|
|
$seederClass = $this->resolveSeeder($config, $class); |
47
|
|
|
|
48
|
|
|
$seederClass->setRunner($this)->setOutput($this->output); |
49
|
|
|
|
50
|
|
|
$this->output->writeInfo("Running seeder class {$class}."); |
51
|
|
|
|
52
|
|
|
$seederClass->run(); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Load all the seeders in the seeders directory. |
57
|
|
|
* |
58
|
|
|
* @param Config $config |
59
|
|
|
*/ |
60
|
|
|
protected function loadSeeders(Config $config) |
61
|
|
|
{ |
62
|
|
|
if (!$this->loaded) { |
63
|
|
|
$seedPath = $config->getSeedDirectory(); |
64
|
|
|
|
65
|
|
|
$files = scandir($seedPath); |
66
|
|
|
|
67
|
|
|
$files = array_filter($files, function ($file) { |
68
|
|
|
return strpos($file, '.php') !== false; |
69
|
|
|
}); |
70
|
|
|
|
71
|
|
|
foreach ($files as $file) { |
72
|
|
|
require_once $seedPath.$file; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
$this->loaded = true; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* Resolve the given seeder class. |
81
|
|
|
* |
82
|
|
|
* @param Config $config |
83
|
|
|
* @param string $class |
84
|
|
|
* |
85
|
|
|
* @return Seeder |
86
|
|
|
*/ |
87
|
|
|
protected function resolveSeeder(Config $config, $class) |
88
|
|
|
{ |
89
|
|
|
if (!class_exists($class)) { |
90
|
|
|
$path = $config->getSeedDirectory(); |
91
|
|
|
|
92
|
|
|
throw FileNotFound::seederNotFound($class, $path); |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
return new $class(); |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|