1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This software package is licensed under AGPL or Commercial license. |
5
|
|
|
* |
6
|
|
|
* @package maslosoft/mangan |
7
|
|
|
* @licence AGPL or Commercial |
8
|
|
|
* @copyright Copyright (c) Piotr Masełkowski <[email protected]> |
9
|
|
|
* @copyright Copyright (c) Maslosoft |
10
|
|
|
* @copyright Copyright (c) Others as mentioned in code |
11
|
|
|
* @link https://maslosoft.com/mangan/ |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Maslosoft\Mangan\Helpers; |
15
|
|
|
|
16
|
|
|
use Maslosoft\Addendum\Interfaces\AnnotatedInterface; |
17
|
|
|
use Maslosoft\Mangan\EntityManager; |
18
|
|
|
use Maslosoft\Mangan\Finder; |
19
|
|
|
use Maslosoft\Mangan\Helpers\PkManager; |
20
|
|
|
use Maslosoft\Mangan\Model\DbRef; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Helper class for db refs |
24
|
|
|
* |
25
|
|
|
* @internal |
26
|
|
|
* @author Piotr Maselkowski <pmaselkowski at gmail.com> |
27
|
|
|
*/ |
28
|
|
|
class DbRefManager |
29
|
|
|
{ |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Extract minimum set of data to create db reference |
33
|
|
|
* @param AnnotatedInterface $model |
34
|
|
|
* @param string $field |
35
|
|
|
* @param AnnotatedInterface $referenced |
36
|
|
|
* @return DbRef |
37
|
|
|
*/ |
38
|
13 |
|
public static function extractRef(AnnotatedInterface $model, $field, AnnotatedInterface $referenced = null) |
39
|
|
|
{ |
40
|
13 |
|
if (null === $referenced) |
41
|
|
|
{ |
42
|
8 |
|
$referenced = $model->$field; |
43
|
|
|
} |
44
|
13 |
|
$dbRef = new DbRef(); |
45
|
13 |
|
$dbRef->pk = PkManager::getFromModel($referenced); |
46
|
13 |
|
$dbRef->class = get_class($referenced); |
47
|
13 |
|
return $dbRef; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public static function createInstanceFrom(DbRef $dbRef) |
51
|
|
|
{ |
52
|
|
|
return (new Finder($dbRef->class))->findByPk($dbRef->pk); |
|
|
|
|
53
|
|
|
} |
54
|
|
|
|
55
|
21 |
|
public static function maybeCreateInstanceFrom($dbRef) |
56
|
|
|
{ |
57
|
21 |
|
if($dbRef instanceof DbRef) |
58
|
|
|
{ |
59
|
|
|
return (new Finder(new $dbRef->class))->findByPk($dbRef->pk); |
60
|
|
|
} |
61
|
21 |
|
return $dbRef; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Save referenced model |
66
|
|
|
* @param AnnotatedInterface $referenced |
67
|
|
|
* @param DbRef $dbRef |
68
|
|
|
*/ |
69
|
8 |
|
public static function save(AnnotatedInterface $referenced, DbRef $dbRef) |
70
|
|
|
{ |
71
|
|
|
// Ensure ref is same as referenced model |
72
|
8 |
|
PkManager::applyToModel($referenced, $dbRef->pk); |
73
|
8 |
|
$em = new EntityManager($referenced); |
74
|
8 |
|
$em->save(); |
75
|
8 |
|
} |
76
|
|
|
|
77
|
|
|
} |
78
|
|
|
|
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: