diff --git a/AutoRoute/Adapter/AdapterInterface.php b/AutoRoute/Adapter/AdapterInterface.php new file mode 100644 index 0000000..fe11659 --- /dev/null +++ b/AutoRoute/Adapter/AdapterInterface.php @@ -0,0 +1,75 @@ + + */ +interface AdapterInterface +{ + /** + * Return locales for object + * + * @return array + */ + public function getLocales($object); + + /** + * Translate the given object into the given locale + * + * @param object $object + * @param string $locale e.g. fr, en, de, be, etc. + */ + public function translateObject($object, $locale); + + /** + * Create a new auto route at the given path + * with the given document as the content. + * + * @param string $path + * @param object $document + * + * @return Route new route document + */ + public function createRoute($path, $document); + + /** + * Return the canonical name for the given class, this is + * required as somethimes an ORM may return a proxy class. + * + * @return string + */ + public function getRealClassName($className); + + /** + * Return true if the content associated with the route + * and the given content object are the same. + * + * @param RouteObjectInterface + * @param object + */ + public function compareRouteContent(RouteObjectInterface $route, $contentObject); + + /** + * Attempt to find a route with the given URL + * + * @param string $url + * + * @return null|Symfony\Cmf\Component\Routing\RouteObjectInterface + */ + public function findRouteForUrl($url); +} diff --git a/AutoRoute/Adapter/PhpcrOdmAdapter.php b/AutoRoute/Adapter/PhpcrOdmAdapter.php new file mode 100644 index 0000000..8da7983 --- /dev/null +++ b/AutoRoute/Adapter/PhpcrOdmAdapter.php @@ -0,0 +1,108 @@ +dm = $dm; + $this->baseRoutePath = $routeBasePath; + } + + public function getLocales($contentDocument) + { + if ($this->dm->isDocumentTranslatable($contentDocument)) { + return $this->dm->getLocalesFor($contentDocument); + } + + return array(); + } + + public function translateObject($contentDocument, $locale) + { + $meta = $this->dm->getMetadataFactory()->getMetadataFor(get_class($contentDocument)); + $contentDocument = $this->dm->findTranslation($meta->getName(), $meta->getIdentifierValue($contentDocument), $locale); + + return $contentDocument; + } + + public function createRoute($path, $contentDocument) + { + $pathElements = explode('/', $path); + $headName = array_pop($pathElements); + $parentPath = implode('/', $pathElements); + + // bypass the ODM ... but changes will still only be + // persisted when the PHPCR session is saved in the ODMs flush(). + NodeHelper::createPath($this->dm->getPhpcrSession(), $parentPath); + + $autoRouteParent = $this->dm->find(null, $parentPath); + + if (!$autoRouteParent) { + throw new \RuntimeException(sprintf( + 'Hmph, could not find parent path "%s", this really should not have happened.', + $parentPath + )); + } + + $headRoute = new AutoRoute(); + $headRoute->setContent($contentDocument); + $headRoute->setName($headName); + $headRoute->setParent($autoRouteParent); + + return $headRoute; + } + + public function getRealClassName($className) + { + return ClassUtils::getRealClass($className); + } + + public function compareRouteContent(RouteObjectInterface $route, $contentDocument) + { + if ($route->getContent() === $contentDocument) { + return true; + } + + return false; + } + + public function getReferringRoutes($contentDocument) + { + return $this->dm->getReferrers($contentDocument, null, null, null, 'Symfony\Cmf\Component\Routing\RouteObjectInterface'); + } + + /** + * {@inheritDoc} + */ + public function findRouteForUrl($url) + { + return $this->dm->find(null, $this->baseRoutePath . $url); + } +} diff --git a/AutoRoute/AutoRouteManager.php b/AutoRoute/AutoRouteManager.php index ac84015..dc59db3 100644 --- a/AutoRoute/AutoRouteManager.php +++ b/AutoRoute/AutoRouteManager.php @@ -11,9 +11,9 @@ namespace Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute; -use Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack\Builder; use Doctrine\Common\Util\ClassUtils; use Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Driver\DriverInterface; +use Metadata\MetadataFactoryInterface; /** * This class is concerned with the automatic creation of route objects. @@ -22,81 +22,68 @@ */ class AutoRouteManager { - protected $factory; protected $driver; + protected $urlGenerator; + protected $defunctRouteHandler; - public function __construct(DriverInterface $driver, Factory $factory, Builder $builder) + /** + * @param DriverInterface $driver Database driver + * @param UrlGeneratorInterface $urlGenerator Routing auto URL generator + * @param DefunctRouteHandlerInterface $defunctRouteHandler Handler for defunct routes + */ + public function __construct( + DriverInterface $driver, + UrlGeneratorInterface $urlGenerator, + DefunctRouteHandlerInterface $defunctRouteHandler + ) { - $this->factory = $factory; - $this->builder = $builder; $this->driver = $driver; + $this->urlGenerator = $urlGenerator; + $this->defunctRouteHandler = $defunctRouteHandler; } /** - * Create or update the automatically generated route for - * the given document. - * - * When this is finished it will support multiple locales. - * - * @param object Mapped document for which to generate the AutoRoute - * - * @return BuilderContext[] + * @param object $document */ - public function updateAutoRouteForDocument($document) + public function buildOperationStack(OperationStack $operationStack, $document) { - $classFqn = ClassUtils::getClass($document); - $locales = $this->driver->getLocales($document) ? : array(null); - - $contexts = array(); - - foreach ($locales as $locale) { - if (null !== $locale) { - $document = $this->driver->translateObject($document, $locale); - } + $urls = $this->getUrlsForDocument($document); - $context = new BuilderContext; + foreach ($urls as $url) { + $existingRoute = $this->driver->findRouteForUrl($url); - $context->setContent($document); - $context->setLocale($locale); + if ($existingRoute) { + $isSameContent = $this->driver->compareRouteContent($existingRoute, $document); - // build path elements - $builderUnitChain = $this->factory->getRouteStackBuilderUnitChain($classFqn); - $builderUnitChain->executeChain($context); + if ($isSameContent) { + continue; + } - // persist the content name element (the autoroute) - $autoRouteStack = new AutoRouteStack($context); - $builderUnit = $this->factory->getContentNameBuilderUnit($classFqn); - $this->builder->build($autoRouteStack, $builderUnit); + $url = $this->urlGenerator->resolveConflict($document, $url); + } - $contexts[] = $context; + $newRoute = $this->driver->createRoute($url, $document); + $operationStack->pushNewRoute($newRoute); } - return $contexts; - } + $this->defunctRouteHandler->handleDefunctRoutes($document, $operationStack); - /** - * Remove all auto routes associated with the given document. - * - * @param object $document Mapped document - * - * @todo: Test me - * - * @return array Array of removed routes - */ - public function removeAutoRoutesForDocument($document) - { - throw new \Exception('Implement me??'); + return $operationStack; } - /** - * Return true if the given document is mapped with AutoRoute - * - * @param object $document Document - * - * @return boolean - */ - public function isAutoRouteable($document) + private function getUrlsForDocument($document) { - return $this->factory->hasMapping(ClassUtils::getClass($document)); + $urls = array(); + $locales = $this->driver->getLocales($document) ? : array(null); + + foreach ($locales as $locale) { + if (null !== $locale) { + $this->driver->translateObject($document, $locale); + } + + $urls[] = $this->urlGenerator->generateUrl($document); + } + + return $urls; } } diff --git a/AutoRoute/AutoRouteStack.php b/AutoRoute/AutoRouteStack.php deleted file mode 100644 index e6ec102..0000000 --- a/AutoRoute/AutoRouteStack.php +++ /dev/null @@ -1,45 +0,0 @@ - - */ -class AutoRouteStack extends RouteStack -{ - public function close() - { - if (count($this->routes) > 1) { - throw new \RuntimeException('You can only add one route to the AutoRouteStack.'); - } - - parent::close(); - } - - public function addRoute($route) - { - // note that we can't type hint here as this method is overridden. - if (!$route instanceof AutoRoute) { - throw new \BadMethodCallException('You must pass an AutoRoute document to addRoute'); - } - - parent::addRoute($route); - } -} diff --git a/AutoRoute/BuilderContext.php b/AutoRoute/BuilderContext.php deleted file mode 100644 index d4928a8..0000000 --- a/AutoRoute/BuilderContext.php +++ /dev/null @@ -1,170 +0,0 @@ - - */ -class BuilderContext -{ - /** @var RouteStack[] */ - protected $routeStacks = array(); - - /** @var RouteStack */ - protected $stagedRouteStack; - - protected $content; - - protected $locale; - - /** - * Return an ordered array of all routes from - * all stacks. - * - * @return array - */ - public function getRoutes() - { - $routes = array(); - foreach ($this->routeStacks as $routeStack) { - $routes = array_merge($routes, $routeStack->getRoutes()); - } - - return $routes; - } - - /** - * Stage a route stack. TBH this is probably not - * required now. Could probably be replaced simply - * with addRouteStack. - */ - public function stageRouteStack(RouteStack $routeStack) - { - $this->stagedRouteStack = $routeStack; - } - - /** - * As with above. This can probably be replaced with something - * simpler. - */ - public function commitRouteStack() - { - if (null === $this->stagedRouteStack) { - throw new \RuntimeException( - 'Cannot commit route stack when there is no route stack to commit '. - '(use stageRouteStack to stage)' - ); - } - - if (false === $this->stagedRouteStack->isClosed()) { - throw new \RuntimeException( - 'Staged route stack is not closed, cannot commit.' - ); - } - - $this->routeStacks[] = $this->stagedRouteStack; - $this->stagedRouteStack = null; - } - - /** - * Return all route stacks. - * - * @return array - */ - public function getRouteStacks() - { - return $this->routeStacks; - } - - /** - * Return the "top" route (last added) in - * the stack. - * - * @return object - */ - public function getTopRoute() - { - $routes = $this->getRoutes(); - - return end($routes); - } - - /** - * Returns the complete path as determined - * by the route stacks. - * - * Note that this path is not absolute. - * - * @return string - */ - public function getFullPath() - { - $paths = array(); - foreach ($this->routeStacks as $routeStack) { - $path = $routeStack->getPath(); - if (!empty($path)) { - $paths[] = $path; - } - } - - $path = implode('/', $paths); - - return $path; - - } - - /** - * Set the content object (e.g. a blog post) - * - * @param object - */ - public function setContent($content) - { - $this->content = $content; - } - - /** - * Returns the content object (e.g. a blog post) - * - * @return object - */ - public function getContent() - { - return $this->content; - } - - /** - * Return the locale for this context - * - * @return string - */ - public function getLocale() - { - return $this->locale; - } - /** - * Set the locale for this context - * - * @param string - */ - public function setLocale($locale) - { - $this->locale = $locale; - } -} diff --git a/AutoRoute/ConflictResolverInterface.php b/AutoRoute/ConflictResolverInterface.php new file mode 100644 index 0000000..7bc941c --- /dev/null +++ b/AutoRoute/ConflictResolverInterface.php @@ -0,0 +1,17 @@ + + */ +class DefunctRouteHandler implements DefunctRouteHandlerInterface +{ + protected $serviceRegistry; + protected $driver; + + /** + * @param ServiceRegistry auto routing service registry (for getting old route action) + * @param DriverInterface auto routing backend driver + * @param MappingFactory auto routing mapping factory + */ + public function __consturct( + ServiceRegistry $serviceRegistry, + DriverInterface $driver, + MappingFactory $mappingFactory + ) + { + $this->serviceRegistry = $serviceRegistry; + $this->driver = $driver; + $this->mappingFactory = $mappingFactory; + } + + /** + * {@inheritDoc} + */ + public function handleDefunctRoutes($oldRoutes, $document, $operationStack) + { + } +} diff --git a/AutoRoute/DefunctRouteHandlerInterface.php b/AutoRoute/DefunctRouteHandlerInterface.php new file mode 100644 index 0000000..ee997fa --- /dev/null +++ b/AutoRoute/DefunctRouteHandlerInterface.php @@ -0,0 +1,27 @@ + + */ +interface DefunctRouteHandlerInterface +{ + /** + * Handle auto routes which refer to the given + * document but which do not correspond to the URLs + * generated. + * + * These routes are defunct - they are routes which + * have used to be used to directly reference the + * content, but which must now either be deleted + * or perhaps replaced with a redirect route, or indeed + * left alone to continue depending on the configuration. + * + * @param object $contentDocument Document which is the subject + * of the routes + * @param string[] $urls List of URLs which now represent + * the set of valid auto routes for this document + */ + public function handleDefunctRoutes($document, $urls); +} diff --git a/AutoRoute/Driver/DriverInterface.php b/AutoRoute/Driver/DriverInterface.php deleted file mode 100644 index 2b60866..0000000 --- a/AutoRoute/Driver/DriverInterface.php +++ /dev/null @@ -1,30 +0,0 @@ - - */ -interface DriverInterface -{ - /** - * Return locales for object - * - * @return array - */ - public function getLocales($object); - - public function translateObject($object, $locale); -} diff --git a/AutoRoute/Driver/PhpcrOdmDriver.php b/AutoRoute/Driver/PhpcrOdmDriver.php deleted file mode 100644 index ce7e700..0000000 --- a/AutoRoute/Driver/PhpcrOdmDriver.php +++ /dev/null @@ -1,47 +0,0 @@ -dm = $dm; - } - - public function getLocales($document) - { - if ($this->dm->isDocumentTranslatable($document)) { - return $this->dm->getLocalesFor($document); - } - - return array(); - } - - public function translateObject($document, $locale) - { - $meta = $this->dm->getMetadataFactory()->getMetadataFor(get_class($document)); - $this->dm->findTranslation(get_class($document), $meta->getIdentifierValue($document), $locale); - - return $document; - } -} diff --git a/AutoRoute/Exception/BadProviderPositionException.php b/AutoRoute/Exception/BadProviderPositionException.php deleted file mode 100644 index f6897bd..0000000 --- a/AutoRoute/Exception/BadProviderPositionException.php +++ /dev/null @@ -1,19 +0,0 @@ - - */ -class BadProviderPositionException extends \RuntimeException -{ -} diff --git a/AutoRoute/Exception/CannotModifyClosedRouteStackException.php b/AutoRoute/Exception/CannotModifyClosedRouteStackException.php deleted file mode 100644 index aff21d9..0000000 --- a/AutoRoute/Exception/CannotModifyClosedRouteStackException.php +++ /dev/null @@ -1,19 +0,0 @@ - - */ -class CannotModifyClosedRouteStackException extends \RuntimeException -{ -} diff --git a/AutoRoute/Exception/ClassNotMappedException.php b/AutoRoute/Exception/ClassNotMappedException.php deleted file mode 100644 index 4011111..0000000 --- a/AutoRoute/Exception/ClassNotMappedException.php +++ /dev/null @@ -1,27 +0,0 @@ - - */ -class ClassNotMappedException extends \Exception -{ - public function __construct($classFqn) - { - $message = sprintf('The class "%s" has not been mapped for auto routing.', - $classFqn - ); - - parent::__construct($message); - } -} diff --git a/AutoRoute/Exception/CouldNotFindRouteException.php b/AutoRoute/Exception/CouldNotFindRouteException.php deleted file mode 100644 index c4a77df..0000000 --- a/AutoRoute/Exception/CouldNotFindRouteException.php +++ /dev/null @@ -1,27 +0,0 @@ - - */ -class CouldNotFindRouteException extends \Exception -{ - public function __construct($path) - { - $message = sprintf('Could not find route component at path "%s".', - $path - ); - - parent::__construct($message); - } -} diff --git a/AutoRoute/Exception/InvalidPathElementException.php b/AutoRoute/Exception/InvalidPathElementException.php deleted file mode 100644 index d44333e..0000000 --- a/AutoRoute/Exception/InvalidPathElementException.php +++ /dev/null @@ -1,19 +0,0 @@ - - */ -class InvalidPathElementException extends \RuntimeException -{ -} diff --git a/AutoRoute/Exception/MissingOptionException.php b/AutoRoute/Exception/MissingOptionException.php deleted file mode 100644 index 1155ad7..0000000 --- a/AutoRoute/Exception/MissingOptionException.php +++ /dev/null @@ -1,27 +0,0 @@ - - */ -class MissingOptionException extends \Exception -{ - public function __construct($context, $key) - { - $message = sprintf('%s expected option %s but did not get it.', - $context, $key - ); - - parent::__construct($message); - } -} diff --git a/AutoRoute/Factory.php b/AutoRoute/Factory.php deleted file mode 100644 index 7e99ce3..0000000 --- a/AutoRoute/Factory.php +++ /dev/null @@ -1,214 +0,0 @@ - - */ -class Factory -{ - /** @var MappingFactory */ - protected $mappingFactory; - - // we lazy-load the builder chains, this will allow us to support - // addition annotation/mapping in the future. - protected $routeStackChains; - - protected $serviceIds = array( - 'provider' => array(), - 'exists_action' => array(), - 'not_exists_action' => array(), - 'route_maker' => array(), - ); - - protected $container; - /** @var Builder */ - protected $builder; - /** @var LoaderInterface * - protected $loader; - protected $options = array();*/ - - public function __construct(MappingFactory $mappingFactory, /*LoaderInterface $loader, */ContainerInterface $container, Builder $builder/*, array $options = array()*/) - { - $this->container = $container; - $this->builder = $builder; - $this->mappingFactory = $mappingFactory; - /*$this->loader = $loader; - $this->options = array_replace(array( - // false -> caching is disabled - 'cache_dir' => false, - 'debug' => false, - 'mapping_cache_class' => 'ProjectAutoRouteMappingFactory', - 'resources' => array(), - ), $options);*/ - } - - /** - * Register an alias for a service ID of the specified type. - * - * e.g. registerAlias('path_provider', 'specified', 'cmf_[...]'); - * - * @param string $type - * @param string $alias - * @param string $id - */ - public function registerAlias($type, $alias, $id) - { - if (!isset($this->serviceIds[$type])) { - throw new \RuntimeException(sprintf('Unknown service ID type "%s"', $type)); - } - - $this->serviceIds[$type][$alias] = $id; - } - - /** - * Creates the route stack builder chain for the given class FQN. - * - * The RouteStackBuilderUnitChain will provide all the route components - * for the content path. - * - * Note that we cache it. - * - * @return RouteStackBuilderUnitChain - */ - public function getRouteStackBuilderUnitChain($classFqn) - { - if (!isset($this->routeStackChains[$classFqn])) { - $this->routeStackChains[$classFqn] = $this->generateRouteStackChain($classFqn); - } - - return $this->routeStackChains[$classFqn]; - } - - /** - * TODO remove - * - * Return the build unit which will generate the content name - * route for the given class FQN. - * - * @param string $classFqn - * - * @return BuilderUnit - */ - public function getContentNameBuilderUnit($classFqn) - { - if (!isset($this->contentNameBuilderUnits[$classFqn])) { - $mapping = $this->getMappingFactory()->getMappingsForClass($classFqn); - $this->contentNameBuilderUnits[$classFqn] = $this->generateBuilderUnit(); - } - - return $this->contentNameBuilderUnits[$classFqn]; - } - - protected function getMappingFactory() - { - return $this->mappingFactory; - /* TODO create native caching - if (null !== $this->mappingFactory) { - return $this->mappingFactory; - } - - $mappingFactory = null; - $getMappingFactory = function () use (&$mappingFactory) { - if (null === $mappingFactory) { - $mappingFactory = new MappingFactory(); - foreach ($this->options['resources'] as $resource) { - $mappingFactory->addMappings($this->loader->load($resource)); - } - } - - return $mappingFactory; - } - - // caching disabled - if (false === $this->options['cache_dir']) { - return $this->mappingFactory = $getMappingFactory(); - } - - // caching - $class = $this->options['mapping_cache_class']; - $cache = new ConfigCache($this->options['cache_dir'].'/'.$class.'php', $this->options['debug']); - if (!$cache->isFresh()) { - // regenerate cache - $dumper = new PhpDumper($getMappingFactory()); - - $cache->write($dumper->dump(array( - 'class' => $class, - ))); - } - - require_once $cache; - - return $this->mappingFactory = new $class;*/ - } - - protected function generateRouteStackChain($classFqn) - { - $mapping = $this->getMappingFactory()->getMappingsForClass($classFqn); - - $routeStackChain = new BuilderUnitChain($this->builder); - - foreach ($mapping->getTokenProviders() as $builderName => $tokenProvider) { - $builderUnit = $this->generateBuilderUnit($tokenProvider); - $routeStackChain->addBuilderUnit($builderName, $builderUnit); - } - - return $routeStackChain; - } - - protected function generateBuilderUnit(TokenProvider $tokenProvider) - { - $pathProvider = $this->getBuilderService($tokenProvider->getProvider(), 'provider'); - $existsAction = $this->getBuilderService($tokenProvider->getExistsAction(), 'exists_action'); - $notExistsAction = $this->getBuilderService($tokenProvider->getNotExistsAction(), 'not_exists_action'); - - $builderUnit = new BuilderUnit( - $config->getProvider(), - $existsAction, - $notExistsAction - ); - - return $builderUnit; - } - - private function getBuilderService($builderConfig, $type) - { - $alias = $builderConfig['name']; - if (!isset($this->serviceIds[$type][$alias])) { - throw new \RuntimeException(sprintf( - '"%s" class with alias "%s" requested, but this alias does not exist. Registered aliases "%s"', - $type, - $alias, - implode(',', array_keys($this->serviceIds[$type])) - )); - } - - $serviceId = $this->serviceIds[$type][$alias]; - - // NOTE: Services must always be defined as scope=prototype for them - // to be stateless (which is good here) - $service = $this->container->get($serviceId); - $service->init($builderConfig['options']); - - return $service; - } -} diff --git a/AutoRoute/Mapping/ClassMetadata.php b/AutoRoute/Mapping/ClassMetadata.php index ff40dd8..a6fa2c9 100644 --- a/AutoRoute/Mapping/ClassMetadata.php +++ b/AutoRoute/Mapping/ClassMetadata.php @@ -106,4 +106,8 @@ public function merge(MergeableInterface $metadata) $this->addTokenProvider($tokenName, $provider, true); } } + + public function getTokenProviderConfigs() + { + } } diff --git a/AutoRoute/OperationStack.php b/AutoRoute/OperationStack.php new file mode 100644 index 0000000..6508206 --- /dev/null +++ b/AutoRoute/OperationStack.php @@ -0,0 +1,20 @@ +persistStack[] = $route; + } + + public function getPersistStack() + { + return $this->persistStack; + } +} diff --git a/AutoRoute/PathActionInterface.php b/AutoRoute/PathActionInterface.php deleted file mode 100644 index e9eae19..0000000 --- a/AutoRoute/PathActionInterface.php +++ /dev/null @@ -1,39 +0,0 @@ - - */ -interface PathActionInterface -{ - /** - * Initialize with config options - * - * @param array $options - */ - public function init(array $options); - - /** - * Perform the action. When the method has finished the - * RouteStack should contain an equal number of routes and - * path elements. - * - * @param RouteStack $stack - */ - public function execute(RouteStack $stack); -} diff --git a/AutoRoute/PathExists/AutoIncrementPath.php b/AutoRoute/PathExists/AutoIncrementPath.php deleted file mode 100644 index d0de7f9..0000000 --- a/AutoRoute/PathExists/AutoIncrementPath.php +++ /dev/null @@ -1,64 +0,0 @@ - - */ -class AutoIncrementPath implements PathActionInterface -{ - protected $dm; - protected $routeMaker; - protected $format = '%s-%d'; - - public function __construct(DocumentManager $dm, RouteMakerInterface $routeMaker) - { - $this->dm = $dm; - $this->routeMaker = $routeMaker; - } - - public function init(array $options) - { - if (isset($options['format'])) { - $this->format = '%s'.$options['format']; - } - } - - public function execute(RouteStack $routeStack) - { - $inc = 1; - - $path = $routeStack->getFullPath(); - - $route = $this->dm->find(null, $path); - $context = $routeStack->getContext(); - - if ($route->getContent() === $context->getContent()) { - $routeStack->addRoute($route); - - return; - } - - do { - $newPath = sprintf($this->format, $path, $inc++); - } while (null !== $this->dm->find(null, $newPath)); - - $routeStack->replaceLastPathElement(PathHelper::getNodeName($newPath)); - $this->routeMaker->make($routeStack); - } -} diff --git a/AutoRoute/PathExists/UsePath.php b/AutoRoute/PathExists/UsePath.php deleted file mode 100644 index e39aa0a..0000000 --- a/AutoRoute/PathExists/UsePath.php +++ /dev/null @@ -1,52 +0,0 @@ - - */ -class UsePath implements PathActionInterface -{ - protected $dm; - - public function __construct(DocumentManager $dm) - { - $this->dm = $dm; - } - - public function init(array $options) - { - } - - public function execute(RouteStack $routeStack) - { - $paths = $routeStack->getFullPaths(); - - foreach ($paths as $path) { - $route = $this->dm->find(null, $path); - - if (!$route) { - throw new \RuntimeException(sprintf( - 'Expected to find a document at "%s", but didn\'t. This shouldn\'t - happen. Maybe we have a race condition?', - $path - )); - } - - $routeStack->addRoute($route); - } - } -} diff --git a/AutoRoute/PathNotExists/CreatePath.php b/AutoRoute/PathNotExists/CreatePath.php deleted file mode 100644 index 73d463b..0000000 --- a/AutoRoute/PathNotExists/CreatePath.php +++ /dev/null @@ -1,38 +0,0 @@ - - */ -class CreatePath implements PathActionInterface -{ - protected $routeMaker; - - public function __construct(RouteMakerInterface $routeMaker) - { - $this->routeMaker = $routeMaker; - } - - public function init(array $options) - { - } - - public function execute(RouteStack $routeStack) - { - $this->routeMaker->make($routeStack); - } -} diff --git a/AutoRoute/PathNotExists/ThrowException.php b/AutoRoute/PathNotExists/ThrowException.php deleted file mode 100644 index 514f1d4..0000000 --- a/AutoRoute/PathNotExists/ThrowException.php +++ /dev/null @@ -1,31 +0,0 @@ - - */ -class ThrowException implements PathActionInterface -{ - public function init(array $options) - { - } - - public function execute(RouteStack $routeStack) - { - throw new CouldNotFindRouteException('/'.$routeStack->getFullPath()); - } -} diff --git a/AutoRoute/PathProvider/ContentDateTimeProvider.php b/AutoRoute/PathProvider/ContentDateTimeProvider.php deleted file mode 100644 index 42840b0..0000000 --- a/AutoRoute/PathProvider/ContentDateTimeProvider.php +++ /dev/null @@ -1,69 +0,0 @@ - - */ -class ContentDateTimeProvider extends ContentMethodProvider -{ - protected $dateFormat; - - public function init(array $options) - { - parent::init($options); - - $options = array_merge(array( - 'date_format' => 'Y-m-d' - ), $options); - - $this->dateFormat = $options['date_format']; - } - - public function providePath(RouteStack $routeStack) - { - $object = $routeStack->getContext()->getContent(); - $method = $this->method; - - if (!method_exists($object, $method)) { - throw new \BadMethodCallException(sprintf('Method "%s" does not exist on class "%s"', $method, get_class($object))); - } - - $date = $object->$method(); - - if (!$date instanceof \DateTime) { - throw new \RuntimeException(sprintf('Method %s:%s must return an instance of DateTime.', - get_class($object), - $method - )); - } - - $string = $date->format($this->dateFormat); - $pathElements = $this->normalizePathElements($string, $object); - - $routeStack->addPathElements($pathElements); - } - - /** - * {@inheritDoc} - */ - public function normalizePathElements($elements, $object) - { - return parent::normalizePathElements(explode('/', $elements), $object); - } -} diff --git a/AutoRoute/PathProvider/ContentMethodProvider.php b/AutoRoute/PathProvider/ContentMethodProvider.php deleted file mode 100644 index 877d1eb..0000000 --- a/AutoRoute/PathProvider/ContentMethodProvider.php +++ /dev/null @@ -1,118 +0,0 @@ - - */ -class ContentMethodProvider implements PathProviderInterface -{ - protected $method; - protected $slugifier; - protected $slugify; - - public function __construct(SlugifierInterface $slugifier) - { - $this->slugifier = $slugifier; - } - - public function init(array $options) - { - if (!isset($options['method'])) { - throw new MissingOptionException(__CLASS__, 'method'); - } - - $options = array_merge(array( - 'slugify' => true - ), $options); - - $this->method = $options['method']; - $this->slugify = $options['slugify']; - } - - public function providePath(RouteStack $routeStack) - { - $object = $routeStack->getContext()->getContent(); - $method = $this->method; - - if (!method_exists($object, $method)) { - throw new \BadMethodCallException(sprintf('Method "%s" does not exist on class "%s"', $method, get_class($object))); - } - - $pathElements = $object->$method(); - $pathElements = $this->normalizePathElements($pathElements, $object); - - // @todo: Validate the validator service. - $routeStack->addPathElements($pathElements); - } - - /** - * Normalize the given $pathElements variable to an array of path elements, - * accepting either an array or a string. - * - * A string will be converted to an array of elements delimiteed by the - * path separator. - * - * If slugify is enabled, each path element will be slugified. - * - * @param mixed $pathElements Either an array or a string - * @param object $object Used in the case of an exception - * - * @return array - */ - protected function normalizePathElements($pathElements, $object) - { - if (is_string($pathElements) || (is_object($pathElements) && method_exists($pathElements, '__toString'))) { - if (substr($pathElements, 0, 1) == '/') { - throw new \RuntimeException('Path must not be absolute.'); - } - - $pathElements = array($pathElements); - } - - if (!is_array($pathElements)) { - throw new \RuntimeException(sprintf( - 'FromObjectMethodProvider wants %s::%s to return an array of route names or a string, got "%s"', - get_class($object), - $this->method, - gettype($pathElements) - )); - } - - if (true === $this->slugify) { - $slugifier = $this->slugifier; - array_walk($pathElements, function (&$pathElement) use ($slugifier) { - $pathElement = $slugifier->slugify($pathElement); - }); - } - - return $pathElements; - } -} diff --git a/AutoRoute/PathProvider/ContentObjectProvider.php b/AutoRoute/PathProvider/ContentObjectProvider.php deleted file mode 100644 index eb14544..0000000 --- a/AutoRoute/PathProvider/ContentObjectProvider.php +++ /dev/null @@ -1,125 +0,0 @@ - - */ -class ContentObjectProvider implements PathProviderInterface -{ - protected $method; - protected $dm; - - public function __construct(DocumentManager $dm) - { - $this->dm = $dm; - } - - public function init(array $options) - { - if (!isset($options['method'])) { - throw new MissingOptionException(__CLASS__, 'method'); - } - - $this->method = $options['method']; - } - - public function providePath(RouteStack $routeStack) - { - $context = $routeStack->getContext(); - - if (count($context->getRouteStacks()) > 0) { - throw new \RuntimeException( - 'ContentObjectProvider must belong to the first builder unit - adding '. - 'the full route path of an existing object would not make any sense otherwise.' - ); - } - - $contentObject = $context->getContent(); - $method = $this->method; - - if (!method_exists($contentObject, $method)) { - throw new \BadMethodCallException(sprintf('Method "%s" does not exist on class "%s"', $method, get_class($contentObject))); - } - - $object = $contentObject->$method(); - - $routeFilter = function ($referrer) use ($object) { - if ($referrer instanceof Route && $referrer->getContent() === $object) { - return true; - } - - return false; - }; - - $referringRoutes = new ArrayCollection; - - if ($this->documentIsPersisted($object)) { - // check to see existing routes - $referrers = $this->dm->getReferrers($object); - $referringRoutes = $referrers->filter($routeFilter); - } - - // Now check to see if there are any scheduled routes - // I think this should be handled by the ODM ... - - $uow = $this->dm->getUnitOfWork(); - $scheduledInserts = $uow->getScheduledInserts(); - $scheduledRoutes = array_filter($scheduledInserts, $routeFilter); - $routes = array_merge($referringRoutes->toArray(), array_values($scheduledRoutes)); - - if (count($routes) > 1) { - throw new \RuntimeException( - 'Multiple referring routes (i.e. translations) not supported yet.' - ); - } - - if (empty($routes)) { - throw new CouldNotFindRouteException(sprintf( - 'Could not find route for object "%s" provided by %s:%s', - get_class($object), - get_class($contentObject), - $method - )); - } - - $route = current($routes); - $id = $route->getId(); - - // get rid of the first path separator (We do have one right ...) - $id = substr($id, 1); - - $pathElements = explode('/', $id); - $routeStack->addPathElements($pathElements); - } - - protected function documentIsPersisted($document) - { - $metadata = $this->dm->getClassMetadata(get_class($document)); - $id = $metadata->getIdentifierValue($document); - $phpcrSession = $this->dm->getPhpcrSession(); - - return $phpcrSession->nodeExists($id); - } -} diff --git a/AutoRoute/PathProvider/LocaleProvider.php b/AutoRoute/PathProvider/LocaleProvider.php deleted file mode 100644 index 43ca92b..0000000 --- a/AutoRoute/PathProvider/LocaleProvider.php +++ /dev/null @@ -1,43 +0,0 @@ - - */ -class LocaleProvider implements PathProviderInterface -{ - public function init(array $options) - { - } - - public function providePath(RouteStack $routeStack) - { - $context = $routeStack->getContext(); - $locale = $context->getLocale(); - - if (!$locale) { - throw new \RuntimeException(sprintf( - 'LocaleProvider requires that a locale is set on the BuilderContext for "%s"', - get_class($context->getContent()) - )); - } - - $routeStack->addPathElements(array($locale)); - } -} diff --git a/AutoRoute/PathProvider/SpecifiedProvider.php b/AutoRoute/PathProvider/SpecifiedProvider.php deleted file mode 100644 index 721eab9..0000000 --- a/AutoRoute/PathProvider/SpecifiedProvider.php +++ /dev/null @@ -1,42 +0,0 @@ - - */ -class SpecifiedProvider implements PathProviderInterface -{ - protected $path; - - public function init(array $options) - { - if (!isset($options['path'])) { - throw new MissingOptionException(__CLASS__, 'path'); - } - - $this->path = $options['path']; - } - - public function providePath(RouteStack $routeStack) - { - if (substr($this->path, 0, 1) == '/') { - $this->path = substr($this->path, 1); - } - - $routeStack->addPathElements(explode('/', $this->path)); - } -} diff --git a/AutoRoute/PathProviderInterface.php b/AutoRoute/PathProviderInterface.php deleted file mode 100644 index 70bd460..0000000 --- a/AutoRoute/PathProviderInterface.php +++ /dev/null @@ -1,33 +0,0 @@ - - */ -interface PathProviderInterface -{ - /** - * Initialize with config options - */ - public function init(array $options); - - /** - * Add path elements to the route stack - * - * @return string - */ - public function providePath(RouteStack $routeStack); -} diff --git a/AutoRoute/RouteMaker/AutoRouteMaker.php b/AutoRoute/RouteMaker/AutoRouteMaker.php deleted file mode 100644 index 3dbaa04..0000000 --- a/AutoRoute/RouteMaker/AutoRouteMaker.php +++ /dev/null @@ -1,114 +0,0 @@ - - */ -class AutoRouteMaker implements RouteMakerInterface -{ - protected $dm; - - public function __construct(DocumentManager $dm) - { - $this->dm = $dm; - } - - public function make(RouteStack $routeStack) - { - $context = $routeStack->getContext(); - $content = $context->getContent(); - - $autoRoute = $this->getAutoRouteForDocument($content); - - if (!$autoRoute) { - $autoRoute = new AutoRoute; - $autoRoute->setContent($content); - } - - $autoRoute->setName($routeStack->getPath()); - $autoRoute->setParent($context->getTopRoute()); - - $routeStack->addRoute($autoRoute); - } - - protected function getAutoRouteForDocument($document) - { - if (!$this->documentIsPersisted($document)) { - return null; - } - - $dm = $this->dm; - $uow = $dm->getUnitOfWork(); - - $referrers = $this->dm->getReferrers($document); - - if ($referrers->count() == 0) { - return null; - } - - // Filter non auto-routes - $referrers = $referrers->filter(function ($referrer) { - if ($referrer instanceof AutoRoute) { - return true; - } - - return false; - }); - - $metadata = $dm->getClassMetadata(get_class($document)); - - $locale = null; // $uow->getLocale($document, $locale); - - // If the document is translated, filter locales - if (null !== $locale) { - throw new \Exception( - 'Translations not yet supported for Auto Routes - '. - 'Should be easy.' - ); - - // array_filter($referrers, function ($referrer) use ($dm, $uow, $locale) { - // $metadata = $dm->getClassMetadata($refferer); - // if ($locale == $uow->getLocaleFor($referrer, $referrer)) { - // return true; - // } - - // return false; - // }); - } - - if ($referrers->count() > 1) { - throw new \RuntimeException(sprintf( - 'More than one auto route for document "%s"', - get_class($document) - )); - } - - return $referrers->current(); - } - - protected function documentIsPersisted($document) - { - $id = $this->dm->getUnitOfWork()->getDocumentId($document); - $phpcrSession = $this->dm->getPhpcrSession(); - - return $phpcrSession->nodeExists($id); - } -} diff --git a/AutoRoute/RouteMaker/DefaultMaker.php b/AutoRoute/RouteMaker/DefaultMaker.php deleted file mode 100644 index cd3c00d..0000000 --- a/AutoRoute/RouteMaker/DefaultMaker.php +++ /dev/null @@ -1,43 +0,0 @@ - - */ -class DefaultMaker implements RouteMakerInterface -{ - protected $autoRouteMaker; - protected $patcher; - - public function __construct(RouteMakerInterface $autoRouteMaker, RouteMakerInterface $patcher) - { - $this->autoRouteMaker = $autoRouteMaker; - $this->patcher = $patcher; - } - - public function make(RouteStack $routeStack) - { - if ($routeStack instanceof AutoRouteStack) { - $this->autoRouteMaker->make($routeStack); - } else { - $this->patcher->make($routeStack); - } - } -} diff --git a/AutoRoute/RouteMaker/GenericMaker.php b/AutoRoute/RouteMaker/GenericMaker.php deleted file mode 100644 index a423932..0000000 --- a/AutoRoute/RouteMaker/GenericMaker.php +++ /dev/null @@ -1,49 +0,0 @@ - - */ -class GenericMaker implements RouteMakerInterface -{ - public function __construct(DocumentManager $dm) - { - $this->dm = $dm; - } - - public function make(RouteStack $routeStack) - { - $paths = $routeStack->getFullPaths(); - $meta = $this->dm->getClassMetadata('Doctrine\ODM\PHPCR\Document\Generic'); - - foreach ($paths as $path) { - $absPath = '/'.$path; - $doc = $this->dm->find(null, $absPath); - - if (null === $doc) { - $doc = new Generic; - $meta->setIdentifierValue($doc, $absPath); - } - - $routeStack->addRoute($doc); - } - } -} diff --git a/AutoRoute/RouteMaker/RouteMaker.php b/AutoRoute/RouteMaker/RouteMaker.php deleted file mode 100644 index eef3e18..0000000 --- a/AutoRoute/RouteMaker/RouteMaker.php +++ /dev/null @@ -1,61 +0,0 @@ - - */ -class RouteMaker implements RouteMakerInterface -{ - protected $defaults = array(); - - public function __construct(DocumentManager $dm) - { - $this->dm = $dm; - } - - public function init(array $options) - { - $options = array_merge(array( - 'defaults' => array(), - ), $options); - - $this->defaults = $options['defaults']; - } - - public function make(RouteStack $routeStack) - { - $paths = $routeStack->getFullPaths(); - - foreach ($paths as $path) { - $absPath = '/'.$path; - $doc = $this->dm->find(null, $absPath); - - if (null === $doc) { - $doc = new Route; - $doc->setDefaults($this->defaults); - $doc->setId($absPath); - } - - $routeStack->addRoute($doc); - } - } -} diff --git a/AutoRoute/RouteMakerInterface.php b/AutoRoute/RouteMakerInterface.php deleted file mode 100644 index 3b0fbba..0000000 --- a/AutoRoute/RouteMakerInterface.php +++ /dev/null @@ -1,25 +0,0 @@ - - * @date 13/03/24 - */ -interface RouteMakerInterface -{ - public function make(RouteStack $routeStack); -} diff --git a/AutoRoute/RoutePatcherInterface.php b/AutoRoute/RoutePatcherInterface.php deleted file mode 100644 index 75d325a..0000000 --- a/AutoRoute/RoutePatcherInterface.php +++ /dev/null @@ -1,34 +0,0 @@ - - */ -interface RoutePatcherInterface -{ - public function patch(RouteStack $routeStack); -} diff --git a/AutoRoute/RouteStack.php b/AutoRoute/RouteStack.php deleted file mode 100644 index 407b464..0000000 --- a/AutoRoute/RouteStack.php +++ /dev/null @@ -1,272 +0,0 @@ - - */ -class RouteStack -{ - protected $pathElements = array(); - protected $routes = array(); - protected $context; - protected $existingRoute; - - protected $closed = false; - - public function __construct(BuilderContext $context) - { - $context->stageRouteStack($this); - $this->context = $context; - } - - /** - * Adds path elements, e.g. - * - * array('this', 'is', 'a', 'path') - * - * @param array - */ - public function addPathElements(array $pathElements) - { - foreach ($pathElements as $pathElement) { - $this->addPathElement($pathElement); - } - } - - /** - * Add a single path element - * - * @param string - */ - public function addPathElement($pathElement) - { - if (!$pathElement) { - throw new Exception\InvalidPathElementException('Empty path element passed to addPAthElement'); - } - - if (false !== strpos($pathElement, '/')) { - throw new Exception\InvalidPathElementException(sprintf( - 'Path elements must not contain the path separator "/", given "%s"', - $pathElement - )); - } - - if (true === $this->closed) { - throw new Exception\CannotModifyClosedRouteStackException( - 'Cannot add path elements to a closed route stack.' - ); - } - - $this->pathElements[] = $pathElement; - } - - /** - * Return all path elements - * - * @return array - */ - public function getPathElements() - { - return $this->pathElements; - } - - /** - * Return all the possible paths, e.g. - * - * Given path is: /this/is/a/path - * - * This method will return: - * - * - /this - * - /this/is - * - /this/is/a/ - * - /this/is/a/path - * - * @return array - */ - public function getPaths() - { - if (empty($this->pathElements)) { - return array(); - } - - $tmp = array(); - - foreach ($this->pathElements as $pathElement) { - $tmp[] = $pathElement; - $paths[] = implode('/', $tmp); - } - - return $paths; - } - - /** - * Same as getPaths but prepends the current builder context - * path. /almost/ giving you the abolute path (you need only - * to add the "/" at the beginning)/ - * - * @see getPaths - * - * @return array - */ - public function getFullPaths() - { - $parentPath = $this->context->getFullPath($this); - - $paths = $this->getPaths(); - - array_walk($paths, function (&$path) use ($parentPath) { - $path = $parentPath ? $parentPath.'/'.$path : $path; - }); - - return $paths; - } - - /** - * Returns the full path, same as getFullPaths but - * only returns the "top" path. - * - * @return string - */ - public function getFullPath() - { - $parentPath = $this->context->getFullPath(); - - $fullPath = $this->getPath(); - - if ($parentPath) { - if (empty($fullPath)) { - $fullPath = $parentPath; - } else { - $fullPath = $parentPath.'/'.$fullPath; - } - } - - return $fullPath; - } - - /** - * Same as getFullPath but prepends the "/" to - * make it absolute. - * - * @return string - */ - public function getAbsolutePath() - { - return '/'.$this->getFullPath(); - } - - /** - * Return the path given by joining all the - * path elements. - * - * @return string - */ - public function getPath() - { - return implode('/', $this->pathElements); - } - - /** - * Replace the last path element in the current path - * - * @param string $name - */ - public function replaceLastPathElement($name) - { - array_pop($this->pathElements); - $this->pathElements[] = $name; - } - - /** - * Add a route to the stack. - * - * Note you can only add routes to an open stack. - * - * @param object - */ - public function addRoute($route) - { - if (true === $this->closed) { - throw new \RuntimeException('Cannot add path elements to a closed route stack.'); - } - - $this->routes[] = $route; - } - - public function addRoutes($routes) - { - foreach ($routes as $route) { - $this->addRoute($route); - } - } - - /** - * Close the stack. Closing a stack will check to see if - * the number of path elements matches the number of routes and - * prevents the addition of more routes. Also it enables the - * getRoutes method. - */ - public function close() - { - if (count($this->routes) != count($this->pathElements)) { - throw new \RuntimeException(sprintf( - 'Attempting to close route stack but the number of path elements (%d) '. - 'does not match number of route elements (%d). Registered path elements: "%s"', - count($this->pathElements), - count($this->routes), - implode(',', $this->pathElements) - )); - } - - $this->closed = true; - } - - /** - * Return all routes, only works if RouteStack is closed. - * - * @return array - */ - public function getRoutes() - { - if (false === $this->closed) { - throw new \RuntimeException( - 'You must close the route stack before retrieving the route nodes.' - ); - } - - return $this->routes; - } - - /** - * Return true if the route stack is closed - * - * @return boolean - */ - public function isClosed() - { - return $this->closed; - } - - /** - * Return the builder context associated with this - * route stack - */ - public function getContext() - { - return $this->context; - } -} diff --git a/AutoRoute/RouteStack/Builder.php b/AutoRoute/RouteStack/Builder.php deleted file mode 100644 index d958719..0000000 --- a/AutoRoute/RouteStack/Builder.php +++ /dev/null @@ -1,50 +0,0 @@ - - */ -class Builder -{ - protected $dm; - - public function __construct(DocumentManager $dm) - { - $this->dm = $dm; - } - - public function build(RouteStack $routeStack, BuilderUnitInterface $rsbu) - { - $rsbu->pathAction($routeStack); - $fullPath = $routeStack->getFullPath(); - $absPath = '/'.$fullPath; - - $existingRoute = $this->dm->find(null, $absPath); - - if ($existingRoute) { - $rsbu->existsAction($routeStack); - } else { - $rsbu->notExistsAction($routeStack); - } - - // hmm ... this seems wierd. Needs some refactoring. - $routeStack->close(); - $routeStack->getContext()->commitRouteStack(); - } -} diff --git a/AutoRoute/RouteStack/BuilderUnit.php b/AutoRoute/RouteStack/BuilderUnit.php deleted file mode 100644 index fa54ed3..0000000 --- a/AutoRoute/RouteStack/BuilderUnit.php +++ /dev/null @@ -1,65 +0,0 @@ - - */ -class BuilderUnit implements BuilderUnitInterface -{ - protected $pathProvider; - protected $existsAction; - protected $notExistsAction; - - public function __construct( - PathProviderInterface $pathProvider, - PathActionInterface $existsAction, - PathActionInterface $notExistsAction - ) { - $this->pathProvider = $pathProvider; - $this->existsAction = $existsAction; - $this->notExistsAction = $notExistsAction; - } - - /** - * {@inheritDoc} - */ - public function pathAction(RouteStack $routeStack) - { - $this->pathProvider->providePath($routeStack); - } - - /** - * {@inheritDoc} - */ - public function existsAction(RouteStack $routeStack) - { - $this->existsAction->execute($routeStack); - } - - /** - * {@inheritDoc} - */ - public function notExistsAction(RouteStack $routeStack) - { - $this->notExistsAction->execute($routeStack); - } -} diff --git a/AutoRoute/RouteStack/BuilderUnitChain.php b/AutoRoute/RouteStack/BuilderUnitChain.php deleted file mode 100644 index 0482093..0000000 --- a/AutoRoute/RouteStack/BuilderUnitChain.php +++ /dev/null @@ -1,45 +0,0 @@ - - */ -class BuilderUnitChain -{ - protected $chain; - protected $builder; - - public function __construct(Builder $builder) - { - $this->builder = $builder; - } - - public function addBuilderUnit($name, BuilderUnitInterface $unit) - { - $this->chain[$name] = $unit; - } - - public function executeChain(BuilderContext $context) - { - foreach ($this->chain as $name => $builderUnit) { - $routeStack = new RouteStack($context); - $this->builder->build($routeStack, $builderUnit); - } - } -} diff --git a/AutoRoute/RouteStack/BuilderUnitInterface.php b/AutoRoute/RouteStack/BuilderUnitInterface.php deleted file mode 100644 index 4c9c0f1..0000000 --- a/AutoRoute/RouteStack/BuilderUnitInterface.php +++ /dev/null @@ -1,72 +0,0 @@ - - */ -interface BuilderUnitInterface -{ - /** - * Provide an ordered list of route names, e.g. - * - * array('this', 'will', 'be', 'a', 'url'); - * - * Would represent: - * - * /this/would/be/a/url - * - * @param RouteStack $routeStack - * - * @return array - */ - public function pathAction(RouteStack $routeStack); - - /** - * Perform an action if the route names given by pathAction - * resolve the an existing document. - * - * The action must ensure that the number of route names - * given by the pathAction add up to the number of routes - * in the RouteStack. - * - * @param RouteStack $routeStack - * - * @return void - action operates on RouteStack. - */ - public function existsAction(RouteStack $routeStack); - - /** - * Perform an action if the route names given by pathAction - * do not resolve the an existing document. - * - * The action must ensure that the number of route names - * given by the pathAction add up to the number of routes - * in the RouteStack. - * - * @param RouteStack $routeStack - * - * @return void - action operates on route stack. - */ - public function notExistsAction(RouteStack $routeStack); -} diff --git a/AutoRoute/ServiceRegistry.php b/AutoRoute/ServiceRegistry.php new file mode 100644 index 0000000..2d45243 --- /dev/null +++ b/AutoRoute/ServiceRegistry.php @@ -0,0 +1,57 @@ +tokenProviders[$name])) { + throw new \InvalidArgumentException(sprintf( + 'Token provider with name "%s" has not been registered', + $name + )); + } + + return $this->tokenProviders[$name]; + } + + /** + * Return the named conflict resolver. + * + * @throws \InvalidArgumentException if the named token provider does not exist. + * + * @return ConflictResolverInterface + */ + public function getConflcitResolver($name) + { + if (!isset($this->conflictResolvers[$name])) { + throw new \InvalidArgumentException(sprintf( + 'Conflict resolver with name "%s" has not been registered', + $name + )); + } + + return $this->conflictResolvers[$name]; + } + + public function regsiterTokenProvider(TokenProviderInterface $provider) + { + $this->tokenProviders[$provider->getName()] = $provider; + } + + public function registerConflictResolver(ConflictResolverInterface $conflictResolver) + { + $this->conflictResolver[$conflictResolver->getName()] = $conflictResolver; + } +} diff --git a/AutoRoute/TokenProviderInterface.php b/AutoRoute/TokenProviderInterface.php new file mode 100644 index 0000000..2ad7740 --- /dev/null +++ b/AutoRoute/TokenProviderInterface.php @@ -0,0 +1,26 @@ + + */ +class UrlGenerator implements UrlGeneratorInterface +{ + protected $driver; + protected $metadataFactory; + protected $serviceRegistry; + + /** + * @param MetadataFactory the metadata factory + * @param DriverInterface the autoroute backend driver (odm ,orm, etc) + * @param ServiceRegistry the auto route service registry + */ + public function __construct( + MetadataFactoryInterface $metadataFactory, + DriverInterface $driver, + ServiceRegistry $serviceRegistry + ) + { + $this->metadataFactory = $metadataFactory; + $this->driver = $driver; + $this->serviceRegistry = $serviceRegistry; + } + + /** + * {@inheritDoc} + */ + public function generateUrl($document) + { + $realClassName = $this->driver->getRealClassName(get_class($document)); + $metadata = $this->metadataFactory->getMetadataForClass($realClassName); + + $tokenProviderConfigs = $metadata->getTokenProviderConfigs(); + + $tokens = array(); + foreach ($tokenProviderConfigs as $name => $options) { + $tokenProvider = $this->serviceRegistry->getTokenProvider($options['provider']); + $tokens['{' . $name . '}'] = $tokenProvider->getValue($document, $options); + } + + $urlSchema = $metadata->getUrlSchema(); + $url = strtr($urlSchema, $tokens); + + return $url; + } + + /** + * {@inheritDoc} + */ + public function resolveConflict($document, $url) + { + $realClassName = $this->driver->getRealClassName($document); + $metadata = $this->factory->getMetadataForClass($realClassName); + + list ($name, $config) = $metadata->getConflictResolverConfig(); + $conflictResolver = $this->serviceRegistry->getConflictResolver($name, $config); + $url = $conflictResolver->resolveConflict($url); + + return $url; + } +} diff --git a/AutoRoute/UrlGeneratorInterface.php b/AutoRoute/UrlGeneratorInterface.php new file mode 100644 index 0000000..663b880 --- /dev/null +++ b/AutoRoute/UrlGeneratorInterface.php @@ -0,0 +1,33 @@ + + */ +interface UrlGeneratorInterface +{ + /** + * Generate a URL for the given document + * + * @param object $document + * + * @return string + */ + public function generateUrl($document); + + /** + * The given URL already exists in the database, this method + * should delegate the task of resolving the conflict to + * the ConflictResolver configured in the mapping for the + * document. + * + * @param object $document + * @param string $url + * + * @return string + */ + public function resolveConflict($document, $url); +} diff --git a/Doctrine/Phpcr/AutoRouteListener.php b/Doctrine/Phpcr/AutoRouteListener.php index 460d6e7..4142475 100644 --- a/Doctrine/Phpcr/AutoRouteListener.php +++ b/Doctrine/Phpcr/AutoRouteListener.php @@ -31,7 +31,7 @@ public function __construct(ContainerInterface $container) /** * @return AutoRouteManager */ - protected function getArm() + protected function getAutoRouteManager() { // lazy load the auto_route_manager service to prevent a cirular-reference // to the document manager. @@ -43,6 +43,7 @@ public function onFlush(ManagerEventArgs $args) /** @var $dm DocumentManager */ $dm = $args->getObjectManager(); $uow = $dm->getUnitOfWork(); + $arm = $this->getAutoRouteManager(); $scheduledInserts = $uow->getScheduledInserts(); $scheduledUpdates = $uow->getScheduledUpdates(); @@ -50,49 +51,20 @@ public function onFlush(ManagerEventArgs $args) $autoRoute = null; foreach ($updates as $document) { - if ($this->getArm()->isAutoRouteable($document)) { - $contexts = $this->getArm()->updateAutoRouteForDocument($document); + if ($arm->isAutoRouteable($document)) { - $persistedRoutes = array(); - - foreach ($contexts as $context) { - foreach ($context->getRoutes() as $route) { - - if ($route instanceof AutoRoute) { - $autoRoute = $route; - $routeParent = $route->getParent(); - $id = spl_object_hash($routeParent).$route->getName(); - } else { - $metadata = $dm->getClassMetadata(get_class($route)); - $id = $metadata->getIdentifierValue($route); - } - - if (isset($persistedRoutes[$id])) { - continue; - } - - $dm->persist($route); - $persistedRoutes[$id] = true; - } - - $uow->computeChangeSets(); - - // For some reason the AutoRoute is not updated even though - // it is persisted above. Re-persisting and recomputing the - // changesets makes this work. - if (null !== $autoRoute) { - $dm->persist($autoRoute); - } + $operationStack = $arm->getOperationStackForDocument($document); + foreach ($operationStack->getPersistStack() as $document) { + $dm->persist($document); $uow->computeChangeSets(); } } } $removes = $uow->getScheduledRemovals(); - foreach ($removes as $document) { - if ($this->getArm()->isAutoRouteable($document)) { + if ($this->getAutoRouteManager()->isAutoRouteable($document)) { $referrers = $dm->getReferrers($document); $referrers = $referrers->filter(function ($referrer) { if ($referrer instanceof AutoRoute) { diff --git a/Tests/Unit/AutoRoute/Adapter/PhpcrOdmAdapterTest.php b/Tests/Unit/AutoRoute/Adapter/PhpcrOdmAdapterTest.php new file mode 100644 index 0000000..bfb5df0 --- /dev/null +++ b/Tests/Unit/AutoRoute/Adapter/PhpcrOdmAdapterTest.php @@ -0,0 +1,158 @@ +dm = $this->prophet->prophesize('Doctrine\ODM\PHPCR\DocumentManager'); + $this->metadataFactory = $this->prophet->prophesize('Doctrine\ODM\PHPCR\Mapping\ClassMetadataFactory'); + $this->metadata = $this->prophet->prophesize('Doctrine\ODM\PHPCR\Mapping\ClassMetadata'); + $this->contentDocument = new \stdClass; + $this->contentDocument2 = new \stdClass; + $this->parentRoute = new \stdClass; + $this->route = $this->prophet->prophesize('Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr\Route'); + + $this->phpcrSession = $this->prophet->prophesize('PHPCR\SessionInterface'); + $this->phpcrRootNode = $this->prophet->prophesize('PHPCR\NodeInterface'); + $this->baseRoutePath = '/test'; + + $this->adapter = new PhpcrOdmAdapter($this->dm->reveal(), $this->baseRoutePath); + } + + public function provideGetLocales() + { + return array( + array(true, array('fr', 'de')), + array(false), + ); + } + + /** + * @dataProvider provideGetLocales + */ + public function testGetLocales($isTranslateable, $locales = array()) + { + $this->dm->isDocumentTranslatable($this->contentDocument) + ->willReturn($isTranslateable); + + if ($isTranslateable) { + $this->dm->getLocalesFor($this->contentDocument) + ->willReturn($locales); + } + + $res = $this->adapter->getLocales($this->contentDocument); + $this->assertEquals($locales, $res); + } + + public function provideTranslatedObject() + { + return array( + array('stdClass', 'some/path', 'fr'), + ); + } + + /** + * @dataProvider provideTranslatedObject + */ + public function testTranslateObject($className, $id, $locale) + { + $this->dm->getMetadataFactory() + ->willReturn($this->metadataFactory->reveal()); + $this->metadataFactory->getMetadataFor($className) + ->willReturn($this->metadata->reveal()); + $this->metadata->getName() + ->willReturn($className); + $this->metadata->getIdentifierValue($this->contentDocument) + ->willReturn($id); + + $this->dm->findTranslation($className, $id, $locale) + ->willReturn($this->contentDocument); + + $res = $this->adapter->translateObject($this->contentDocument, $locale); + $this->assertSame($this->contentDocument, $res); + } + + public function provideCreateRoute() + { + return array( + array('/foo/bar', '/foo', 'bar', true) + ); + } + + /** + * @dataProvider provideCreateRoute + */ + public function testCreateRoute($path, $expectedParentPath, $expectedName, $parentPathExists) + { + $this->dm->getPhpcrSession()->willReturn($this->phpcrSession); + $this->phpcrSession->getRootNode()->willReturn($this->phpcrRootNode); + if ($parentPathExists) { + $this->dm->find(null, $expectedParentPath) + ->willReturn($this->parentRoute); + } else { + $this->dm->find(null, $expectedParentPath) + ->willReturn(null); + } + + $res = $this->adapter->createRoute($path, $this->contentDocument); + $this->assertNotNull($res); + $this->assertInstanceOf('Symfony\Cmf\Bundle\RoutingAutoBundle\Model\AutoRoute', $res); + $this->assertEquals($expectedName, $res->getName()); + $this->assertSame($this->parentRoute, $res->getParent()); + $this->assertSame($this->contentDocument, $res->getContent()); + } + + public function testGetRealClassName() + { + $res = $this->adapter->getRealClassName('Class/Foo'); + $this->assertEquals('Class/Foo', $res); + } + + public function provideCompareRouteContent() + { + return array( + array(true), + array(false), + ); + } + + /** + * @dataProvider provideCompareRouteContent + */ + public function testCompareRouteContent($isMatch) + { + $this->route->getContent()->willReturn($this->contentDocument); + $content = $isMatch ? $this->contentDocument : $this->contentDocument2; + + $this->adapter->compareRouteContent($this->route->reveal(), $this->contentDocument); + } + + public function testGetReferringRoutes() + { + $this->dm->getReferrers($this->contentDocument, null, null, null, 'Symfony\Cmf\Component\Routing\RouteObjectInterface') + ->willReturn(array($this->route)); + $res = $this->adapter->getReferringRoutes($this->contentDocument); + + $this->assertSame(array($this->route->reveal()), $res); + } + + public function testFindRouteForUrl() + { + $url = '/this/is/url'; + $expectedRoutes = array($this->route->reveal()); + + $this->dm->find(null, $this->baseRoutePath . $url)->willReturn($expectedRoutes); + + $res = $this->adapter->findRouteForUrl($url); + $this->assertSame($expectedRoutes, $res); + } +} diff --git a/Tests/Unit/AutoRoute/AutoRouteManagerTest.php b/Tests/Unit/AutoRoute/AutoRouteManagerTest.php index d421adc..8551fe6 100644 --- a/Tests/Unit/AutoRoute/AutoRouteManagerTest.php +++ b/Tests/Unit/AutoRoute/AutoRouteManagerTest.php @@ -1,76 +1,83 @@ factory = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Factory' - )->disableOriginalConstructor()->getMock(); - - $this->builder = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack\Builder' - )->disableOriginalConstructor()->getMock(); - - $this->driver = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Driver\DriverInterface' + $this->driver = $this->getMock('Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Driver\DriverInterface'); + $this->urlGenerator = $this->getMock('Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\UrlGeneratorInterface'); + $this->defunctRouteHandler = $this->getMock('Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\DefunctRouteHandlerInterface'); + $this->autoRouteManager = new AutoRouteManager( + $this->driver, + $this->urlGenerator, + $this->defunctRouteHandler ); + } - $this->arm = new AutoRouteManager($this->driver, $this->factory, $this->builder); - - $this->builderUnitChain = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack\BuilderUnitChain' - )->disableOriginalConstructor()->getMock(); - - $this->cnbu = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack\BuilderUnitInterface' + public function provideBuildOperationStack() + { + return array( + array( + array( + 'locales' => array('en', 'fr', 'de', 'be'), + 'urls' => array( + '/en/this-is-an-route' => array('conflict' => false), + '/fr/this-is-an-route' => array('conflict' => false), + '/de/this-is-an-route' => array('conflict' => false), + '/be/this-is-an-route' => array('conflict' => false), + ), + 'existingRoute' => false, + ), + ), ); } - public function testUpdateAutoRouteForDocument() + /** + * @dataProvider provideBuildOperationStack + */ + public function testBuildOperationStack($params) { - $testCase = $this; - $this->factory->expects($this->once()) - ->method('getRouteStackBuilderUnitChain') - ->will($this->returnValue($this->builderUnitChain)); - $this->factory->expects($this->once()) - ->method('getContentNameBuilderUnit') - ->with('stdClass') - ->will($this->returnValue($this->cnbu)); + $params = array_merge(array( + 'locales' => array(), + 'urls' => array(), + ), $params); + + $this->driver->expects($this->once()) + ->method('getLocales') + ->will($this->returnValue($params['locales'])); + + $localesCount = count($params['locales']); + $urls = $params['urls']; + $indexedUrls = array_keys($urls); + $expectedRoutes = array(); + $document = new \stdClass; + + for ($i = 0; $i < $localesCount; $i++) { + $expectedRoutes[] = $this->getMock('Symfony\Cmf\Component\Routing\RouteObjectInterface'); + + $this->urlGenerator->expects($this->exactly($localesCount)) + ->method('generateUrl') + ->with($document) + ->will($this->returnCallback(function () use ($i, $indexedUrls) { + return $indexedUrls[$i]; + })); - $this->builderUnitChain->expects($this->once()) - ->method('executeChain') - ->will($this->returnCallback(function ($context) use ($testCase) { - $testCase->assertInstanceOf( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\BuilderContext', - $context - ); - })); + $this->driver->expects($this->exactly($localesCount)) + ->method('createRoute') + ->will($this->returnCallback(function ($url, $document) use ($i, $expectedRoutes) { + return $expectedRoutes[$i]; + })); + } - $this->builder->expects($this->once()) - ->method('build') - ->will($this->returnCallback(function ($stack, $builderUnit) use ($testCase) { - $testCase->assertInstanceOf( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\AutoRouteStack', - $stack - ); - $testCase->assertSame($testCase->cnbu, $builderUnit); - })); + $operationStack = new OperationStack(); + $this->autoRouteManager->buildOperationStack($operationStack, $document); - $stdClass = new \stdClass; - $this->arm->updateAutoRouteForDocument($stdClass); + $res = $operationStack->getPersistStack(); + $this->assertEquals($expectedRoutes, $res); } } diff --git a/Tests/Unit/AutoRoute/BuilderContextTest.php b/Tests/Unit/AutoRoute/BuilderContextTest.php deleted file mode 100644 index 80e8ed0..0000000 --- a/Tests/Unit/AutoRoute/BuilderContextTest.php +++ /dev/null @@ -1,104 +0,0 @@ -builderContext = new BuilderContext(); - $this->routeStack = $this->getMockBuilder('Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack')->disableOriginalConstructor()->getMock(); - $this->object = new \stdClass; - } - - public function testStageAndCommitRouteStack() - { - $this->routeStack->expects($this->once()) - ->method('isClosed') - ->will($this->returnValue(true)); - - $this->builderContext->stageRouteStack($this->routeStack); - $this->builderContext->commitRouteStack(); - - $this->assertCount(1, $this->builderContext->getRouteStacks()); - } - - public function testIgnoreEmptyPath() - { - $this->routeStack->expects($this->at(3)) - ->method('getPath') - ->will($this->returnValue('route')); - - $this->routeStack->expects($this->at(4)) - ->method('getPath') - ->will($this->returnValue('')); - - $this->routeStack->expects($this->at(5)) - ->method('getPath') - ->will($this->returnValue('foo/bar')); - - $this->routeStack->expects($this->exactly(3)) - ->method('isClosed') - ->will($this->returnValue(true)); - - for ($i = 0; $i < 3; $i++) { - $this->builderContext->stageRouteStack($this->routeStack); - $this->builderContext->commitRouteStack(); - } - - $this->assertCount(3, $this->builderContext->getRouteStacks()); - $this->assertEquals('route/foo/bar', $this->builderContext->getFullPath()); - } - - /** - * @expectedException \RuntimeException - */ - public function testStageOpenRouteStack() - { - $this->routeStack->expects($this->once()) - ->method('isClosed') - ->will($this->returnValue(false)); - - $this->builderContext->stageRouteStack($this->routeStack); - $this->builderContext->commitRouteStack(); - } - - public function testSetObject() - { - $this->builderContext->setContent($this->object); - $this->assertSame($this->object, $this->builderContext->getContent()); - } - - /** - * @expectedException \RuntimeException - */ - public function testCommitWithNoStagedRouteStack() - { - $this->builderContext->commitRouteStack(); - } - - public function testGetRoutes() - { - $this->routeStack->expects($this->once()) - ->method('getRoutes') - ->will($this->returnValue(array( - $r1 = new \stdClass, - $r2 = new \stdClass, - ))); - $this->builderContext->stageRouteStack($this->routeStack); - $this->builderContext->commitRouteStack(); - $routes = $this->builderContext->getRoutes(); - $this->assertSame(array($r1, $r2), $routes); - } -} diff --git a/Tests/Unit/AutoRoute/FactoryTest.php b/Tests/Unit/AutoRoute/FactoryTest.php deleted file mode 100644 index cf0209a..0000000 --- a/Tests/Unit/AutoRoute/FactoryTest.php +++ /dev/null @@ -1,135 +0,0 @@ -builder = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack\Builder' - )->disableOriginalConstructor()->getMock(); - - $this->container = $this->getMock( - 'Symfony\Component\DependencyInjection\ContainerInterface' - ); - $this->mappingFactory = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Mapping\MappingFactory' - ); - - $this->bucf = new Factory( - $this->mappingFactory, $this->container, $this->builder - ); - - $this->fixedPath = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\PathProviderInterface' - ); - $this->dynamicPath = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\PathProviderInterface' - ); - $this->createPath = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\PathActionInterface' - ); - $this->throwExceptionPath = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\PathActionInterface' - ); - - $this->dicMap = array( - 'fixed_service_id' => $this->fixedPath, - 'dynamic_service_id' => $this->dynamicPath, - 'create_service_id' => $this->createPath, - 'throw_excep_service_id' => $this->throwExceptionPath, - ); - - $this->bucf->registerAlias('provider', 'fixed', 'fixed_service_id'); - $this->bucf->registerAlias('provider', 'dynamic', 'dynamic_service_id'); - $this->bucf->registerAlias('exists_action', 'create', 'create_service_id'); - $this->bucf->registerAlias('not_exists_action', 'throw_excep', 'throw_excep_service_id'); - } - - /** TODO refactor - public function provideTestGetChain() - { - return array( - array( - array( - 'content_path' => array( - 'path_units' => array( - 'base' => array( - 'provider' => array( - 'name' => 'fixed', - 'options' => array( - 'message' => 'foobar', - ), - ), - 'exists_action' => array( - 'strategy' => 'create', - 'options' => array(), - ), - 'not_exists_action' => array( - 'strategy' => 'throw_excep', - 'options' => array(), - ), - ), - ), - ), - 'content_name' => array( - 'provider' => array( - 'name' => 'fixed', - 'options' => array( - 'message' => 'barfoo', - ), - ), - 'exists_action' => array( - 'strategy' => 'create', - 'options' => array(), - ), - 'not_exists_action' => array( - 'strategy' => 'throw_excep', - 'options' => array(), - ), - ), - ), - array( - 'fixed_service_id' => array('message' => 'foobar'), - ), - ), - ); - } - - /** - * @dataProvider provideTestGetChain - * - public function testGetChain($config, $assertOptions) - { - $dicMap = $this->dicMap; - $this->container->expects($this->any()) - ->method('get') - ->will($this->returnCallback(function ($serviceId) use ($dicMap) { - return $dicMap[$serviceId]; - })); - - foreach ($assertOptions as $serviceId => $assertOptions) { - $dicMap[$serviceId]->expects($this->once()) - ->method('init') - ->with($assertOptions); - } - - $this->mappingFactory->expects($this->any()) - ->method('getMappingsForClass') - ->with($this->equalTo('stdClass')) - ->will($this->returnValue($config)); - $this->bucf->getRouteStackBuilderUnitChain('stdClass'); - }*/ -} diff --git a/Tests/Unit/AutoRoute/PathExists/AutoIncrementPathTest.php b/Tests/Unit/AutoRoute/PathExists/AutoIncrementPathTest.php deleted file mode 100644 index f91f0f5..0000000 --- a/Tests/Unit/AutoRoute/PathExists/AutoIncrementPathTest.php +++ /dev/null @@ -1,151 +0,0 @@ -routeMaker = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteMakerInterface' - ); - - $this->dm = $this->getMockBuilder('Doctrine\ODM\PHPCR\DocumentManager') - ->disableOriginalConstructor() - ->getMock(); - - $this->routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - - $this->builderContext = $this->getMock('Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\BuilderContext'); - - $this->aiPath = new AutoIncrementPath($this->dm, $this->routeMaker); - $this->route1 = $this->getMockBuilder('Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr\Route') - ->disableOriginalConstructor() - ->getMock(); - $this->route2 = $this->getMockBuilder('Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr\Route') - ->disableOriginalConstructor() - ->getMock(); - - $this->content1 = new \stdClass; - $this->content2 = new \stdClass; - } - - public function provideAutoIncrement() - { - return array( - array(false), - array(true), - ); - } - - /** - * @dataProvider provideAutoIncrement - */ - public function testAutoIncrement($testUpdate) - { - $this->routeStack->expects($this->once()) - ->method('getFullPath') - ->will($this->returnValue('/foo/bar')); - - $this->routeStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - - // if we test update we have the same content found - // by the DM and set in the builder context - $this->dm->expects($this->at(0)) - ->method('find') - ->with(null, '/foo/bar') - ->will($this->returnValue($this->route1)); - - $this->route1->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->content1)); - - if (true === $testUpdate) { - $this->builderContext->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->content1)); - } else { - $this->builderContext->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->content2)); - } - - if (false === $testUpdate) { - $this->dm->expects($this->at(1)) - ->method('find') - ->with(null, '/foo/bar-1') - ->will($this->returnValue(new \stdClass)); - - $this->dm->expects($this->at(2)) - ->method('find') - ->with(null, '/foo/bar-2') - ->will($this->returnValue(null)); - - $this->routeStack->expects($this->once()) - ->method('replaceLastPathElement') - ->with('bar-2'); - - $this->routeMaker->expects($this->once()) - ->method('make') - ->with($this->routeStack); - } - - $this->aiPath->execute($this->routeStack); - } - - public function testFormatOption() - { - $this->routeStack->expects($this->once()) - ->method('getFullPath') - ->will($this->returnValue('/foo/bar')); - - $this->routeStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - - $this->dm->expects($this->at(0)) - ->method('find') - ->with(null, '/foo/bar') - ->will($this->returnValue($this->route1)); - - $this->route1->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->content1)); - - $this->builderContext->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->content2)); - - $this->dm->expects($this->at(1)) - ->method('find') - ->with(null, '/foo/bar1') - ->will($this->returnValue(null)); - - $this->routeStack->expects($this->once()) - ->method('replaceLastPathElement') - ->with('bar1'); - - $this->routeMaker->expects($this->once()) - ->method('make') - ->with($this->routeStack); - - $aiPath = new AutoIncrementPath($this->dm, $this->routeMaker); - $aiPath->init(array('format' => '%d')); - $aiPath->execute($this->routeStack); - } -} diff --git a/Tests/Unit/AutoRoute/PathExists/UsePathTest.php b/Tests/Unit/AutoRoute/PathExists/UsePathTest.php deleted file mode 100644 index 3eac96d..0000000 --- a/Tests/Unit/AutoRoute/PathExists/UsePathTest.php +++ /dev/null @@ -1,52 +0,0 @@ -dm = $this->getMockBuilder('Doctrine\ODM\PHPCR\DocumentManager') - ->disableOriginalConstructor() - ->getMock(); - - $this->routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - - $this->usePath = new UsePath($this->dm); - $this->routeObject = new \stdClass; - } - - public function testUse() - { - $this->routeStack->expects($this->once()) - ->method('getFullPaths') - ->will($this->returnValue(array( - 'foobar' - ))); - - $this->routeStack->expects($this->once()) - ->method('addRoute') - ->with($this->routeObject); - - $this->dm->expects($this->at(0)) - ->method('find') - ->with(null, 'foobar') - ->will($this->returnValue($this->routeObject)); - - $this->usePath->execute($this->routeStack); - } - -} diff --git a/Tests/Unit/AutoRoute/PathNotExists/CreatePathTest.php b/Tests/Unit/AutoRoute/PathNotExists/CreatePathTest.php deleted file mode 100644 index 27d9c20..0000000 --- a/Tests/Unit/AutoRoute/PathNotExists/CreatePathTest.php +++ /dev/null @@ -1,38 +0,0 @@ -routeMaker = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteMakerInterface' - ); - - $this->routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - - $this->createPath = new CreatePath($this->routeMaker); - } - - public function testCreatePath() - { - $this->routeMaker->expects($this->once()) - ->method('make') - ->with($this->routeStack); - $this->createPath->execute($this->routeStack); - } -} diff --git a/Tests/Unit/AutoRoute/PathNotExists/ThrowExceptionTest.php b/Tests/Unit/AutoRoute/PathNotExists/ThrowExceptionTest.php deleted file mode 100644 index 312df6f..0000000 --- a/Tests/Unit/AutoRoute/PathNotExists/ThrowExceptionTest.php +++ /dev/null @@ -1,34 +0,0 @@ -routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - - $this->throwException = new ThrowException(); - } - - /** - * @expectedException Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Exception\CouldNotFindRouteException - */ - public function testThrowException() - { - $this->throwException->execute($this->routeStack); - } -} diff --git a/Tests/Unit/AutoRoute/PathProvider/ContentDateTimeProviderTest.php b/Tests/Unit/AutoRoute/PathProvider/ContentDateTimeProviderTest.php deleted file mode 100644 index 0feae6e..0000000 --- a/Tests/Unit/AutoRoute/PathProvider/ContentDateTimeProviderTest.php +++ /dev/null @@ -1,110 +0,0 @@ -builderContext = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\BuilderContext' - ); - $this->routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - $this->slugifier = $this->getMock( - 'Symfony\Cmf\Bundle\CoreBundle\Slugifier\SlugifierInterface' - ); - - $this->provider = new ContentDateTimeProvider($this->slugifier); - $this->object = new ContentDateTimeTestClass(); - } - - /** - * @expectedException Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Exception\MissingOptionException - */ - public function testProvidePath_noDateTime() - { - $this->provider->init(array()); - } - - /** - * @expectedException \BadMethodCallException - */ - public function testProvideDateTime_invalidDateTime() - { - $this->routeStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - $this->builderContext->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->object)); - $this->provider->init(array('method' => 'invalidDateTime')); - $this->provider->providePath($this->routeStack); - } - - public function setupTest($slugify = true) - { - $this->routeStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - $this->builderContext->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->object)); - - if ($slugify) { - $this->slugifier->expects($this->any()) - ->method('slugify') - ->will($this->returnCallback(function ($el) { return $el; })); - } - } - - public function testProvideDateTime() - { - $this->setupTest(); - $this->routeStack->expects($this->once()) - ->method('addPathElements') - ->with(array('2013', '03', '21')); - - $this->provider->init(array( - 'method' => 'getDate', - 'date_format' => 'Y/m/d' - )); - - $this->provider->providePath($this->routeStack); - } - - /** - * @expectedException \BadMethodCallException - */ - public function testProvideBadDateTime() - { - $this->setupTest(); - $this->provider->providePath($this->routeStack); - } -} - -class ContentDateTimeTestClass -{ - public function getDate() - { - return new \DateTime('2013/03/21'); - } - - public function getBadDate() - { - return "thisisastring"; - } -} diff --git a/Tests/Unit/AutoRoute/PathProvider/ContentMethodProviderTest.php b/Tests/Unit/AutoRoute/PathProvider/ContentMethodProviderTest.php deleted file mode 100644 index 8f83dba..0000000 --- a/Tests/Unit/AutoRoute/PathProvider/ContentMethodProviderTest.php +++ /dev/null @@ -1,173 +0,0 @@ -builderContext = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\BuilderContext' - ); - $this->routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - $this->slugifier = $this->getMock( - 'Symfony\Cmf\Bundle\CoreBundle\Slugifier\SlugifierInterface' - ); - - $this->provider = new ContentMethodProvider($this->slugifier); - $this->object = new ContentMethodTestClass(); - } - - /** - * @expectedException Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Exception\MissingOptionException - */ - public function testProvidePath_noMethod() - { - $this->provider->init(array()); - } - - /** - * @expectedException \BadMethodCallException - */ - public function testProvideMethod_invalidMethod() - { - $this->routeStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - $this->builderContext->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->object)); - $this->provider->init(array('method' => 'invalidMethod')); - $this->provider->providePath($this->routeStack); - } - - public function setupTest($slugify = true) - { - $this->routeStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - $this->builderContext->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->object)); - - if ($slugify) { - $this->slugifier->expects($this->any()) - ->method('slugify') - ->will($this->returnCallback(function ($el) { return $el; })); - } - } - - public function testProvideMethod() - { - $this->setupTest(); - $this->routeStack->expects($this->once()) - ->method('addPathElements') - ->with(array('this', 'is', 'path')); - - $this->provider->init(array('method' => 'getSlug')); - $this->provider->providePath($this->routeStack); - } - - public function testProvideMethodNoSlugify() - { - $this->setupTest(false); - $this->routeStack->expects($this->once()) - ->method('addPathElements') - ->with(array('this', 'is', 'path')); - - $this->provider->init(array('method' => 'getSlug', 'slugify' => false)); - $this->provider->providePath($this->routeStack); - } - - public function testProvideMethodWithString() - { - $this->setupTest(); - $this->routeStack->expects($this->once()) - ->method('addPathElements') - ->with(array('this/is/a/path')); - - $this->provider->init(array('method' => 'getStringSlug')); - $this->provider->providePath($this->routeStack); - } - - /** - * @expectedException \RuntimeException - */ - public function testProvideMethodWithAbsolute() - { - $this->setupTest(); - - $this->provider->init(array('method' => 'getAbsoluteSlug')); - $this->provider->providePath($this->routeStack); - } - - public function testProvideMethodObjectToString() - { - $this->setupTest(); - - $this->provider->init(array('method' => 'getStringObjectSlug')); - $this->provider->providePath($this->routeStack); - } - - /** - * @expectedException \RunTimeException - */ - public function testProvideMethodWrongType() - { - $this->setupTest(); - - $this->provider->init(array('method' => 'getWrongTypeSlug')); - $this->provider->providePath($this->routeStack); - } -} - -class ContentMethodTestClass -{ - public function getSlug() - { - return array('this', 'is', 'path'); - } - - public function getStringSlug() - { - return 'this/is/a/path'; - } - - public function getAbsoluteSlug() - { - return '/this/is/absolute'; - } - - public function getStringObjectSlug() - { - return new StringObject(); - } - - public function getWrongTypeSlug() - { - return new \StdClass(); - } - -} - -class StringObject -{ - public function __toString() - { - return 'this/is/from/an/object'; - } -} diff --git a/Tests/Unit/AutoRoute/PathProvider/ContentObjectProviderTest.php b/Tests/Unit/AutoRoute/PathProvider/ContentObjectProviderTest.php deleted file mode 100644 index a65af89..0000000 --- a/Tests/Unit/AutoRoute/PathProvider/ContentObjectProviderTest.php +++ /dev/null @@ -1,160 +0,0 @@ -metadata = $this->getMockBuilder( - 'Doctrine\ODM\PHPCR\Mapping\ClassMetadata' - )->disableOriginalConstructor()->getMock(); - - $this->phpcrSession = $this->getMock( - 'PHPCR\SessionInterface' - ); - - $this->builderContext = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\BuilderContext' - ); - $this->routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - - $this->dm = $this->getMockBuilder('Doctrine\ODM\PHPCR\DocumentManager') - ->disableOriginalConstructor() - ->getMock(); - - $this->uow = $this->getMockBuilder('Doctrine\ODM\PHPCR\UnitOfWork') - ->disableOriginalConstructor() - ->getMock(); - - $this->contentObject = new \stdClass; - $this->route1 = $this->getMock('Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr\Route'); - $this->object = new ContentObjectTestClass($this->contentObject); - - $this->provider = new ContentObjectProvider($this->dm); - } - - protected function setupDocumentPersisted($isPersisted) - { - $this->dm->expects($this->any()) - ->method('getClassMetadata') - ->will($this->returnValue($this->metadata)); - $this->dm->expects($this->once()) - ->method('getPhpcrSession') - ->will($this->returnValue($this->phpcrSession)); - $this->phpcrSession->expects($this->once()) - ->method('nodeExists') - ->will($this->returnValue($isPersisted)); - } - - /** - * @expectedException Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Exception\MissingOptionException - */ - public function testProvidePath_noMethod() - { - $this->provider->init(array()); - } - - /** - * @expectedException \BadMethodCallException - */ - public function testProvideMethod_invalidMethod() - { - $this->routeStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - $this->builderContext->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->object)); - $this->provider->init(array('method' => 'invalidMethod')); - $this->provider->providePath($this->routeStack); - } - - protected function setupTest($slugify = true) - { - $this->routeStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - $this->builderContext->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->object)); - $this->dm->expects($this->once()) - ->method('getUnitOfWork') - ->will($this->returnValue($this->uow)); - } - - protected function getReferrersCollection($referrers) - { - $refCollection = $this->getMockBuilder('Doctrine\ODM\PHPCR\ReferrersCollection') - ->disableOriginalConstructor() - ->getMock(); - $refCollection->expects($this->any()) - ->method('filter') - ->will($this->returnCallback(function ($callback) use ($referrers) { - return new ArrayCollection(array_filter($referrers, $callback)); - })); - - return $refCollection; - } - - public function testProvideObjectWithReferrers() - { - $this->setupTest(); - $this->setupDocumentPersisted(true); - $this->dm->expects($this->once()) - ->method('getReferrers') - ->will($this->returnValue($this->getReferrersCollection(array( - $this->route1, - )))); - - $this->route1->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->contentObject)); - - $this->route1->expects($this->once()) - ->method('getId') - ->will($this->returnValue('/this/is/path')); - - $this->uow->expects($this->once()) - ->method('getScheduledInserts') - ->will($this->returnValue(array())); - - $this->routeStack->expects($this->once()) - ->method('addPathElements') - ->with(array('this', 'is', 'path')); - - $this->provider->init(array('method' => 'getObject')); - $this->provider->providePath($this->routeStack); - } -} - -class ContentObjectTestClass -{ - protected $contentObject; - - public function __construct($contentObject) - { - $this->contentObject = $contentObject; - } - - public function getObject() - { - return $this->contentObject; - } -} diff --git a/Tests/Unit/AutoRoute/PathProvider/LocaleProviderTest.php b/Tests/Unit/AutoRoute/PathProvider/LocaleProviderTest.php deleted file mode 100644 index 2948cc5..0000000 --- a/Tests/Unit/AutoRoute/PathProvider/LocaleProviderTest.php +++ /dev/null @@ -1,62 +0,0 @@ -builderContext = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\BuilderContext' - ); - $this->routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - - $this->provider = new LocaleProvider(); - } - - /** - * @expectedException RuntimeException - * @expectedExceptionMessage LocaleProvider requires that a locale is set on the BuilderContext for "stdClass" - */ - public function testProvidePathNoLocale() - { - $this->routeStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - - $this->builderContext->expects($this->once()) - ->method('getContent') - ->will($this->returnValue(new \stdClass)); - $this->provider->providePath($this->routeStack); - } - - public function testProvidePath() - { - $this->routeStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - $this->builderContext->expects($this->once()) - ->method('getLocale') - ->will($this->returnValue('fr')); - - $this->routeStack->expects($this->once()) - ->method('addPathElements') - ->with(array('fr')); - - $res = $this->provider->providePath($this->routeStack); - } -} diff --git a/Tests/Unit/AutoRoute/PathProvider/SpecifiedProviderTest.php b/Tests/Unit/AutoRoute/PathProvider/SpecifiedProviderTest.php deleted file mode 100644 index ba70a10..0000000 --- a/Tests/Unit/AutoRoute/PathProvider/SpecifiedProviderTest.php +++ /dev/null @@ -1,56 +0,0 @@ -provider = new SpecifiedProvider; - $this->routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - } - - /** - * @expectedException Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Exception\MissingOptionException - */ - public function testProvidePath_noPath() - { - $this->provider->init(array()); - } - - public function providePath() - { - return array( - array('foo/bar'), - array('/foo/bar'), - ); - } - - /** - * @dataProvider providePath - */ - public function testProvidePath($path) - { - $this->provider->init(array( - 'path' => $path - )); - $this->routeStack->expects($this->once()) - ->method('addPathElements') - ->with(array('foo', 'bar')); - $this->provider->providePath($this->routeStack); - } -} diff --git a/Tests/Unit/AutoRoute/RouteMaker/AutoRouteMakerTest.php b/Tests/Unit/AutoRoute/RouteMaker/AutoRouteMakerTest.php deleted file mode 100644 index 24ef6e6..0000000 --- a/Tests/Unit/AutoRoute/RouteMaker/AutoRouteMakerTest.php +++ /dev/null @@ -1,118 +0,0 @@ -dm = $this->getMockBuilder( - 'Doctrine\ODM\PHPCR\DocumentManager' - )->disableOriginalConstructor()->getMock(); - - $this->uow = $this->getMockBuilder( - 'Doctrine\ODM\PHPCR\UnitOfWork' - )->disableOriginalConstructor()->getMock(); - - $this->metadata = $this->getMockBuilder( - 'Doctrine\ODM\PHPCR\Mapping\ClassMetadata' - )->disableOriginalConstructor()->getMock(); - - $this->phpcrSession = $this->getMock( - 'PHPCR\SessionInterface' - ); - - $this->arm = new AutoRouteMaker($this->dm); - $this->doc = new \stdClass; - - $this->autoRoute1 = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\Model\AutoRoute' - ); - $this->autoRoute2 = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\Model\AutoRoute' - ); - $this->nonAutoRoute = new \stdClass; - - $this->autoRouteStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\AutoRouteStack' - )->disableOriginalConstructor()->getMock(); - - $this->builderContext = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\BuilderContext' - ); - } - - protected function setupDocumentPersisted($isPersisted) - { - $this->dm->expects($this->any()) - ->method('getUnitOfWork') - ->will($this->returnValue($this->uow)); - $this->dm->expects($this->once()) - ->method('getPhpcrSession') - ->will($this->returnValue($this->phpcrSession)); - $this->phpcrSession->expects($this->once()) - ->method('nodeExists') - ->will($this->returnValue($isPersisted)); - } - - public function testCreateOrUpdateAutoRouteForExisting() - { - $this->setupDocumentPersisted(true); - - $this->dm->expects($this->once()) - ->method('getReferrers') - ->will($this->returnValue(new ArrayCollection(array( - $this->autoRoute1, - $this->nonAutoRoute - )))); - - $this->autoRouteStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - - $this->builderContext->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->doc)); - - $this->autoRouteStack->expects($this->once()) - ->method('addRoute') - ->with($this->autoRoute1); - - $this->arm->make($this->autoRouteStack); - } - - public function testCreateOrUpdateAutoRouteForNew() - { - $this->setupDocumentPersisted(false); - - $testCase = $this; - - $this->autoRouteStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - - $this->builderContext->expects($this->once()) - ->method('getContent') - ->will($this->returnValue($this->doc)); - - $this->autoRouteStack->expects($this->once()) - ->method('addRoute') - ->will($this->returnCallback(function ($route) use ($testCase) { - $testCase->assertInstanceOf('Symfony\Cmf\Bundle\RoutingAutoBundle\Model\AutoRoute', $route); - })); - - $this->arm->make($this->autoRouteStack); - } -} diff --git a/Tests/Unit/AutoRoute/RouteMaker/DefaultMakerTest.php b/Tests/Unit/AutoRoute/RouteMaker/DefaultMakerTest.php deleted file mode 100644 index 8e24644..0000000 --- a/Tests/Unit/AutoRoute/RouteMaker/DefaultMakerTest.php +++ /dev/null @@ -1,56 +0,0 @@ -autoRouteMaker = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteMakerInterface' - ); - - $this->routeMaker = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteMakerInterface' - ); - - $this->routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - $this->autoRouteStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\AutoRouteStack' - )->disableOriginalConstructor()->getMock(); - - $this->defaultMaker = new DefaultMaker( - $this->autoRouteMaker, - $this->routeMaker - ); - } - - public function testMakeWithAutoRouteStack() - { - $this->autoRouteMaker->expects($this->once()) - ->method('make') - ->with($this->autoRouteStack); - $this->defaultMaker->make($this->autoRouteStack); - } - - public function testMakeWithNormalRouteStack() - { - $this->routeMaker->expects($this->once()) - ->method('make') - ->with($this->routeStack); - $this->defaultMaker->make($this->routeStack); - } -} diff --git a/Tests/Unit/AutoRoute/RouteMaker/GenericMakerTest.php b/Tests/Unit/AutoRoute/RouteMaker/GenericMakerTest.php deleted file mode 100644 index e3e34e9..0000000 --- a/Tests/Unit/AutoRoute/RouteMaker/GenericMakerTest.php +++ /dev/null @@ -1,73 +0,0 @@ -dm = $this->getMockBuilder( - 'Doctrine\ODM\PHPCR\DocumentManager' - )->disableOriginalConstructor()->getMock(); - - $this->routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - - $this->classMetadata = $this->getMockBuilder( - 'Doctrine\ODM\PHPCR\Mapping\ClassMetadata' - )->disableOriginalConstructor()->getMock(); - - $this->routeMaker = new $this->makerClass($this->dm); - } - - // Note that this tests everything apart from ensuring - // that the correct routes are added with addRoute, we - // only assert that 2 routes are added. - public function testMake() - { - $this->routeStack->expects($this->once()) - ->method('getFullPaths') - ->will($this->returnValue(array( - 'test', - 'test/foo', - ))); - - $this->dm->expects($this->once()) - ->method('getClassMetadata') - ->with($this->routeClass) - ->will($this->returnValue($this->classMetadata)); - - $this->routeStack->expects($this->exactly(2)) - ->method('addRoute'); - - // If anybody knows of a better way to do this ... - $test = $this; - $routeClass = $this->routeClass; - $this->classMetadata->expects($this->exactly(2)) - ->method('setIdentifierValue') - ->will($this->returnCallback(function ($doc, $id) use ($test, $routeClass) { - static $i = 0; - $expected = array('/test', '/test/foo'); - - $test->assertInstanceOf($routeClass, $doc); - $test->assertEquals($expected[$i++], $id); - })); - - $this->routeMaker->make($this->routeStack); - } -} diff --git a/Tests/Unit/AutoRoute/RouteMaker/RouteMakerTest.php b/Tests/Unit/AutoRoute/RouteMaker/RouteMakerTest.php deleted file mode 100644 index e350a05..0000000 --- a/Tests/Unit/AutoRoute/RouteMaker/RouteMakerTest.php +++ /dev/null @@ -1,52 +0,0 @@ -routeMaker->init(array( - 'defaults' => array('_controller' => 'foobar') - )); - - $this->routeStack->expects($this->once()) - ->method('getFullPaths') - ->will($this->returnValue(array( - 'test', - 'test/foo', - ))); - - $test = $this; - $this->routeStack->expects($this->exactly(2)) - ->method('addRoute') - ->will($this->returnCallback(function ($doc) use ($test) { - static $i = 0; - $expected = array('/test', '/test/foo'); - - $test->assertInstanceOf( - $test->routeClass, - $doc - ); - - $test->assertEquals($expected[$i++], $doc->getId()); - $defaults = $doc->getDefaults(); - $test->assertTrue(isset($defaults['_controller'])); - $test->assertEquals('foobar', $defaults['_controller']); - })); - - $this->routeMaker->make($this->routeStack); - } -} diff --git a/Tests/Unit/AutoRoute/RouteStack/BuilderTest.php b/Tests/Unit/AutoRoute/RouteStack/BuilderTest.php deleted file mode 100644 index e2ba716..0000000 --- a/Tests/Unit/AutoRoute/RouteStack/BuilderTest.php +++ /dev/null @@ -1,103 +0,0 @@ -dm = $this->getMockBuilder( - 'Doctrine\ODM\PHPCR\DocumentManager' - )->disableOriginalConstructor()->getMock();; - - $this->routeStackBuilder = new Builder($this->dm); - $this->routeStackBuilderUnit = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack\BuilderUnitInterface' - ); - $this->builderContext = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\BuilderContext' - ); - $this->routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - $this->route1 = new \stdClass; - } - - public function testNotExists() - { - $this->routeStackBuilderUnit->expects($this->once()) - ->method('pathAction') - ->with($this->routeStack); - $this->routeStack->expects($this->once()) - ->method('getFullPath') - ->will($this->returnValue('test/path')); - - $this->dm->expects($this->once()) - ->method('find') - ->with(null, '/test/path') - ->will($this->returnValue(null)); - - $this->routeStackBuilderUnit->expects($this->once()) - ->method('notExistsAction') - ->with($this->routeStack); - - $this->routeStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - - $this->routeStack->expects($this->once()) - ->method('close'); - - $this->routeStackBuilder->build($this->routeStack, $this->routeStackBuilderUnit); - } - - public function testExists() - { - $this->routeStackBuilderUnit->expects($this->once()) - ->method('pathAction') - ->with($this->routeStack); - - $this->routeStack->expects($this->once()) - ->method('getFullPath') - ->will($this->returnValue('test/path')); - - $this->routeStack->expects($this->once()) - ->method('getContext') - ->will($this->returnValue($this->builderContext)); - - $this->routeStackBuilderUnit->expects($this->exactly(1)) - ->method('existsAction') - ->with($this->routeStack); - - $this->routeStack->expects($this->once()) - ->method('close'); - - // first two node paths exist, third is OK - $this->dm->expects($this->exactly(1)) - ->method('find') - ->with(null, '/test/path') - ->will($this->returnCallback(function ($path) { - static $count = 0; - if ($count == 2) { - return false; - } - - $count++; - - return new \stdClass; - })); - - $this->routeStackBuilder->build($this->routeStack, $this->routeStackBuilderUnit); - } -} diff --git a/Tests/Unit/AutoRoute/RouteStack/BuilderUnitChainTest.php b/Tests/Unit/AutoRoute/RouteStack/BuilderUnitChainTest.php deleted file mode 100644 index 560bcc6..0000000 --- a/Tests/Unit/AutoRoute/RouteStack/BuilderUnitChainTest.php +++ /dev/null @@ -1,52 +0,0 @@ -builder = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack\Builder' - )->disableOriginalConstructor()->getMock(); - - $this->builderUnitChain = new BuilderUnitChain($this->builder); - $this->builderUnit1 = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack\BuilderUnitInterface' - ); - $this->builderUnit2 = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack\BuilderUnitInterface' - )->disableOriginalConstructor()->getMock(); - $this->builderContext = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\BuilderContext' - ); - } - - public function testExecute() - { - // note that we cannot (or I do not know how to) test the "with" - // part because we instantiate the RouteStack in the class. - $this->builder->expects($this->at(0)) - ->method('build'); - // ->with($this->builderUnit1, $this->builderContext); - $this->builder->expects($this->at(1)) - ->method('build'); - // ->with($this->builderUnit2, $this->builderContext); - - $this->builderUnitChain->addBuilderUnit('builder_1', $this->builderUnit1); - $this->builderUnitChain->addBuilderUnit('builder_2', $this->builderUnit2); - $this->builderUnitChain->executeChain($this->builderContext); - } -} diff --git a/Tests/Unit/AutoRoute/RouteStack/BuilderUnitTest.php b/Tests/Unit/AutoRoute/RouteStack/BuilderUnitTest.php deleted file mode 100644 index 6f7b158..0000000 --- a/Tests/Unit/AutoRoute/RouteStack/BuilderUnitTest.php +++ /dev/null @@ -1,60 +0,0 @@ -pathProvider = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\PathProviderInterface' - ); - $this->pathExists = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\PathActionInterface' - ); - $this->pathNotExists = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\PathActionInterface' - ); - $this->routeStack = $this->getMockBuilder( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\RouteStack' - )->disableOriginalConstructor()->getMock(); - - $this->builderUnit = new BuilderUnit( - $this->pathProvider, - $this->pathExists, - $this->pathNotExists - ); - } - - public function testPathAction() - { - $this->pathProvider->expects($this->once()) - ->method('providePath'); - $this->builderUnit->pathAction($this->routeStack); - } - - public function testExistsAction() - { - $this->pathExists->expects($this->once()) - ->method('execute'); - $this->builderUnit->existsAction($this->routeStack); - } - - public function testNotExistsAction() - { - $this->pathNotExists->expects($this->once()) - ->method('execute'); - $this->builderUnit->notExistsAction($this->routeStack); - } -} diff --git a/Tests/Unit/AutoRoute/RouteStackTest.php b/Tests/Unit/AutoRoute/RouteStackTest.php deleted file mode 100644 index 862611d..0000000 --- a/Tests/Unit/AutoRoute/RouteStackTest.php +++ /dev/null @@ -1,89 +0,0 @@ -builderContext = $this->getMock( - 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\BuilderContext' - ); - $this->routeStack = new RouteStack($this->builderContext); - $this->route1 = new \stdClass; - $this->route2 = new \stdClass; - } - - public function testGetEmptyPath() - { - $this->assertEmpty($this->routeStack->getPaths()); - $this->assertEquals('', $this->routeStack->getFullPath()); - } - - public function testAddPathElement() - { - $this->routeStack->addPathElements(array('foo', 'bar')); - $this->assertEquals(array('foo', 'bar'), $this->routeStack->getPathElements()); - $this->routeStack->addPathElement('boz'); - $this->assertEquals(array('foo', 'bar', 'boz'), $this->routeStack->getPathElements()); - } - - /** - * @expectedException Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Exception\CannotModifyClosedRouteStackException - */ - public function testAddPathElementToClosed() - { - $this->routeStack->close(); - $this->routeStack->addPathElement('asd'); - } - - /** - * @expectedException Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Exception\InvalidPathElementException - */ - public function testAddEmptyPathElement() - { - $this->routeStack->addPathElement(''); - } - - /** - * @expectedException Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Exception\InvalidPathElementException - */ - public function testAddPathElementWithPathSeparator() - { - $this->routeStack->addPathElement('this/is/wrong'); - } - - public function testReplaceLastPathElement() - { - $this->routeStack->addPathElements(array('foo', 'bar')); - $this->routeStack->replaceLastPathElement('baz'); - $path = $this->routeStack->getPath(); - $this->assertEquals('foo/baz', $path); - } - - public function testGetFullPaths() - { - $this->builderContext->expects($this->once()) - ->method('getFullPath') - ->will($this->returnValue('')); - $this->routeStack->addPathElements(array('bar', 'foo')); - $fullPaths = $this->routeStack->getFullPaths(); - - $this->assertCount(2, $fullPaths); - $this->assertEquals(array( - 'bar', - 'bar/foo', - ), $fullPaths); - } -} diff --git a/Tests/Unit/AutoRoute/UrlGeneratorTest.php b/Tests/Unit/AutoRoute/UrlGeneratorTest.php new file mode 100644 index 0000000..87e3aae --- /dev/null +++ b/Tests/Unit/AutoRoute/UrlGeneratorTest.php @@ -0,0 +1,113 @@ +metadataFactory = $this->prophet->prophesize( + 'Metadata\MetadataFactoryInterface' + ); + $this->metadata = $this->prophet->prophesize( + 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Mapping\ClassMetadata' + ); + $this->driver = $this->prophet->prophesize( + 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\Driver\DriverInterface' + ); + $this->serviceRegistry = $this->prophet->prophesize( + 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\ServiceRegistry' + ); + $this->tokenProvider = $this->prophet->prophesize( + 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\TokenProviderInterface' + ); + + $this->urlGenerator = new UrlGenerator( + $this->metadataFactory->reveal(), + $this->driver->reveal(), + $this->serviceRegistry->reveal() + ); + } + + public function provideGenerateUrl() + { + return array( + array( + '/this/is/{token_the_first}/a/url', + '/this/is/foobar_value/a/url', + array( + 'token_the_first' => array( + 'provider' => 'foobar_provider', + 'value' => 'foobar_value', + ), + ), + ), + array( + '/{this}/{is}/{token_the_first}/a/url', + '/that/was/foobar_value/a/url', + array( + 'token_the_first' => array( + 'provider' => 'foobar_provider', + 'value' => 'foobar_value', + ), + 'this' => array( + 'provider' => 'barfoo_provider', + 'value' => 'that', + ), + 'is' => array( + 'provider' => 'dobar_provider', + 'value' => 'was', + ), + ), + ), + ); + } + + /** + * @dataProvider provideGenerateUrl + */ + public function testGenerateUrl($urlSchema, $expectedUrl, $tokenProviderConfigs) + { + $document = new \stdClass; + $this->driver->getRealClassName('stdClass')->shouldBeCalled() + ->willReturn('ThisIsMyStandardClass'); + + $this->metadataFactory->getMetadataForClass('ThisIsMyStandardClass') + ->willReturn($this->metadata); + + $this->metadata->getTokenProviderConfigs() + ->willReturn($tokenProviderConfigs); + + $this->metadata->getUrlSchema() + ->willReturn($urlSchema); + + foreach ($tokenProviderConfigs as $tokenName => $tokenProviderConfig) { + $providerName = $tokenProviderConfig['provider']; + + $this->tokenProviders[$providerName] = $this->prophet->prophesize( + 'Symfony\Cmf\Bundle\RoutingAutoBundle\AutoRoute\TokenProviderInterface' + ); + + $this->serviceRegistry->getTokenProvider($tokenProviderConfig['provider']) + ->willReturn($this->tokenProviders[$providerName]); + + $this->tokenProviders[$providerName]->getValue($document, $tokenProviderConfig) + ->willReturn($tokenProviderConfig['value']); + } + + $res = $this->urlGenerator->generateUrl($document); + + $this->assertEquals($expectedUrl, $res); + } +} diff --git a/Tests/Unit/BaseTestCase.php b/Tests/Unit/BaseTestCase.php new file mode 100644 index 0000000..4edee2a --- /dev/null +++ b/Tests/Unit/BaseTestCase.php @@ -0,0 +1,20 @@ +prophet = new Prophet(); + } + + public function tearDown() + { + $this->prophet->checkPredictions(); + } +} diff --git a/Tests/Unit/DependencyInjection/ConfigurationTest.php b/Tests/Unit/DependencyInjection/ConfigurationTest.php deleted file mode 100644 index 04e4d95..0000000 --- a/Tests/Unit/DependencyInjection/ConfigurationTest.php +++ /dev/null @@ -1,54 +0,0 @@ - false, - 'mapping' => array( - 'paths' => array( - 'Resources/config/SpecificObject.yml', - 'Resources/config/foo.xml', - ), - ), - ); - - $sources = array_map(function ($path) { - return __DIR__.'/../../Resources/Fixtures/'.$path; - }, array( - 'config/config.yml', - 'config/config.xml', - 'config/config.php', - )); - - foreach ($sources as $source) { - $this->assertProcessedConfigurationEquals($expectedConfiguration, array($source)); - } - } -} diff --git a/Tests/Unit/DependencyInjection/XmlSchemaTest.php b/Tests/Unit/DependencyInjection/XmlSchemaTest.php deleted file mode 100644 index c33bc14..0000000 --- a/Tests/Unit/DependencyInjection/XmlSchemaTest.php +++ /dev/null @@ -1,29 +0,0 @@ -assertSchemaAcceptsXml($xmlFiles, __DIR__.'/../../../Resources/config/schema/routing-auto-1.0.xsd'); - } -} diff --git a/composer.json b/composer.json index 7c3c1fd..6b0ea21 100644 --- a/composer.json +++ b/composer.json @@ -21,6 +21,7 @@ "require-dev": { "symfony-cmf/testing": "1.1.*", "symfony/yaml": "~2.1.0", + "phpspec/prophecy": "1.1.*", "matthiasnoback/symfony-dependency-injection-test": "0.*", "matthiasnoback/symfony-config-test": "0.*" },