RoutingLoader::getControllerFolder()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Admingenerator\GeneratorBundle\Routing;
4
5
use Symfony\Component\Config\Loader\FileLoader;
6
use Symfony\Component\Config\Resource\FileResource;
7
use Symfony\Component\Routing\RouteCollection;
8
use Symfony\Component\Routing\Route;
9
use Symfony\Component\Finder\Finder;
10
use Symfony\Component\Yaml\Yaml;
11
12
class RoutingLoader extends FileLoader
13
{
14
    // Assoc beetween a controller and its route path
15
    //@todo make an object for this
16
    protected $actions = array(
17
        'list' => array(
18
            'path'         => '/',
19
            'defaults'     => array(),
20
            'requirements' => array(),
21
            'methods'      => array('GET'),
22
        ),
23
        'excel'=> array(
24
            'path'         => '/excel/{key}',
25
            'defaults'     => array('key'=>null),
26
            'requirements' => array(),
27
            'methods'      => array('GET'),
28
            'controller'   => 'excel',
29
        ),
30
        'edit' => array(
31
            'path'         => '/{pk}/edit',
32
            'defaults'     => array(),
33
            'requirements' => array(),
34
            'methods'      => array('GET'),
35
        ),
36
        'update' => array(
37
            'path'         => '/{pk}/update',
38
            'defaults'     => array(),
39
            'requirements' => array(),
40
            'methods'      => array('POST'),
41
            'controller'   => 'edit',
42
        ),
43
        'show' => array(
44
            'path'         => '/{pk}/show',
45
            'defaults'     => array(),
46
            'requirements' => array(),
47
            'methods'      => array('GET'),
48
        ),
49
        'object' => array(
50
            'path'         => '/{pk}/{action}',
51
            'defaults'     => array(),
52
            'requirements' => array(),
53
            'methods'      => array('GET', 'POST'),
54
            'controller'   => 'actions',
55
        ),
56
        'batch' => array(
57
            'path'         => '/batch',
58
            'defaults'     => array(),
59
            'requirements' => array(),
60
            'methods'      => array('POST'),
61
            'controller'   => 'actions',
62
        ),
63
        'new' => array(
64
            'path'         => '/new',
65
            'defaults'     => array(),
66
            'requirements' => array(),
67
            'methods'      => array('GET'),
68
        ),
69
        'create' => array(
70
            'path'         => '/create',
71
            'defaults'     => array(),
72
            'requirements' => array(),
73
            'methods'      => array('POST'),
74
            'controller'   => 'new',
75
        ),
76
        'filters' => array(
77
            'path'         => '/filter',
78
            'defaults'     => array(),
79
            'requirements' => array(),
80
            'methods'      => array('POST', 'GET'),
81
            'controller'   => 'list',
82
        ),
83
        'scopes' => array(
84
            'path'         => '/scope/{group}/{scope}',
85
            'defaults'     => array(),
86
            'requirements' => array(),
87
            'methods'      => array('POST', 'GET'),
88
            'controller'   => 'list',
89
        ),
90
    );
91
92
    /**
93
     * @var array
94
     */
95
    protected $yaml = array();
96
97
    public function load($resource, $type = null)
98
    {
99
        $collection = new RouteCollection();
100
101
        $resource = str_replace('\\', '/', $resource);
102
        $this->yaml = Yaml::parse(file_get_contents($this->getGeneratorFilePath($resource)));
103
104
        $namespace = $this->getNamespaceFromResource($resource);
105
        $bundle_name = $this->getBundleNameFromResource($resource);
106
107
        foreach ($this->actions as $controller => $datas) {
108
            $action = 'index';
109
110
            $loweredNamespace = str_replace(array('/', '\\'), '_', $namespace);
111
            if ($controller_folder = $this->getControllerFolder($resource)) {
112
                $route_name = $loweredNamespace . '_' . $bundle_name . '_' . $controller_folder . '_' . $controller;
113
            } else {
114
                $route_name = $loweredNamespace . '_' . $bundle_name . '_' . $controller;
115
            }
116
117
            if (in_array($controller, array('edit', 'update', 'object', 'show')) &&
118
                null !== $pk_requirement = $this->getFromYaml('params.pk_requirement', null)) {
119
                $datas['requirements'] = array_merge(
120
                    $datas['requirements'],
121
                    array('pk' => $pk_requirement)
122
                );
123
            }
124
125
            if (isset($datas['controller'])) {
126
                $action     = $controller;
127
                $controller = $datas['controller'];
128
            }
129
130
            $controllerName = $resource.ucfirst($controller).'Controller.php';
131
            if (!is_file($controllerName)) {
132
                // TODO: what does it mean if controller is not a file??
133
                continue;
134
            }
135
136
            if ($controller_folder) {
137
                $datas['defaults']['_controller'] = $namespace . '\\'
138
                        . $bundle_name . '\\Controller\\'
139
                        . $controller_folder . '\\'
140
                        . ucfirst($controller) . 'Controller::'
141
                        . $action . 'Action';
142
            } else {
143
                $datas['defaults']['_controller'] = $loweredNamespace
144
                        . $bundle_name . ':'
145
                        . ucfirst($controller) . ':' . $action;
146
            }
147
148
            $route = new Route($datas['path'], $datas['defaults'], $datas['requirements']);
149
            $route->setMethods($datas['methods']);
150
151
            $route_name = ltrim($route_name, '_'); // fix routes in AppBundle without vendor
152
153
            $collection->add($route_name, $route);
154
            $collection->addResource(new FileResource($controllerName));
155
        }
156
157
        return $collection;
158
    }
159
160
    public function supports($resource, $type = null)
161
    {
162
        return 'admingenerator' == $type;
163
    }
164
165
    /**
166
     * @return string
167
     */
168
    protected function getControllerFolder($resource)
169
    {
170
        preg_match('#.+/.+Bundle/Controller?/(.*?)/?$#', $resource, $matches);
171
172
        return $matches[1];
173
    }
174
175
    /**
176
     * @return string
177
     */
178
    protected function getBundleNameFromResource($resource)
179
    {
180
        preg_match('#.+/(.+Bundle)/Controller?/(.*?)/?$#', $resource, $matches);
181
182
        return $matches[1];
183
    }
184
185
    protected function getNamespaceFromResource($resource)
186
    {
187
        $finder = Finder::create()
188
            ->name('*Bundle.php')
189
            ->depth(0)
190
            ->in(realpath($resource.'/../../')) // ressource is controller folder
191
            ->getIterator();
192
193
        foreach ($finder as $file) {
194
            preg_match('/namespace (.+);/', file_get_contents($file->getRealPath()), $matches);
195
196
            return implode('\\', explode('\\', $matches[1], -1)); // Remove the short bundle name
197
        }
198
199
        throw new \Exception(sprintf('Bundle file not found in %s.', realpath($resource.'/../../')));
200
    }
201
202
    /**
203
     * @return string
204
     */
205
    protected function getGeneratorFilePath($resource)
206
    {
207
        // TODO: use the GeneratorsFinder
208
        // Find the *-generator.yml
209
        $finder = Finder::create()
210
            ->name($this->getControllerFolder($resource).'-generator.yml')
211
            ->in(realpath($resource.'/../../Resources/config/'))
212
            ->getIterator();
213
214
        foreach ($finder as $file) {
215
            return $file->getRealPath();
216
        }
217
218
        throw new \Exception(sprintf(
219
            'Generator file for %s not found in %s',
220
            $this->getControllerFolder($resource),
221
            realpath($resource.'/../../Resources/config/')
222
        ));
223
    }
224
225
    /**
226
     * @param string $yaml_path string with point for levels
227
     */
228 View Code Duplication
    protected function getFromYaml($yaml_path, $default = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
229
    {
230
        $search_in = $this->yaml;
231
        $yaml_path = explode('.', $yaml_path);
232
        foreach ($yaml_path as $key) {
233
            if (!isset($search_in[$key])) {
234
                return $default;
235
            }
236
            $search_in = $search_in[$key];
237
        }
238
239
        return $search_in;
240
    }
241
}
242