Completed
Push — feature/code-analysis ( 05bab0...e964aa )
by Jonathan
02:58
created

TaskController   C

Complexity

Total Complexity 21

Size/Duplication

Total Lines 174
Duplicated Lines 24.14 %

Coupling/Cohesion

Components 1
Dependencies 19

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 19
dl 42
loc 174
rs 6.875
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
B save() 13 56 9
A __construct() 0 5 1
A trigger() 0 15 2
C setStatus() 29 29 7
B edit() 0 35 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * webtrees-lib: MyArtJaub library for webtrees
4
 *
5
 * @package MyArtJaub\Webtrees
6
 * @subpackage AdminTasks
7
 * @author Jonathan Jaubart <[email protected]>
8
 * @copyright Copyright (c) 2012-2016, Jonathan Jaubart
9
 * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3
10
 */
11
namespace MyArtJaub\Webtrees\Module\AdminTasks;
12
13
use Fisharebest\Webtrees\Auth;
14
use Fisharebest\Webtrees\Controller\AjaxController;
15
use Fisharebest\Webtrees\Controller\PageController;
16
use Fisharebest\Webtrees\Filter;
17
use Fisharebest\Webtrees\FlashMessages;
18
use Fisharebest\Webtrees\I18N;
19
use Fisharebest\Webtrees\Log;
20
use Fisharebest\Webtrees\Module;
21
use Fisharebest\Webtrees\Module\AbstractModule;
22
use Fisharebest\Webtrees\Theme;
23
use Fisharebest\Webtrees\Theme\AdministrationTheme;
24
use MyArtJaub;
25
use MyArtJaub\Webtrees\Controller\JsonController;
26
use MyArtJaub\Webtrees\Globals;
27
use MyArtJaub\Webtrees\Module\AdminTasks\Model\ConfigurableTaskInterface;
28
use MyArtJaub\Webtrees\Module\AdminTasks\Model\TaskProviderInterface;
29
use MyArtJaub\Webtrees\Mvc\Controller\MvcController;
30
use MyArtJaub\Webtrees\Mvc\View\ViewBag;
31
use MyArtJaub\Webtrees\Mvc\View\ViewFactory;
32
33
/**
34
 * Controller for Tasks
35
 */
36
class TaskController extends MvcController
37
{    
38
    /**
39
     * Tasks Provider
40
     * @var TaskProviderInterface $provider
41
     */
42
    protected $provider;    
43
    
44
    /**
45
     * Constructor for Admin Config controller
46
     * @param AbstractModule $module
47
     */
48
    public function __construct(AbstractModule $module) {
49
        parent::__construct($module);
50
        
51
        $this->provider = $this->module->getProvider();
52
    }    
53
    
54
    /**
55
     * Pages
56
     */        
57
	
58
	/**
59
	 * Task@trigger
60
	 */
61
	public function trigger() 
62
	{
63
		$controller = new AjaxController();
64
		$controller->pageHeader();
65
		
66
		$task_name = Filter::get('task');
67
		$token_submitted = Filter::get('force');
68
		$token = $this->module->getSetting('MAJ_AT_FORCE_EXEC_TOKEN');
69
		
70
		$tasks = $this->provider->getTasksToRun($token == $token_submitted, $task_name);
0 ignored issues
show
Documentation introduced by
$token == $token_submitted is of type boolean, but the function expects a false|string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
71
		
72
		foreach($tasks as $task) {
73
			$task->execute();		
74
		}
75
	}	
76
	
77
	/**
78
	 * Task@setStatus
79
	 */
80 View Code Duplication
    public function setStatus() {          
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
81
        $controller = new JsonController();
82
        
83
        $task_name = Filter::get('task');
84
        $task = $this->provider->getTask($task_name, false);
85
        
86
        $controller->restrictAccess(
87
            true // Filter::checkCsrf()   -- Cannot use CSRF on a GET request (modules can only work with GET requests)
88
            &&  Auth::isAdmin() 
89
            && $task
90
        );
91
        
92
        $status = Filter::getBool('status');
93
        $res = array('task' => $task->getName() , 'error' => null);
94
        try{
95
            $this->provider->setTaskStatus($task, $status);
0 ignored issues
show
Bug introduced by
It seems like $task defined by $this->provider->getTask($task_name, false) on line 84 can be null; however, MyArtJaub\Webtrees\Modul...erface::setTaskStatus() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
96
            $res['status'] = $status;
97
			Log::addConfigurationLog('Module '.$this->module->getName().' : Admin Task "'.$task->getName().'" has been '. ($status ? 'enabled' : 'disabled') .'.');
98
        }
99
        catch (\Exception $ex) {
100
            $res['error'] = $ex->getMessage();
101
			Log::addErrorLog('Module '.$this->module->getName().' : Admin Task "'.$task->getName().'" could not be ' . ($status ? 'enabled' : 'disabled') .'. Error: '. $ex->getMessage());
102
        }
103
        
104
        $controller->pageHeader();
105
        if($res['error']) http_response_code(500);
106
        
107
        $controller->encode($res);
108
    }
109
	
110
	/**
111
	 * Task@edit
112
	 */
113
	public function edit() {
114
	    $tree = Globals::getTree();
115
        $task_name = Filter::get('task');
116
        $task = $this->provider->getTask($task_name, false);
117
		
118
        Theme::theme(new AdministrationTheme)->init($tree);
119
        $controller = new PageController();        
120
        $controller
121
            ->restrictAccess(Auth::isAdmin() && $task)
122
			->setPageTitle(I18N::translate('Edit the administrative task'))
123
            ->addInlineJavascript('
124
                function toggleRemainingOccurrences() {
125
                    if($("input:radio[name=\'is_limited\']:checked").val() == 1) {
126
                        $("#nb_occurences").show();
127
                    }
128
                    else {
129
                        $("#nb_occurences").hide();
130
                    }
131
                }
132
        
133
                $("[name=\'is_limited\']").on("change", toggleRemainingOccurrences);
134
                toggleRemainingOccurrences();
135
            ')
136
        ;
137
        
138
        
139
        $data = new ViewBag();        
140
        $data->set('title', $controller->getPageTitle());
141
		$data->set('admin_config_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig&ged=' . $tree->getNameUrl());
142
        $data->set('module_title', $this->module->getTitle());
143
		$data->set('save_url', 'module.php?mod=' . $this->module->getName() . '&mod_action=Task@save&ged=' . $tree->getNameUrl());
144
		$data->set('task', $task);
145
		    
146
        ViewFactory::make('TaskEdit', $this, $controller, $data)->render();	
147
	}	
148
	
149
	/**
150
	 * Task@save
151
	 */
152
	public function save() {		
153
        $tmp_contrl = new PageController();
154
				
155
        $tmp_contrl->restrictAccess(
156
            Auth::isAdmin() 
157
            && Filter::checkCsrf()
158
         );
159
        
160
		$task_name      = Filter::post('task');
161
        $frequency    	= Filter::postInteger('frequency');
162
        $is_limited  	= Filter::postInteger('is_limited', 0, 1);
163
        $nb_occur       = Filter::postInteger('nb_occur');
164
				
165
		$task = $this->provider->getTask($task_name, false);
166
        
167
        $success = false; 
168
        if($task) {
169
			$task->setFrequency($frequency);
170
			if($is_limited == 1) {
171
				$task->setRemainingOccurrences($nb_occur);
172
			}
173
			else {
174
				$task->setRemainingOccurrences(0);
175
			}
176
			
177
			$res = $task->save();
178
						
179
			if($res) {						
180 View Code Duplication
				if($task instanceof MyArtJaub\Webtrees\Module\AdminTasks\Model\ConfigurableTaskInterface) {
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...
181
					$res = $task->saveConfig();
182
					
183
					if(!$res) {
184
						FlashMessages::addMessage(I18N::translate('An error occured while updating the specific settings of administrative task “%s”', $task->getTitle()), 'danger');
185
						Log::addConfigurationLog('Module '.$this->module->getName().' : AdminTask “'. $task->getName() .'” specific settings could not be updated. See error log.');
186
					}
187
				}
188
			
189 View Code Duplication
				if($res) {
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...
190
					FlashMessages::addMessage(I18N::translate('The administrative task “%s” has been successfully updated', $task->getTitle()), 'success');
191
					Log::addConfigurationLog('Module '.$this->module->getName().' : AdminTask “'.$task->getName() .'” has been updated.');
192
					$success = true;
193
				}
194
			}
195
			else {
196
				FlashMessages::addMessage(I18N::translate('An error occured while updating the administrative task “%s”', $task->getTitle()), 'danger');
197
				Log::addConfigurationLog('Module '.$this->module->getName().' : AdminTask “'. $task->getName() .'” could not be updated. See error log.');
198
			}
199
			
200
        }
201
        
202
        $redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=AdminConfig';
203
        if(!$success) {
204
			$redirection_url = 'module.php?mod=' . $this->module->getName() . '&mod_action=Task@edit&task='. $task->getName();
205
        }        
206
        header('Location: ' . WT_BASE_URL . $redirection_url);
207
	}
208
     
209
}