Skip to content

[9.x] Unify trait set up/tear down and other hooks under a Hook implementation #39947

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 19 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/Illuminate/Console/Concerns/CreatesMatchingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,35 @@

namespace Illuminate\Console\Concerns;

use Illuminate\Support\Hooks\Hook;
use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputOption;

trait CreatesMatchingTest
{
/**
* Register "initialize" hook.
*
* @return \Illuminate\Support\Hooks\Hook
*/
public function registerCreatesMatchingTestInitializeHook(): Hook
{
return Hook::make('initialize', fn () => $this->addTestOptions());
}

/**
* Register "generate" hook.
*
* @return \Illuminate\Support\Hooks\Hook
*/
public function registerCreatesMatchingTestGenerateHook(): Hook
{
return Hook::make('generate', function ($name, $path) {
// We want to run test creation after generation, so we'll return a callback to execute at the end
return fn () => $this->handleTestCreation($path);
});
}

/**
* Add the standard command options for generating matching tests.
*
Expand Down
24 changes: 11 additions & 13 deletions src/Illuminate/Console/GeneratorCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

namespace Illuminate\Console;

use Illuminate\Console\Concerns\CreatesMatchingTest;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Hookable;
use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputArgument;

abstract class GeneratorCommand extends Command
{
use Hookable;

/**
* The filesystem instance.
*
Expand Down Expand Up @@ -109,11 +111,9 @@ public function __construct(Filesystem $files)
{
parent::__construct();

if (in_array(CreatesMatchingTest::class, class_uses_recursive($this))) {
$this->addTestOptions();
}

$this->files = $files;

$this->runHooks('initialize');
}

/**
Expand Down Expand Up @@ -156,18 +156,16 @@ public function handle()
return false;
}

// Next, we will generate the path to the location where this class' file should get
// Finally, we will generate the path to the location where this class' file should get
// written. Then, we will build the class and make the proper replacements on the
// stub files so that it gets the correctly formatted namespace and class name.
$this->makeDirectory($path);

$this->files->put($path, $this->sortImports($this->buildClass($name)));
$this->runHooks('generate', [$name, $path], function () use ($name, $path) {
$this->makeDirectory($path);

$this->info($this->type.' created successfully.');
$this->files->put($path, $this->sortImports($this->buildClass($name)));

if (in_array(CreatesMatchingTest::class, class_uses_recursive($this))) {
$this->handleTestCreation($path);
}
$this->info($this->type.' created successfully.');
});
}

/**
Expand Down
57 changes: 57 additions & 0 deletions src/Illuminate/Contracts/Support/Hook.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace Illuminate\Contracts\Support;

interface Hook
{
/**
* Indicates this hook should be run with higher priority.
*
* @var int
*/
public const PRIORITY_HIGH = 100;

/**
* Indicates this hook should be run with normal priority.
*
* @var int
*/
public const PRIORITY_NORMAL = 200;

/**
* Indicates this hook should be run with lower priority.
*
* @var int
*/
public const PRIORITY_LOW = 300;

/**
* Run the hook.
*
* @param object|string $instance
* @param array $arguments
*/
public function run($instance, array $arguments = []);

/**
* Clean up after the hook.
*
* @param object|string $instance
* @param array $arguments
*/
public function cleanup($instance, array $arguments = []);

/**
* Get the name of the hook.
*
* @return string
*/
public function getName();

/**
* Get the priority of the hook.
*
* @return int
*/
public function getPriority();
}
19 changes: 14 additions & 5 deletions src/Illuminate/Database/Console/Seeds/WithoutModelEvents.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,26 @@
namespace Illuminate\Database\Console\Seeds;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Events\NullDispatcher;
use Illuminate\Support\Hooks\Hook;

trait WithoutModelEvents
{
/**
* Prevent model events from being dispatched by the given callback.
* Prevent model events from being dispatched when the seeder is invoked.
*
* @param callable $callback
* @return callable
* @return Hook
*/
public function withoutModelEvents(callable $callback)
public static function withoutModelEvents(): Hook
{
return fn () => Model::withoutEvents($callback);
return Hook::make('run', function () {
if (! $dispatcher = Model::getEventDispatcher()) {
return null;
}

Model::setEventDispatcher(new NullDispatcher($dispatcher));

return fn () => Model::setEventDispatcher($dispatcher);
});
}
}
53 changes: 26 additions & 27 deletions src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection as BaseCollection;
use Illuminate\Support\Hookable;
use Illuminate\Support\Hooks\ConventionalHook;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\ForwardsCalls;
use JsonSerializable;
Expand All @@ -32,7 +34,8 @@ abstract class Model implements Arrayable, ArrayAccess, CanBeEscapedWhenCastToSt
Concerns\HasTimestamps,
Concerns\HidesAttributes,
Concerns\GuardsAttributes,
ForwardsCalls;
ForwardsCalls,
Hookable;

/**
* The connection name for the model.
Expand Down Expand Up @@ -252,36 +255,34 @@ protected static function boot()
static::bootTraits();
}

/**
* Register a conventions-based hook for boot[trait name] methods.
*
* @return \Illuminate\Support\Hooks\ConventionalHook
*/
public static function registerBootHook(): ConventionalHook
{
return new ConventionalHook('boot');
}

/**
* Register a conventions-based hook for initialize[trait name] methods.
*
* @return \Illuminate\Support\Hooks\ConventionalHook
*/
public static function registerInitializeHook(): ConventionalHook
{
return new ConventionalHook('initialize');
}

/**
* Boot all of the bootable traits on the model.
*
* @return void
*/
protected static function bootTraits()
{
$class = static::class;

$booted = [];

static::$traitInitializers[$class] = [];

foreach (class_uses_recursive($class) as $trait) {
$method = 'boot'.class_basename($trait);

if (method_exists($class, $method) && ! in_array($method, $booted)) {
forward_static_call([$class, $method]);

$booted[] = $method;
}

if (method_exists($class, $method = 'initialize'.class_basename($trait))) {
static::$traitInitializers[$class][] = $method;

static::$traitInitializers[$class] = array_unique(
static::$traitInitializers[$class]
);
}
}
static::runStaticHooks('boot');
}

/**
Expand All @@ -291,9 +292,7 @@ protected static function bootTraits()
*/
protected function initializeTraits()
{
foreach (static::$traitInitializers[static::class] as $method) {
$this->{$method}();
}
$this->runHooks('initialize');
}

/**
Expand Down
20 changes: 8 additions & 12 deletions src/Illuminate/Database/Seeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@

use Illuminate\Console\Command;
use Illuminate\Container\Container;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Support\Arr;
use Illuminate\Support\Hookable;
use InvalidArgumentException;

abstract class Seeder
{
use Hookable;

/**
* The container instance.
*
Expand Down Expand Up @@ -171,16 +173,10 @@ public function __invoke(array $parameters = [])
throw new InvalidArgumentException('Method [run] missing from '.get_class($this));
}

$callback = fn () => isset($this->container)
? $this->container->call([$this, 'run'], $parameters)
: $this->run(...$parameters);

$uses = array_flip(class_uses_recursive(static::class));

if (isset($uses[WithoutModelEvents::class])) {
$callback = $this->withoutModelEvents($callback);
}

return $callback();
return $this->runHooks('run', $this, function () use ($parameters) {
return isset($this->container)
? $this->container->call([$this, 'run'], $parameters)
: $this->run(...$parameters);
});
}
}
11 changes: 11 additions & 0 deletions src/Illuminate/Foundation/Testing/DatabaseMigrations.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,22 @@

use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\Traits\CanConfigureMigrationCommands;
use Illuminate\Support\Hooks\Hook;

trait DatabaseMigrations
{
use CanConfigureMigrationCommands;

/**
* Register test case hook.
*
* @return \Illuminate\Support\Hooks\Hook
*/
public function registerDatabaseMigrationsHook(): Hook
{
return new Hook('setUp', fn () => $this->runDatabaseMigrations(), 55);
}

/**
* Define hooks to migrate the database before and after each test.
*
Expand Down
12 changes: 12 additions & 0 deletions src/Illuminate/Foundation/Testing/DatabaseTransactions.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,20 @@

namespace Illuminate\Foundation\Testing;

use Illuminate\Support\Hooks\Hook;

trait DatabaseTransactions
{
/**
* Register test case hook.
*
* @return \Illuminate\Support\Hooks\Hook
*/
public function registerDatabaseTransactionsHook(): Hook
{
return new Hook('setUp', fn () => $this->beginDatabaseTransaction(), 60);
}

/**
* Handle database transactions on the specified connections.
*
Expand Down
11 changes: 11 additions & 0 deletions src/Illuminate/Foundation/Testing/RefreshDatabase.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,22 @@

use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\Traits\CanConfigureMigrationCommands;
use Illuminate\Support\Hooks\Hook;

trait RefreshDatabase
{
use CanConfigureMigrationCommands;

/**
* Register test case hook.
*
* @return \Illuminate\Support\Hooks\Hook
*/
public function registerRefreshDatabaseHook(): Hook
{
return new Hook('setUp', fn () => $this->refreshDatabase(), 50);
}

/**
* Define hooks to migrate the database before and after each test.
*
Expand Down
Loading