Completed
Push — master ( 366a5b...a17b2a )
by
unknown
17:34 queued 14:29
created

NewTenant::cmdAddStructure()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 32

Duplication

Lines 15
Ratio 46.88 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 0
dl 15
loc 32
rs 9.408
c 0
b 0
f 0
1
<?php
2
namespace Kitodo\Dlf\Module;
3
4
/**
5
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
6
 *
7
 * This file is part of the Kitodo and TYPO3 projects.
8
 *
9
 * @license GNU General Public License version 3 or later.
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 */
13
14
use Kitodo\Dlf\Common\Helper;
15
16
/**
17
 * Module 'New Tenant' for the 'dlf' extension.
18
 *
19
 * @author Sebastian Meyer <[email protected]>
20
 * @package TYPO3
21
 * @subpackage dlf
22
 * @access public
23
 */
24
class NewTenant extends \Kitodo\Dlf\Common\AbstractModule {
25
    protected $markerArray = [
26
        'CSH' => '',
27
        'MOD_MENU' => '',
28
        'CONTENT' => '',
29
    ];
30
31
    /**
32
     * Add metadata configuration
33
     *
34
     * @access protected
35
     *
36
     * @return void
37
     */
38
    protected function cmdAddMetadata() {
39
        // Include metadata definition file.
40
        include_once(\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($this->extKey).'Resources/Private/Data/MetadataDefaults.php');
41
        $i = 0;
42
        // Build data array.
43
        foreach ($metadataDefaults as $index_name => $values) {
0 ignored issues
show
Bug introduced by
The variable $metadataDefaults does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
44
            $formatIds = [];
45
            foreach ($values['format'] as $format) {
46
                $formatIds[] = uniqid('NEW');
47
                $data['tx_dlf_metadataformat'][end($formatIds)] = $format;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = 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...
48
                $data['tx_dlf_metadataformat'][end($formatIds)]['pid'] = intval($this->id);
0 ignored issues
show
Bug introduced by
The variable $data 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...
49
                $i++;
50
            }
51
            $data['tx_dlf_metadata'][uniqid('NEW')] = [
52
                'pid' => intval($this->id),
53
                'label' => $GLOBALS['LANG']->getLL($index_name),
54
                'index_name' => $index_name,
55
                'format' => implode(',', $formatIds),
56
                'default_value' => $values['default_value'],
57
                'wrap' => (!empty($values['wrap']) ? $values['wrap'] : $GLOBALS['TCA']['tx_dlf_metadata']['columns']['wrap']['config']['default']),
58
                'index_tokenized' => $values['index_tokenized'],
59
                'index_stored' => $values['index_stored'],
60
                'index_indexed' => $values['index_indexed'],
61
                'index_boost' => $values['index_boost'],
62
                'is_sortable' => $values['is_sortable'],
63
                'is_facet' => $values['is_facet'],
64
                'is_listed' => $values['is_listed'],
65
                'index_autocomplete' => $values['index_autocomplete'],
66
            ];
67
            $i++;
68
        }
69
        $_ids = Helper::processDBasAdmin($data, [], TRUE);
70
        // Check for failed inserts.
71 View Code Duplication
        if (count($_ids) == $i) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
72
            // Fine.
73
            Helper::addMessage(
74
                Helper::getMessage('flash.metadataAddedMsg'),
75
                Helper::getMessage('flash.metadataAdded', TRUE),
76
                \TYPO3\CMS\Core\Messaging\FlashMessage::OK
77
            );
78
        } else {
79
            // Something went wrong.
80
            Helper::addMessage(
81
                Helper::getMessage('flash.metadataNotAddedMsg'),
82
                Helper::getMessage('flash.metadataNotAdded', TRUE),
83
                \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
84
            );
85
        }
86
    }
87
88
    /**
89
     * Add Solr core
90
     *
91
     * @access protected
92
     *
93
     * @return void
94
     */
95
    protected function cmdAddSolrCore() {
96
        // Build data array.
97
        $data['tx_dlf_solrcores'][uniqid('NEW')] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = 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...
98
            'pid' => intval($this->id),
99
            'label' => $GLOBALS['LANG']->getLL('solrcore').' (PID '.$this->id.')',
100
            'index_name' => '',
101
        ];
102
        $_ids = Helper::processDBasAdmin($data);
103
        // Check for failed inserts.
104 View Code Duplication
        if (count($_ids) == 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
            // Fine.
106
            Helper::addMessage(
107
                Helper::getMessage('flash.solrcoreAddedMsg'),
108
                Helper::getMessage('flash.solrcoreAdded', TRUE),
109
                \TYPO3\CMS\Core\Messaging\FlashMessage::OK
110
            );
111
        } else {
112
            // Something went wrong.
113
            Helper::addMessage(
114
                Helper::getMessage('flash.solrcoreNotAddedMsg'),
115
                Helper::getMessage('flash.solrcoreNotAdded', TRUE),
116
                \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
117
            );
118
        }
119
    }
120
121
    /**
122
     * Add structure configuration
123
     *
124
     * @access protected
125
     *
126
     * @return void
127
     */
128
    protected function cmdAddStructure() {
129
        // Include structure definition file.
130
        include_once(\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($this->extKey).'Resources/Private/Data/StructureDefaults.php');
131
        // Build data array.
132
        foreach ($structureDefaults as $index_name => $values) {
0 ignored issues
show
Bug introduced by
The variable $structureDefaults does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
133
            $data['tx_dlf_structures'][uniqid('NEW')] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = 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...
134
                'pid' => intval($this->id),
135
                'toplevel' => $values['toplevel'],
136
                'label' => $GLOBALS['LANG']->getLL($index_name),
137
                'index_name' => $index_name,
138
                'oai_name' => $values['oai_name'],
139
                'thumbnail' => 0,
140
            ];
141
        }
142
        $_ids = Helper::processDBasAdmin($data, [], TRUE);
0 ignored issues
show
Bug introduced by
The variable $data 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...
143
        // Check for failed inserts.
144 View Code Duplication
        if (count($_ids) == count($structureDefaults)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
145
            // Fine.
146
            Helper::addMessage(
147
                Helper::getMessage('flash.structureAddedMsg'),
148
                Helper::getMessage('flash.structureAdded', TRUE),
149
                \TYPO3\CMS\Core\Messaging\FlashMessage::OK
150
            );
151
        } else {
152
            // Something went wrong.
153
            Helper::addMessage(
154
                Helper::getMessage('flash.structureNotAddedMsg'),
155
                Helper::getMessage('flash.structureNotAdded', TRUE),
156
                \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
157
            );
158
        }
159
    }
160
161
    /**
162
     * Main function of the module
163
     *
164
     * @access public
165
     *
166
     * @param \Psr\Http\Message\ServerRequestInterface $request: The request object
0 ignored issues
show
Documentation introduced by
There is no parameter named $request:. Did you maybe mean $request?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
167
     * @param \Psr\Http\Message\ResponseInterface $response: The response object
0 ignored issues
show
Documentation introduced by
There is no parameter named $response:. Did you maybe mean $response?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
168
     *
169
     * @return \Psr\Http\Message\ResponseInterface The response object
170
     */
171
    public function main(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response) {
172
        $this->response = $response;
173
        // Initialize module.
174
        $this->MCONF = [
175
            'name' => 'tools_dlfNewTenantModule',
176
            'access' => 'admin'
177
        ];
178
        $GLOBALS['BE_USER']->modAccess($this->MCONF, 1);
179
        parent::init();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (init() instead of main()). Are you sure this is correct? If so, you might want to change this to $this->init().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
180
        $this->pageInfo = \TYPO3\CMS\Backend\Utility\BackendUtility::readPageAccess($this->id, $this->perms_clause);
181
        // Is the user allowed to access this page?
182
        $access = is_array($this->pageInfo) && $GLOBALS['BE_USER']->isAdmin();
183
        if ($this->id && $access) {
184
            // Check if page is sysfolder.
185
            if ($this->pageInfo['doktype'] != 254) {
186
                Helper::addMessage(
187
                    Helper::getMessage('flash.wrongPageTypeMsg'),
188
                    Helper::getMessage('flash.wrongPageType', TRUE),
189
                    \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
190
                );
191
                $this->markerArray['CONTENT'] .= Helper::renderFlashMessages();
192
                $this->printContent();
193
                return $this->response;
194
            }
195
            // Should we do something?
196
            if (!empty($this->CMD)) {
197
                // Sanitize input...
198
                $_method = 'cmd'.ucfirst($this->CMD);
199
                // ...and unset to prevent infinite looping.
200
                unset ($this->CMD);
201
                if (method_exists($this, $_method)) {
202
                    $this->$_method();
203
                }
204
            }
205
            // Check for existing structure configuration.
206
            $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
207
                'uid',
208
                'tx_dlf_structures',
209
                'pid='.intval($this->id)
210
                    .Helper::whereClause('tx_dlf_structures')
211
            );
212 View Code Duplication
            if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
213
                // Fine.
214
                Helper::addMessage(
215
                    Helper::getMessage('flash.structureOkayMsg'),
216
                    Helper::getMessage('flash.structureOkay', TRUE),
217
                    \TYPO3\CMS\Core\Messaging\FlashMessage::OK
218
                );
219
            } else {
220
                // Configuration missing.
221
                $_url = \TYPO3\CMS\Core\Utility\GeneralUtility::locationHeaderUrl(\TYPO3\CMS\Core\Utility\GeneralUtility::linkThisScript(['id' => $this->id, 'CMD' => 'addStructure']));
222
                Helper::addMessage(
223
                    sprintf(Helper::getMessage('flash.structureNotOkayMsg'), $_url),
224
                    Helper::getMessage('flash.structureNotOkay', TRUE),
225
                    \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
226
                );
227
            }
228
            // Check for existing metadata configuration.
229
            $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
230
                'uid',
231
                'tx_dlf_metadata',
232
                'pid='.intval($this->id)
233
                    .Helper::whereClause('tx_dlf_metadata')
234
            );
235 View Code Duplication
            if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
236
                // Fine.
237
                Helper::addMessage(
238
                    Helper::getMessage('flash.metadataOkayMsg'),
239
                    Helper::getMessage('flash.metadataOkay', TRUE),
240
                    \TYPO3\CMS\Core\Messaging\FlashMessage::OK
241
                );
242
            } else {
243
                // Configuration missing.
244
                $_url = \TYPO3\CMS\Core\Utility\GeneralUtility::locationHeaderUrl(\TYPO3\CMS\Core\Utility\GeneralUtility::linkThisScript(['id' => $this->id, 'CMD' => 'addMetadata']));
245
                Helper::addMessage(
246
                    sprintf(Helper::getMessage('flash.metadataNotOkayMsg'), $_url),
247
                    Helper::getMessage('flash.metadataNotOkay', TRUE),
248
                    \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
249
                );
250
            }
251
            // Check for existing Solr core.
252
            $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
253
                'uid,pid',
254
                'tx_dlf_solrcores',
255
                'pid IN ('.intval($this->id).',0)'
256
                    .Helper::whereClause('tx_dlf_solrcores')
257
            );
258
            if ($GLOBALS['TYPO3_DB']->sql_num_rows($result)) {
259
                $resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
260 View Code Duplication
                if ($resArray['pid']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
261
                    // Fine.
262
                    Helper::addMessage(
263
                        Helper::getMessage('flash.solrcoreOkayMsg'),
264
                        Helper::getMessage('flash.solrcoreOkay', TRUE),
265
                        \TYPO3\CMS\Core\Messaging\FlashMessage::OK
266
                    );
267
                } else {
268
                    // Default core available, but this is deprecated.
269
                    $_url = \TYPO3\CMS\Core\Utility\GeneralUtility::locationHeaderUrl(\TYPO3\CMS\Core\Utility\GeneralUtility::linkThisScript(['id' => $this->id, 'CMD' => 'addSolrcore']));
270
                    Helper::addMessage(
271
                        sprintf(Helper::getMessage('flash.solrcoreDeprecatedMsg'), $_url),
272
                        Helper::getMessage('flash.solrcoreDeprecatedOkay', TRUE),
273
                        \TYPO3\CMS\Core\Messaging\FlashMessage::NOTICE
274
                    );
275
                }
276
            } else {
277
                // Solr core missing.
278
                $_url = \TYPO3\CMS\Core\Utility\GeneralUtility::locationHeaderUrl(\TYPO3\CMS\Core\Utility\GeneralUtility::linkThisScript(['id' => $this->id, 'CMD' => 'addSolrcore']));
279
                Helper::addMessage(
280
                    sprintf(Helper::getMessage('flash.solrcoreMissingMsg'), $_url),
281
                    Helper::getMessage('flash.solrcoreMissing', TRUE),
282
                    \TYPO3\CMS\Core\Messaging\FlashMessage::WARNING
283
                );
284
            }
285
            $this->markerArray['CONTENT'] .= Helper::renderFlashMessages();
286
        } else {
287
            // TODO: Ändern!
288
            $this->markerArray['CONTENT'] .= 'You are not allowed to access this page or have not selected a page, yet.';
289
        }
290
        $this->printContent();
291
        return $this->response;
292
    }
293
}
294