Skip to content

Instantly share code, notes, and snippets.

@xphere
Created September 28, 2017 01:11
Show Gist options
  • Save xphere/d536cf02eb638f9c97ba6dfe61d10668 to your computer and use it in GitHub Desktop.
Save xphere/d536cf02eb638f9c97ba6dfe61d10668 to your computer and use it in GitHub Desktop.
PhpArrayRouteLoader
<?php
namespace Berny\Symfony\Routing;
use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Routing\RouteCollectionBuilder;
final class PhpArrayRouteLoader extends FileLoader
{
private $environment;
private $defaultPath;
public function load($file, $type = null)
{
$path = $this->locator->locate($file);
$resources = $this->locateResources($path);
$collection = $this->buildCollection($resources);
$collection->addResource(new FileResource($path));
$collection->addResource(new FileResource(__FILE__));
return $collection;
}
public function supports($resource, $type = null)
{
return $type === 'php_array_resource'
&& is_string($resource)
&& 'php' === pathinfo($resource, PATHINFO_EXTENSION)
;
}
public function setEnvironment(string $environment)
{
$this->environment = $environment;
}
public function setDefaultPath(string $defaultPath)
{
$this->defaultPath = $defaultPath;
}
private function locateResources($path)
{
$resources = $this->fromPhpFile($path);
$resources = $this->filterByEnvironment($resources, $this->environment ?? '');
if (!empty($this->defaultPath)) {
$resources = $this->withDefaultPath($resources);
}
return $resources;
}
private function fromPhpFile(string $path): iterable
{
return require $path;
}
private function filterByEnvironment(iterable $resources, string $environment): iterable
{
foreach ($resources as $resource => $environments) {
if (
$environments === true
|| $environments === $environment
|| ($environments[$environment] ?? false)
) {
yield $resource;
}
}
}
private function withDefaultPath(iterable $resources): iterable
{
foreach ($resources as $resource) {
if ($resource[0] !== '/') {
$resource = $this->defaultPath . $resource;
}
yield $resource;
}
}
private function buildCollection(iterable $resources)
{
$builder = new RouteCollectionBuilder($this);
foreach ($resources as $resource) {
$builder->import($resource);
}
return $builder->build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment