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(); |
|
|
|
|
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
|
|
|
|