Skip to content

Commit

Permalink
Allow use of @-refs in faker provider calls, fixes #50
Browse files Browse the repository at this point in the history
  • Loading branch information
Seldaek committed Feb 5, 2014
1 parent ecfed6a commit 62abcdc
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Nelmio/Alice/Loader/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,19 @@ private function process($data, array $variables)
return $match[0];
}, $args);

// replace references to other objects
$args = preg_replace_callback('{(?:\b|^)(?:(?<multi>\d+)x )?(?<!\\\\)@(?<reference>[a-z0-9_.*-]+)(?:\->(?<property>[a-z0-9_-]+))?(?:\b|$)}i', function ($match) use ($that) {
$multi = ('' !== $match['multi']) ? $match['multi'] : null;
$property = isset($match['property']) ? $match['property'] : null;
if (strpos($match['reference'], '*')) {
return '$that->getRandomReferences(' . var_export($match['reference'], true) . ', ' . var_export($multi, true) . ', ' . var_export($property, true) . ')';
}
if (null !== $multi) {
throw new \UnexpectedValueException('To use multiple references you must use a mask like "'.$match['multi'].'x @user*", otherwise you would always get only one item.');
}
return '$that->getReference(' . var_export($match['reference'], true) . ', ' . var_export($property, true) . ')';
}, $args);

$locale = var_export($matches['locale'], true);
$name = var_export($matches['name'], true);

Expand Down
17 changes: 17 additions & 0 deletions tests/Nelmio/Alice/Loader/BaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,23 @@ public function testLoadParsesPropertyReferencesGetter()
$this->assertEquals($res['user1']->getAge(), $res['user2']->favoriteNumber);
}

public function testLoadParsesReferencesInFakerProviders()
{
$loader = new Base('en_US', array(new FakerProvider));
$res = $loader->load(array(
self::USER => array(
'bob' => array(
'username' => 'Bob',
),
'user' => array(
'username' => '<noop(@bob)>',
),
),
));

$this->assertEquals($res['bob'], $res['user']->username);
}

/**
* @expectedException UnexpectedValueException
* @expectedExceptionMessage Property doesnotexist is not defined for reference user1
Expand Down

0 comments on commit 62abcdc

Please sign in to comment.