Completed
Pull Request — master (#554)
by
unknown
02:15
created

AbstractLinkViewHelper   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 91
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
wmc 12
lcom 2
cbo 2
dl 0
loc 91
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A initializeArguments() 0 12 1
A renderLink() 0 21 2
B getPageUid() 0 19 9
1
<?php
2
3
/**
4
 * Link to anything ;).
5
 */
6
declare(strict_types=1);
7
8
namespace HDNET\Calendarize\ViewHelpers\Link;
9
10
use TYPO3\CMS\Core\Utility\MathUtility;
11
use TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder;
12
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper;
13
14
/**
15
 * Link to anything ;).
16
 */
17
abstract class AbstractLinkViewHelper extends AbstractTagBasedViewHelper
18
{
19
    /**
20
     * Tag type.
21
     *
22
     * @var string
23
     */
24
    protected $tagName = 'a';
25
26
    /**
27
     * Store the last href to avoid escaping for the URI view Helper.
28
     *
29
     * @var string
30
     */
31
    protected $lastHref = '';
32
33
    /**
34
     * Arguments initialization.
35
     */
36
    public function initializeArguments()
37
    {
38
        parent::initializeArguments();
39
        $this->registerUniversalTagAttributes();
40
        $this->registerTagAttribute('target', 'string', 'Target of link', false);
41
        $this->registerTagAttribute(
42
            'rel',
43
            'string',
44
            'Specifies the relationship between the current document and the linked document',
45
            false
46
        );
47
    }
48
49
    /**
50
     * render the link.
51
     *
52
     * @param int|null $pageUid          target page. See TypoLink destination
53
     * @param array    $additionalParams query parameters to be attached to the resulting URI
54
     * @param bool     $absolute
55
     *
56
     * @return string Rendered page URI
57
     */
58
    public function renderLink($pageUid = null, array $additionalParams = [], $absolute = false, $section = '')
59
    {
60
        /** @var UriBuilder $uriBuilder */
61
        $uriBuilder = $this->renderingContext->getControllerContext()->getUriBuilder();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TYPO3Fluid\Fluid\Core\Re...nderingContextInterface as the method getControllerContext() does only exist in the following implementations of said interface: TYPO3\CMS\Fluid\Core\Rendering\RenderingContext.

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...
62
        // $uriBuilder = $this->renderingContext->getUriBuilder(); // Typo3 11 and later
63
        $this->lastHref = $uriBuilder->reset()
64
            ->setTargetPageUid($pageUid)
65
            ->setSection($section)
66
            ->setArguments($additionalParams)
67
            ->setCreateAbsoluteUri($absolute)
68
            ->build();
69
        if ('' !== $this->lastHref) {
70
            $this->tag->addAttribute('href', $this->lastHref);
71
            $this->tag->setContent($this->renderChildren());
72
            $result = $this->tag->render();
73
        } else {
74
            $result = $this->renderChildren();
75
        }
76
77
        return $result;
78
    }
79
80
    /**
81
     * Get the right page Uid.
82
     *
83
     * @param int         $pageUid
84
     * @param string|null $contextName
85
     *
86
     * @return int
87
     */
88
    protected function getPageUid($pageUid, $contextName = null)
89
    {
90
        if (MathUtility::canBeInterpretedAsInteger($pageUid) && $pageUid > 0) {
91
            return (int)$pageUid;
92
        }
93
        if (null === $contextName && $this->actionName) {
94
            $contextName = $this->actionName . 'Pid';
0 ignored issues
show
Bug introduced by
The property actionName does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
95
        }
96
97
        // by settings
98
        if ($contextName && $this->templateVariableContainer->exists('settings')) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $contextName of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
99
            $settings = $this->templateVariableContainer->get('settings');
100
            if (isset($settings[$contextName]) && MathUtility::canBeInterpretedAsInteger($settings[$contextName])) {
101
                return (int)$settings[$contextName];
102
            }
103
        }
104
105
        return (int)$GLOBALS['TSFE']->id;
106
    }
107
}
108