Passed
Pull Request — master (#92)
by Daniel
06:25
created

RouteGenerator::createFromPage()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 15
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 25
ccs 0
cts 15
cp 0
crap 12
rs 9.7666
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentsBundle\Helper\Route;
15
16
use Cocur\Slugify\SlugifyInterface;
17
use Doctrine\Persistence\ManagerRegistry;
18
use Silverback\ApiComponentsBundle\Entity\Core\AbstractPage;
19
use Silverback\ApiComponentsBundle\Entity\Core\Route;
20
use Silverback\ApiComponentsBundle\Exception\InvalidArgumentException;
21
22
/**
23
 * @author Daniel West <[email protected]>
24
 */
25
class RouteGenerator
26
{
27
    private SlugifyInterface $slugify;
28
    private ManagerRegistry $registry;
29
30
    public function __construct(SlugifyInterface $slugify, ManagerRegistry $registry)
31
    {
32
        $this->slugify = $slugify;
33
        $this->registry = $registry;
34
    }
35
36
    public function createFromPage(AbstractPage $page, ?Route $route = null): Route
37
    {
38
        $entityManager = $this->registry->getManagerForClass($className = \get_class($page));
39
        if (!$entityManager) {
40
            throw new InvalidArgumentException(sprintf('Could not find entity manager for %s', $className));
41
        }
42
        $uow = $entityManager->getUnitOfWork();
0 ignored issues
show
Bug introduced by
The method getUnitOfWork() does not exist on Doctrine\Persistence\ObjectManager. It seems like you code against a sub-type of Doctrine\Persistence\ObjectManager such as Doctrine\ORM\EntityManagerInterface or Doctrine\ORM\Decorator\EntityManagerDecorator. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

42
        /** @scrutinizer ignore-call */ 
43
        $uow = $entityManager->getUnitOfWork();
Loading history...
43
        /** @var AbstractPage $originalPage */
44
        $originalPage = $uow->getOriginalEntityData($page);
45
        $existingRoute = $originalPage['route'];
46
47
        $route = $route ?? new Route();
48
49
        $path = $this->slugify->slugify($page->getTitle());
50
51
        $route
52
            ->setName(sprintf('generated-%s', $path))
53
            ->setPath('/' . ltrim($path, '/'));
54
        $page->setRoute($route);
55
56
        if ($existingRoute) {
57
            $existingRoute->setRedirect($route);
58
        }
59
60
        return $route;
61
    }
62
}
63