Seed.php 5.44 KB
Newer Older
冯超鹏's avatar
冯超鹏 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace Hyperf\Database\Seeders;

use Hyperf\Database\Connection;
use Hyperf\Database\ConnectionResolverInterface as Resolver;
use Hyperf\Database\Model\Model;
use Hyperf\Database\Schema\Grammars\Grammar;
use Hyperf\Utils\Collection;
use Hyperf\Utils\Filesystem\Filesystem;
use Hyperf\Utils\Str;
use Symfony\Component\Console\Output\OutputInterface;

class Seed
{
    /**
     * The filesystem instance.
     *
     * @var \Hyperf\Utils\Filesystem\Filesystem
     */
    protected $files;

    /**
     * The connection resolver instance.
     *
     * @var \Hyperf\Database\ConnectionResolverInterface
     */
    protected $resolver;

    /**
     * The name of the default connection.
     *
     * @var string
     */
    protected $connection;

    /**
     * The paths to all of the seeder files.
     *
     * @var array
     */
    protected $paths = [];

    /**
     * The output interface implementation.
     *
     * @var OutputInterface
     */
    protected $output;

    /**
     * Create a new seed instance.
     */
    public function __construct(Resolver $resolver, Filesystem $files)
    {
        $this->files = $files;
        $this->resolver = $resolver;
    }

    /**
     * Run the pending seeders at a given path.
     *
     * @param array|string $paths
     * @return array
     */
    public function run($paths = [], array $options = [])
    {
        $files = $this->getSeederFiles($paths);

        $this->requireFiles($files);

        $this->runSeeders($files, $options);

        return $files;
    }

    /**
     * Set the default connection name.
     */
    public function setConnection(string $name): void
    {
        if (! is_null($name)) {
            $this->resolver->setDefaultConnection($name);
        }

        $this->connection = $name;
    }

    /**
     * Run an array of seeders.
     */
    public function runSeeders(array $seeders, array $options = [])
    {
        if (count($seeders) === 0) {
            return;
        }

        foreach ($seeders as $file) {
            $this->runSeeder($file);
        }
    }

    /**
     * Run a seeder.
     *
     * @param string $file
     */
    public function runSeeder($file)
    {
        Model::unguarded(function () use ($file) {
            $seeder = $this->resolve(
                $name = $this->getSeederName($file)
            );

            $this->note("<comment>Seed:</comment> {$name}");

            $connection = $this->resolveConnection(
                $seeder->getConnection()
            );

            $callback = function () use ($seeder) {
                if (method_exists($seeder, 'run')) {
                    $seeder->run();
                }
            };

            if ($this->getSchemaGrammar($connection)->supportsSchemaTransactions() && $seeder->withinTransaction) {
                $connection->transaction($callback);
            } else {
                $callback();
            }

            $this->note("<info>Seeded:</info> {$name}");
        });
    }

    /**
     * Resolve a seeder instance from a file.
     */
    public function resolve(string $file): object
    {
        $class = Str::studly($file);

        return new $class();
    }

    /**
     * Resolve the database connection instance.
     *
     * @return Connection
     */
    public function resolveConnection(string $connection)
    {
        return $this->resolver->connection($connection ?: $this->connection);
    }

    /**
     * Get all of the seeder files in a given path.
     *
     * @param array|string $paths
     * @return array
     */
    public function getSeederFiles($paths)
    {
        return Collection::make($paths)->flatMap(function ($path) {
            return Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path . '/*.php');
        })->filter()->sortBy(function ($file) {
            return $this->getSeederName($file);
        })->values()->keyBy(function ($file) {
            return $this->getSeederName($file);
        })->all();
    }

    /**
     * Get the name of the seeder.
     *
     * @param string $path
     * @return string
     */
    public function getSeederName($path)
    {
        return str_replace('.php', '', basename($path));
    }

    /**
     * Require in all the seeder files in a given path.
     */
    public function requireFiles(array $files)
    {
        foreach ($files as $file) {
            $this->files->requireOnce($file);
        }
    }

    /**
     * Set the output implementation that should be used by the console.
     *
     * @return $this
     */
    public function setOutput(OutputInterface $output)
    {
        $this->output = $output;

        return $this;
    }

    /**
     * Get the schema grammar out of a migration connection.
     *
     * @param Connection $connection
     */
    protected function getSchemaGrammar($connection): Grammar
    {
        if (is_null($grammar = $connection->getSchemaGrammar())) {
            $connection->useDefaultSchemaGrammar();

            $grammar = $connection->getSchemaGrammar();
        }

        return $grammar;
    }

    /**
     * Write a note to the console's output.
     *
     * @param string $message
     */
    protected function note($message)
    {
        if ($this->output) {
            $this->output->writeln($message);
        }
    }
}