Skip to content

Commit

Permalink
Allow url data to overwrite Entity data.
Browse files Browse the repository at this point in the history
When a routing parameter is defined in the URL array it should overwrite
the entity data. This gives us a way to explicitly overwrite the entity
data if necessary.

Refs #11455
  • Loading branch information
markstory committed Nov 25, 2017
1 parent 89c1885 commit 933681b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Routing/Route/EntityRoute.php
Expand Up @@ -28,7 +28,10 @@ class EntityRoute extends Route
{
/**
* Match by entity and map its fields to the URL pattern by comparing the
* field names with the template vars
* field names with the template vars.
*
* If a routing key is defined in both `$url` and the entity, the value defined
* in `$url` will be preferred.
*
* @param array $url Array of parameters to convert to a string.
* @param array $context An array of the current request context.
Expand All @@ -45,7 +48,9 @@ public function match(array $url, array $context = [])
preg_match_all('@:(\w+)@', $this->template, $matches);

foreach ($matches[1] as $field) {
$url[$field] = $entity[$field];
if (!isset($url[$field]) && isset($entity[$field])) {
$url[$field] = $entity[$field];
}
}
}

Expand Down
28 changes: 28 additions & 0 deletions tests/TestCase/Routing/Route/EntityRouteTest.php
Expand Up @@ -23,6 +23,34 @@
*/
class EntityRouteTest extends TestCase
{
/**
* test that route keys take precedence to object properties.
*
* @return void
*/
public function testMatchRouteKeyPrecedence()
{
$entity = new Article([
'category_id' => 2,
'slug' => 'article-slug'
]);

$route = $route = new EntityRoute(
'/articles/:category_id/:slug',
[
'_name' => 'articlesView',
]
);

$result = $route->match([
'slug' => 'other-slug',
'_entity' => $entity,
'_name' => 'articlesView'
]);

$this->assertEquals('/articles/2/other-slug', $result);
}

/**
* test that routes match their pattern.
*
Expand Down

0 comments on commit 933681b

Please sign in to comment.