InvestformPresenter   B
last analyzed

Complexity

Total Complexity 38

Size/Duplication

Total Lines 374
Duplicated Lines 9.09 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 7
Bugs 0 Features 0
Metric Value
wmc 38
c 7
b 0
f 0
lcom 1
cbo 13
dl 34
loc 374
rs 8.3999

17 Methods

Rating   Name   Duplication   Size   Complexity  
A startup() 0 4 1
A beforeRender() 0 4 1
A renderDefault() 0 5 1
B createComponentGrid() 0 56 6
A handleGridOperations() 0 11 2
A actionDownloadGrid() 0 20 1
A actionDeleteGrid() 0 18 2
A createComponentForm() 0 51 3
A actionUpdate() 0 8 1
B actionSend() 0 40 4
A actionDelete() 0 13 1
A actionDownload() 0 7 1
A actionContacted() 0 12 2
A actionPaid() 17 17 3
A actionClosed() 17 17 3
A actionDefault() 0 4 1
B formSubmitted() 0 61 5

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
/**
4
 * This file is part of the Investform module for webcms2.
5
 * Copyright (c) @see LICENSE
6
 */
7
8
namespace AdminModule\InvestformModule;
9
10
use Nette\Forms\Form;
11
use WebCMS\InvestformModule\Common\PdfPrinter;
12
use WebCMS\InvestformModule\Common\EmailSender;
13
use WebCMS\InvestformModule\Entity\Address;
14
15
/**
16
 * Description of
17
 *
18
 * @author Tomas Voslar <[email protected]>
19
 */
20
class InvestformPresenter extends BasePresenter
21
{
22
    private $investment;
23
24
    protected function startup()
25
    {
26
    	parent::startup();
27
    }
28
29
    protected function beforeRender()
30
    {
31
	   parent::beforeRender();
32
    }
33
34
    protected function createComponentGrid($name)
35
    {
36
        $grid = $this->createGrid($this, $name, "\WebCMS\InvestformModule\Entity\Investment");
37
38
        $grid->setFilterRenderType(\Grido\Components\Filters\Filter::RENDER_INNER);
39
        $grid->addFilterDateRange('created', 'Created');
40
41
        $grid->addColumnDate('created', 'Created', \Grido\Components\Columns\Date::FORMAT_DATETIME)
42
            ->setSortable();
43
        $grid->addColumnNumber('id', 'Contract id')->setSortable();
44
45
        $grid->addColumnText('pin', 'Business Id')->setCustomRender(function($item) {
46
            if ($item->getBusinessman()) {
47
                return $item->getBusinessman()->getBusinessId();
48
            } else {
49
                return $item->getPin();
50
            }
51
        });
52
53
        $grid->addColumnText('name', 'Name')->setCustomRender(function($item) {
54
            return $item->getAddress()->getName() . ' ' . $item->getAddress()->getLastname();
55
        });
56
        $grid->addColumnText('company', 'Company')->setCustomRender(function($item) {
57
            return $item->getCompany();
58
        });
59
        //TODO prekladac
60
        $grid->addColumnText('demand', 'Demand')->setCustomRender(function($item) {
0 ignored issues
show
Unused Code introduced by
The parameter $item 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...
61
            return "Odesláno";
62
        });
63
        $grid->addColumnText('contract', 'Contract')->setCustomRender(function($item) {
64
            return $item->getContractSend() ? 'Odesláno' : 'Neodesláno';
65
        });
66
        $grid->addColumnText('contractClosed', 'Contract closed')->setCustomRender(function($item) {
67
            return $item->getContractClosed() ? 'Yes' : 'No';
68
        });
69
        $grid->addColumnText('contractPaid', 'Contract paid')->setCustomRender(function($item) {
70
            return $item->getContractPaid() ? 'Yes' : 'No';
71
        });
72
        $grid->addColumnText('clientContacted', 'Client contacted')->setCustomRender(function($item) {
73
            return $item->getClientContacted() ? 'Yes' : 'No';
74
        });
75
76
        $grid->addActionHref("send", 'Send', 'send', array('idPage' => $this->actualPage->getId()))->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-primary', 'ajax', 'purple')));
77
        $grid->addActionHref("download", 'Download', 'download', array('idPage' => $this->actualPage->getId()))->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-primary', 'purple')));
78
        $grid->addActionHref("update", 'Edit', 'update', array('idPage' => $this->actualPage->getId()))->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-primary', 'ajax', 'green')));
79
        $grid->addActionHref("delete", 'Delete', 'delete', array('idPage' => $this->actualPage->getId()))->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-danger'), 'data-confirm' => 'Are you sure you want to delete this item?'));
80
        $grid->addActionHref("closed", 'Contract closed', 'closed', array('idPage' => $this->actualPage->getId()))->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-primary', 'ajax', 'green')));
81
        $grid->addActionHref("paid", 'Contract Paid', 'paid', array('idPage' => $this->actualPage->getId()))->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-primary', 'ajax', 'green')));
82
        $grid->addActionHref("contacted", 'Contacted', 'contacted', array('idPage' => $this->actualPage->getId()))->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-primary', 'ajax', 'green')));
83
84
        // $operations = array('downloadGrid' => 'Download', 'deleteGrid' => 'Delete');
85
        // $grid->setOperation($operations, $this->handleGridOperations)
86
        //     ->setConfirm('deleteGrid', 'Are you sure you want to delete %i items?');
87
88
        return $grid;
89
    }
90
91
    /**
92
     * Common handler for grid operations.
93
     * @param string $operation
94
     * @param array $id
95
     */
96
    public function handleGridOperations($operation, $id)
97
    {
98
        if (!$id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
99
            $this->flashMessage('No rows selected.', 'error');
100
        }
101
102
        $this->forward($operation, array(
103
            'idPage' => $this->actualPage->getId(),
104
            'id' => $id
105
        ));
106
    }
107
108
    public function actionDownloadGrid()
109
    {
110
        $rows = $this->getParameter('id');
0 ignored issues
show
Unused Code introduced by
$rows 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...
111
112
        // $zipSubfolder = 's' . date('Y-m-d-H-i-s');
113
114
        // foreach ($rows as $key => $value) {
115
        //     $investment = $this->em->getRepository('\WebCMS\InvestformModule\Entity\Investment')->find($value);
116
117
        //     $zip = new PdfPrinter($investment);            
118
119
        //     $zip->savePdfToZip($zipSubfolder);
120
        // }
121
        
122
        $this->flashMessage("Done.", 'success');
123
124
        $this->forward('default', array(
125
            'idPage' => $this->actualPage->getId()
126
        ));
127
    }
128
129
    public function actionDeleteGrid()
130
    {
131
        $rows = $this->getParameter('id');
132
        
133
        foreach ($rows as $key => $value) {
134
            $investment = $this->em->getRepository('\WebCMS\InvestformModule\Entity\Investment')->find($value);
135
136
            $this->em->remove($investment);
137
        }
138
139
        $this->em->flush();
140
141
        $this->flashMessage("Contracts has been deleted", 'success');
142
143
        $this->forward('default', array(
144
            'idPage' => $this->actualPage->getId()
145
        ));
146
    }
147
148
    public function createComponentForm($name)
0 ignored issues
show
Unused Code introduced by
The parameter $name 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...
149
    {
150
        $form = $this->createForm();
151
152
        $form->addText('phone', 'Phone');
153
        $form->addText('email', 'Email');
154
        $form->addText('birthdateNumber', 'Birthdate number');
155
        $form->addText('company', 'Company');
156
        $form->addText('registrationNumber', 'Registration number');
157
        $form->addText('investment', 'Investment amount');
158
        $form->addText('bankAccount', 'Bank account');
159
        $form->addSelect('investmentLength', 'Investment length', array(3 => 3, 5 => 5));
160
        $form->addText('pin', 'Pin');
161
162
        $address = $form->addContainer('Address');
163
        $address->addText('name', 'Name:');
164
        $address->addText('lastname', 'Lastname:');
165
        $address->addText('street', 'Street:');
166
        $address->addText('postcode', 'Postcode:');
167
        $address->addText('city', 'City:');
168
169
        $postalAddress = $form->addContainer('PostalAddress');
170
        $postalAddress->addText('name', 'Name:');
171
        $postalAddress->addText('lastname', 'Lastname:')
172
            ->addConditionOn($form['PostalAddress']['name'], Form::FILLED)
173
            ->addRule(Form::FILLED, 'Lastname is mandatory.');
174
        $postalAddress->addText('street', 'Street:')
175
            ->addConditionOn($form['PostalAddress']['name'], Form::FILLED)
176
            ->addRule(Form::FILLED, 'Street is mandatory.');
177
        $postalAddress->addText('postcode', 'Postcode:')
178
            ->addConditionOn($form['PostalAddress']['name'], Form::FILLED)
179
            ->addRule(Form::FILLED, 'Postcode is mandatory.');
180
        $postalAddress->addText('city', 'City:')
181
            ->addConditionOn($form['PostalAddress']['name'], Form::FILLED)
182
            ->addRule(Form::FILLED, 'City is mandatory.');
183
184
        if (is_object($this->investment->getAddress())) {
185
            $address->setDefaults($this->investment->getAddress()->toArray());    
186
        }
187
        
188
        if (is_object($this->investment->getPostalAddress())) {
189
            $postalAddress->setDefaults($this->investment->getPostalAddress()->toArray());
190
        }
191
192
        $form->addSubmit('save', 'Save');
193
        $form->setDefaults($this->investment->toArray());
194
195
        $form->onSuccess[] = callback($this, 'formSubmitted');
196
197
        return $form;
198
    }
199
200
    public function formSubmitted($form)
201
    {
202
        $values = $form->getValues();
203
204
        $this->investment->setPhone($values->phone);
205
        $this->investment->setEmail($values->email);
206
        $this->investment->setBirthdateNumber($values->birthdateNumber);
207
        $this->investment->setCompany($values->company);
208
        $this->investment->setPin($values->pin);
209
        $this->investment->setBankAccount(str_replace('_', '', $values->bankAccount));
210
        $this->investment->setRegistrationNumber($values->registrationNumber);
211
        $this->investment->setInvestment($values->investment);
212
        $this->investment->setInvestmentLength($values->investmentLength);
213
214
        if (!empty($values->pin)) {
215
            //check if businessman exists
216
            $businessman = $this->em->getRepository('WebCMS\InvestformModule\Entity\Businessman')->findOneBy(array(
217
                'businessId' => $values->pin
218
            ));
219
            if ($businessman) {
220
                $this->investment->setBusinessman($businessman);
221
            }
222
        }
223
224
        $address = $this->investment->getAddress();
225
        $address->setName($values->Address->name);
226
        $address->setLastname($values->Address->lastname);
227
        $address->setStreet($values->Address->street);
228
        $address->setPostcode($values->Address->postcode);
229
        $address->setCity($values->Address->city);
230
231
        $postalAddress = $this->investment->getPostalAddress();
232
        if(!is_object($postalAddress)) {
233
            $postalAddress = new Address;
234
            
235
            $this->investment->setPostalAddress($postalAddress);
236
            $this->em->persist($postalAddress);
237
        }
238
239
        $postalAddress->setName($values->PostalAddress->name);
240
        $postalAddress->setLastname($values->PostalAddress->lastname);
241
        $postalAddress->setStreet($values->PostalAddress->street);
242
        $postalAddress->setPostcode($values->PostalAddress->postcode);
243
        $postalAddress->setCity($values->PostalAddress->city);
244
245
        $this->em->flush();
246
247
        $this->flashMessage('Contract has been updated.', 'success');
248
249
        $roles = $this->user->getIdentity()->getRoles();
250
        if (count(array_intersect(array('superadmin', 'admin'), $roles)) > 0) {
251
            $this->forward('default', array(
252
                'idPage' => $this->actualPage->getId()
253
            ));
254
        } else {
255
            $this->forward('Businessman:default', array(
256
                'idPage' => $this->actualPage->getId()
257
            ));
258
        }
259
        
260
    }
261
262
    public function actionUpdate($id, $idPage)
263
    {
264
        $this->reloadContent();
265
266
        $this->investment = $this->em->getRepository('\WebCMS\InvestformModule\Entity\Investment')->find($id);
267
268
        $this->template->idPage = $idPage;
0 ignored issues
show
Documentation introduced by
The property $template is declared private in Nette\Application\UI\Control. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Bug introduced by
Accessing idPage on the interface Nette\Templating\ITemplate suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
269
    }
270
271
    public function actionSend($id, $idPage, $from = NULL)
272
    {
273
        $investment = $this->em->getRepository('\WebCMS\InvestformModule\Entity\Investment')->find($id);
274
275
        if ($investment->getBirthdateNumber()) {
276
            
277
            $emailSender = new EmailSender($this->settings, $investment, 'contract');
278
            $emailSender->send();
279
280
            $investment->setContractSend(true);
281
            $this->em->flush();
282
283
            $this->flashMessage('Contract has been sent to the client\'s email address.', 'success');
284
285
        } else {
286
287
            $this->flashMessage("Please fill client's birthdate number.", 'error');
288
289
        }
290
291
        if ($from == 'businessman') {
292
            
293
            $this->forward('Businessman:detail', array(
294
                'id' => $investment->getBusinessman()->getId(),
295
                'idPage' => $idPage
296
            ));
297
298
        } elseif ($from == 'company') {
299
            
300
            //TODO
301
302
        } else {
303
304
            $this->forward('default', array(
305
                'idPage' => $this->actualPage->getId()
306
            ));
307
308
        }
309
        
310
    }
311
312
    public function actionDelete($id)
313
    {
314
        $investment = $this->em->getRepository('\WebCMS\InvestformModule\Entity\Investment')->find($id);
315
316
        $this->em->remove($investment);
317
        $this->em->flush();
318
319
        $this->flashMessage('Investment has been removed.', 'success');
320
321
        $this->forward('default', array(
322
            'idPage' => $this->actualPage->getId()
323
        ));
324
    }
325
326
    public function actionDownload($id)
327
    {        
328
        $investment = $this->em->getRepository('\WebCMS\InvestformModule\Entity\Investment')->find($id);
329
        $pdfPrinter = new PdfPrinter($investment);
330
331
        $this->sendResponse($pdfPrinter->printPdfContract(true, $investment->getInvestmentDate()));
0 ignored issues
show
Documentation introduced by
$pdfPrinter->printPdfCon...t->getInvestmentDate()) is of type null|string, but the function expects a object<Nette\Application\IResponse>.

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...
332
    }
333
334
    public function actionContacted($id, $idPage)
0 ignored issues
show
Unused Code introduced by
The parameter $idPage 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...
335
    {
336
        $investment = $this->em->getRepository('\WebCMS\InvestformModule\Entity\Investment')->find($id);
337
        $investment->setClientContacted($investment->getClientContacted() ? false : true);
338
339
        $this->em->flush();
340
341
        $this->flashMessage('Parameter has been changed.', 'success');
342
        $this->forward('default', array(
343
            'idPage' => $this->actualPage->getId()
344
        ));
345
    }
346
347 View Code Duplication
    public function actionPaid($id, $idPage)
0 ignored issues
show
Unused Code introduced by
The parameter $idPage 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...
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...
348
    {
349
        $investment = $this->em->getRepository('\WebCMS\InvestformModule\Entity\Investment')->find($id);
350
351
        if ($investment->getContractClosed()) {
352
            $investment->setContractPaid($investment->getContractPaid() ? false : true);
353
354
            $this->em->flush();
355
356
            $this->flashMessage('Parameter has been changed.', 'success');
357
        } else {
358
            $this->flashMessage('Contract must be closed first.', 'error');
359
        }
360
        $this->forward('default', array(
361
            'idPage' => $this->actualPage->getId()
362
        ));
363
    }
364
365 View Code Duplication
    public function actionClosed($id, $idPage)
0 ignored issues
show
Unused Code introduced by
The parameter $idPage 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...
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...
366
    {
367
        $investment = $this->em->getRepository('\WebCMS\InvestformModule\Entity\Investment')->find($id);
368
369
        if ($investment->getContractSend()) {
370
            $investment->setContractClosed($investment->getContractClosed() ? false : true);
371
372
            $this->em->flush();
373
374
            $this->flashMessage('Parameter has been changed.', 'success');
375
        } else {
376
            $this->flashMessage('Contract must be sent first.', 'error');
377
        }
378
        $this->forward('default', array(
379
            'idPage' => $this->actualPage->getId()
380
        ));
381
    }
382
383
    public function actionDefault($idPage)
384
    {
385
386
    }
387
388
    public function renderDefault($idPage)
389
    {
390
    	$this->reloadContent();
391
    	$this->template->idPage = $idPage;
0 ignored issues
show
Documentation introduced by
The property $template is declared private in Nette\Application\UI\Control. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Bug introduced by
Accessing idPage on the interface Nette\Templating\ITemplate suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
392
    }
393
}
394