From fdcf21cbe15b190a56d12dc88d16546d33623d4f Mon Sep 17 00:00:00 2001 From: Cody Phillips Date: Sat, 25 Apr 2015 14:25:59 -0700 Subject: [PATCH] Closure support for fixtures Fixes #8 --- src/Codesleeve/Fixture/Drivers/Eloquent.php | 4 ++++ src/Codesleeve/Fixture/Drivers/Standard.php | 9 ++++++--- tests/fixtures/orm/users.php | 7 ++++++- tests/fixtures/standard/users.php | 7 ++++++- 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/Codesleeve/Fixture/Drivers/Eloquent.php b/src/Codesleeve/Fixture/Drivers/Eloquent.php index 5a91bc2..6c5fe3f 100644 --- a/src/Codesleeve/Fixture/Drivers/Eloquent.php +++ b/src/Codesleeve/Fixture/Drivers/Eloquent.php @@ -61,6 +61,10 @@ public function buildRecords($tableName, array $records) foreach ($recordValues as $columnName => $columnValue) { $camelKey = camel_case($columnName); + if (is_callable($columnValue)) { + $columnValue = call_user_func($columnValue, $recordValues); + } + // If a column name exists as a method on the model, we will just assume // it is a relationship and we'll generate the primary key for it and store // it as a foreign key on the model. diff --git a/src/Codesleeve/Fixture/Drivers/Standard.php b/src/Codesleeve/Fixture/Drivers/Standard.php index c8eeb46..9c60202 100644 --- a/src/Codesleeve/Fixture/Drivers/Standard.php +++ b/src/Codesleeve/Fixture/Drivers/Standard.php @@ -41,9 +41,12 @@ public function buildRecords($tableName, array $records) $this->tables[$tableName] = $tableName; foreach ($records as $recordName => $recordValues) { - // Generate a hash for this record's primary key. We'll simply hash the name of the - // fixture into an integer value so that related fixtures don't have to rely on - // an auto-incremented primary key when creating foreign keys. + array_walk($recordValues, function (&$value) use ($recordValues) { + if (is_callable($value)) { + $value = call_user_func($value, $recordValues); + } + }); + $recordValues = $this->setForeignKeys($recordValues); $recordValues = array_merge($recordValues, array('id' => $this->generateKey($recordName))); diff --git a/tests/fixtures/orm/users.php b/tests/fixtures/orm/users.php index cafacf5..4481f06 100644 --- a/tests/fixtures/orm/users.php +++ b/tests/fixtures/orm/users.php @@ -2,7 +2,12 @@ return array ( 'Travis' => array ( - 'first_name' => 'Travis', + 'first_name' => function ($record) { + if ('Bennett' === $record['last_name']) { + return 'Travis'; + } + return null; + }, 'last_name' => 'Bennett', 'roles' => 'endUser|active:1, root' ), diff --git a/tests/fixtures/standard/users.php b/tests/fixtures/standard/users.php index fa1fa7e..1d13dc5 100644 --- a/tests/fixtures/standard/users.php +++ b/tests/fixtures/standard/users.php @@ -2,7 +2,12 @@ return array ( 'Travis' => array ( - 'first_name' => 'Travis', + 'first_name' => function ($record) { + if ('Bennett' === $record['last_name']) { + return 'Travis'; + } + return null; + }, 'last_name' => 'Bennett' ) );