Completed
Push — master ( 910ab8...21dbb8 )
by Tim
29s queued 11s
created

BackendController   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 159
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 6
dl 0
loc 159
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A optionAction() 0 6 1
A listAction() 0 23 2
A getPids() 0 10 2
A getPageTitles() 0 14 3
A getOptions() 0 14 3
A getDifferentTypesAndLocations() 0 17 3
A isPageAllowed() 0 15 4
A getAllowedDbMounts() 0 9 2
A getBackendUser() 0 4 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);
74
            if ($row) {
75
                $title = BackendUtility::getRecordTitle('pages', $row);
76
                $results[$pageId] = '"' . $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...
77
                continue;
78
            }
79
            // fallback to uid
80
            $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...
81
        }
82
        return $results;
83
    }
84
85
    /**
86
     * Get option request.
87
     *
88
     * @return OptionRequest
89
     */
90
    protected function getOptions()
91
    {
92
        try {
93
            $info = $GLOBALS['BE_USER']->getSessionData('calendarize_be');
94
            $object = @unserialize((string)$info);
95
            if ($object instanceof OptionRequest) {
96
                return $object;
97
            }
98
99
            return new OptionRequest();
100
        } catch (\Exception $exception) {
101
            return new OptionRequest();
102
        }
103
    }
104
105
    /**
106
     * Get the differnet locations for new entries.
107
     *
108
     * @return array
109
     */
110
    protected function getDifferentTypesAndLocations()
111
    {
112
        /**
113
         * @var array<int>
114
         */
115
        $mountPoints = $this->getAllowedDbMounts();
116
117
        $typeLocations = [];
118
        foreach ($this->indexRepository->findDifferentTypesAndLocations() as $entry) {
119
            $pageId = $entry['pid'];
120
            if ($this->isPageAllowed($pageId, $mountPoints)) {
121
                $typeLocations[$entry['foreign_table']][$pageId] = $entry['unique_register_key'];
122
            }
123
        }
124
125
        return $typeLocations;
126
    }
127
128
    /**
129
     * Check if access to page is allowed for current user.
130
     *
131
     * @param int $pageId
132
     * @param array $mountPoints
133
     * @return bool
134
     */
135
    protected function isPageAllowed(int $pageId, array $mountPoints):bool
136
    {
137
        if ($this->getBackendUser()->isAdmin()) {
138
            return true;
139
        }
140
141
        // check if any mountpoint is in rootline
142
        $rootline = BackendUtility::BEgetRootLine($pageId, '');
143
        foreach ($rootline as $entry) {
144
            if (in_array((int)$entry['uid'], $mountPoints)) {
145
                return true;
146
            }
147
        }
148
        return false;
149
    }
150
151
    /**
152
     * Get allowed mountpoints. Returns temporary mountpoint when temporary mountpoint is used.
153
     *
154
     * copied from core TreeController
155
     *
156
     * @return int[]
157
     */
158
    protected function getAllowedDbMounts(): array
159
    {
160
        $dbMounts = (int)($this->getBackendUser()->uc['pageTree_temporaryMountPoint'] ?? 0);
161
        if (!$dbMounts) {
162
            $dbMounts = array_map('intval', $this->getBackendUser()->returnWebmounts());
163
            return array_unique($dbMounts);
164
        }
165
        return [$dbMounts];
166
    }
167
168
    /**
169
     * @return BackendUserAuthentication
170
     */
171
    protected function getBackendUser(): BackendUserAuthentication
172
    {
173
        return $GLOBALS['BE_USER'];
174
    }
175
176
}
177