Completed
Push — master ( d535d3...8c6cf6 )
by Felix
16:53
created

Tx_FeatureFlag_System_Typo3_Cli   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 175
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

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

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 21 2
B main() 0 27 6
A getAction() 0 4 1
A getArgument() 0 4 1
A init() 0 4 1
A isSchedulerInstalled() 0 4 1
A getSchedulerTaskUid() 0 13 4
A flagEntries() 0 13 3
A setFeatureStatus() 0 9 2
A flushCaches() 0 7 1
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 32 and the first side effect is on line 209.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
/***************************************************************
4
 *  Copyright notice
5
 *
6
 *  (c) 2016 AOE GmbH <[email protected]>
7
 *
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 3 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
28
/**
29
 * @package FeatureFlag
30
 * @subpackage System_Typo3
31
 */
32
class Tx_FeatureFlag_System_Typo3_Cli extends \TYPO3\CMS\Core\Controller\CommandLineController
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
Coding Style introduced by
This class is not in CamelCase format.

Classes in PHP are usually named in CamelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database provider becomes DatabaseProvider.

Loading history...
33
{
34
    /**
35
     * @var string
36
     */
37
    protected $extKey = 'feature_flag';
38
    /**
39
     * @var string
40
     */
41
    protected $prefixId = 'tx_featureflag_system_typo3_cli';
42
    /**
43
     * @var string
44
     */
45
    protected $scriptRelPath = 'Classes/System/Typo3/Cli.php';
46
47
    /**
48
     * @var TYPO3\CMS\Scheduler\Scheduler
49
     */
50
    protected $scheduler;
51
52
    /**
53
     * @var Tx_FeatureFlag_Service
54
     */
55
    protected $service;
56
57
    /**
58
     * constructor
59
     */
60
    public function __construct()
61
    {
62
        parent::__construct();
63
        if (!defined('TYPO3_cliMode')) {
64
            die('Access denied: CLI only.');
0 ignored issues
show
Coding Style Compatibility introduced by
The method __construct() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
65
        }
66
        $this->cli_options = array_merge($this->cli_options, array());
67
        $this->cli_help = array_merge($this->cli_help, array(
68
            'name' => $this->prefixId,
69
            'synopsis' => $this->extKey . ' command',
70
            'description' => 'This script can flag all configured tables by feature flags.',
71
            'examples' => 'typo3/cli_dispatch.phpsh ' . $this->extKey . ' [flagEntries]',
72
            'author' => '(c) 2013 AOE GmbH <[email protected]>',
73
        ));
74
        $this->conf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][$this->extKey]);
0 ignored issues
show
Bug introduced by
The property conf 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...
75
76
        $this->scheduler = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Scheduler\\Scheduler');
77
78
        $this->service = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class)
79
            ->get(Tx_FeatureFlag_Service::class);
80
    }
81
82
    /**
83
     * @param $argv
84
     * @return int
85
     */
86
    public function main($argv)
0 ignored issues
show
Unused Code introduced by
The parameter $argv is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
87
    {
88
        $this->init();
89
        try {
90
            switch ($this->getAction()) {
91
                case 'activate':
92
                    $this->setFeatureStatus($this->getArgument(), true);
93
                    break;
94
                case 'deactivate':
95
                    $this->setFeatureStatus($this->getArgument(), false);
96
                    break;
97
                case 'flagEntries':
98
                    $this->flagEntries();
99
                    break;
100
                case 'flushCaches':
101
                    $this->flushCaches();
102
                    break;
103
                default:
104
                    $this->cli_help();
105
                    break;
106
            }
107
        } catch (Exception $e) {
108
            return 1;
109
        }
110
111
        return 0;
112
    }
113
114
    /**
115
     * @return string
116
     */
117
    private function getAction()
118
    {
119
        return (string)$this->cli_args['_DEFAULT'][1];
120
    }
121
122
    /**
123
     * @return string
124
     */
125
    private function getArgument()
126
    {
127
        return (string)$this->cli_args['_DEFAULT'][2];
128
    }
129
130
    /**
131
     * @return void
132
     */
133
    private function init()
134
    {
135
        $this->cli_validateArgs();
136
    }
137
138
    /**
139
     * check if scheduler is installed
140
     *
141
     * @return boolean
142
     */
143
    private function isSchedulerInstalled()
144
    {
145
        return is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['cliKeys']['scheduler']);
146
    }
147
148
    /**
149
     * @return int
150
     */
151
    private function getSchedulerTaskUid()
152
    {
153
        foreach ($this->scheduler->fetchTasksWithCondition() as $task) {
0 ignored issues
show
Bug introduced by
The call to fetchTasksWithCondition() misses a required argument $where.

This check looks for function calls that miss required arguments.

Loading history...
154
            if ($task instanceof Tx_FeatureFlag_System_Typo3_Task_FlagEntries) {
155
                $taskUid = $task->getTaskUid();
156
            }
157
        }
158
159
        if (null === $taskUid) {
0 ignored issues
show
Bug introduced by
The variable $taskUid 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...
160
            throw new RuntimeException('scheduler task for feature_flag was not found');
161
        }
162
        return $taskUid;
163
    }
164
165
    /**
166
     * @throws RuntimeException
167
     */
168
    private function flagEntries()
169
    {
170
        if ($this->isSchedulerInstalled()) {
171
            $taskUid = $this->getSchedulerTaskUid();
172
            $task = $this->scheduler->fetchTask($taskUid);
173
174
            if ($this->scheduler->isValidTaskObject($task)) {
175
                $this->scheduler->executeTask($task);
176
            } else {
177
                throw new RuntimeException('task-object of feature-flag-task is not valid!');
178
            }
179
        }
180
    }
181
182
    /**
183
     * Enable or disable features. $features can be a comma-separated list of feature names
184
     * @param String $features
185
     */
186
    private function setFeatureStatus($features, $enabled)
187
    {
188
        $features = array_map('trim', explode(',', $features));
189
        foreach ($features as $feature) {
190
            echo $feature;
191
            $this->service->updateFeatureFlag($feature, $enabled);
192
        }
193
        $this->service->flagEntries();
194
    }
195
196
    /**
197
     * Clear all page caches
198
     */
199
    private function flushCaches()
200
    {
201
        /** @var Tx_FeatureFlag_System_Typo3_CacheManager $cacheManager */
202
        $cacheManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class)
203
            ->get(Tx_FeatureFlag_System_Typo3_CacheManager::class);
204
        $cacheManager->clearAllCaches();
205
    }
206
}
207
208
/** @var Tx_FeatureFlag_System_Typo3_Cli $cli */
209
$cli = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('Tx_FeatureFlag_System_Typo3_Cli');
210
exit($cli->main($_SERVER['argv']));
211