Completed
Pull Request — master (#19)
by
unknown
19:27
created

RequestViewHelper::initializeObject()   A

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 0
1
<?php
2
namespace MOC\NotFound\ViewHelpers;
3
4
use Neos\Flow\Annotations as Flow;
5
use Neos\Flow\Core\Bootstrap;
6
use Neos\Flow\Http\Client\CurlEngine;
7
use Neos\Flow\Http\Client\CurlEngineException;
8
use Neos\Flow\Http\Helper\RequestInformationHelper;
9
use Neos\Flow\Mvc\Exception\NoMatchingRouteException;
10
use Neos\FluidAdaptor\Core\ViewHelper\AbstractViewHelper;
11
use Neos\FluidAdaptor\Core\ViewHelper\Exception as ViewHelperException;
12
use Neos\Http\Factories\ServerRequestFactory;
13
use Neos\Neos\Domain\Service\ContentDimensionPresetSourceInterface;
14
use Neos\Neos\Routing\FrontendNodeRoutePartHandler;
15
use Psr\Http\Message\ServerRequestInterface;
16
17
/**
18
 * Loads the content of a given URL
19
 */
20
class RequestViewHelper extends AbstractViewHelper
21
{
22
    /**
23
     * @Flow\Inject(lazy=false)
24
     * @var Bootstrap
25
     */
26
    protected $bootstrap;
27
28
    /**
29
     * @Flow\Inject
30
     * @var ContentDimensionPresetSourceInterface
31
     */
32
    protected $contentDimensionPresetSource;
33
34
    /**
35
     * @Flow\Inject
36
     * @var ServerRequestFactory
37
     */
38
    protected $serverRequestFactory;
39
40
    /**
41
     * @Flow\InjectConfiguration(path="routing.supportEmptySegmentForDimensions", package="Neos.Neos")
42
     * @var boolean
43
     */
44
    protected $supportEmptySegmentForDimensions;
45
46
    /**
47
     * @return void
48
     * @throws ViewHelperException
49
     * @api
50
     */
51
    public function initializeArguments()
52
    {
53
        parent::initializeArguments();
54
        $this->registerArgument('path', 'string', 'Path', false, '404');
55
    }
56
57
    /**
58
     * @return string
59
     * @throws \RuntimeException
60
     * @throws CurlEngineException
61
     * @throws NoMatchingRouteException
62
     */
63
    public function render() : string
64
    {
65
        $path = $this->arguments['path'];
66
        $this->appendFirstUriPartIfValidDimension($path);
67
68
        $request = $this->bootstrap->getActiveRequestHandler()->getHttpRequest();
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.

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...
69
        \assert($request instanceof ServerRequestInterface);
70
71
        $userAgent = $request->getHeader('User-Agent');
72
        if (isset($userAgent[0]) && strncmp($userAgent[0], 'Flow', 4) === 0) {
73
            // To prevent a request loop, requests from Flow will be ignored.
74
            return '';
75
        }
76
77
        $uri = RequestInformationHelper::generateBaseUri($request)->withPath($path);
78
        // By default, the ServerRequestFactory sets the User-Agent header to "Flow/" followed by the version branch.
79
        $serverRequest = $this->serverRequestFactory->createServerRequest('GET', $uri);
80
        $response = (new CurlEngine())->sendRequest($serverRequest);
81
82
        if ($response->getStatusCode() === 404) {
83
            throw new NoMatchingRouteException(sprintf('Uri with path "%s" could not be found.', $uri), 1426446160);
84
        }
85
86
        return $response->getBody()->getContents();
87
    }
88
89
    /**
90
     * @param string $path
91
     * @return void
92
     */
93
    protected function appendFirstUriPartIfValidDimension(&$path)
94
    {
95
        $requestPath = ltrim($this->controllerContext->getRequest()->getHttpRequest()->getUri()->getPath(), '/');
96
        $matches = [];
97
        preg_match(FrontendNodeRoutePartHandler::DIMENSION_REQUEST_PATH_MATCHER, $requestPath, $matches);
98
        if (!isset($matches['firstUriPart']) && !isset($matches['dimensionPresetUriSegments'])) {
99
            return;
100
        }
101
102
        $dimensionPresets = $this->contentDimensionPresetSource->getAllPresets();
103
        if (count($dimensionPresets) === 0) {
104
            return;
105
        }
106
107
        $firstUriPartExploded = explode('_', $matches['firstUriPart'] ?: $matches['dimensionPresetUriSegments']);
108
        if ($this->supportEmptySegmentForDimensions) {
109
            foreach ($firstUriPartExploded as $uriSegment) {
110
                $uriSegmentIsValid = false;
111
                foreach ($dimensionPresets as $dimensionName => $dimensionPreset) {
112
                    $preset = $this->contentDimensionPresetSource->findPresetByUriSegment($dimensionName, $uriSegment);
113
                    if ($preset !== null) {
114
                        $uriSegmentIsValid = true;
115
                        break;
116
                    }
117
                }
118
                if (!$uriSegmentIsValid) {
119
                    return;
120
                }
121
            }
122
        } else {
123
            if (count($firstUriPartExploded) !== count($dimensionPresets)) {
124
                $this->appendDefaultDimensionPresetUriSegments($dimensionPresets, $path);
125
                return;
126
            }
127
            foreach ($dimensionPresets as $dimensionName => $dimensionPreset) {
128
                $uriSegment = array_shift($firstUriPartExploded);
129
                $preset = $this->contentDimensionPresetSource->findPresetByUriSegment($dimensionName, $uriSegment);
130
                if ($preset === null) {
131
                    $this->appendDefaultDimensionPresetUriSegments($dimensionPresets, $path);
132
                    return;
133
                }
134
            }
135
        }
136
137
        $path = $matches['firstUriPart'] . '/' . $path;
138
    }
139
140
    /**
141
     * @param array $dimensionPresets
142
     * @param string $path
143
     * @return void
144
     */
145
    protected function appendDefaultDimensionPresetUriSegments(array $dimensionPresets, &$path) {
146
        $defaultDimensionPresetUriSegments = [];
147
        foreach ($dimensionPresets as $dimensionName => $dimensionPreset) {
148
            $defaultDimensionPresetUriSegments[] = $dimensionPreset['presets'][$dimensionPreset['defaultPreset']]['uriSegment'];
149
        }
150
        $path = implode('_', $defaultDimensionPresetUriSegments) . '/' . $path;
151
    }
152
}
153