En raison du déménagement des baies serveurs, les services gitlab.irstea.fr et mattermost.irstea.fr seront interrompus le samedi 2 octobre 2021 au matin. Ils devraient revenir à la normale dans la journée.

GenerateCommand.php 10.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
<?php

/*
 * Copyright (C) 2015 IRSTEA
 * All rights reserved.
 */
namespace Irstea\PlantUmlBundle\Command;

use Doctrine\ORM\EntityManagerInterface;
10
use Irstea\PlantUmlBundle\Doctrine\AssociationDecorator;
11
use Irstea\PlantUmlBundle\Doctrine\DoctrineNamespace;
12
use Irstea\PlantUmlBundle\Doctrine\EntityDecorator;
13
use Irstea\PlantUmlBundle\Model\ClassFilterInterface;
14
15
16
17
use Irstea\PlantUmlBundle\Model\ClassVisitor;
use Irstea\PlantUmlBundle\Model\Decorator\CompositeDecorator;
use Irstea\PlantUmlBundle\Model\Decorator\FilteringDecorator;
use Irstea\PlantUmlBundle\Model\Decorator\InheritanceDecorator;
18
use Irstea\PlantUmlBundle\Model\Decorator\InterfaceDecorator;
19
use Irstea\PlantUmlBundle\Model\Decorator\NullDecorator;
20
use Irstea\PlantUmlBundle\Model\Decorator\TraitDecorator;
21
22
23
use Irstea\PlantUmlBundle\Model\DecoratorInterface;
use Irstea\PlantUmlBundle\Model\Filter\AcceptAllFilter;
use Irstea\PlantUmlBundle\Model\Filter\Composite\AllFilter;
24
25
use Irstea\PlantUmlBundle\Model\Filter\DirectoryFilter;
use Irstea\PlantUmlBundle\Model\Filter\NamespaceFilter;
26
use Irstea\PlantUmlBundle\Model\Namespace_\BundleNamespace;
27
use Irstea\PlantUmlBundle\Model\Namespace_\FlatNamespace;
28
29
use Irstea\PlantUmlBundle\Model\Namespace_\Php\RootNamespace;
use Irstea\PlantUmlBundle\Model\NamespaceInterface;
30
use Irstea\PlantUmlBundle\Writer\OutputWriter;
31
use ReflectionClass;
32
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
33
34
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Console\Input\InputArgument;
35
36
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
37
38
39
40
41
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Security\Core\Exception\InvalidArgumentException;
use Symfony\Component\Security\Core\Exception\RuntimeException;
42

43

44
45
46
47
48
/**
 * Description of ImportAffiliationCommand
 *
 * @author Guillaume Perréal <guillaume.perreal@irstea.fr>
 */
49
class GenerateCommand extends ContainerAwareCommand
50
{
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
    /**
     * @var string[]
     */
    private $bundles;

    /**
     * @var KernelInterface
     */
    private $kernel;

    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

66
67
68
    protected function configure()
    {
        $this
69
70
71
72
73
74
75
76
77
78
79
80
81
            ->setName('irstea:plantuml:generate')
            ->setDescription("Génère un graphe en PlantUML.")
            ->addArgument('graph', InputArgument::REQUIRED, 'Nom du graphe à générer');
    }

    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        parent::initialize($input, $output);

        // @todo: DI
        $this->bundles = $this->getContainer()->getParameter('kernel.bundles');
        $this->kernel =  $this->getContainer()->get('kernel');
        $this->entityManager =  $this->getContainer()->get('doctrine.orm.entity_manager');
82
83
84
85
86
87
88
89
90
91
92
    }

    /**
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     *
     * @SuppressWarnings(UnusedFormalParameter)
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
93
94
95
96
97
        $name = $input->getArgument('graph');
        $graphs = $this->getContainer()->getParameter('irstea_plant_uml.graphs');
        if (!isset($graphs[$name])) {
            throw new InvalidArgumentException("Le graphe '$name' n'est pas défini.");
        }
98

99
        $config = $graphs[$name];
100

101
102
103
104
105
        $classes = $this->findClasses($config['sources']);
        if (empty($classes)) {
            $output->writeln("Nothing to analyze.");
            return 0;
        }
106

107
108
        $namespace = $this->buildNamespace($config['layout']['namespaces']);
        $displayFilter = $this->buildFilter($config['layout']);
109

110
        $decorator = $this->buildDecorator($config['decoration']);
111

112
        $visitor = new ClassVisitor($decorator, $displayFilter, $namespace);
113

114
115
        foreach($classes as $class) {
            $visitor->visitClass($class);
116
        }
117

118
119
120
121
        $writer = new OutputWriter($output);
        $writer->write("@startuml\n");
        $visitor->outputTo($writer);
        $writer->write("@enduml\n");
122
    }
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212

    /**
     * @param ReflectionClass[]
     */
    protected function findClasses(array $config)
    {
        switch($config['type']) {
            case 'entities':
                $classes = $this->findEntities($config['entity_manager']);
                break;
            case 'classes':
                $classes = $this->findClassesInDirectories($config['directories']);
                break;
        }

        $filter = $this->buildFilter($config);
        if ($filter) {
            return array_filter($classes, [$filter, 'accept']);
        }

        return $classes;
    }

    /**
     * @return ReflectionClass[]
     */
    protected function findEntities($managerName)
    {
        $doctrine = $this->getContainer()->get('doctrine');
        $this->entityManager = $doctrine->getManager($managerName);

        $classes = [];
        foreach($this->entityManager->getMetadataFactory()->getAllMetadata() as $metadata) {
            $classes[$metadata->getName()] = $metadata->getReflectionClass();
        }

        return $classes;
    }

    /**
     *
     * @return ReflectionClass[]
     */
    protected function findClassesInDirectories($directories)
    {
        $paths = $this->parseDirectories($directories);

        $files = Finder::create()
            ->in($paths)
            ->files()
            ->name('*.php')
            ->getIterator();

        foreach($files as $file)
        {
            /* @var $file SplFileInfo */
            $path = $file->getPathname();
            try {
                irstea_plantmul_include($path);
            } catch(Exception $ex) {
                printf("%s: %s (%s)\n", $path, get_class($ex), $ex->getMessage());
            }
        }

        $filter = new DirectoryFilter($paths);
        $classes = [];
        foreach(get_declared_classes() as $className) {
            $class = new ReflectionClass($className);
            if ($filter->accept($class)) {
                $classes[$className] = $class;
            }
        }

        return $classes;
    }

    /**
     * @param array $config
     * @return DecoratorInterface
     * @throws RuntimeException
     */
    protected function buildDecorator(array $config)
    {
        $decorators = [];

        foreach($config['decorators'] as $decorator) {
            switch($decorator) {
                case 'inheritance':
                    $decorators[] = new InheritanceDecorator();
                    break;
213
214
215
216
217
218
                case 'interfaces':
                    $decorators[] = new InterfaceDecorator();
                    break;
                case 'traits':
                    $decorators[] = new TraitDecorator();
                    break;
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
                case 'entity':
                    $decorators[] = new EntityDecorator($this->entityManager->getMetadataFactory());
                    break;
                case 'associations':
                    $decorators[] = new AssociationDecorator($this->entityManager->getMetadataFactory());
                    break;
                /*default:
                    throw new RuntimeException("Decorator '$decorator' not yet implemented");*/
            }
        }

        if (empty($decorators)) {
            return NullDecorator::instance();
        }

        if (count($decorators) === 1) {
            $decorator = $decorators[0];
        } else {
            $decorator = new CompositeDecorator($decorators);
        }

        $filter = $this->buildFilter($config);
        if ($filter) {
            $decorator = new FilteringDecorator($decorator, $filter);
        }

        return $decorator;
    }

    /**
     * @param string $config
     * @return NamespaceInterface
     */
    protected function buildNamespace($config)
    {
        switch($config) {
            case 'php':
                return new RootNamespace();
            case 'flat':
                return new FlatNamespace();
            case 'entities':
                return new DoctrineNamespace($this->entityManager->getConfiguration()->getEntityNamespaces());
            case 'bundles':
                return new BundleNamespace($this->bundles);
        }
    }

    /**
     * @param array $config
     * @return ClassFilterInterface|null
     */
    protected function buildFilter(array $config)
    {
        $filters = array_merge(
            isset($config['include']) ? $this->buildSubFilters($config['include'], false) : [],
            isset($config['exclude']) ? $this->buildSubFilters($config['exclude'], true) : []
        );

        switch(count($filters)) {
            case 0:
                return null;
            case 1:
                return $filters[0];
            default:
                return new AllFilter($filters);
        }
    }

    /**
     * @param array $config
     * @param boolean $notFound
     * @return ClassFilterInterface|null
     */
    protected function buildSubFilters(array $config, $notFound)
    {
        $filters = [];

        if (!empty($config['directories'])) {
            $paths = $this->parseDirectories($config['directories']);
            $filters[] = new DirectoryFilter($paths, $notFound);
        }

        if (!empty($config['namespaces'])) {
            $namespaces = $this->parseNamespaces($config['namespaces']);
            $filters[] = new NamespaceFilter($namespaces, $notFound);
        }

        return $filters;
    }

    /**
     * @param array $paths
     * @return array
     */
    protected function parseDirectories(array $paths)
    {
        $actualPaths = [];
        foreach($paths as $path) {
            if (preg_match('/^@(\w+)(.*)$/', $path, $groups)) {
                $bundle = $this->kernel->getBundle($groups[1]);
                $path = $bundle->getPath() . $groups[2];
            }
            $actualPaths[] = realpath($path);
        }
        return $actualPaths;
    }

    /**
     * @param array $paths
     * @return array
     */
    protected function parseNamespaces(array $namespaces)
    {
        $actualNamespaces = [];
        foreach($namespaces as $namespace) {
            if (preg_match('/^@(\w+)(.*)$/', $namespace, $groups)) {
                $bundle = $this->kernel->getBundle($groups[1]);
                $namespace = $bundle->getNamespace() . $groups[2];
            }
            $actualNamespaces[] = $namespace;
        }
        return $actualNamespaces;
    }

343
}
344
345
346
347
348

function irstea_plantmul_include($filepath)
{
    @include_once($filepath);
}