3
declare(strict_types=1);
6
* This file is part of CodeIgniter 4 framework.
8
* (c) CodeIgniter Foundation <admin@codeigniter.com>
10
* For the full copyright and license information, please view
11
* the LICENSE file that was distributed with this source code.
14
namespace CodeIgniter\Database;
16
use CodeIgniter\CLI\CLI;
20
use InvalidArgumentException;
28
* The name of the database group to use.
30
* @var non-empty-string
35
* Where we can find the Seed files.
42
* An instance of the main Database configuration
49
* Database Connection instance
56
* Database Forge instance.
63
* If true, will not display CLI messages.
67
protected $silent = false;
70
* Faker Generator instance.
74
private static ?Generator $faker = null;
79
public function __construct(Database $config, ?BaseConnection $db = null)
81
$this->seedPath = $config->filesPath ?? APPPATH . 'Database/';
83
if ($this->seedPath === '') {
84
throw new InvalidArgumentException('Invalid filesPath set in the Config\Database.');
87
$this->seedPath = rtrim($this->seedPath, '\\/') . '/Seeds/';
89
if (! is_dir($this->seedPath)) {
90
throw new InvalidArgumentException('Unable to locate the seeds directory. Please check Config\Database::filesPath');
93
$this->config = &$config;
95
$db ??= Database::connect($this->DBGroup);
98
$this->forge = Database::forge($this->DBGroup);
102
* Gets the Faker Generator instance.
106
public static function faker(): ?Generator
108
if (self::$faker === null && class_exists(Factory::class)) {
109
self::$faker = Factory::create();
116
* Loads the specified seeder and runs it.
118
* @throws InvalidArgumentException
120
public function call(string $class)
122
$class = trim($class);
125
throw new InvalidArgumentException('No seeder was specified.');
128
if (! str_contains($class, '\\')) {
129
$path = $this->seedPath . str_replace('.php', '', $class) . '.php';
131
if (! is_file($path)) {
132
throw new InvalidArgumentException('The specified seeder is not a valid file: ' . $path);
135
// Assume the class has the correct namespace
136
// @codeCoverageIgnoreStart
137
$class = APP_NAMESPACE . '\Database\Seeds\\' . $class;
139
if (! class_exists($class, false)) {
142
// @codeCoverageIgnoreEnd
145
/** @var Seeder $seeder */
146
$seeder = new $class($this->config);
147
$seeder->setSilent($this->silent)->run();
151
if (is_cli() && ! $this->silent) {
152
CLI::write("Seeded: {$class}", 'green');
157
* Sets the location of the directory that seed files can be located in.
161
public function setPath(string $path)
163
$this->seedPath = rtrim($path, '\\/') . '/';
169
* Sets the silent treatment.
173
public function setSilent(bool $silent)
175
$this->silent = $silent;
181
* Run the database seeds. This is where the magic happens.
183
* Child classes must implement this method and take care
184
* of inserting their data here.
188
* @codeCoverageIgnore
190
public function run()