Completed
Push — master ( e43ea6...048027 )
by Adam
03:04
created

TEntityContainer::injectEntityManager()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
/**
3
 * TEntityContainer.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:Forms!
9
 * @subpackage     Forms
10
 * @since          1.0.0
11
 *
12
 * @date           10.01.16
13
 */
14
15
declare(strict_types = 1);
16
17
namespace IPub\Forms\Forms;
18
19
use Doctrine\ORM;
20
21
use Nette;
22
use Nette\Forms;
23
24
use IPub;
25
use IPub\Forms\Exceptions;
26
27
/**
28
 * Form trait for entity binding
29
 *
30
 * @package        iPublikuj:Forms!
31
 * @subpackage     Forms
32
 *
33
 * @author         Adam Kadlec <[email protected]>
34
 *
35
 * @method Nette\Application\UI\Form getForm($need = TRUE)
36
 * @method setValues($values, $erase = FALSE)
37
 */
38
trait TEntityContainer
39
{
40
	/**
41
	 * @var mixed
42
	 */
43
	private $entity;
44
45
	/**
46
	 * @param array|\Traversable $values
47
	 * @param bool $erase
48
	 */
49
	public function setDefaults($values, $erase = FALSE)
50
	{
51
		$form = $this->getForm(FALSE);
52
53
		if (!$form || !$form->isAnchored() || !$form->isSubmitted()) {
54
			if ($this->isEntity($values)) {
55
				$this->bindEntity($this, $values, $erase);
0 ignored issues
show
Bug introduced by
It seems like $values defined by parameter $values on line 49 can also be of type array; however, IPub\Forms\Forms\TEntityContainer::bindEntity() does only seem to accept object, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
56
57
			} else {
58
				$this->setValues($values, $erase);
59
			}
60
		}
61
	}
62
63
	/**
64
	 * @param mixed $entity
65
	 */
66
	public function setEntity($entity)
67
	{
68
		$this->entity = $entity;
69
70
		if (method_exists($entity, 'getId')) {
71
			$this->setId((string) $entity->getId());
0 ignored issues
show
Bug introduced by
It seems like setId() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
72
		}
73
	}
74
75
	/**
76
	 * @return mixed
77
	 */
78
	public function getEntity()
79
	{
80
		return $this->entity;
81
	}
82
83
	/**
84
	 * @param Nette\ComponentModel\Component $formElement
85
	 * @param object $entity
86
	 * @param bool $erase
87
	 *
88
	 * @throws Exceptions\InvalidArgumentException
89
	 */
90
	private function bindEntity($formElement, $entity, $erase)
91
	{
92
		$classMetadata = $this->getMetadata($entity);
93
94
		foreach (self::iterate($formElement) as $name => $component) {
0 ignored issues
show
Documentation introduced by
$formElement is of type object<Nette\ComponentModel\Component>, but the function expects a object<Nette\Forms\ICont...<Nette\Forms\Container>.

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...
95
			if ($component instanceof Forms\IControl) {
96
				if (($classMetadata->hasField($name) || $classMetadata->hasAssociation($name)) && $value = $classMetadata->getFieldValue($entity, $name)) {
97 View Code Duplication
					if (is_object($value) && $this->isEntity($value)) {
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...
98
						$UoW = $this->entityManager->getUnitOfWork();
0 ignored issues
show
Bug introduced by
The property entityManager does not seem to exist. Did you mean entity?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
99
						$value = $UoW->getSingleIdentifierValue($value);
100
101
						$component->setValue($value);
102
103
					} else {
104
						$component->setValue($value);
105
					}
106
107
				} else {
108
					$methodName = 'get' . ucfirst($name);
109
110
					if (method_exists($entity, $methodName) && $value = call_user_func([$entity, $methodName])) {
111 View Code Duplication
						if (is_object($value) && $this->isEntity($value)) {
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...
112
							$UoW = $this->entityManager->getUnitOfWork();
0 ignored issues
show
Bug introduced by
The property entityManager does not seem to exist. Did you mean entity?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
113
							$value = $UoW->getSingleIdentifierValue($value);
114
115
							$component->setValue($value);
116
117
						} else {
118
							$component->setValue($value);
119
						}
120
121
					} else {
122
						if ($erase) {
123
							$component->setValue(NULL);
124
						}
125
					}
126
				}
127
128
			} elseif ($component instanceof Forms\Container) {
129
				if (($classMetadata->hasField($name) || $classMetadata->hasAssociation($name)) && $value = $classMetadata->getFieldValue($entity, $name)) {
130 View Code Duplication
					if (is_object($value) && $this->isEntity($value)) {
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...
131
						$this->bindEntity($component, $value, $erase);
132
133
					} else {
134
						$component->setValues($value, $erase);
135
					}
136
137
				} else {
138
					$methodName = 'get' . ucfirst($name);
139
140
					if (method_exists($entity, $methodName) && $value = call_user_func([$entity, $methodName])) {
141 View Code Duplication
						if (is_object($value) && $this->isEntity($value)) {
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...
142
							$this->bindEntity($component, $value, $erase);
143
144
						} else {
145
							$component->setValues($value, $erase);
146
						}
147
148
					} else {
149
						if ($erase) {
150
							$component->setValues([], $erase);
151
						}
152
					}
153
				}
154
			}
155
		}
156
	}
157
158
	/**
159
	 * @param object $entity
160
	 *
161
	 * @return ORM\Mapping\ClassMetadata
162
	 *
163
	 * @throws Exceptions\InvalidArgumentException
164
	 */
165
	private function getMetadata($entity) : ORM\Mapping\ClassMetadata
166
	{
167
		if (!$this->isEntity($entity)) {
168
			throw new Exceptions\InvalidArgumentException(sprintf('Expected object, "%s" given.', gettype($entity)));
169
		}
170
171
		return $this->entityManager->getClassMetadata(get_class($entity));
0 ignored issues
show
Bug introduced by
The property entityManager does not seem to exist. Did you mean entity?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
172
	}
173
174
	/**
175
	 * @param mixed $entity
176
	 *
177
	 * @return bool
178
	 */
179
	private function isEntity($entity) : bool
180
	{
181
		return is_object($entity) && $this->entityManager->getMetadataFactory()->hasMetadataFor(get_class($entity));
0 ignored issues
show
Bug introduced by
The property entityManager does not seem to exist. Did you mean entity?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
182
	}
183
184
	/**
185
	 * @param Forms\IControl|Forms\Container $formElement
186
	 *
187
	 * @return array|\ArrayIterator
188
	 *
189
	 * @throws Exceptions\InvalidArgumentException
190
	 */
191
	private static function iterate($formElement)
192
	{
193
		if ($formElement instanceof Forms\Container) {
194
			return $formElement->getComponents();
195
196
		} elseif ($formElement instanceof Forms\IControl) {
197
			return [$formElement];
198
199
		} else {
200
			throw new Exceptions\InvalidArgumentException(sprintf('Expected Nette\Forms\Container or Nette\Forms\IControl, but "%s" given', get_class($formElement)));
201
		}
202
	}
203
}
204