InvestformPresenter   B
last analyzed

Complexity

Total Complexity 43

Size/Duplication

Total Lines 399
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 14

Importance

Changes 7
Bugs 0 Features 1
Metric Value
wmc 43
c 7
b 0
f 1
lcom 2
cbo 14
dl 0
loc 399
rs 8.3157

13 Methods

Rating   Name   Duplication   Size   Complexity  
A startup() 0 4 1
A beforeRender() 0 4 1
B createComponentForm() 0 39 1
A createComponentStep2Form() 0 53 3
C validateBirthdateNumber() 0 32 12
A validateBankAccount() 0 17 3
A validatePart() 0 12 2
B actionDefault() 0 27 6
B formSubmitted() 0 107 6
B step2formSubmitted() 0 47 4
A handlegetNetIncome() 0 17 2
A sendPdf() 0 5 1
A renderDefault() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like InvestformPresenter often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use InvestformPresenter, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * This file is part of the Investform module for webcms2.
5
 * Copyright (c) @see LICENSE
6
 */
7
8
namespace FrontendModule\InvestformModule;
9
10
use Nette\Forms\Form;
11
use WebCMS\InvestformModule\Entity\Investment;
12
use WebCMS\InvestformModule\Entity\Address;
13
use WebCMS\InvestformModule\Common\PdfPrinter;
14
use WebCMS\InvestformModule\Common\EmailSender;
15
use WebCMS\InvestformModule\Entity\Businessman;
16
use Nette\Mail\Message;
17
18
/**
19
 * Description of InvestformPresenter
20
 *
21
 * @author Tomas Voslar <[email protected]>
22
 */
23
class InvestformPresenter extends BasePresenter
24
{
25
	private $id;
26
27
	/* \Nette\Http\Session */
28
	public $businessmanSession;
29
	
30
	protected function startup() 
31
    {
32
		parent::startup();
33
	}
34
35
	protected function beforeRender()
36
    {
37
		parent::beforeRender();	
38
	}
39
	
40
	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...
41
	{
42
		$form = $this->createForm('form-submit', 'default', null);
43
44
		$form->addText('name', 'Name')->setRequired('Name is mandatory.');
45
		$form->addText('lastname', 'Lastname')->setRequired('Lastname is mandatory.');
46
		$form->addText('street', 'Street')->setRequired('Street is mandatory.');
47
		$form->addText('date', 'Date')->setRequired('Date is mandatory.');
48
		$form->addText('postcode', 'Postcode')
49
			->setRequired('Postcode is mandatory.')
50
			->addRule(Form::PATTERN, 'Postcode must contain 5 numbers.', '([0-9]\s*){5}');
51
		$form->addText('city', 'City')->setRequired('City is mandatory.');
52
		$form->addText('phone', 'Phone')->setRequired('Phone is mandatory.');
53
		$form->addText('email', 'Email')
54
			->addRule(Form::EMAIL, 'This email is not valid.')
55
			->setRequired('Email is mandatory.');
56
		$form->addCheckbox('invest', 'Invest');
57
		$form->addText('company', 'Company')
58
			->addConditionOn($form['invest'], Form::EQUAL, true)
59
	        ->addRule(Form::FILLED, 'Company name is madatory.');
60
		$form->addText('registrationNumber', 'Registration number')
61
			->addConditionOn($form['invest'], Form::EQUAL, true)
62
	        ->addRule(Form::FILLED, 'Registration number is mandatory.');
63
		$form->addText('bankAccountPrefix', 'Bank account')
64
			->addRule(callback($this, 'validateBankAccount'), "Bank acccount prefix is not valid`.");
65
		$form->addText('bankAccount', 'Bank account')
66
			->setRequired('Bank account is mandatory.');
67
			// ->addRule(callback($this, 'validateBankAccount'), "Bank acccount is not valid`.");
68
		$form->addSelect('investmentAmount', 'Investment amount', $this->amountItems)
69
			->setRequired('Amount of investment is mandatory.');
70
		$form->addSelect('investmentLength', 'Investment length', array(3 => 'Tříletý', 5 => 'Pětiletý'))
71
			->setRequired('Investment length is mandatory.');
72
73
		$form->addSubmit('send', 'Send');
74
75
		$form->onSuccess[] = callback($this, 'formSubmitted');
76
77
		return $form;
78
	}
79
80
	public function createComponentStep2Form($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...
81
	{
82
		$parameters = $this->getParameter('parameters');
83
		$form = $this->createForm('step2Form-submit', 'default', null, array(
84
			'2',
85
			'hash' => $parameters[1]
86
		));
87
88
		$investment = $this->em->getRepository('WebCMS\InvestformModule\Entity\Investment')->findOneByHash($parameters[1]);
89
		$companyNumber = $investment->getRegistrationNumber();
90
		if (empty($companyNumber)) {
91
			$form->addText('birthdateNumber', 'Birthdate number')
92
				->setRequired('Birthdate number is mandatory.')
93
				->addRule(callback($this, 'validateBirthdateNumber'), "Birthdate can contain just numbers.");
94
		} else {
95
			$form->addHidden('birthdateNumber');
96
		}
97
98
		if (isset($this->businessmanSession->id)) {
99
100
			$form->addHidden('pin', $this->businessmanSession->id);
101
102
			$form['pin']->getControlPrototype()->setClass('session');
103
		} else {
104
			$form->addText('pin', 'Pin number');
105
		}
106
		
107
108
		$form->addCheckbox('postalAddress', 'Postal address');
109
		$form->addText('name', 'Name')
110
			->addConditionOn($form['postalAddress'], Form::EQUAL, true)
111
	        ->addRule(Form::FILLED, 'Name is mandatory.');
112
		$form->addText('lastname', 'Lastname')
113
			->addConditionOn($form['postalAddress'], Form::EQUAL, true)
114
	        ->addRule(Form::FILLED, 'Lastname is mandatory.');
115
		$form->addText('street', 'Street')
116
			->addConditionOn($form['postalAddress'], Form::EQUAL, true)
117
	        ->addRule(Form::FILLED, 'Street is mandatory.');
118
		$form->addText('postcode', 'Postcode')
119
			->addConditionOn($form['postalAddress'], Form::EQUAL, true)
120
			->addRule(Form::PATTERN, 'Postcode must contain 5 numbers.', '([0-9]\s*){5}')
121
	        ->addRule(Form::FILLED, 'Postcode is mandatory.');
122
		$form->addText('city', 'City')
123
			->addConditionOn($form['postalAddress'], Form::EQUAL, true)
124
	        ->addRule(Form::FILLED, 'City is mandatory.');
125
	    $form->addHidden('idUser')->setDefaultValue($this->id);
126
127
		$form->addSubmit('send', 'Send');
128
129
		$form->onSuccess[] = callback($this, 'step2formSubmitted');
130
131
		return $form;
132
	}
133
134
	public function validateBirthdateNumber($control)
135
	{
136
		$rc = $control->getValue();
137
138
	    if (!preg_match('#^\s*(\d\d)(\d\d)(\d\d)[ /]*(\d\d\d)(\d?)\s*$#', $rc, $matches)) {
139
	        return false;
140
	    }
141
142
	    list(, $year, $month, $day, $ext, $c) = $matches;
143
144
	    if ($c === '') {
145
	        return $year < 54;
146
	    }
147
148
	    $mod = ($year . $month . $day . $ext) % 11;
149
	    if ($mod === 10) $mod = 0;
150
	    if ($mod !== (int) $c) {
151
	        return false;
152
	    }
153
154
	    $year += $year < 54 ? 2000 : 1900;
155
156
	    if ($month > 70 && $year > 2003) $month -= 70;
157
	    elseif ($month > 50) $month -= 50;
158
	    elseif ($month > 20 && $year > 2003) $month -= 20;
159
160
	    if (!checkdate($month, $day, $year)) {
161
	        return false;
162
	    }
163
164
	    return true;
165
	}
166
167
	public function validateBankAccount($control)
168
	{
169
		$number = $control->getValue();
170
171
		$parts = explode('/', $number);
172
		$baNumber = $parts[0];
173
174
		$parts = explode('-', $baNumber);
175
176
		foreach ($parts as $part) {
177
			if (!$this->validatePart($part)) {
178
				return false;
179
			}
180
		}
181
182
		return true;
183
	}
184
185
	/**
186
	 *    A  B C D  E  F G H I J
187
	 * _________________________
188
	 * s  6  3 7 9  10 5 8 4 2 1
189
	 * n  10 9 8 7  6  5 4 3 2 1
190
	 * 
191
	 * S = J *1 I *2 H *4 G *8 F*5 E *10 D*9 C*7 B*3 A *6
192
	 * 
193
	 * @param  [type] $part [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
194
	 * @return [type]       [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
195
	 */
196
	private function validatePart($part)
197
	{
198
		$scales = array(1, 2, 4, 8, 5, 10, 9, 7, 3, 6);
199
		$toValidate = array_reverse(str_split($part));
200
201
		$controlSum = 0;
202
		for ($i=0; $i < count($toValidate); $i++) { 
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
203
			$controlSum += $toValidate[$i] * $scales[$i];
204
		}
205
		
206
		return $controlSum % 11 === 0;
207
	}
208
209
	public function actionDefault($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id 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...
210
    {	
211
    	$parameters = $this->getParameter();
212
    	$parameters = $parameters['parameters'];
213
214
    	$this->businessmanSession = $this->getSession('businessman');
215
216
    	if (array_key_exists(0, $parameters) && $parameters[0] === '2') {
217
218
    		if (isset($parameters[1])) {
219
				$hash = $parameters[1];
220
221
	    		$investment = $this->em->getRepository('\WebCMS\InvestformModule\Entity\Investment')->findOneByHash($hash);
222
	    		$this->id = $investment->getId();
223
224
	    		$this->template->setFile(APP_DIR . '/templates/investform-module/Investform/step2.latte');
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
It seems like you code against a concrete implementation and not the interface Nette\Templating\ITemplate as the method setFile() does only exist in the following implementations of said interface: Nette\Templating\FileTemplate.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
225
    		} else {
226
    			$this->template->setFile(APP_DIR . '/templates/investform-module/Investform/contactLater.latte');
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
It seems like you code against a concrete implementation and not the interface Nette\Templating\ITemplate as the method setFile() does only exist in the following implementations of said interface: Nette\Templating\FileTemplate.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
227
    		}
228
229
    		
230
    	} else if(array_key_exists(0, $parameters) && $parameters[0] === 'final') {
231
    		$this->template->setFile(APP_DIR . '/templates/investform-module/Investform/final.latte');
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
It seems like you code against a concrete implementation and not the interface Nette\Templating\ITemplate as the method setFile() does only exist in the following implementations of said interface: Nette\Templating\FileTemplate.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
232
    	}
233
234
    	$this->template->form = $this->createComponentForm('form');
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 form 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...
235
	}
236
	
237
	public function formSubmitted($form)
238
	{
239
240
		$values = $form->getValues();
241
242
		if ($this->getUser()->isLoggedIn()) {
243
244
			$address = new Address;
245
			$address->setName($values->name);
246
			$address->setLastname($values->lastname);
247
			$address->setStreet($values->street);
248
			$address->setPostcode($values->postcode);
249
			$address->setCity($values->city);
250
251
			$this->em->persist($address);
252
253
			$investment = new Investment;
254
			$investment->setPhone($values->phone);
255
			$investment->setEmail($values->email);
256
			$investment->setInvestmentDate(new \Datetime(date('Y-m-d', strtotime($values->date))));
257
			$investment->setInvestment($values->investmentAmount);
258
			$investment->setInvestmentLength($values->investmentLength);
259
			$investment->setRegistrationNumber($values->registrationNumber);
260
			$investment->setCompany($values->company);
261
			$investment->setAddress($address);
262
263
			$investment->setContractSend(false);
264
			$investment->setContractPaid(false);
265
			$investment->setContractClosed(false);
266
			$investment->setClientContacted(false);
267
268
			$values->bankAccount = ltrim($values->bankAccount, '0');
269
270
			if (!empty($values->bankAccountPrefix)) {
271
				$bankAccount = str_replace('_', '', $values->bankAccountPrefix).'-'.str_replace('_', '', $values->bankAccount);
272
			} else {
273
				$bankAccount = str_replace('_', '', $values->bankAccount);
274
			}
275
			$investment->setBankAccount($bankAccount);
276
277
			if (isset($this->businessmanSession->id)) {
278
				$businessman = $this->em->getRepository('WebCMS\InvestformModule\Entity\Businessman')->find($this->businessmanSession->id);
279
				$investment->setBusinessman($businessman);
280
			}
281
282
			$this->em->persist($investment);
283
			$this->em->flush();
284
			$investment->getHash();
285
			$this->em->flush();
286
287
			$this->sendPdf($investment, 'form');
288
289
		} else {
290
			$infoEmail = $this->settings->get('Info email', \WebCMS\Settings::SECTION_BASIC, 'text')->getValue();
0 ignored issues
show
Bug introduced by
The method getValue cannot be called on $this->settings->get('In...:SECTION_BASIC, 'text') (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
291
			if (!empty($infoEmail)) {
292
293
				$mailBody = '<h3>Zájem o investici</h3>';
294
				$mailBody .= '<hr><br />';
295
				$mailBody .= '<h4>Kontaktní údaje</h4>';
296
				$mailBody .= '<p>';
297
				$mailBody .= $values->name.' '.$values->lastname.'<br />';
298
				$mailBody .= $values->street.', '.$values->postcode.' '.$values->city.'<br />';
299
				$mailBody .= $values->phone.', '.$values->email.'<br />';
300
				$mailBody .= '</p><br />';
301
				$mailBody .= '<h4>Zadaná investice - údaje</h4>';
302
				$mailBody .= '<p>';
303
				$mailBody .= 'Výše investice: '.$values->investmentAmount.'<br />';
304
				$mailBody .= 'Varianta dluhopisu: '.$values->investmentLength.'<br />';
305
				$mailBody .= '</p>';
306
307
				$mail = new Message;
308
				$mail->setFrom($infoEmail)
309
				    ->addTo($infoEmail)
310
				    ->setSubject('Zájem o investici - '.$values->name.' '.$values->lastname)
311
				    ->setHTMLBody($mailBody);
312
313
				$mail->send();
314
			}
315
		}
316
317
		
318
319
		if ($this->getUser()->isLoggedIn()) {
320
321
			$this->redirect('default', array(
322
				'path' => $this->actualPage->getPath(),
323
				'abbr' => $this->abbr,
324
				'parameters' => array(
325
					'2',
326
					'hash' => $investment->getHash()
0 ignored issues
show
Bug introduced by
The variable $investment 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...
327
				)
328
			));
329
330
		} else {
331
332
			$this->redirect('default', array(
333
				'path' => $this->actualPage->getPath(),
334
				'abbr' => $this->abbr,
335
				'parameters' => array(
336
					'2'
337
				)
338
			));
339
340
		}
341
342
		
343
	}
344
345
	public function step2formSubmitted($form)
346
	{
347
		$values = $form->getValues();
348
		
349
		$investment = $this->em->getRepository('WebCMS\InvestformModule\Entity\Investment')->find($values->idUser);
350
		$investment->setBirthdateNumber($values->birthdateNumber);
351
352
		if (isset($this->businessmanSession->id)) {
353
			$businessman = $this->em->getRepository('WebCMS\InvestformModule\Entity\Businessman')->find($this->businessmanSession->id);
354
			$investment->setBusinessman($businessman);
355
		} else {
356
			//check if businessman exists
357
			$businessman = $this->em->getRepository('WebCMS\InvestformModule\Entity\Businessman')->findOneBy(array(
358
				'businessId' => $values->pin
359
			));
360
			if ($businessman) {
361
				$investment->setBusinessman($businessman);
362
			}
363
			$investment->setPin($values->pin);
364
		}
365
366
		$investment->setContractSend(true);
367
368
		if ($values->postalAddress) {
369
			$address = new Address;
370
			$address->setName($values->name);
371
			$address->setLastname($values->lastname);
372
			$address->setStreet($values->street);
373
			$address->setPostcode($values->postcode);
374
			$address->setCity($values->city);
375
376
			$this->em->persist($address);
377
378
			$investment->setPostalAddress($address);
379
		}
380
381
		$this->sendPdf($investment, 'contract');
382
		$this->em->flush();
383
384
		$this->redirect('default', array(
385
			'path' => $this->actualPage->getPath(),
386
			'abbr' => $this->abbr,
387
			'parameters' => array(
388
				'final'
389
			)
390
		));
391
	}
392
393
	public function handlegetNetIncome($amount, $length, $date)
394
	{
395
396
		$from = strtotime($date);
397
		if ($length == 5) {
398
			$to = strtotime('2020-11-30');
399
		} else {
400
			$to = strtotime('2017-10-30');
401
		}
402
403
		$length = ($to - $from) / 60 / 60 / 24 / 365;
404
405
		$fvoa = new \WebCMS\InvestformModule\Common\FutureValueOfAnnuityCalculator($amount, $length);
406
407
		$this->payload->profit = \WebCMS\Helpers\SystemHelper::price($fvoa->getTotalProfit(), '%.0n');
0 ignored issues
show
Documentation introduced by
The property $payload is declared private in Nette\Application\UI\Presenter. 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...
408
		$this->sendPayload();
409
	}
410
411
	public function sendPdf($investment, $type)
412
	{
413
		$emailSender = new EmailSender($this->settings, $investment, $type);
414
		$emailSender->send();
415
	}
416
417
	public function renderDefault($id)
418
    {	
419
		$this->template->id = $id;
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 id 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...
420
	}
421
}
422