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