ci4

Форк
0
/
Seeder.php 
193 строки · 4.1 Кб
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace CodeIgniter\Database;
15

16
use CodeIgniter\CLI\CLI;
17
use Config\Database;
18
use Faker\Factory;
19
use Faker\Generator;
20
use InvalidArgumentException;
21

22
/**
23
 * Class Seeder
24
 */
25
class Seeder
26
{
27
    /**
28
     * The name of the database group to use.
29
     *
30
     * @var non-empty-string
31
     */
32
    protected $DBGroup;
33

34
    /**
35
     * Where we can find the Seed files.
36
     *
37
     * @var string
38
     */
39
    protected $seedPath;
40

41
    /**
42
     * An instance of the main Database configuration
43
     *
44
     * @var Database
45
     */
46
    protected $config;
47

48
    /**
49
     * Database Connection instance
50
     *
51
     * @var BaseConnection
52
     */
53
    protected $db;
54

55
    /**
56
     * Database Forge instance.
57
     *
58
     * @var Forge
59
     */
60
    protected $forge;
61

62
    /**
63
     * If true, will not display CLI messages.
64
     *
65
     * @var bool
66
     */
67
    protected $silent = false;
68

69
    /**
70
     * Faker Generator instance.
71
     *
72
     * @deprecated
73
     */
74
    private static ?Generator $faker = null;
75

76
    /**
77
     * Seeder constructor.
78
     */
79
    public function __construct(Database $config, ?BaseConnection $db = null)
80
    {
81
        $this->seedPath = $config->filesPath ?? APPPATH . 'Database/';
82

83
        if ($this->seedPath === '') {
84
            throw new InvalidArgumentException('Invalid filesPath set in the Config\Database.');
85
        }
86

87
        $this->seedPath = rtrim($this->seedPath, '\\/') . '/Seeds/';
88

89
        if (! is_dir($this->seedPath)) {
90
            throw new InvalidArgumentException('Unable to locate the seeds directory. Please check Config\Database::filesPath');
91
        }
92

93
        $this->config = &$config;
94

95
        $db ??= Database::connect($this->DBGroup);
96

97
        $this->db    = $db;
98
        $this->forge = Database::forge($this->DBGroup);
99
    }
100

101
    /**
102
     * Gets the Faker Generator instance.
103
     *
104
     * @deprecated
105
     */
106
    public static function faker(): ?Generator
107
    {
108
        if (self::$faker === null && class_exists(Factory::class)) {
109
            self::$faker = Factory::create();
110
        }
111

112
        return self::$faker;
113
    }
114

115
    /**
116
     * Loads the specified seeder and runs it.
117
     *
118
     * @throws InvalidArgumentException
119
     */
120
    public function call(string $class)
121
    {
122
        $class = trim($class);
123

124
        if ($class === '') {
125
            throw new InvalidArgumentException('No seeder was specified.');
126
        }
127

128
        if (! str_contains($class, '\\')) {
129
            $path = $this->seedPath . str_replace('.php', '', $class) . '.php';
130

131
            if (! is_file($path)) {
132
                throw new InvalidArgumentException('The specified seeder is not a valid file: ' . $path);
133
            }
134

135
            // Assume the class has the correct namespace
136
            // @codeCoverageIgnoreStart
137
            $class = APP_NAMESPACE . '\Database\Seeds\\' . $class;
138

139
            if (! class_exists($class, false)) {
140
                require_once $path;
141
            }
142
            // @codeCoverageIgnoreEnd
143
        }
144

145
        /** @var Seeder $seeder */
146
        $seeder = new $class($this->config);
147
        $seeder->setSilent($this->silent)->run();
148

149
        unset($seeder);
150

151
        if (is_cli() && ! $this->silent) {
152
            CLI::write("Seeded: {$class}", 'green');
153
        }
154
    }
155

156
    /**
157
     * Sets the location of the directory that seed files can be located in.
158
     *
159
     * @return $this
160
     */
161
    public function setPath(string $path)
162
    {
163
        $this->seedPath = rtrim($path, '\\/') . '/';
164

165
        return $this;
166
    }
167

168
    /**
169
     * Sets the silent treatment.
170
     *
171
     * @return $this
172
     */
173
    public function setSilent(bool $silent)
174
    {
175
        $this->silent = $silent;
176

177
        return $this;
178
    }
179

180
    /**
181
     * Run the database seeds. This is where the magic happens.
182
     *
183
     * Child classes must implement this method and take care
184
     * of inserting their data here.
185
     *
186
     * @return void
187
     *
188
     * @codeCoverageIgnore
189
     */
190
    public function run()
191
    {
192
    }
193
}
194

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.