Completed
Pull Request — master (#530)
by
unknown
02:40
created

BackendController::getPageTitles()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
/**
4
 * BackendController.
5
 */
6
declare(strict_types=1);
7
8
namespace HDNET\Calendarize\Controller;
9
10
use HDNET\Calendarize\Domain\Model\Request\OptionRequest;
11
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
12
use TYPO3\CMS\Backend\Utility\BackendUtility;
13
use TYPO3\CMS\Core\Messaging\FlashMessage;
14
15
/**
16
 * BackendController.
17
 */
18
class BackendController extends AbstractController
19
{
20
    /**
21
     * Basic backend list.
22
     */
23
    public function listAction()
24
    {
25
        $this->settings['timeFormat'] = 'H:i';
26
        $this->settings['dateFormat'] = 'd.m.Y';
27
28
        $options = $this->getOptions();
29
        $typeLocations = $this->getDifferentTypesAndLocations();
30
31
        $pids = $this->getPids($typeLocations);
32
        if ($pids) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $pids of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
33
            $indices = $this->indexRepository->findAllForBackend($options, $pids);
34
        } else {
35
            $indices = [];
36
        }
37
38
        $this->view->assignMultiple([
39
            'indices' => $indices,
40
            'typeLocations' => $typeLocations,
41
            'pids' => $this->getPageTitles($pids),
42
            'settings' => $this->settings,
43
            'options' => $options,
44
        ]);
45
    }
46
47
    /**
48
     * Option action.
49
     *
50
     * @param \HDNET\Calendarize\Domain\Model\Request\OptionRequest $options
51
     */
52
    public function optionAction(OptionRequest $options)
53
    {
54
        $GLOBALS['BE_USER']->setAndSaveSessionData('calendarize_be', serialize($options));
55
        $this->addFlashMessage('Options saved', '', FlashMessage::OK, true);
56
        $this->forward('list');
57
    }
58
59
    protected function getPids(array $typeLocations)
60
    {
61
        $pids = [];
62
        foreach ($typeLocations as $locations) {
63
            $pids = array_merge($pids, array_keys($locations));
64
        }
65
        $pids = array_unique($pids);
66
67
        return array_combine($pids, $pids);
68
    }
69
70
    protected function getPageTitles(array $pids): array
71
    {
72
        foreach ($pids as $pageId) {
73
            $row = BackendUtility::getRecord('pages', $pageId, 'title');
74
            if ($row['title'] ?? '') {
75
                $results[$pageId] = '"' . $row['title'] . '" (#' . $pageId . ')';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$results was never initialized. Although not strictly required by PHP, it is generally a good practice to add $results = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
76
            } else {
77
                $results[$pageId] = '#' . $pageId;
0 ignored issues
show
Bug introduced by
The variable $results does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
78
            }
79
        }
80
        return $results;
81
    }
82
83
    /**
84
     * Get option request.
85
     *
86
     * @return OptionRequest
87
     */
88
    protected function getOptions()
89
    {
90
        try {
91
            $info = $GLOBALS['BE_USER']->getSessionData('calendarize_be');
92
            $object = @unserialize((string)$info);
93
            if ($object instanceof OptionRequest) {
94
                return $object;
95
            }
96
97
            return new OptionRequest();
98
        } catch (\Exception $exception) {
99
            return new OptionRequest();
100
        }
101
    }
102
103
    /**
104
     * Get the differnet locations for new entries.
105
     *
106
     * @return array
107
     */
108
    protected function getDifferentTypesAndLocations()
109
    {
110
        /**
111
         * @var array<int>
112
         */
113
        $mountPoints = $this->getAllowedDbMounts();
114
115
        $typeLocations = [];
116
        foreach ($this->indexRepository->findDifferentTypesAndLocations() as $entry) {
117
            $pageId = $entry['pid'];
118
            if ($this->isPageAllowed($pageId, $mountPoints)) {
119
                $typeLocations[$entry['foreign_table']][$pageId] = $entry['unique_register_key'];
120
            }
121
        }
122
123
        return $typeLocations;
124
    }
125
126
    /**
127
     * Check if access to page is allowed for current user.
128
     *
129
     * @param int $pageId
130
     * @param array $mountPoints
131
     * @return bool
132
     */
133
    protected function isPageAllowed(int $pageId, array $mountPoints):bool
134
    {
135
        if ($this->getBackendUser()->isAdmin()) {
136
            return true;
137
        }
138
139
        // check if any mountpoint is in rootline
140
        $rootline = BackendUtility::BEgetRootLine($pageId, '');
141
        foreach ($rootline as $entry) {
142
            if (in_array((int)$entry['uid'], $mountPoints)) {
143
                return true;
144
            }
145
        }
146
        return false;
147
    }
148
149
    /**
150
     * Get allowed mountpoints. Returns temporary mountpoint when temporary mountpoint is used.
151
     *
152
     * copied from core TreeController
153
     *
154
     * @return int[]
155
     */
156
    protected function getAllowedDbMounts(): array
157
    {
158
        $dbMounts = (int)($this->getBackendUser()->uc['pageTree_temporaryMountPoint'] ?? 0);
159
        if (!$dbMounts) {
160
            $dbMounts = array_map('intval', $this->getBackendUser()->returnWebmounts());
161
            return array_unique($dbMounts);
162
        }
163
        return [$dbMounts];
164
    }
165
166
    /**
167
     * @return BackendUserAuthentication
168
     */
169
    protected function getBackendUser(): BackendUserAuthentication
170
    {
171
        return $GLOBALS['BE_USER'];
172
    }
173
174
}
175