From fa446dc78a17aaf922585a9b25b804181a451914 Mon Sep 17 00:00:00 2001 From: Kevin Bui Date: Thu, 4 Jan 2024 01:12:01 +1100 Subject: [PATCH] [10.x] Make the Schema Builder macroable (#49547) * make the schema builder macroable * stop passing the parameter to the closure. --- src/Illuminate/Database/Schema/Builder.php | 3 ++ .../Database/SchemaBuilderTest.php | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/Illuminate/Database/Schema/Builder.php b/src/Illuminate/Database/Schema/Builder.php index c4b3da940265..770c6c52655c 100755 --- a/src/Illuminate/Database/Schema/Builder.php +++ b/src/Illuminate/Database/Schema/Builder.php @@ -5,11 +5,14 @@ use Closure; use Illuminate\Container\Container; use Illuminate\Database\Connection; +use Illuminate\Support\Traits\Macroable; use InvalidArgumentException; use LogicException; class Builder { + use Macroable; + /** * The database connection instance. * diff --git a/tests/Integration/Database/SchemaBuilderTest.php b/tests/Integration/Database/SchemaBuilderTest.php index 7f3c8546881f..fbd42e13c489 100644 --- a/tests/Integration/Database/SchemaBuilderTest.php +++ b/tests/Integration/Database/SchemaBuilderTest.php @@ -384,4 +384,33 @@ public function testSystemVersionedTables() DB::statement('create table `test` (`foo` int) WITH system versioning;'); } + + public function testAddingMacros() + { + Schema::macro('foo', fn () => 'foo'); + + $this->assertEquals('foo', Schema::foo()); + + Schema::macro('hasForeignKeyForColumn', function (string $column, string $table, string $foreignTable) { + return collect(Schema::getForeignKeys($table)) + ->contains(function (array $foreignKey) use ($column, $foreignTable) { + return collect($foreignKey['columns'])->contains($column) + && $foreignKey['foreign_table'] == $foreignTable; + }); + }); + + Schema::create('questions', function (Blueprint $table) { + $table->id(); + $table->string('body'); + }); + + Schema::create('answers', function (Blueprint $table) { + $table->id(); + $table->string('body'); + $table->foreignId('question_id')->constrained(); + }); + + $this->assertTrue(Schema::hasForeignKeyForColumn('question_id', 'answers', 'questions')); + $this->assertFalse(Schema::hasForeignKeyForColumn('body', 'answers', 'questions')); + } }