waiting.php ➔ absences_waitingRequestList()   D
last analyzed

Complexity

Conditions 9
Paths 144

Size

Total Lines 105
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 56
c 0
b 0
f 0
nc 144
nop 0
dl 0
loc 105
rs 4.606

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
 * OVIDENTIA http://www.ovidentia.org                                   *
4
 ************************************************************************
5
 * Copyright (c) 2003 by CANTICO ( http://www.cantico.fr )              *
6
 *                                                                      *
7
 * This file is part of Ovidentia.                                      *
8
 *                                                                      *
9
 * Ovidentia is free software; you can redistribute it and/or modify    *
10
 * it under the terms of the GNU General Public License as published by *
11
 * the Free Software Foundation; either version 2, or (at your option)  *
12
 * any later version.													*
13
 *																		*
14
 * This program is distributed in the hope that it will be useful, but  *
15
 * WITHOUT ANY WARRANTY; without even the implied warranty of			*
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.					*
17
 * See the  GNU General Public License for more details.				*
18
 *																		*
19
 * You should have received a copy of the GNU General Public License	*
20
 * along with this program; if not, write to the Free Software			*
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,*
22
 * USA.																	*
23
************************************************************************/
24
25
include_once $babInstallPath."utilit/afincl.php";
26
include_once dirname(__FILE__).'/utilit/vacincl.php';
27
include_once dirname(__FILE__).'/functions.php';
28
include_once dirname(__FILE__).'/utilit/agent.class.php';
29
include_once dirname(__FILE__).'/utilit/request.class.php';
30
31
32
33
34
function absences_waitingEmails()
35
{
36
    $W = bab_Widgets();
37
    $page = $W->babPage();
38
    
39
    $page->setTitle(absences_translate('Waiting requests by approvers'));
40
    
41
    $arr = absences_getRequestsApprovers(null);
42
    
43
    $tree = $W->SimpleTreeView();
44
    $root = $tree->createRootNode('Emails', 'Root');
0 ignored issues
show
Unused Code introduced by
$root is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
45
    
46
    $mailId = 0;
47
    foreach($arr as $email) {
48
        $mailId++;
49
        $element = $tree->createElement('email'.$mailId, 'email', 'Mail '.$mailId);
50
        $tree->appendElement($element, 'Root');
51
        
52
        $approvers = $tree->createElement('approvers'.$mailId, 'approvers', absences_translate('Approvers'));
53
        $approvers->setIcon($GLOBALS['babInstallPath'] . 'skins/ovidentia/images/Puces/folder.gif');
54
        $tree->appendElement($approvers, 'email'.$mailId);
55
        
56
        $requests = $tree->createElement('requests'.$mailId, 'requests', absences_translate('Requests'));
57
        $requests->setIcon($GLOBALS['babInstallPath'] . 'skins/ovidentia/images/Puces/folder.gif');
58
        $tree->appendElement($requests, 'email'.$mailId);
59
        
60
        foreach($email['approvers'] as $id_user) {
61
            $user = $tree->createElement('user'.$id_user, 'user', bab_getUserName($id_user));
62
            $tree->appendElement($user, 'approvers'.$mailId);
63
        }
64
       
65
        foreach($email['requests'] as $request) {
66
            
67
            /*@var $request absences_Request */
68
            
69
            $reqnode = $tree->createElement('request'.$request->id, 'request', $request->getUserName().' : '.$request->getTitle());
70
            
71
            try {
72
                $tree->appendElement($reqnode, 'requests'.$mailId);
73
            } catch (ErrorException $e) {
0 ignored issues
show
Bug introduced by
The class ErrorException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
74
                bab_debug($e->getMessage());
75
            }
76
        }
77
    }
78
    
79
    $page->addItem($tree);
80
	$page->displayHtml();
81
}
82
83
84
85
86
function absences_waitingRequestList()
87
{
88
	$W = bab_Widgets();
89
	$page = $W->babPage();
90
	
91
	$page->addStyleSheet(absences_Addon()->getStylePath().'vacation.css');
92
	$page->setTitle(absences_translate('Waiting requests'));
93
	
94
	$f = new absences_getRequestSearchForm();
95
	
96
	$I = new absences_RequestIterator();
97
	$I->status = '';
98
	
99
	
100
	if ($userid = $f->param('userid'))
101
	{
102
	    $I->users = array($userid);
103
	}
104
	
105
	if ($organization = $f->param('organization'))
106
	{
107
	    $I->organization = array($organization);
0 ignored issues
show
Documentation Bug introduced by
It seems like array($organization) of type array<integer,?,{"0":"?"}> is incompatible with the declared type integer of property $organization.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
108
	}
109
	
110
	$datePicker = $W->DatePicker();
111
	
112
	if ('0000-00-00' !== $begin = $datePicker->getISODate($f->param('dateb', null)))
113
	{
114
	    $I->startFrom = $begin;
0 ignored issues
show
Documentation Bug introduced by
It seems like $begin can also be of type false. However, the property $startFrom is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
115
	}
116
	
117
	if ('0000-00-00' !== $end = $datePicker->getISODate($f->param('datee', null)))
118
	{
119
	    $I->startTo = $end;
0 ignored issues
show
Documentation Bug introduced by
It seems like $end can also be of type false. However, the property $startTo is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
120
	}
121
	
122
	bab_functionality::includeOriginal('Icons');
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class bab_functionality as the method includeOriginal() does only exist in the following sub-classes of bab_functionality: Func_Archive, Func_Archive_Zip, Func_Archive_Zip_ZipArchive, Func_Archive_Zip_Zlib, Func_CalendarBackend, Func_CalendarBackend_Ovi, Func_ContextActions, Func_ContextActions_Article, Func_ContextActions_ArticleTopic, Func_Home, Func_Home_Ovidentia, Func_Icons, Func_Icons_Default, Func_Ovml, Func_Ovml_Container, Func_Ovml_Container_Addon, Func_Ovml_Container_Article, Func_Ovml_Container_ArticleCategories, Func_Ovml_Container_ArticleCategory, Func_Ovml_Container_ArticleCategoryNext, Func_Ovml_Container_ArticleCategoryPrevious, Func_Ovml_Container_ArticleFiles, Func_Ovml_Container_ArticleNext, Func_Ovml_Container_ArticlePrevious, Func_Ovml_Container_ArticleTopic, Func_Ovml_Container_ArticleTopicNext, Func_Ovml_Container_ArticleTopicPrevious, Func_Ovml_Container_ArticleTopics, Func_Ovml_Container_Articles, Func_Ovml_Container_ArticlesHomePages, Func_Ovml_Container_CalendarCategories, Func_Ovml_Container_CalendarEventDomains, Func_Ovml_Container_CalendarEvents, Func_Ovml_Container_CalendarGroupEvents, Func_Ovml_Container_CalendarResourceEvents, Func_Ovml_Container_CalendarUserEvents, Func_Ovml_Container_Calendars, Func_Ovml_Container_DbDirectories, Func_Ovml_Container_DbDirectory, Func_Ovml_Container_DbDirectoryAcl, Func_Ovml_Container_DbDirectoryEntry, Func_Ovml_Container_DbDirectoryEntryFields, Func_Ovml_Container_DbDirectoryFields, Func_Ovml_Container_DbDirectoryMemberFields, Func_Ovml_Container_DbDirectoryMembers, Func_Ovml_Container_Delegation, Func_Ovml_Container_DelegationAdministrators, Func_Ovml_Container_DelegationItems, Func_Ovml_Container_DelegationManaged, Func_Ovml_Container_Delegations, Func_Ovml_Container_DelegationsCategories, Func_Ovml_Container_DelegationsCategory, Func_Ovml_Container_DelegationsManaged, Func_Ovml_Container_Faq, Func_Ovml_Container_FaqNext, Func_Ovml_Container_FaqPrevious, Func_Ovml_Container_FaqQuestion, Func_Ovml_Container_FaqQuestionNext, Func_Ovml_Container_FaqQuestionPrevious, Func_Ovml_Container_FaqQuestions, Func_Ovml_Container_FaqSubCategories, Func_Ovml_Container_FaqSubCategory, Func_Ovml_Container_Faqs, Func_Ovml_Container_File, Func_Ovml_Container_FileFields, Func_Ovml_Container_FileNext, Func_Ovml_Container_FilePrevious, Func_Ovml_Container_Files, Func_Ovml_Container_Folder, Func_Ovml_Container_FolderNext, Func_Ovml_Container_FolderPrevious, Func_Ovml_Container_Folders, Func_Ovml_Container_Forum, Func_Ovml_Container_ForumNext, Func_Ovml_Container_ForumPrevious, Func_Ovml_Container_Forums, Func_Ovml_Container_IfEqual, Func_Ovml_Container_IfGreaterThan, Func_Ovml_Container_IfGreaterThanOrEqual, Func_Ovml_Container_IfIsSet, Func_Ovml_Container_IfLessThan, Func_Ovml_Container_IfLessThanOrEqual, Func_Ovml_Container_IfNotEqual, Func_Ovml_Container_IfNotIsSet, Func_Ovml_Container_IfUserMemberOfGroups, Func_Ovml_Container_Multipages, Func_Ovml_Container_ObjectsInfo, Func_Ovml_Container_OrgPathToEntity, Func_Ovml_Container_OrgUserEntities, Func_Ovml_Container_OvmlArray, Func_Ovml_Container_OvmlArrayFields, Func_Ovml_Container_OvmlSoap, Func_Ovml_Container_ParentsArticleCategory, Func_Ovml_Container_Post, Func_Ovml_Container_PostFiles, Func_Ovml_Container_RecentArticles, Func_Ovml_Container_RecentComments, Func_Ovml_Container_RecentFaqQuestions, Func_Ovml_Container_RecentFiles, Func_Ovml_Container_RecentPosts, Func_Ovml_Container_RecentThreads, Func_Ovml_Container_SitemapCustomNode, Func_Ovml_Container_SitemapEntries, Func_Ovml_Container_SitemapEntry, Func_Ovml_Container_SitemapPath, Func_Ovml_Container_Soap, Func_Ovml_Container_SubFolders, Func_Ovml_Container_Tags, Func_Ovml_Container_Thread, Func_Ovml_Container_TmProjects, Func_Ovml_Container_TmSpaces, Func_Ovml_Container_TmTaskFields, Func_Ovml_Container_TmTasks, Func_Ovml_Container_WaitingArticles, Func_Ovml_Container_WaitingComments, Func_Ovml_Container_WaitingFiles, Func_Ovml_Container_WaitingPosts, Func_Ovml_Function, Func_Ovml_Function_AOAddition, Func_Ovml_Function_AODivision, Func_Ovml_Function_AOModulus, Func_Ovml_Function_AOMultiplication, Func_Ovml_Function_AOSubtraction, Func_Ovml_Function_AddStyleSheet, Func_Ovml_Function_Addon, Func_Ovml_Function_Ajax, Func_Ovml_Function_ArticleTree, Func_Ovml_Function_CurrentNode, Func_Ovml_Function_FileTree, Func_Ovml_Function_Get, Func_Ovml_Function_GetCookie, Func_Ovml_Function_GetCsrfProtectToken, Func_Ovml_Function_GetCurrentAdmGroup, Func_Ovml_Function_GetLanguage, Func_Ovml_Function_GetPageTitle, Func_Ovml_Function_GetPath, Func_Ovml_Function_GetSelectedSkinPath, Func_Ovml_Function_GetSessionVar, Func_Ovml_Function_GetVar, Func_Ovml_Function_Header, Func_Ovml_Function_IfNotIsSet, Func_Ovml_Function_Include, Func_Ovml_Function_NextArticle, Func_Ovml_Function_Post, Func_Ovml_Function_PreviousArticle, Func_Ovml_Function_PreviousOrNextArticle, Func_Ovml_Function_PutArray, Func_Ovml_Function_PutSoapArray, Func_Ovml_Function_PutVar, Func_Ovml_Function_Recurse, Func_Ovml_Function_Request, Func_Ovml_Function_SetCookie, Func_Ovml_Function_SetSessionVar, Func_Ovml_Function_SitemapCustomNodeId, Func_Ovml_Function_SitemapMenu, Func_Ovml_Function_SitemapPosition, Func_Ovml_Function_SitemapUrl, Func_Ovml_Function_Translate, Func_Ovml_Function_UrlContent, Func_Ovml_Function_WebStat, Func_PortalAuthentication, Func_PortalAuthentication_AuthOvidentia, Func_PwdComplexity, Func_PwdComplexity_DefaultPortal, Func_SearchUi, Func_SitemapDynamicNode, Func_SitemapDynamicNode_Topic, Func_UserEditor, Func_WorkingHours, Func_WorkingHours_Ovidentia, Ovml_Container_Sitemap, bab_ArithmeticOperator, bab_Ovml_Container_Operator, bab_rgp. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
123
	
124
	$table = $W->BabTableView();
125
	$table->addClass(Func_Icons::ICON_LEFT_16);
126
	
127
	$table->addItem($W->Label(absences_translate('Request type'))		, 0, 0);
128
	$table->addItem($W->Label(absences_translate('Appliquant'))			, 0, 1);
129
	$table->addItem($W->Label(absences_translate('Approver(s)'))		, 0, 2);
130
	$table->addItem($W->Label(absences_translate('Approbation sheme'))	, 0, 3);
131
	$table->addItem($W->Label(absences_translate('Last action date'))	, 0, 4);
132
	$table->addItem($W->Label(absences_translate('Last action'))		, 0, 5);
133
	$table->addItem($W->Label(absences_translate('Edit'))				, 0, 6);
134
	$table->addItem($W->Label(absences_translate('Delete'))				, 0, 7);
135
	
136
	$table->addHeadRow(0);
137
	
138
	$row = 1;
139
	foreach($I as $request)
140
	{
141
		/* @var $request absences_Request */
142
		
143
		$appliquant = absences_Agent::getFromIdUser($request->id_user);
144
		$approbation = $appliquant->getApprobation();
145
		
146
		if ($movement = $request->getLastMovement())
147
		{
148
			$last_createdOn = $movement->createdOn;
149
			$last_message = $movement->message;
150
		} else {
151
			$last_createdOn = '';
152
			$last_message = '';
153
		}
154
		
155
		
156
		$table->addItem($W->Label($request->getRequestType())															, $row, 0 );
157
		$table->addItem($W->Label($appliquant->getName())																, $row, 1 );
158
		$table->addItem($W->Label($request->getNextApprovers())															, $row, 2 );
159
		$table->addItem($W->Label($approbation['name'].sprintf(' (%s)', $approbation['type']))							, $row, 3 );
160
		$table->addItem($W->Label(bab_shortDate(bab_mktime($last_createdOn)))											, $row, 4 );
161
		$table->addItem($W->Label($last_message)																		, $row, 5 );
162
		$table->addItem($W->Link($W->Icon('', Func_Icons::ACTIONS_DOCUMENT_EDIT), $request->getManagerEditUrl())		, $row, 6 );
163
		
164
		
165
		$deleteLink = $W->Link($W->Icon('', Func_Icons::ACTIONS_EDIT_DELETE), $request->getManagerDeleteUrl());
166
		
167
		if (!($request instanceof absences_Entry))
168
		{
169
			$deleteLink->setConfirmationMessage(absences_translate('Do you really want to delete?'));	
170
		}
171
		
172
		
173
		$table->addItem($deleteLink	, $row, 7 );
174
		
175
		if ($request->approbAlert())
176
		{
177
			$table->addRowClass($row, 'widget-strong');
178
		}
179
		
180
		$row++;
181
	}
182
	
183
	
184
	
185
	
186
	$page->addItem($f->getForm());
187
	$page->addItem($table);
188
	
189
	$page->displayHtml();
190
}
191
192
193
194
195
196
197
// main
198
bab_requireCredential();
199
$agent = absences_Agent::getCurrentUser();
200
if( !$agent->isManager())
201
{
202
	$babBody->msgerror = absences_translate("Access denied");
203
	return;
204
}
205
206
207
if ($agent->isInPersonnel())
208
{
209
	$babBody->addItemMenu("vacuser", absences_translate("Vacations"), absences_addon()->getUrl()."vacuser");
210
}
211
212
$babBody->addItemMenu("menu", absences_translate("Management"), absences_addon()->getUrl()."vacadm&idx=menu");
213
214
215
$idx = bab_rp('idx', "list");
216
217
218 View Code Duplication
switch($idx)
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...
219
{
220
    case 'emails':
221
        $babBody->addItemMenu("emails", absences_translate("By approvers"), absences_addon()->getUrl()."waiting&idx=emails");
222
        absences_waitingEmails();
223
        break;
224
    
225
    
226
	default:
227
	case 'list':
228
		$babBody->addItemMenu("list", absences_translate("Waiting requests"), absences_addon()->getUrl()."waiting&idx=list");
229
		absences_waitingRequestList();
230
		break;
231
}
232
233
$babBody->setCurrentItemMenu($idx);
234
bab_siteMap::setPosition('absences','User');