InheritanceDecorator.php 2.14 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php

/*
 * © 2016 IRSTEA
 * Guillaume Perréal <guillaume.perreal@irstea.fr>
 * Tous droits réservés.
 */

namespace Irstea\PlantUmlBundle\Model\Decorator;

use Irstea\PlantUmlBundle\Model\ClassVisitor;
use Irstea\PlantUmlBundle\Model\ClassVisitorInterface;
use Irstea\PlantUmlBundle\Model\DecoratorInterface;
use Irstea\PlantUmlBundle\Model\NodeInterface;
use ReflectionClass;

/**
 * Description of InheritanceDecorator
 *
 * @author Guillaume Perréal <guillaume.perreal@irstea.fr>
 */
class InheritanceDecorator implements DecoratorInterface
{
    public function decorate($className, NodeInterface $node, ClassVisitorInterface $visitor)
    {
        $class = new ReflectionClass($className);

        $parent = $class->getParentClass();
        $traits = $class->getTraitNames();
        $interfaces = $class->getInterfaceNames();

        $indirectInterfaces = array_filter(
            array_map(
                function ($i) { return $i->getInterfaceNames(); },
                $class->getInterfaces()
            )
        );

        if (!empty($indirectInterfaces)) {
            $indirectInterfaces = call_user_func_array('array_merge', $indirectInterfaces);
            $interfaces = array_diff($interfaces, $indirectInterfaces);
        }

        if ($parent) {
            $traits = array_diff($traits, $parent->getTraitNames());
            $interfaces = array_diff($interfaces, $parent->getInterfaceNames());
            $this->visitRelations($node, [$parent->getName()], 'Irstea\PlantUmlBundle\Model\Arrow\ExtendsClass', $visitor);
        }

        $this->visitRelations($node, $interfaces, 'Irstea\PlantUmlBundle\Model\Arrow\ImplementsInterface', $visitor);
        $this->visitRelations($node, $traits, 'Irstea\PlantUmlBundle\Model\Arrow\UsesTrait', $visitor);

        return $this;
    }

    protected function visitRelations(NodeInterface $source, array $classNames, $relationClass, ClassVisitorInterface $visitor)
    {
        foreach ($classNames as $className) {
            $target = $visitor->visitClass($className);
            if ($target) {
                $source->addArrow(new $relationClass($source, $target));
            }
        }
    }
}