Router::match()   B
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
c 0
b 0
f 0
rs 8.5806
cc 4
eloc 17
nc 8
nop 1
1
<?php
2
3
namespace Tkotosz\CatalogRouter\Controller;
4
5
use Tkotosz\CatalogRouter\Model\Exception\EntityDataNotFoundException;
6
use Tkotosz\CatalogRouter\Model\Service\CatalogUrlPathResolver;
7
use Tkotosz\CatalogRouter\Model\UrlPath;
8
use Magento\Framework\App\ActionFactory;
9
use Magento\Framework\App\Action\Forward;
10
use Magento\Framework\App\RequestInterface;
11
use Magento\Framework\App\Request\Http as HttpRequest;
12
use Magento\Framework\App\RouterInterface;
13
use Magento\Framework\Url;
14
use Magento\Store\Model\StoreManagerInterface;
15
16
class Router implements RouterInterface
17
{
18
    /**
19
     * @var ActionFactory
20
     */
21
    protected $actionFactory;
22
    
23
    /**
24
     * @var CatalogUrlPathResolver
25
     */
26
    private $catalogUrlPathResolver;
27
    
28
    /**
29
     * @var StoreManagerInterface
30
     */
31
    private $storeManager;
32
33
    /**
34
     * @param ActionFactory          $actionFactory
35
     * @param CatalogUrlPathResolver $catalogUrlPathResolver
36
     * @param StoreManagerInterface  $storeManager
37
     */
38
    public function __construct(
39
        ActionFactory $actionFactory,
40
        CatalogUrlPathResolver $catalogUrlPathResolver,
41
        StoreManagerInterface $storeManager
42
    ) {
43
        $this->actionFactory = $actionFactory;
44
        $this->catalogUrlPathResolver = $catalogUrlPathResolver;
45
        $this->storeManager = $storeManager;
46
    }
47
48
    /**
49
     * @param RequestInterface $request
50
     * 
51
     * @return ActionInterface
52
     */
53
    public function match(RequestInterface $request)
54
    {
55
        if (!($request instanceof HttpRequest)) {
56
            return null;
57
        }
58
59
        if ($request->getControllerName()) {
60
            return null;
61
        }
62
63
        try {
64
            $urlPath = new UrlPath($request->getPathInfo());
65
            $entity = $this->catalogUrlPathResolver->resolve($urlPath, $this->storeManager->getStore()->getId());
66
            $request->setModuleName('catalog')
67
                ->setControllerName($entity->getType())
68
                ->setActionName('view')
69
                ->setParam('id', $entity->getId());
70
            
71
            $request->setAlias(Url::REWRITE_REQUEST_PATH_ALIAS, $urlPath->getIdentifier());
72
            $result = $this->actionFactory->create(Forward::class);
73
        } catch (EntityDataNotFoundException $e) {
74
            $result = null;
75
        }
76
77
        return $result;
78
    }
79
}
80