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\RoutableInterface; |
20
|
|
|
use Silverback\ApiComponentsBundle\Entity\Core\Route; |
21
|
|
|
use Silverback\ApiComponentsBundle\Exception\InvalidArgumentException; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @author Daniel West <[email protected]> |
25
|
|
|
*/ |
26
|
|
|
class RouteGenerator implements RouteGeneratorInterface |
27
|
|
|
{ |
28
|
|
|
private SlugifyInterface $slugify; |
29
|
|
|
private ManagerRegistry $registry; |
30
|
|
|
|
31
|
|
|
public function __construct(SlugifyInterface $slugify, ManagerRegistry $registry) |
32
|
|
|
{ |
33
|
|
|
$this->slugify = $slugify; |
34
|
|
|
$this->registry = $registry; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function create(RoutableInterface $object, ?Route $route = null): Route |
38
|
|
|
{ |
39
|
|
|
$entityManager = $this->registry->getManagerForClass($className = \get_class($object)); |
40
|
|
|
if (!$entityManager) { |
41
|
|
|
throw new InvalidArgumentException(sprintf('Could not find entity manager for %s', $className)); |
42
|
|
|
} |
43
|
|
|
$uow = $entityManager->getUnitOfWork(); |
|
|
|
|
44
|
|
|
/** @var AbstractPage $originalPage */ |
45
|
|
|
$originalPage = $uow->getOriginalEntityData($object); |
46
|
|
|
$existingRoute = $originalPage['route']; |
47
|
|
|
|
48
|
|
|
$route = $route ?? new Route(); |
49
|
|
|
|
50
|
|
|
$path = $this->slugify->slugify($object->getTitle()); |
51
|
|
|
|
52
|
|
|
$route |
53
|
|
|
->setName(sprintf('generated-%s', $path)) |
54
|
|
|
->setPath('/' . ltrim($path, '/')); |
55
|
|
|
$object->setRoute($route); |
56
|
|
|
|
57
|
|
|
if ($existingRoute) { |
58
|
|
|
$existingRoute->setRedirect($route); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return $route; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|