Skip to content

Instantly share code, notes, and snippets.

@stevelacey
Last active October 7, 2015 21:18
Show Gist options
  • Save stevelacey/3226510 to your computer and use it in GitHub Desktop.
Save stevelacey/3226510 to your computer and use it in GitHub Desktop.
Symfony2: use object to set route parameters
<?php
namespace Acme\BaseBundle\Routing\Generator;
use Symfony\Component\Routing\Generator\UrlGenerator as BaseUrlGenerator;
use Doctrine\Common\Util\Inflector;
/**
* UrlGenerator generates URL based on a set of routes.
*
* @api
*/
class UrlGenerator extends BaseUrlGenerator
{
protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens)
{
if (is_object($parameters)) {
$object = $parameters;
$parameters = array();
}
if (isset($parameters['object']) && is_object($parameters['object'])) {
$object = $parameters['object'];
}
if (isset($object)) {
$parameters = array_replace($this->context->getParameters(), $parameters);
$tparams = array_replace($defaults, $parameters);
$requiredParameters = array_diff_key(array_flip($variables), $tparams);
$parameters += $this->getParametersFromObject(array_flip($requiredParameters), $object);
unset($parameters['object']);
}
return parent::doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens);
}
protected function getParametersFromObject($keys, $object)
{
$parameters = array();
foreach ($keys as $key) {
$relation = $object;
$method = 'get' . Inflector::classify($key);
if (method_exists($relation, $method)) {
$relation = $relation->$method();
} else {
$segments = explode('_', $key);
if (count($segments) > 1) {
foreach ($segments as $segment) {
$method = 'get' . Inflector::classify($segment);
if (method_exists($relation, $method)) {
$relation = $relation->$method();
} else {
$relation = $object;
break;
}
}
}
}
if ($object !== $relation) {
$parameters[$key] = $relation;
}
}
return $parameters;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment