Skip to content

Commit

Permalink
v3
Browse files Browse the repository at this point in the history
  • Loading branch information
pmaxs committed Sep 6, 2021
1 parent 95d064a commit 732197d
Show file tree
Hide file tree
Showing 9 changed files with 103 additions and 217 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Installation
Usage
-----

Add param `__path2query__` with default value `1`.
Add param `__path2query__` with default value `""` and requirement `".*"`.
Such routes are processed by this bundle in order to add query vars to Request from path.

Ex.:
Expand All @@ -20,7 +20,7 @@ Ex.:
class DefaultController extends AbstractController
{
/**
* @Route("/xxx", defaults={"__path2query__"=1})
* @Route("/xxx/{__path2query__}", requirements={"__path2query__"=".*"}, defaults={"__path2query__"=""})
*/
public function indexAction(Request $request)
{
Expand Down
23 changes: 0 additions & 23 deletions src/DependencyInjection/Compiler/SetJMSI18nRouting.php

This file was deleted.

9 changes: 6 additions & 3 deletions src/DependencyInjection/Compiler/SetRouterPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@

namespace Pmaxs\Path2queryBundle\DependencyInjection\Compiler;

use Pmaxs\Path2queryBundle\Generator\Path2QueryUrlGenerator;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class SetRouterPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
$routerDefinition = $container->getDefinition('router.default');
$routerDefinition->setArgument(2, array_merge($routerDefinition->getArgument(2), [
'generator_class' => Path2QueryUrlGenerator::class,
]));

$container->setAlias('router', 'pmaxs_path2query.router');
}
}
17 changes: 2 additions & 15 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,12 @@
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
* This is the class that validates and merges configuration from your app/config files.
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('doctrine');

if (method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->getRootNode();
} else {
$rootNode = $treeBuilder->root('pmaxs_path2query');
}
$treeBuilder = new TreeBuilder('pmaxs_path2query');
$rootNode = $treeBuilder->getRootNode();

// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
Expand Down
11 changes: 1 addition & 10 deletions src/DependencyInjection/PmaxsPath2queryExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,12 @@
namespace Pmaxs\Path2queryBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\ExpressionLanguage\Expression;

/**
* This is the class that loads and manages your bundle configuration.
*
* @link http://symfony.com/doc/current/cookbook/bundles/extension.html
*/
class PmaxsPath2queryExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
Expand Down
79 changes: 6 additions & 73 deletions src/EventListener/Path2QueryListener.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

namespace Pmaxs\Path2queryBundle\EventListener;

use Pmaxs\Path2queryBundle\Router\Path2QueryRouter;
Expand All @@ -9,66 +10,24 @@
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RouterInterface;

/**
* Listener to resolve locale from path or host
*/
class Path2QueryListener implements EventSubscriberInterface
{
/**
* Route collection
* @var RouterInterface
*/
protected $router;

/**
* Constructor
* @param RouterInterface $router
*/
public function __construct(RouterInterface $router)
{
$this->router = $router;
}

/**
* @inheritdoc
*/
public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array(
array('setupRoutes', 33),
array('resolveQuery', 0),
),
);
}

/**
* Setups routes, adds query parameter
* @param RequestEvent $event
*/
public function setupRoutes(RequestEvent $event)
{
if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) {
return;
}

foreach ($this->router->getPath2QueryRouteCollection() as $routeName => $route) {
if (!$route->getDefault(Path2QueryRouter::ENABLED_PARAM)) {
continue;
}

$route
->setPath(rtrim($route->getPath(), '/') . '/{' . Path2QueryRouter::QUERY_PARAM . '}')
->setRequirement(Path2QueryRouter::QUERY_PARAM, '.*')
->setDefault(Path2QueryRouter::QUERY_PARAM, '')
;
}
return [
KernelEvents::REQUEST => [
['resolveQuery', 0],
],
];
}

/**
* Resolves query from path
* @param RequestEvent $event
*/
public function resolveQuery(RequestEvent $event)
{
$request = $event->getRequest();
Expand All @@ -88,30 +47,4 @@ public function resolveQuery(RequestEvent $event)
}
}
}

/**
* Resolves query from path
* @param RequestEvent $event
*/
public function resolveQuery1(RequestEvent $event)
{
$request = $event->getRequest();

if (($query = $request->get(Path2QueryRouter::QUERY_PARAM))) {
$query = explode('/', trim($query, '/'));

foreach ($query as $queryPart) {
$queryPart = urldecode($queryPart);
$queryPart = explode('-', $queryPart, 2);
$param = isset($queryPart[0]) ? trim($queryPart[0]) : null;
$value = isset($queryPart[1]) ? trim($queryPart[1]) : null;

if (isset($param) && strlen($param) && !$request->query->has($param)) {
$_REQUEST[$param] = $value;
$_GET[$param] = $value;
$request->query->set($param, $value);
}
}
}
}
}
79 changes: 79 additions & 0 deletions src/Generator/Path2QueryUrlGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php

namespace Pmaxs\Path2queryBundle\Generator;

use Pmaxs\Path2queryBundle\Router\Path2QueryRouter;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Generator\CompiledUrlGenerator;
use Symfony\Component\Routing\RequestContext;

class Path2QueryUrlGenerator extends CompiledUrlGenerator
{
private $compiledRoutes = [];
private $defaultLocale;

public function __construct(array $compiledRoutes, RequestContext $context, LoggerInterface $logger = null, string $defaultLocale = null)
{
$this->compiledRoutes = $compiledRoutes;
$this->context = $context;
$this->logger = $logger;
$this->defaultLocale = $defaultLocale;
}

public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH)
{
$locale = $parameters['_locale']
?? $this->context->getParameter('_locale')
?: $this->defaultLocale;

if (null !== $locale) {
do {
if (($this->compiledRoutes[$name.'.'.$locale][1]['_canonical_route'] ?? null) === $name) {
$name .= '.'.$locale;
break;
}
} while (false !== $locale = strstr($locale, '_', true));
}

if (!isset($this->compiledRoutes[$name])) {
throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
}

[$variables, $defaults, $requirements, $tokens, $hostTokens, $requiredSchemes] = $this->compiledRoutes[$name];

if (isset($defaults['_canonical_route']) && isset($defaults['_locale'])) {
if (!\in_array('_locale', $variables, true)) {
unset($parameters['_locale']);
} elseif (!isset($parameters['_locale'])) {
$parameters['_locale'] = $defaults['_locale'];
}
}

if (in_array(Path2QueryRouter::QUERY_PARAM, $variables)) {
$query = '';
$queryVars = [];

foreach ($parameters as $var => $val) {
if (!in_array($var, $variables)) {
$queryVars[$var] = $val;
unset($parameters[$var]);
}
}

if (!empty($queryVars)) {
foreach ($queryVars as $var => $val) {
if (is_null($var) || !strlen($var) || is_null($val) || !strlen($val)) {
continue;
}

$query.= '/' . urlencode($var) . '/' . urlencode($val);
}
}

$parameters[Path2QueryRouter::QUERY_PARAM] = ltrim($query, '/');
}

return $this->doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, $requiredSchemes);
}
}
3 changes: 2 additions & 1 deletion src/PmaxsPath2queryBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ class PmaxsPath2queryBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
$container->addCompilerPass(new SetJMSI18nRouting());
parent::build($container);

$container->addCompilerPass(new SetRouterPass());
}
}
Loading

0 comments on commit 732197d

Please sign in to comment.