1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Junker\Silex\Provider; |
4
|
|
|
|
5
|
|
|
use Silex\Application; |
6
|
|
|
use Silex\ServiceProviderInterface; |
7
|
|
|
use Symfony\Component\Config\ConfigCacheInterface; |
8
|
|
|
use Symfony\Component\Config\ConfigCacheFactory; |
9
|
|
|
use Symfony\Component\Routing\Loader\YamlFileLoader; |
10
|
|
|
use Symfony\Component\Routing\RouteCollection; |
11
|
|
|
use Symfony\Component\Config\FileLocator; |
12
|
|
|
use Junker\Silex\PhpRouteCollectionDumper; |
13
|
|
|
|
14
|
|
|
class YamlRouteServiceProvider implements ServiceProviderInterface |
15
|
|
|
{ |
16
|
|
|
protected $cacheDirPath; |
17
|
|
|
protected $configFilePath; |
18
|
|
|
protected $configCacheFactory; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param string $configFilePath Path to config file |
22
|
|
|
* @param null|array $options Provider options |
23
|
|
|
*/ |
24
|
|
|
public function __construct($configFilePath, $options = null) |
25
|
|
|
{ |
26
|
|
|
if (is_array($options)) { |
27
|
|
|
if (isset($options['cache_dir'])) { |
28
|
|
|
$this->cacheDirPath = $options['cache_dir']; |
29
|
|
|
} |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$this->configFilePath = $configFilePath; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function register(Application $app) |
36
|
|
|
{ |
37
|
|
|
$app['routes'] = $app->share($app->extend('routes', function(RouteCollection $routes, Application $app) { |
38
|
|
|
if ($this->cacheDirPath) { |
39
|
|
|
$cache = $this->getConfigCacheFactory($app['debug'])->cache($this->cacheDirPath.'/routes.cache.php', |
40
|
|
|
function(ConfigCacheInterface $cache) { |
41
|
|
|
$collection = $this->loadRouteCollection(); |
42
|
|
|
|
43
|
|
|
$content = PhpRouteCollectionDumper::dump($collection); |
44
|
|
|
|
45
|
|
|
$cache->write($content, $collection->getResources()); |
46
|
|
|
} |
47
|
|
|
); |
48
|
|
|
|
49
|
|
|
$collection = include $cache->getPath(); |
50
|
|
|
} else { |
51
|
|
|
$collection = $this->loadRouteCollection(); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$routes->addCollection($collection); |
55
|
|
|
|
56
|
|
|
return $routes; |
57
|
|
|
})); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function boot(Application $app) |
61
|
|
|
{ |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @param bool $debug Is debug mode enabled |
66
|
|
|
* |
67
|
|
|
* @return ConfigCacheFactory |
68
|
|
|
*/ |
69
|
|
|
private function getConfigCacheFactory($debug) |
70
|
|
|
{ |
71
|
|
|
if ($this->configCacheFactory === null) { |
72
|
|
|
$this->configCacheFactory = new ConfigCacheFactory($debug); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return $this->configCacheFactory; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
protected function loadRouteCollection() |
79
|
|
|
{ |
80
|
|
|
$loader = new YamlFileLoader(new FileLocator(dirname($this->configFilePath))); |
81
|
|
|
|
82
|
|
|
$collection = $loader->load($this->configFilePath); |
83
|
|
|
|
84
|
|
|
return $collection; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|