Skip to content

[WIP] ORM based dynamic routing #122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jul 31, 2013
34 changes: 32 additions & 2 deletions CmfRoutingBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Symfony\Cmf\Bundle\RoutingBundle;

use Doctrine\Bundle\PHPCRBundle\DependencyInjection\Compiler\DoctrinePhpcrMappingsPass;
use Symfony\Cmf\Bundle\CoreBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
Expand Down Expand Up @@ -33,10 +34,39 @@ public function build(ContainerBuilder $container)
realpath(__DIR__ . '/Resources/config/doctrine-model') => 'Symfony\Cmf\Bundle\RoutingBundle\Model',
realpath(__DIR__ . '/Resources/config/doctrine-phpcr') => 'Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr',
),
array('cmf_routing.manager_name')
array('cmf_routing.dynamic.persistence.phpcr.manager_name'),
'cmf_routing.backend_type_phpcr'
)
);
}

if (class_exists('Symfony\Cmf\Bundle\CoreBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass')) {
$container->addCompilerPass($this->buildBaseOrmCompilerPass());
$container->addCompilerPass(
DoctrineOrmMappingsPass::createXmlMappingDriver(
array(
realpath(__DIR__ . '/Resources/config/doctrine-model') => 'Symfony\Cmf\Bundle\RoutingBundle\Model',
realpath(__DIR__ . '/Resources/config/doctrine-orm') => 'Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Orm',
),
array('cmf_routing.dynamic.persistence.orm.manager_name'),
'cmf_routing.backend_type_orm'
)
);
}
}

private function buildBaseOrmCompilerPass()
{
$arguments = array(array(realpath(__DIR__ . '/Resources/config/doctrine-base')), '.orm.xml');
$locator = new Definition('Doctrine\Common\Persistence\Mapping\Driver\DefaultFileLocator', $arguments);
$driver = new Definition('Doctrine\ORM\Mapping\Driver\XmlDriver', array($locator));

return new DoctrineOrmMappingsPass(
$driver,
array('Symfony\Component\Routing'),
array('cmf_routing.dynamic.persistence.orm.manager_name'),
'cmf_routing.backend_type_orm'
);
}

/**
Expand All @@ -55,7 +85,7 @@ private function buildBasePhpcrCompilerPass()
return new DoctrinePhpcrMappingsPass(
$driver,
array('Symfony\Component\Routing'),
array('cmf_routing.manager_name'),
array('cmf_routing.dynamic.persistence.phpcr.manager_name'),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i guess we need this fix even if we do not merge this PR

'cmf_routing.backend_type_phpcr'
);
}
Expand Down
19 changes: 16 additions & 3 deletions DependencyInjection/CmfRoutingExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@ private function setupDynamicRouter(array $config, ContainerBuilder $container,
$hasProvider = true;
$hasContentRepository = true;
}

if (!empty($config['persistence']['orm']['enabled'])) {
$this->loadOrmProvider($config['persistence']['orm'], $loader, $container);
$hasProvider = true;
}

if (isset($config['route_provider_service_id'])) {
$container->setAlias('cmf_routing.route_provider', $config['route_provider_service_id']);
$hasProvider = true;
Expand Down Expand Up @@ -142,10 +148,10 @@ public function loadPhpcrProvider($config, XmlFileLoader $loader, ContainerBuild

$container->setParameter($this->getAlias() . '.backend_type_phpcr', true);

$container->setParameter($this->getAlias() . '.persistence.phpcr.route_basepath', $config['route_basepath']);
$container->setParameter($this->getAlias() . '.persistence.phpcr.content_basepath', $config['content_basepath']);
$container->setParameter($this->getAlias() . '.dynamic.persistence.phpcr.route_basepath', $config['route_basepath']);
$container->setParameter($this->getAlias() . '.dynamic.persistence.phpcr.content_basepath', $config['content_basepath']);

$container->setParameter($this->getAlias() . '.manager_name', $config['manager_name']);
$container->setParameter($this->getAlias() . '.dynamic.persistence.phpcr.manager_name', $config['manager_name']);

$container->setAlias($this->getAlias() . '.route_provider', $this->getAlias() . '.phpcr_route_provider');
$container->setAlias($this->getAlias() . '.content_repository', $this->getAlias() . '.phpcr_content_repository');
Expand All @@ -171,6 +177,13 @@ public function loadSonataPhpcrAdmin($config, XmlFileLoader $loader, ContainerBu
$loader->load('admin-phpcr.xml');
}

public function loadOrmProvider($config, XmlFileLoader $loader, ContainerBuilder $container)
{
$container->setParameter($this->getAlias() . '.dynamic.persistence.orm.manager_name', $config['manager_name']);
$container->setParameter($this->getAlias() . '.backend_type_orm', true);
$loader->load('provider_orm.xml');
}

/**
* Returns the base path for the XSD files.
*
Expand Down
6 changes: 6 additions & 0 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ public function getConfigTreeBuilder()
->end()
->end()
->end()
->arrayNode('orm')
->children()
->scalarNode('enabled')->defaultNull()->end()
->scalarNode('manager_name')->defaultNull()->end()
->end()
->end()
->end()
->end()
->scalarNode('uri_filter_regexp')->defaultValue('')->end()
Expand Down
1 change: 1 addition & 0 deletions Doctrine/DoctrineProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ abstract class DoctrineProvider
public function __construct(ManagerRegistry $managerRegistry, $className = null)
{
$this->managerRegistry = $managerRegistry;
$this->className = $className;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this too

}

/**
Expand Down
61 changes: 61 additions & 0 deletions Doctrine/Orm/ContentRepository.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

namespace Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Orm;

use Symfony\Cmf\Component\Routing\ContentRepositoryInterface;
use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\DoctrineProvider;

/**
* Abstract content repository for ORM
*
* @author teito
*/
class ContentRepository extends DoctrineProvider implements ContentRepositoryInterface
{
/**
* Determine target class and id for this content
*
* @param mixed $identifier as produced by getContentId
*
* @return array with model first element, id second
*/
protected function getModelAndId($identifier)
{
return explode(':', $identifier, 2);
}

/**
* {@inheritDoc}
*/
public function findById($id)
{
list($model, $modelId) = $this->getModelAndId($id);

return $this->getObjectManager()->getRepository($model)->find($modelId);
}

/**
* {@inheritDoc}
*/
public function getContentId($content)
{
if (! is_object($content)) {
return null;
}

try {
$meta = $this->getObjectManager()->getClassMetadata(get_class($content));
$ids = $meta->getIdentifierValues($content);
if (0 !== count($ids)) {
throw new \Exception('Multi identifier values not supported in ' . get_class($content));
}

return implode(':', array(
get_class($content),
reset($ids)
));
} catch (\Exception $e) {
return null;
}
}
}
22 changes: 22 additions & 0 deletions Doctrine/Orm/Route.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Orm;

use Symfony\Cmf\Bundle\RoutingBundle\Model\Route as RouteModel;

/**
* ORM route version.
* @author matteo caberlotto [email protected]
*/
class Route extends RouteModel
{
/**
* {@inheritDoc}
*/
protected $name;

/**
* {@inheritDoc}
*/
protected $position;
}
103 changes: 103 additions & 0 deletions Doctrine/Orm/RouteProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?php

namespace Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Orm;

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Exception\RouteNotFoundException;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Cmf\Component\Routing\RouteProviderInterface;
use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\DoctrineProvider;

/**
* Provider loading routes from Doctrine
*
* This is <strong>NOT</strong> not a doctrine repository but just the route
* provider for the NestedMatcher. (you could of course implement this
* interface in a repository class, if you need that)
*
* @author [email protected]
*/
class RouteProvider extends DoctrineProvider implements RouteProviderInterface
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you forget a use statement for DoctrineProvider?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, there's some more missing which is going to be submitted in a pull request tonite, then code will be available for review

{
protected function getCandidates($url)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this logic the same as with the ODM? Should we encapsulate it in a class?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, the phpcr is using id prefix all over the place here

{
$candidates = array();
if ('/' !== $url) {
if (preg_match('/(.+)\.[a-z]+$/i', $url, $matches)) {
$candidates[] = $url;
$url = $matches[1];
}

$part = $url;
while (false !== ($pos = strrpos($part, '/'))) {
$candidates[] = $part;
$part = substr($url, 0, $pos);
}
}

$candidates[] = '/';

return $candidates;
}

/**
* {@inheritDoc}
*/
public function getRouteByName($name, $parameters = array())
{
$route = $this->getRoutesRepository()->findBy(array('name' => $name));
if (!$route) {
throw new RouteNotFoundException("No route found for name '$name'");
}

return $route;
}

public function getRoutesByNames($names, $parameters = array())
{
}

public function getRouteCollectionForRequest(Request $request)
{
$url = $request->getPathInfo();

$candidates = $this->getCandidates($url);

$collection = new RouteCollection();

if (empty($candidates)) {
return $collection;
}

try {
$routes = $this->getRoutesRepository()->findByStaticPrefix($candidates, array('position' => 'ASC'));

foreach ($routes as $key => $route) {
if (preg_match('/.+\.([a-z]+)$/i', $url, $matches)) {
if ($route->getDefault('_format') === $matches[1]) {
continue;
}

$route->setDefault('_format', $matches[1]);
}
// SYMFONY 2.1 COMPATIBILITY: tweak route name
$key = trim(preg_replace('/[^a-z0-9A-Z_.]/', '_', $key), '_');
$collection->add($key, $route);
}
} catch (RepositoryException $e) {
// TODO: how to determine whether this is a relevant exception or not?
// for example, getting /my//test (note the double /) is just an invalid path
// and means another router might handle this.
// but if the PHPCR backend is down for example, we want to alert the user
}

return $collection;
}

protected function getRoutesRepository()
{
return $this->getObjectManager()->getRepository($this->className);
}
}
6 changes: 3 additions & 3 deletions Resources/config/admin-phpcr.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@
</call>

<call method="setContentRoot">
<argument>%cmf_routing.persistence.phpcr.content_basepath%</argument>
<argument>%cmf_routing.dynamic.persistence.phpcr.content_basepath%</argument>
</call>

<call method="setRouteRoot">
<argument>%cmf_routing.persistence.phpcr.route_basepath%</argument>
<argument>%cmf_routing.dynamic.persistence.phpcr.route_basepath%</argument>
</call>
<call method="setControllerResolver">
<argument type="service" id="controller_resolver" />
Expand All @@ -47,7 +47,7 @@
</call>

<call method="setRouteRoot">
<argument>%cmf_routing.persistence.phpcr.route_basepath%</argument>
<argument>%cmf_routing.dynamic.persistence.phpcr.route_basepath%</argument>
</call>
</service>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd">

<mapped-superclass name="Symfony\Component\Routing\Route">
<field name="host" type="string"/>
<field name="defaults" type="array"/>
<field name="requirements" type="array"/>
<field name="options" type="array"/>
</mapped-superclass>

</doctrine-mapping>
16 changes: 16 additions & 0 deletions Resources/config/doctrine-model/Route.orm.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd">

<mapped-superclass name="Symfony\Cmf\Bundle\RoutingBundle\Model\Route">
<field name="variablePattern" type="string"/>
<field name="addFormatPattern" type="boolean"/>
<field name="staticPrefix" type="string"/>

<indexes>
<index name="name_idx" columns="name"/>
<index name="prefix_idx" columns="staticPrefix"/>
</indexes>
</mapped-superclass>

</doctrine-mapping>
16 changes: 16 additions & 0 deletions Resources/config/doctrine-orm/Route.orm.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd">

<entity name="Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Orm\Route" table="orm_routes">

<id name="id" type="integer" column="id">
<generator strategy="AUTO"/>
</id>

<field name="name" type="string" unique="true"/>
<field name="position" type="integer"/>

</entity>

</doctrine-mapping>
Loading