Passed
Push — master ( eb013e...37f747 )
by Jonathan
04:35
created

SosaConfigController::index()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 56
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 30
nc 6
nop 0
dl 0
loc 56
rs 9.44
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * webtrees-lib: MyArtJaub library for webtrees
4
 *
5
 * @package MyArtJaub\Webtrees
6
 * @subpackage Sosa
7
 * @author Jonathan Jaubart <[email protected]>
8
 * @copyright Copyright (c) 2009-2016, Jonathan Jaubart
9
 * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3
10
 */
11
namespace MyArtJaub\Webtrees\Module\Sosa;
12
13
use Fisharebest\Webtrees\Auth;
14
use Fisharebest\Webtrees\Controller\AjaxController;
15
use Fisharebest\Webtrees\Controller\BaseController;
16
use Fisharebest\Webtrees\Controller\PageController;
17
use Fisharebest\Webtrees\Filter;
18
use Fisharebest\Webtrees\FlashMessages;
19
use Fisharebest\Webtrees\I18N;
20
use Fisharebest\Webtrees\Individual;
21
use Fisharebest\Webtrees\User;
22
use MyArtJaub\Webtrees\Globals;
23
use MyArtJaub\Webtrees\Module\Sosa\Model\SosaCalculator;
24
use MyArtJaub\Webtrees\Mvc\Controller\MvcController;
25
use MyArtJaub\Webtrees\Mvc\View\ViewBag;
26
use MyArtJaub\Webtrees\Mvc\View\ViewFactory;
27
28
/**
29
 * Controller for SosaConfig
30
 */
31
class SosaConfigController extends MvcController
32
{      
33
    /**
34
     * Check if the user can update the sosa ancestors list
35
     * 
36
     * @return bool
37
     */
38
    protected function canUpdate() {        
39
        $user_id = Filter::postInteger('userid', -1) ?: Filter::getInteger('userid', -1);
40
        return Auth::check() && 
41
            ( 
42
                $user_id == Auth::user()->getUserId() ||        // Allow update for yourself
43
                ($user_id == -1 && Auth::isManager(Globals::getTree()))   // Allow a manager to update the default user
44
             );
45
    }
46
    
47
    /**
48
     * Saves Sosa's user preferences (root individual for the user).
49
     * 
50
     * @param BaseController $controller
51
     * @return bool True is saving successfull
52
     */
53
    protected function update(BaseController $controller) {
54
        $wt_tree = Globals::getTree();
55
        if($this->canUpdate() && Filter::checkCsrf()) 
56
        {            
57
            $indi = Individual::getInstance(Filter::post('rootid'), $wt_tree);
58
            $user = User::find(Filter::postInteger('userid', -1));
59
            
60
            if($user  && $indi) {
61
                $wt_tree->setUserPreference($user, 'MAJ_SOSA_ROOT_ID', $indi->getXref());
62
                $controller->addInlineJavascript('
63
                    $( document ).ready(function() {
64
                        majComputeSosa('.$user->getUserId().');
65
                    });');
66
                FlashMessages::addMessage(I18N::translate('The preferences have been updated.'));
67
                return true;
68
            }
69
        }
70
        FlashMessages::addMessage(I18N::translate('An error occurred while saving data...'), 'danger');
71
        return false;
72
    }
73
    
74
    /**
75
     * Pages
76
     */
77
    
78
    /**
79
     * SosaConfig@index
80
     */
81
    public function index() {
82
        $wt_tree = Globals::getTree();
83
        $controller = new PageController();
84
        $controller
85
        ->setPageTitle(I18N::translate('Sosa Configuration'))
86
        ->restrictAccess(Auth::check())
87
        ->addExternalJavascript(WT_AUTOCOMPLETE_JS_URL)
88
        ->addInlineJavascript('autocomplete();')
89
        ->addInlineJavascript('
90
            $( document ).ready(function() {
91
                $("#bt_sosa_compute").click(function() {
92
                    majComputeSosa($("#maj_sosa_input_userid, #maj-sosa-config-select option:selected").val());
93
                 });
94
            });
95
            
96
            function majComputeSosa(user_id) {
97
                jQuery("#bt_sosa_compute").prop( "disabled", true );
98
                jQuery("#bt_sosa_computing").empty().html("<i class=\"icon-loading-small\"></i>&nbsp;'. I18N::translate('Computing...') .'");
99
                jQuery("#bt_sosa_computing").load(
100
		          "module.php?mod='.$this->module->getName().'&mod_action=SosaConfig@computeAll&ged='.$wt_tree->getNameUrl().'&userid=" + user_id,
101
		          function() {
102
			         jQuery("#bt_sosa_compute").prop( "disabled", false );
103
                  });
104
            }');
105
        
106
        $action = Filter::post('action');
107
        if($action === 'update') $this->update($controller);
108
        
109
        $view_bag = new ViewBag();
110
        $view_bag->set('title', $controller->getPageTitle());
111
        $view_bag->set('tree', $wt_tree);
112
        $view_bag->set('form_url', 'module.php?mod='.$this->module->getName().'&mod_action=SosaConfig&ged='.$wt_tree->getNameUrl());
113
        
114
        $users_root = array();
115
        $users_js_array = 'var users_array = [];';
116
        if(Auth::check()) {
117
            $root_id = $wt_tree->getUserPreference(Auth::user(), 'MAJ_SOSA_ROOT_ID');
118
            $users_root[] = array( 'user' => Auth::user(), 'rootid' => $root_id);
119
            $users_js_array .=  'users_array["'.Auth::user()->getUserId().'"] = "' . $root_id . '";';
120
            
121
            if(Auth::isManager($wt_tree)) {
122
                $default_user = User::find(-1);
123
                $default_root_id = $wt_tree->getUserPreference($default_user, 'MAJ_SOSA_ROOT_ID');
124
                $users_root[] = array( 'user' => $default_user, 'rootid' => $default_root_id);
125
                $users_js_array .=  'users_array["'.$default_user->getUserId().'"] = "' . $default_root_id . '";';
126
            }
127
        }
128
        $view_bag->set('users_settings', $users_root);       
129
        
130
        $controller->addInlineJavascript($users_js_array . '            
131
                $("#maj-sosa-config-select").change(function() {
132
                    $("#rootid").val(users_array[this.value]);
133
                });
134
             ');
135
        
136
        ViewFactory::make('SosaConfig', $this, $controller, $view_bag)->render();   
137
    }
138
    
139
    /**
140
     * SosaConfig@computeAll
141
     */
142
    public function computeAll() {        
143
        $controller = new AjaxController();
144
        $controller->restrictAccess($this->canUpdate());
145
        
146
        $view_bag = new ViewBag();
147
        $view_bag->set('is_success', false);
148
        
149
        $user = User::find(Filter::getInteger('userid', -1));
150
        if($user) {
151
            $calculator = new SosaCalculator(Globals::getTree(), $user);
152
            if($calculator->computeAll()) $view_bag->set('is_success', true);
153
        }
154
        ViewFactory::make('SosaComputeResult', $this, $controller, $view_bag)->render();
155
    }
156
    
157
    /**
158
     * SosaConfig@computePartial
159
     */
160
    public function computePartial() {
161
        $wt_tree = Globals::getTree();
162
        $controller = new AjaxController();
163
        $controller->restrictAccess($this->canUpdate());
164
    
165
        $view_bag = new ViewBag();
166
        $view_bag->set('is_success', false);
167
    
168
        $user = User::find(Filter::getInteger('userid', -1));
169
        $indi = Individual::getInstance(Filter::get('pid', WT_REGEX_XREF), $wt_tree);
170
        
171
        if($user && $indi) {
172
            $calculator = new SosaCalculator($wt_tree, $user);
173
            if($calculator->computeFromIndividual($indi)) $view_bag->set('is_success', true);
174
        }
175
        else {
176
            $view_bag->set('error', I18N::translate('Non existing individual'));
177
        }
178
            
179
        ViewFactory::make('SosaComputeResult', $this, $controller, $view_bag)->render();
180
    }
181
    
182
}