Completed
Push — master ( 118c60...254398 )
by Litera
03:47
created

VisitorForm::setMealField()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
rs 9.4285
1
<?php
2
3
namespace App\Components\Forms;
4
5
use App\Repositories\ProgramRepository;
6
use App\Models\ProvinceModel;
7
use App\Models\BlockModel;
8
use App\Models\MealModel;
9
use App\Models\MeetingModel;
10
use Nette\Application\UI\Form;
11
use App\Services\SkautIS\UserService;
12
use Nette\Forms\Controls\SubmitButton;
13
use Nette\Utils\ArrayHash;
14
15
class VisitorForm extends BaseForm
16
{
17
18
	const TEMPLATE_NAME = 'VisitorForm';
19
20
	const MESSAGE_REQUIRED = 'Hodnota musí být vyplněna!';
21
	const MESSAGE_MAX_LENGTH = '%label nesmí mít více jak %d znaků!';
22
23
	/**
24
	 * @var Closure
25
	 */
26
	public $onVisitorSave;
27
28
    /**
29
     * @var Closure
30
     */
31
    public $onVisitorReset;
32
33
	/**
34
	 * @var ProvinceModel
35
	 */
36
	protected $provinceModel;
37
38
	/**
39
	 * @var ProgramRepository
40
	 */
41
	protected $programRepository;
42
43
	/**
44
	 * @var BlockModel
45
	 */
46
	protected $blockModel;
47
48
	/**
49
	 * @var  MeetingModel
50
	 */
51
	protected $meetingModel;
52
53
	/**
54
	 * @var array
55
	 */
56
	protected $mealFields = [];
57
58
	/**
59
	 * @var array
60
	 */
61
	protected $programFields = [];
62
63
    /**
64
     * VisitorForm constructor.
65
     * @param ProvinceModel     $province
66
     * @param ProgramRepository $program
67
     * @param BlockModel        $block
68
     * @param MeetingModel      $meeting
69
     */
70 View Code Duplication
	public function __construct(
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...
71
		ProvinceModel $province,
72
		ProgramRepository $program,
73
		BlockModel $block,
74
		MeetingModel $meeting
75
	) {
76
		$this->setProvinceModel($province);
77
		$this->setProgramRepository($program);
78
		$this->setBlockModel($block);
79
		$this->setMeetingModel($meeting);
80
	}
81
82
	/**
83
	 * @return void
84
	 */
85
	public function render()
86
	{
87
		$this->setMealFields();
88
		$this->setProgramFields();
89
90
		$template = $this->getTemplate();
91
		$template->setFile($this->buildTemplatePath());
92
		$template->meals = $this->getMealFields();
0 ignored issues
show
Bug introduced by
Accessing meals on the interface Nette\Application\UI\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...
93
		$template->programs = $this->getProgramFields();
0 ignored issues
show
Bug introduced by
Accessing programs on the interface Nette\Application\UI\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...
94
		$template->render();
95
	}
96
97
	/**
98
	 * @param  array|ArrayHash $defaults
99
	 * @return self
100
	 */
101
	public function setDefaults($defaults): BaseForm
102
	{
103
		$this['visitorForm']->setDefaults($defaults);
104
105
		return $this;
106
	}
107
108
	/**
109
	 * @return Form
110
	 */
111
	public function createComponentVisitorForm(): Form
112
	{
113
		$provinces = $this->getProvinceModel()->all();
114
115
		$form = new Form;
116
117
		$form->addText('name', 'Jméno:', 30)
118
			->setRequired(static::MESSAGE_REQUIRED)
0 ignored issues
show
Documentation introduced by
static::MESSAGE_REQUIRED is of type string, but the function expects a boolean.

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...
119
			->addRule(Form::MAX_LENGTH, static::MESSAGE_MAX_LENGTH, 20)
120
			->getLabelPrototype()->setAttribute('class', 'required');
121
		$form->addText('surname', 'Příjmení:', 30)
122
			->setRequired(static::MESSAGE_REQUIRED)
0 ignored issues
show
Documentation introduced by
static::MESSAGE_REQUIRED is of type string, but the function expects a boolean.

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...
123
			->addRule(Form::MAX_LENGTH, static::MESSAGE_MAX_LENGTH, 30)
124
			->getLabelPrototype()->setAttribute('class', 'required');
125
		$form->addText('nick', 'Přezdívka:', 30)
126
			->setRequired(static::MESSAGE_REQUIRED)
0 ignored issues
show
Documentation introduced by
static::MESSAGE_REQUIRED is of type string, but the function expects a boolean.

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...
127
			->addRule(Form::MAX_LENGTH, static::MESSAGE_MAX_LENGTH, 20)
128
			->getLabelPrototype()->setAttribute('class', 'required');
129
		$form->addEmail('email', 'E-mail:')
130
			->setRequired(static::MESSAGE_REQUIRED)
0 ignored issues
show
Documentation introduced by
static::MESSAGE_REQUIRED is of type string, but the function expects a boolean.

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...
131
            ->setAttribute('size', 30)
0 ignored issues
show
Documentation introduced by
30 is of type integer, but the function expects a boolean.

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...
132
			->getLabelPrototype()->setAttribute('class', 'required');
133
        $form->addTbDatePicker('birthday', 'Datum narození:', null, 16)
134
            ->setRequired(static::MESSAGE_REQUIRED)
135
            ->setFormat('d.m.Y')
136
            ->setAttribute('placeholder', 'dd. mm. rrrr')
137
            ->setAttribute('id', 'birthday')
138
            ->setAttribute('class', 'datePicker')
139
            ->getLabelPrototype()->setAttribute('class', 'required');
140
		$form->addText('street', 'Ulice:', 30)
141
			->setRequired(static::MESSAGE_REQUIRED)
0 ignored issues
show
Documentation introduced by
static::MESSAGE_REQUIRED is of type string, but the function expects a boolean.

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...
142
			->addRule(Form::MAX_LENGTH, static::MESSAGE_MAX_LENGTH, 30)
143
			->getLabelPrototype()->setAttribute('class', 'required');
144
		$form->addText('city', 'Město:', 30)
145
			->setRequired(static::MESSAGE_REQUIRED)
0 ignored issues
show
Documentation introduced by
static::MESSAGE_REQUIRED is of type string, but the function expects a boolean.

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...
146
			->addRule(Form::MAX_LENGTH, static::MESSAGE_MAX_LENGTH, 64)
147
			->getLabelPrototype()->setAttribute('class', 'required');
148
		$form->addText('postal_code', 'PSČ:', 30)
149
			->setRequired(static::MESSAGE_REQUIRED)
0 ignored issues
show
Documentation introduced by
static::MESSAGE_REQUIRED is of type string, but the function expects a boolean.

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...
150
			->addRule(Form::PATTERN, 'Číslo musí být ve formátu nnnnn!', '[1-9]{1}[0-9]{4}')
151
			->setAttribute('placeholder', '12345')
0 ignored issues
show
Documentation introduced by
'12345' is of type string, but the function expects a boolean.

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...
152
			->getLabelPrototype()->setAttribute('class', 'required');
153
		$form->addText('group_num', 'Číslo středika/přístavu:', 30)
154
			->setRequired(static::MESSAGE_REQUIRED)
0 ignored issues
show
Documentation introduced by
static::MESSAGE_REQUIRED is of type string, but the function expects a boolean.

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...
155
			->addRule(Form::PATTERN, 'Číslo musí být ve formátu nnn.nn!', '[1-9]{1}[0-9a-zA-Z]{2}\.[0-9a-zA-Z]{1}[0-9a-zA-Z]{1}')
156
			->setAttribute('placeholder', '214.02')
0 ignored issues
show
Documentation introduced by
'214.02' is of type string, but the function expects a boolean.

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...
157
			->getLabelPrototype()->setAttribute('class', 'required');
158
		$form->addText('group_name', 'Název střediska/přístavu:', 30)
159
			->setRequired(static::MESSAGE_REQUIRED)
0 ignored issues
show
Documentation introduced by
static::MESSAGE_REQUIRED is of type string, but the function expects a boolean.

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...
160
			->addRule(Form::MAX_LENGTH, static::MESSAGE_MAX_LENGTH, 50)
161
			->setAttribute('placeholder', '2. přístav Poutníci Kolín')
0 ignored issues
show
Documentation introduced by
'2. přístav Poutníci Kolín' is of type string, but the function expects a boolean.

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...
162
			->getLabelPrototype()->setAttribute('class', 'required');
163
		$form->addText('troop_name', 'Název oddílu:', 30)
164
			->setAttribute('placeholder', '22. oddíl Galeje')
0 ignored issues
show
Documentation introduced by
'22. oddíl Galeje' is of type string, but the function expects a boolean.

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...
165
			->addCondition(Form::FILLED, true)
166
				->addRule(Form::MAX_LENGTH, static::MESSAGE_MAX_LENGTH, 50);
167
168
		$form->addSelect('province', 'Kraj:', $provinces)
169
			->setPrompt('zvolte kraj');
170
171
		$form = $this->buildMealSwitcher($form);
172
173
		$form->addTextArea('arrival', 'Informace o příjezdu:', 50, 3)
174
			->setAttribute('placeholder', 'Napište, prosím, stručně jakým dopravním prostředkem a v kolik hodin (přibližně) přijedete na místo srazu.');
0 ignored issues
show
Documentation introduced by
'Napište, prosím, stru...edete na místo srazu.' is of type string, but the function expects a boolean.

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...
175
		$form->addTextArea('departure', 'Informace o odjezdu:', 50, 3)
176
			->setAttribute('placeholder', 'Napište, prosím, stručně jakým dopravním prostředkem a v kolik hodin (přibližně) sraz opustíte.');
0 ignored issues
show
Documentation introduced by
'Napište, prosím, stru...žně) sraz opustíte.' is of type string, but the function expects a boolean.

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...
177
		$form->addTextArea('comment', 'Dotazy, přání, připomínky, stížnosti:', 50, 8);
178
		$form->addTextArea('question', 'Vaše nabídka:', 50, 8)
179
			->setAttribute('placeholder', 'Vaše nabídka na sdílení dobré praxe (co u vás umíte dobře a jste ochotni se o to podělit)');
0 ignored issues
show
Documentation introduced by
'Vaše nabídka na sdíl...otni se o to podělit)' is of type string, but the function expects a boolean.

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...
180
		$form->addTextArea('question2', 'Počet a typy lodí:', 50, 8)
181
			->setAttribute('placeholder', 'Počet a typy lodí, které sebou přivezete (vyplňte pokud ano)');
0 ignored issues
show
Documentation introduced by
'Počet a typy lodí, kt...e (vyplňte pokud ano)' is of type string, but the function expects a boolean.

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...
182
        $form->addText('bill', 'Zaplaceno:', 30)
183
            ->setDefaultValue(0);
184
        $form->addText('cost', 'Poplatek:', 30)
185
            ->setDefaultValue($this->getMeetingModel()->getPrice('cost'));
186
187
		$form = $this->buildProgramSwitcher($form);
188
189
		$form->addHidden('mid', $this->getMeetingId());
190
        $form->addHidden('meeting', $this->getMeetingId());
191
		$form->addHidden('backlink');
192
193
        $form->addSubmit('save', 'Uložit')
194
            ->setAttribute('class', 'btn-primary')
0 ignored issues
show
Documentation introduced by
'btn-primary' is of type string, but the function expects a boolean.

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...
195
            ->onClick[] = [$this, 'processSave'];
196
        $form->addSubmit('reset', 'Storno')
197
            ->setAttribute('class', 'btn-reset')
0 ignored issues
show
Documentation introduced by
'btn-reset' is of type string, but the function expects a boolean.

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...
198
            ->onClick[] = [$this, 'processReset'];
199
200
201
        $form = $this->setupRendering($form);
202
203
		$form->onSuccess[] = [$this, 'processForm'];
204
205
		return $form;
206
	}
207
208
    /**
209
     * @param  SubmitButton $button
210
     * @return void
211
     */
212
    public function processSave(SubmitButton $button)
213
    {
214
        $visitor = $button->getForm()->getValues();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Nette\ComponentModel\IComponent as the method getValues() does only exist in the following implementations of said interface: Nette\Application\UI\Form, Nette\Forms\Container, Nette\Forms\Form.

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...
215
216
        $this->onVisitorSave($this, $visitor);
0 ignored issues
show
Documentation Bug introduced by
The method onVisitorSave does not exist on object<App\Components\Forms\VisitorForm>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
217
    }
218
219
    /**
220
     * @param  SubmitButton $button
221
     * @return void
222
     */
223
    public function processReset(SubmitButton $button)
224
    {
225
        $visitor = $button->getForm()->getValues();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Nette\ComponentModel\IComponent as the method getValues() does only exist in the following implementations of said interface: Nette\Application\UI\Form, Nette\Forms\Container, Nette\Forms\Form.

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...
226
227
        $this->onVisitorReset($this, $visitor);
0 ignored issues
show
Documentation Bug introduced by
The method onVisitorReset does not exist on object<App\Components\Forms\VisitorForm>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
228
    }
229
230
	/**
231
	 * @param  Form   $form
232
	 * @return Form
233
	 */
234
	protected function buildProgramSwitcher(Form $form): Form
235
	{
236
		$programBlocks = $this->fetchProgramBlocks();
237
238
		foreach ($programBlocks as $block) {
239
240
			$programsInBlock = $this->getProgramRepository()->findByBlockId($block->id);
241
242
			$programs = [
243
				0 => 'Nebudu přítomen'
244
			];
245
246
			foreach ($programsInBlock as $program) {
247
				$programs[$program->id] = $program->name;
248
			}
249
250
			$form->addRadioList(
251
				'blck_' . $block->id,
252
				$block->day . ', ' . $block->from .' - ' . $block->to .' : ' . $block->name,
253
				$programs
254
			)->setDefaultValue(0)
255
			->setDisabled($this->filterFilledCapacity($programs));
0 ignored issues
show
Documentation introduced by
$this->filterFilledCapacity($programs) is of type array, but the function expects a boolean.

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...
256
		}
257
258
		return $form;
259
	}
260
261
	/**
262
	 * @param  Form   $form
263
	 * @return Form
264
	 */
265
	protected function buildMealSwitcher(Form $form): Form
266
	{
267
		$yesNoArray = [
268
			'ne'  => 'ne',
269
			'ano' => 'ano',
270
		];
271
272
		foreach ($this->fetchMeals() as $name => $label) {
273
			$this->setMealField($name);
274
			$form->addSelect($name, $label . ':', $yesNoArray);
275
		}
276
277
		return $form;
278
	}
279
280
	/**
281
	 * @return ProvinceModel
282
	 */
283
	protected function getProvinceModel(): ProvinceModel
284
	{
285
		return $this->provinceModel;
286
	}
287
288
	/**
289
	 * @param  ProvinceModel $model
290
	 * @return self
291
	 */
292
	protected function setProvinceModel(ProvinceModel $model): self
293
	{
294
		$this->provinceModel = $model;
295
296
		return $this;
297
	}
298
299
	/**
300
	 * @return ProgramRepository
301
	 */
302
	protected function getProgramRepository(): ProgramRepository
303
	{
304
		return $this->programRepository;
305
	}
306
307
	/**
308
	 * @param  ProgramRepository $repository
309
	 * @return self
310
	 */
311
	protected function setProgramRepository(ProgramRepository $repository): self
312
	{
313
		$this->programRepository = $repository;
314
315
		return $this;
316
	}
317
318
	/**
319
	 * @return BlockModel
320
	 */
321
	protected function getBlockModel(): BlockModel
322
	{
323
		return $this->blockModel;
324
	}
325
326
	/**
327
	 * @param  BlockModel $model
328
	 * @return self
329
	 */
330
	protected function setBlockModel(BlockModel $model): self
331
	{
332
		$this->blockModel = $model;
333
334
		return $this;
335
	}
336
337
	/**
338
	 * @return MeetingModel
339
	 */
340
	protected function getMeetingModel(): MeetingModel
341
	{
342
		return $this->meetingModel;
343
	}
344
345
	/**
346
	 * @param  MeetingModel $model
347
	 * @return VisitorForm
348
	 */
349
	protected function setMeetingModel(MeetingModel $model): VisitorForm
350
	{
351
		$this->meetingModel = $model;
352
353
		return $this;
354
	}
355
356
	/**
357
	 * @return array
358
	 */
359
	protected function getMealFields(): array
360
	{
361
		return $this->mealFields;
362
	}
363
364
	/**
365
	 * @param  string $meal
366
	 * @return self
367
	 */
368
	protected function setMealField(string $meal): self
369
	{
370
		if(!in_array($meal, $this->mealFields)) {
371
			$this->mealFields[] = $meal;
372
		}
373
374
		return $this;
375
	}
376
377
	/**
378
	 * @return array
379
	 */
380
	protected function getProgramFields(): array
381
	{
382
		return $this->programFields;
383
	}
384
385
	/**
386
	 * @param  string $program
387
	 * @return self
388
	 */
389
	protected function setProgramField(string $program): self
390
	{
391
		$this->programFields[] = $program;
392
393
		return $this;
394
	}
395
396
	/**
397
	 * @return self
398
	 */
399
	protected function setProgramFields(): self
400
	{
401
		$programBlocks = $this->fetchProgramBlocks();
402
403
		foreach ($programBlocks as $block) {
404
			$programFieldName = 'blck_' . $block->id;
405
			$this->setProgramField($programFieldName);
406
		}
407
408
		return $this;
409
	}
410
411
	/**
412
	 * @return  self
413
	 */
414
	protected function setMealFields(): self
415
	{
416
		$meals = $this->fetchMeals();
417
418
		foreach ($meals as $name => $label) {
419
			$this->setMealField($name);
420
		}
421
422
		return $this;
423
	}
424
425
	/**
426
	 * @return Row
427
	 */
428
	protected function fetchProgramBlocks()
429
	{
430
		return $this->getBlockModel()->getProgramBlocks($this->getMeetingId());
431
	}
432
433
	/**
434
	 * @return array
435
	 */
436
	protected function fetchMeals()
437
	{
438
		return MealModel::$meals;
439
	}
440
441
	/**
442
	 * @return UserService
443
	 */
444
	protected function getUserService()
445
	{
446
		return $this->userService;
0 ignored issues
show
Documentation introduced by
The property userService does not exist on object<App\Components\Forms\VisitorForm>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
447
	}
448
449
	/**
450
	 * @param  UserService $service
451
	 * @return $this
452
	 */
453
	protected function setUserService(UserService $service)
454
	{
455
		$this->userService = $service;
0 ignored issues
show
Documentation introduced by
The property userService does not exist on object<App\Components\Forms\VisitorForm>. Since you implemented __set, maybe consider adding a @property annotation.

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...
456
457
		return $this;
458
	}
459
460
	/**
461
	 * @param  array  $programs
462
	 * @return array
463
	 */
464
	protected function filterFilledCapacity(array $programs = []): array
465
	{
466
		return array_keys(
467
			array_filter($programs, function($name, $id) {
468
				if ($id) {
469
					$visitorsOnProgram = $this->getProgramRepository()->countVisitors($id);
470
					$programCapacity = $this->getProgramRepository()->find($id)->capacity;
471
472
					return $visitorsOnProgram >= $programCapacity;
473
				}
474
			}, ARRAY_FILTER_USE_BOTH)
475
		);
476
	}
477
478
}
479