Test Failed
Push — develop ( 4ac156...4a39bf )
by Daniel
06:06
created

RouteFactory   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 30
dl 0
loc 57
rs 10
c 0
b 0
f 0
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B createFromRouteAwareEntity() 0 27 6
A getRoutePrefix() 0 7 2
1
<?php
2
3
namespace Silverback\ApiComponentBundle\Factory;
4
5
use Cocur\Slugify\SlugifyInterface;
6
use Silverback\ApiComponentBundle\Entity\Content\AbstractContent;
7
use Silverback\ApiComponentBundle\Entity\Route\Route;
8
use Silverback\ApiComponentBundle\Entity\Route\RouteAwareInterface;
9
use Silverback\ApiComponentBundle\Repository\RouteRepository;
10
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
11
12
class RouteFactory
13
{
14
    private $slugify;
15
    private $repository;
16
17
    public function __construct(
18
        SlugifyInterface $slugify,
19
        RouteRepository $repository
20
    ) {
21
        $this->slugify = $slugify;
22
        $this->repository = $repository;
23
    }
24
25
    /**
26
     * @param RouteAwareInterface $entity
27
     * @param int|null $postfix
28
     * @return Route
29
     */
30
    public function createFromRouteAwareEntity(RouteAwareInterface $entity, int $postfix = 0): Route
31
    {
32
        $pageRoute = $this->slugify->slugify($entity->getDefaultRoute() ?: '');
33
        $routePrefix = $this->getRoutePrefix($entity);
34
        $fullRoute = $routePrefix . $pageRoute;
35
        if ($postfix > 0) {
36
            $fullRoute .= '-' . $postfix;
37
        }
38
        $existing = $this->repository->find($fullRoute);
39
        if ($existing) {
40
            return $this->createFromRouteAwareEntity($entity, $postfix + 1);
41
        }
42
        $converter = new CamelCaseToSnakeCaseNameConverter();
43
        $generatedName = $converter->normalize(str_replace(' ', '', $entity->getDefaultRouteName()));
44
        $name = $generatedName;
45
        $counter = 0;
46
        while ($this->repository->findOneBy(['name' => $name])) {
47
            $counter++;
48
            $name = sprintf('%s-%s', $generatedName, $counter);
49
        }
50
        $route = new Route();
51
        $route->setName($name)->setRoute($fullRoute);
52
        if ($entity instanceof AbstractContent) {
53
            $route->setContent($entity);
54
        }
55
        $entity->addRoute($route);
56
        return $route;
57
    }
58
    /**
59
     * @param RouteAwareInterface $entity
60
     * @return string
61
     */
62
    private function getRoutePrefix(RouteAwareInterface $entity): string
63
    {
64
        $parent = $entity->getParentRoute();
65
        if ($parent) {
66
            return $parent->getRoute() . '/';
67
        }
68
        return '/';
69
    }
70
}
71