Completed
Push — master ( 9b84d0...43de24 )
by Tim
14s queued 10s
created

BackendController::setOptions()   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 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\Backend\Utility\BackendUtility;
12
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
13
use TYPO3\CMS\Core\Pagination\ArrayPaginator;
14
use TYPO3\CMS\Core\Pagination\SimplePagination;
15
use TYPO3\CMS\Extbase\Pagination\QueryResultPaginator;
16
17
/**
18
 * BackendController.
19
 */
20
class BackendController extends AbstractController
21
{
22
    const OPTIONS_KEY = 'calendarize_be';
23
24
    /**
25
     * Basic backend list.
26
     */
27
    public function listAction(OptionRequest $options = null, int $currentPage = 1)
28
    {
29
        $this->settings['timeFormat'] = 'H:i';
30
        $this->settings['dateFormat'] = 'd.m.Y';
31
32
        if (null === $options) {
33
            $options = $this->getOptions();
34
        } else {
35
            $this->setOptions($options);
36
        }
37
38
        $typeLocations = $this->getDifferentTypesAndLocations();
39
40
        $pids = $this->getPids($typeLocations);
41
        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...
42
            $indices = $this->indexRepository->findAllForBackend($options, $pids);
43
            $paginator = new QueryResultPaginator($indices, $currentPage, 50);
0 ignored issues
show
Bug introduced by
It seems like $indices defined by $this->indexRepository->...ackend($options, $pids) on line 42 can also be of type array; however, TYPO3\CMS\Extbase\Pagina...aginator::__construct() does only seem to accept object<TYPO3\CMS\Extbase...e\QueryResultInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
44
        } else {
45
            $indices = [];
46
            $paginator = new ArrayPaginator($indices, $currentPage, 50);
47
        }
48
        $pagination = new SimplePagination($paginator);
49
50
        $this->view->assignMultiple([
51
            'indices' => $indices,
52
            'typeLocations' => $typeLocations,
53
            'pids' => $this->getPageTitles($pids),
54
            'settings' => $this->settings,
55
            'options' => $options,
56
            'paginator' => $paginator,
57
            'pagination' => $pagination,
58
            'totalAmount' => $indices->count(),
59
        ]);
60
    }
61
62
    protected function getPids(array $typeLocations)
63
    {
64
        $pids = [];
65
        foreach ($typeLocations as $locations) {
66
            $pids = array_merge($pids, array_keys($locations));
67
        }
68
        $pids = array_unique($pids);
69
70
        return array_combine($pids, $pids);
71
    }
72
73
    protected function getPageTitles(array $pids): array
74
    {
75
        foreach ($pids as $pageId) {
76
            $row = BackendUtility::getRecord('pages', $pageId);
77
            if ($row) {
78
                $title = BackendUtility::getRecordTitle('pages', $row);
79
                $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...
80
                continue;
81
            }
82
            // fallback to uid
83
            $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...
84
        }
85
86
        return $results;
87
    }
88
89
    /**
90
     * Get option request.
91
     *
92
     * @return OptionRequest
93
     */
94
    protected function getOptions(): OptionRequest
95
    {
96
        try {
97
            $info = $GLOBALS['BE_USER']->getSessionData(self::OPTIONS_KEY) ?? '';
98
            if ('' !== $info) {
99
                $object = @unserialize($info, ['allowed_classes' => [OptionRequest::class]]);
100
                if ($object instanceof OptionRequest) {
101
                    return $object;
102
                }
103
            }
104
        } catch (\Exception $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
105
        }
106
107
        return new OptionRequest();
108
    }
109
110
    /**
111
     * Persists options data.
112
     *
113
     * @param OptionRequest $options
114
     */
115
    protected function setOptions(OptionRequest $options)
116
    {
117
        $GLOBALS['BE_USER']->setAndSaveSessionData(self::OPTIONS_KEY, serialize($options));
118
    }
119
120
    /**
121
     * Get the differnet locations for new entries.
122
     *
123
     * @return array
124
     */
125
    protected function getDifferentTypesAndLocations()
126
    {
127
        /**
128
         * @var array<int>
129
         */
130
        $mountPoints = $this->getAllowedDbMounts();
131
132
        $typeLocations = [];
133
        foreach ($this->indexRepository->findDifferentTypesAndLocations() as $entry) {
134
            $pageId = $entry['pid'];
135
            if ($this->isPageAllowed($pageId, $mountPoints)) {
136
                $typeLocations[$entry['foreign_table']][$pageId] = $entry['unique_register_key'];
137
            }
138
        }
139
140
        return $typeLocations;
141
    }
142
143
    /**
144
     * Check if access to page is allowed for current user.
145
     *
146
     * @param int   $pageId
147
     * @param array $mountPoints
148
     *
149
     * @return bool
150
     */
151
    protected function isPageAllowed(int $pageId, array $mountPoints): bool
152
    {
153
        if ($this->getBackendUser()->isAdmin()) {
154
            return true;
155
        }
156
157
        // check if any mountpoint is in rootline
158
        $rootline = BackendUtility::BEgetRootLine($pageId, '');
159
        foreach ($rootline as $entry) {
160
            if (\in_array((int)$entry['uid'], $mountPoints)) {
161
                return true;
162
            }
163
        }
164
165
        return false;
166
    }
167
168
    /**
169
     * Get allowed mountpoints. Returns temporary mountpoint when temporary mountpoint is used.
170
     *
171
     * copied from core TreeController
172
     *
173
     * @return int[]
174
     */
175
    protected function getAllowedDbMounts(): array
176
    {
177
        $dbMounts = (int)($this->getBackendUser()->uc['pageTree_temporaryMountPoint'] ?? 0);
178
        if (!$dbMounts) {
179
            $dbMounts = array_map('intval', $this->getBackendUser()->returnWebmounts());
180
181
            return array_unique($dbMounts);
182
        }
183
184
        return [$dbMounts];
185
    }
186
187
    /**
188
     * @return BackendUserAuthentication
189
     */
190
    protected function getBackendUser(): BackendUserAuthentication
191
    {
192
        return $GLOBALS['BE_USER'];
193
    }
194
}
195