Completed
Pull Request — devel (#144)
by Litera
03:43
created

BlockForm::getBlockRepository()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Components\Forms;
4
5
use App\Entities\BlockEntity;
6
use App\Repositories\BlockRepository;
7
use App\Repositories\CategoryRepository;
8
use Nette\Application\UI\Form;
9
use Nette\Forms\Controls\SubmitButton;
10
11
class BlockForm extends BaseForm
12
{
13
14
	const TEMPLATE_NAME = 'BlockForm';
15
16
	const MESSAGE_REQUIRED = 'Hodnota musí být vyplněna!';
17
	const MESSAGE_MAX_LENGTH = '%label nesmí mít více jak %d znaků!';
18
19
	/**
20
	 * @var Closure
21
	 */
22
	public $onBlockSave;
23
24
	/**
25
	 * @var Closure
26
	 */
27
	public $onBlockReset;
28
29
	/**
30
	 * @var BlockRepository
31
	 */
32
	protected $blockRepository;
33
34
	/**
35
	 * @var CategoryRepository
36
	 */
37
	protected $categoryRepository;
38
39
	/**
40
	 * @var array
41
	 */
42
	protected $days = [
43
		'pátek'  => 'pátek',
44
		'sobota' => 'sobota',
45
		'neděle' => 'neděle',
46
	];
47
48
	/**
49
	 * @var array
50
	 */
51
	protected $hours = [
52
		0 => "00","01","02","03","04","05","06","07","08","09",
53
			 "10","11","12","13","14","15","16","17","18","19",
54
			 "20","21","22","23"
55
	];
56
57
	/**
58
	 * @var array
59
	 */
60
	protected $minutes = [
61
		00 => "00",
62
		05 => "05",
63
		10 => "10",
64
		15 => "15",
65
		20 => "20",
66
		25 => "25",
67
		30 => "30",
68
		35 => "35",
69
		40 => "40",
70
		45 => "45",
71
		50 => "50",
72
		55 => "55",
73
	];
74
75
	/**
76
	 * @param BlockRepository    $blockRepository
77
	 * @param CategoryRepository $categoryRepository
78
	 */
79
	public function __construct(
80
		BlockRepository $blockRepository,
81
		CategoryRepository $categoryRepository
82
	) {
83
		$this->setBlockRepository($blockRepository);
84
		$this->setCategoryRepository($categoryRepository);
85
	}
86
87
	/**
88
	 * @return void
89
	 */
90
	public function render()
91
	{
92
		$template = $this->getTemplate();
93
		$template->setFile($this->buildTemplatePath());
94
		$template->backlink = 'Block:listing';
0 ignored issues
show
Bug introduced by
Accessing backlink 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...
95
		$template->render();
96
	}
97
98
	/**
99
	 * @param  array $defaults
100
	 * @return self
101
	 */
102
	public function setDefaults(BlockEntity $defaults): self
103
	{
104
        $defaults = $this->guardDefaults($defaults);
105
106
		$this['blockForm']->setDefaults($defaults->toArray());
107
108
		return $this;
109
	}
110
111
	/**
112
	 * @return Form
113
	 */
114
	public function createComponentBlockForm(): Form
115
	{
116
		$form = new Form;
117
118
		$form->addText('name', 'Název:')
119
			->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...
120
			->addRule(Form::MAX_LENGTH, static::MESSAGE_MAX_LENGTH, 50)
121
			->setAttribute('size', 50)
0 ignored issues
show
Documentation introduced by
50 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...
122
			->getLabelPrototype()->setAttribute('class', 'required');
123
		$form->addSelect('day', 'Den:', $this->days)
124
			->setRequired();
125
		$form->addSelect('start_hour', null, $this->hours)
126
			->setDefaultValue(date('G'));
127
		$form->addSelect('start_minute', null, $this->minutes);
128
		$form->addSelect('end_hour', null, $this->hours)
129
			->setDefaultValue(date('G', strtotime('+1 hour')));
130
		$form->addSelect('end_minute', null, $this->minutes);
131
		$form->addTextArea('description', 'Popis:')
132
			->setAttribute('rows', 10)
0 ignored issues
show
Documentation introduced by
10 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...
133
			->setAttribute('cols', 80);
0 ignored issues
show
Documentation introduced by
80 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...
134
		$form->addText('tutor', 'Lektor:')
135
			->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...
136
		$form->addText('email', 'E-mail:')
137
			->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...
138
		$form->addText('capacity', 'Kapacita:')
139
			->setDefaultValue(0)
140
			->setAttribute('size', 10)
0 ignored issues
show
Documentation introduced by
10 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...
141
			->setAttribute('placeholder', 0);
0 ignored issues
show
Documentation introduced by
0 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...
142
		$form->addCheckbox('program')
143
		    ->setDefaultValue(1);
144
		$form->addCheckbox('display_progs')
145
			->setDefaultValue(0);
146
		$form->addSelect('category', 'Kategorie:', $this->buildCategorySelect());
147
148
		$form->addHidden('id');
149
		$form->addHidden('guid');
150
		$form->addHidden('backlink');
151
152
		$form->addSubmit('save', 'Uložit')
153
			->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...
154
			->onClick[] = [$this, 'processForm'];
155
		$form->addSubmit('reset', 'Storno')
156
			->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...
157
			->onClick[] = [$this, 'processReset'];
158
159
		$form = $this->setupRendering($form);
160
161
		return $form;
162
	}
163
164
	/**
165
	 * @param  SubmitButton $button
166
	 * @return void
167
	 */
168
	public function processForm(SubmitButton $button)
169
	{
170
		$block = $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...
171
172
		$this->onBlockSave($this, $block);
0 ignored issues
show
Documentation Bug introduced by
The method onBlockSave does not exist on object<App\Components\Forms\BlockForm>? 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...
173
	}
174
175
	/**
176
	 * @param  SubmitButton $button
177
	 * @return void
178
	 */
179
	public function processReset(SubmitButton $button)
180
	{
181
		$block = $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...
182
183
		$this->onBlockReset($this, $block);
0 ignored issues
show
Documentation Bug introduced by
The method onBlockReset does not exist on object<App\Components\Forms\BlockForm>? 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...
184
	}
185
186
	/**
187
	 * @return array
188
	 */
189 View Code Duplication
	protected function buildCategorySelect(): array
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...
190
	{
191
		$categories = $this->getCategoryRepository()->findAll();
192
193
		$selectContent = [];
194
195
		foreach($categories as $category) {
196
			$selectContent[$category->id] = $category->name;
197
		}
198
199
		return $selectContent;
200
	}
201
202
    /**
203
     * @param  BlockEntity $defaults
204
     * @return BlockEntity
205
     */
206
	protected function guardDefaults(BlockEntity $defaults): BlockEntity
207
    {
208
        if(!array_key_exists($defaults->category, $this->buildCategorySelect()) )
209
        {
210
            $defaults->category = 0;
211
        }
212
213
        return $defaults;
214
    }
215
216
	/**
217
	 * @return BlockRepository
218
	 */
219
	public function getBlockRepository(): BlockRepository
220
	{
221
		return $this->blockRepository;
222
	}
223
224
	/**
225
	 * @param BlockRepository $blockRepository
0 ignored issues
show
Documentation introduced by
There is no parameter named $blockRepository. Did you maybe mean $repository?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
226
	 *
227
	 * @return self
228
	 */
229
	public function setBlockRepository(BlockRepository $repository): self
230
	{
231
		$this->blockRepository = $repository;
232
233
		return $this;
234
	}
235
236
	/**
237
	 * @return CategoryRepository
238
	 */
239
	public function getCategoryRepository(): CategoryRepository
240
	{
241
		return $this->categoryRepository;
242
	}
243
244
	/**
245
	 * @param CategoryRepository $categoryRepository
0 ignored issues
show
Documentation introduced by
There is no parameter named $categoryRepository. Did you maybe mean $repository?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
246
	 *
247
	 * @return self
248
	 */
249
	public function setCategoryRepository(CategoryRepository $repository): self
250
	{
251
		$this->categoryRepository = $repository;
252
253
		return $this;
254
	}
255
}
256