resolveValue()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
namespace MOC\Redirects\Routing;
3
4
use Doctrine\ORM\QueryBuilder;
5
use Neos\Flow\Annotations as Flow;
6
use Neos\Flow\Core\Bootstrap;
7
use Neos\Flow\Http\Uri;
8
use Neos\Flow\Mvc\Routing\DynamicRoutePart;
9
use Neos\ContentRepository\Domain\Model\NodeData;
10
11
/**
12
 * A route part handler for finding nodes specifically in the website's frontend.
13
 */
14
class RedirectFrontendNodeRoutePartHandler extends DynamicRoutePart
15
{
16
17
    /**
18
     * @Flow\Inject
19
     * @var \Doctrine\Common\Persistence\ObjectManager
20
     */
21
    protected $entityManager;
22
23
    /**
24
     * @Flow\Inject
25
     * @var Bootstrap
26
     */
27
    protected $bootstrap;
28
29
    /**
30
     * @param string $requestPath The request path to be matched
31
     * @return string value to match
32
     */
33
    protected function findValueToMatch($requestPath)
34
    {
35
        return $requestPath;
36
    }
37
38
    /**
39
     * @param string $requestPath
40
     * @return boolean TRUE if the $requestPath could be matched, otherwise FALSE
41
     */
42
    protected function matchValue($requestPath)
43
    {
44
        /** @var Uri $uri */
45
        $uri = $this->bootstrap->getActiveRequestHandler()->getHttpRequest()->getUri();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Neos\Flow\Core\RequestHandlerInterface as the method getHttpRequest() does only exist in the following implementations of said interface: Neos\Flow\Http\RequestHandler, Neos\Flow\Tests\FunctionalTestRequestHandler, Neos\Setup\Core\RequestHandler.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
46
        $relativeUrl = rtrim($uri->getPath(), '/');
47
        $relativeUrlWithQueryString = $relativeUrl . ($uri->getQuery() ? '?' . $uri->getQuery() : '');
48
        $absoluteUrl = $uri->getHost() . $relativeUrl;
49
        $absoluteUrlWithQueryString = $uri->getHost() . $relativeUrlWithQueryString;
50
51
        if (empty($relativeUrl)) {
52
            return false;
53
        }
54
55
        /** @var QueryBuilder $queryBuilder */
56
        $queryBuilder = $this->entityManager->createQueryBuilder();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Common\Persistence\ObjectManager as the method createQueryBuilder() does only exist in the following implementations of said interface: Doctrine\ORM\Decorator\EntityManagerDecorator, Doctrine\ORM\EntityManager.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
57
        $queryBuilder->select('n')
58
            ->distinct()
59
            ->from('Neos\ContentRepository\Domain\Model\NodeData', 'n')
60
            ->where('n.workspace = :workspace')
61
            ->setParameter('workspace', 'live')
62
            ->andWhere('n.properties LIKE :relativeUrl')
63
            ->setParameter('relativeUrl', '%"redirectUrl"%' . str_replace('/', '\\\\\\/', ltrim($relativeUrl, '/')) . '%');
64
65
        $query = $queryBuilder->getQuery();
66
        $nodes = $query->getResult();
67
        if (empty($nodes)) {
68
            return false;
69
        }
70
71
        foreach ($nodes as $node) {
72
            /** @var NodeData $node */
73
            // Prevent partial matches
74
            $redirectUrl = trim(preg_replace('#^https?://#', '', $node->getProperty('redirectUrl')), '/');
75
            if (in_array($redirectUrl, [$relativeUrl, $relativeUrlWithQueryString, $absoluteUrl, $absoluteUrlWithQueryString], true)) {
76
                $matchingNode = $node;
77
                break;
78
            }
79
        }
80
81
        if (!isset($matchingNode)) {
82
            return false;
83
        }
84
85
        $this->setName('node');
86
        $this->value = $matchingNode->getPath();
87
88
        return true;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return true; (boolean) is incompatible with the return type of the parent method Neos\Flow\Mvc\Routing\DynamicRoutePart::matchValue of type false|Neos\Flow\Mvc\Routing\Dto\MatchResult.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
89
    }
90
91
    /**
92
     * @param string $value value to resolve
93
     * @return boolean TRUE if value could be resolved successfully, otherwise FALSE.
94
     */
95
    protected function resolveValue($value)
96
    {
97
        return false;
98
    }
99
100
}
101