1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @copyright Copyright (c) Flipbox Digital Limited |
5
|
|
|
* @license https://github.com/flipboxfactory/craft-element-lists/LICENSE |
6
|
|
|
* @link https://github.com/flipboxfactory/craft-element-lists/ |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace flipbox\craft\element\lists\actions\source; |
10
|
|
|
|
11
|
|
|
use Craft; |
12
|
|
|
use craft\base\Field; |
13
|
|
|
use flipbox\craft\ember\actions\ManageTrait; |
14
|
|
|
use flipbox\craft\ember\helpers\SiteHelper; |
15
|
|
|
use flipbox\craft\element\lists\actions\ResolverTrait; |
16
|
|
|
use flipbox\craft\element\lists\records\Association; |
17
|
|
|
use yii\base\Action; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @author Flipbox Factory <[email protected]> |
21
|
|
|
* @since 2.0.0 |
22
|
|
|
*/ |
23
|
|
|
class Associate extends Action |
24
|
|
|
{ |
25
|
|
|
use ManageTrait, |
26
|
|
|
ResolverTrait; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $field |
30
|
|
|
* @param string $source |
31
|
|
|
* @param string $target |
32
|
|
|
* @param int|null $siteId |
33
|
|
|
* @param int|null $sortOrder |
34
|
|
|
* @return mixed |
35
|
|
|
* @throws \yii\web\HttpException |
36
|
|
|
*/ |
37
|
|
|
public function run( |
38
|
|
|
string $field, |
39
|
|
|
string $source, |
40
|
|
|
string $target, |
41
|
|
|
int $siteId = null, |
42
|
|
|
int $sortOrder = null |
43
|
|
|
) { |
44
|
|
|
|
45
|
|
|
// Resolve |
46
|
|
|
$field = $this->resolveField($field); |
47
|
|
|
$source = $this->resolveElement($source); |
48
|
|
|
$target = $this->resolveElement($target); |
49
|
|
|
|
50
|
|
|
/** @var Field $field */ |
51
|
|
|
|
52
|
|
|
$siteId = $this->resolveSiteId($siteId ?: $source->siteId); |
53
|
|
|
|
54
|
|
|
$query = Association::find() |
55
|
|
|
->fieldId($field->id) |
56
|
|
|
->sourceId($source->getId() ?: false) |
57
|
|
|
->targetId($target->getId() ?: false); |
58
|
|
|
|
59
|
|
|
if ($siteId) { |
|
|
|
|
60
|
|
|
$query->siteId($siteId); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
if (!$record = $query->one()) { |
64
|
|
|
$record = new Association([ |
65
|
|
|
'fieldId' => $field->id, |
66
|
|
|
'sourceId' => $source->getId(), |
67
|
|
|
'targetId' => $target->getId(), |
68
|
|
|
'siteId' => $siteId |
69
|
|
|
]); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
if ($sortOrder) { |
73
|
|
|
$record->sortOrder = $sortOrder; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return $this->runInternal($record); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* @inheritdoc |
81
|
|
|
* @param Association $record |
82
|
|
|
* @throws \Exception |
83
|
|
|
*/ |
84
|
|
|
protected function performAction(Association $record): bool |
85
|
|
|
{ |
86
|
|
|
return $record->save(); |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
integer
values, zero is a special case, in particular the following results might be unexpected: