Completed
Push — master ( e088fc...e52644 )
by Adam
02:49
created

Widget::beforeRender()   F

Complexity

Conditions 12
Paths 321

Size

Total Lines 83
Code Lines 45

Duplication

Lines 18
Ratio 21.69 %

Importance

Changes 0
Metric Value
dl 18
loc 83
rs 3.7956
c 0
b 0
f 0
cc 12
eloc 45
nc 321
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Widget.php
4
 *
5
 * @copyright      More in license.md
6
 * @license        http://www.ipublikuj.eu
7
 * @author         Adam Kadlec http://www.ipublikuj.eu
8
 * @package        iPublikuj:Widgets!
9
 * @subpackage     Widgets
10
 * @since          1.0.0
11
 *
12
 * @date           15.09.14
13
 */
14
15
declare(strict_types = 1);
16
17
namespace IPub\Widgets\Widgets;
18
19
use Nette;
20
use Nette\Application;
21
use Nette\ComponentModel;
22
use Nette\Localization;
23
use Nette\Utils;
24
25
use IPub;
26
use IPub\Widgets;
27
use IPub\Widgets\Decorators;
28
use IPub\Widgets\Entities;
29
use IPub\Widgets\Exceptions;
30
use Tracy\Debugger;
31
32
/**
33
 * Widgets control definition
34
 *
35
 * @package        iPublikuj:Widgets!
36
 * @subpackage     Widgets
37
 *
38
 * @author         Adam Kadlec <[email protected]>
39
 *
40
 * @property Application\UI\ITemplate $template
41
 */
42
abstract class Widget extends Widgets\Application\UI\BaseControl implements IWidget
43
{
44
	/**
45
	 * @var Entities\IData
46
	 */
47
	protected $data;
48
49
	/**
50
	 * @param Entities\IData $data
51
	 * @param ComponentModel\IContainer $parent
52
	 * @param string $name
53
	 */
54
	public function __construct(
55
		Entities\IData $data,
56
		ComponentModel\IContainer $parent = NULL,
57
		string $name = NULL
58
	) {
59
		parent::__construct($parent, $name);
60
61
		$this->data = $data;
62
	}
63
64
	/**
65
	 * {@inheritdoc}
66
	 */
67
	public function getTitle()
68
	{
69
		$title = $this->data->getTitle();
70
71
		return $title ? $title : '';
72
	}
73
74
	/**
75
	 * {@inheritdoc}
76
	 */
77
	public function getDescription()
78
	{
79
		return $this->data->getDescription();
80
	}
81
82
	/**
83
	 * {@inheritdoc}
84
	 */
85
	public function getPriority()
86
	{
87
		return $this->data->getPriority();
88
	}
89
90
	/**
91
	 * {@inheritdoc}
92
	 */
93
	public function getStatus()
94
	{
95
		return $this->data->getStatus();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->data->getStatus(); (boolean) is incompatible with the return type declared by the interface IPub\Widgets\Widgets\IWidget::getStatus of type integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
96
	}
97
98
	/**
99
	 * {@inheritdoc}
100
	 */
101
	public function getPosition()
102
	{
103
		return $this->data->getPosition();
104
	}
105
106
	/**
107
	 * Before render actions
108
	 */
109
	protected function beforeRender()
110
	{
111
		// Check if control has template
112
		if (!$this->template instanceof Nette\Bridges\ApplicationLatte\Template) {
113
			throw new Exceptions\InvalidStateException('Widgets container control is without template.');
114
		}
115
116
		// Get widget title
117
		$name = $this->getTitle();
118
119
		// If widget name has space...
120
		$pos = mb_strpos($name, ' ');
121
		if ($pos !== FALSE && mb_strpos($name, '||') === FALSE) {
122
			$name = Utils\Html::el('span')
123
				->addAttributes(['class' => 'color'])
124
				->setText(mb_substr($name, 0, $pos))
125
				->render();
126
127
			// Modify widget name
128
			$name = $name . mb_substr($name, $pos);
129
		}
130
131
		// If widget name has subtitle...
132
		$pos = mb_strpos($name, '||');
133
		if ($pos !== FALSE) {
134
			$title = Utils\Html::el('span')
135
				->addAttributes(['class' => 'title'])
136
				->setText(mb_substr($name, 0, $pos))
137
				->render();
138
139
			$subtitle = Utils\Html::el('span')
140
				->addAttributes(['class' => 'subtitle'])
141
				->setText(mb_substr($name, $pos + 2))
142
				->render();
143
144
			// Split name to title & subtitle
145
			$name = $title . $subtitle;
146
		}
147
148
		// Set badge if exists
149 View Code Duplication
		if ($badge = $this->data->getBadge()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
150
			$badge = Utils\Html::el('span')
151
				->addAttributes(['class' => 'badge badge-' . $badge])
152
				->render();
153
		}
154
155
		// Set icon if exists
156 View Code Duplication
		if ($icon = $this->data->getIcon()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
157
			$icon = Utils\Html::el('span')
158
				->addAttributes(['class' => 'icon icon-' . $icon])
159
				->render();
160
		}
161
162
		// Assign basic widget data to template
163
		$this->template->add('badge', $badge);
164
		$this->template->add('icon', $icon);
165
		$this->template->add('title', [
166
			'text'   => $name,
167
			'insert' => $this->data->getParam('widget.title.insert', TRUE),
0 ignored issues
show
Documentation introduced by
TRUE is of type boolean, but the function expects a string|null.

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...
168
			'hidden' => $this->data->getParam('widget.title.hidden', FALSE)
0 ignored issues
show
Documentation introduced by
FALSE is of type boolean, but the function expects a string|null.

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...
169
		]);
170
171
		// Check if translator is available
172
		if ($this->getTranslator() instanceof Localization\ITranslator) {
173
			$this->template->setTranslator($this->getTranslator());
174
		}
175
176
		$templateFile = $this->getTemplate()->getFile();
177
178
		if (is_callable($templateFile)) {
179
			$templateFile = call_user_func($templateFile);
180
		}
181
182
		// If template was not defined before...
183 View Code Duplication
		if ($templateFile === NULL) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
184
			// Get component actual dir
185
			$dir = dirname($this->getReflection()->getFileName());
186
187
			// ...try to get base component template file
188
			$templateFile = $this->templateFile !== NULL && is_file($this->templateFile) ? $this->templateFile : $dir . DIRECTORY_SEPARATOR . 'template' . DIRECTORY_SEPARATOR . 'default.latte';
189
			$this->template->setFile($templateFile);
190
		}
191
	}
192
193
	/**
194
	 * Render widget
195
	 */
196
	public function render()
197
	{
198
		$this->beforeRender();
199
200
		// Render component template
201
		$this->template->render();
202
	}
203
204
	/**
205
	 * Convert widget name to string representation
206
	 *
207
	 * @return string
208
	 */
209
	public function __toString()
210
	{
211
		$class = explode('\\', get_class($this));
212
213
		return end($class);
214
	}
215
}
216