-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathUniqueCustomFieldValue.php
More file actions
81 lines (64 loc) · 2.65 KB
/
UniqueCustomFieldValue.php
File metadata and controls
81 lines (64 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
declare(strict_types=1);
namespace Relaticle\CustomFields\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Relations\Relation;
use Relaticle\CustomFields\CustomFields;
use Relaticle\CustomFields\Enums\CustomFieldsFeature;
use Relaticle\CustomFields\FeatureSystem\FeatureManager;
use Relaticle\CustomFields\FieldTypeSystem\FieldManager;
use Relaticle\CustomFields\Models\CustomField;
use Relaticle\CustomFields\Services\TenantContextService;
final class UniqueCustomFieldValue implements ValidationRule
{
public function __construct(
private readonly CustomField $customField,
private readonly string|int|null $ignoreEntityId = null,
) {}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (blank($value)) {
return;
}
$values = is_array($value) ? $value : [$value];
$fieldType = app(FieldManager::class)->getFieldTypeInstance($this->customField->type);
foreach ($values as $singleValue) {
if (blank($singleValue)) {
continue;
}
$normalizedValue = $fieldType
? $fieldType->setValue((string) $singleValue)
: (string) $singleValue;
if ($this->existsOnAnotherEntity($normalizedValue)) {
$fail(__('custom-fields::custom-fields.validation.unique_value', [
'value' => $singleValue,
]));
return;
}
}
}
private function existsOnAnotherEntity(string $normalizedValue): bool
{
$valueModel = CustomFields::newValueModel();
$valueColumn = $this->customField->getValueColumn();
$entityType = $this->customField->entity_type;
$morphAlias = Relation::getMorphAlias($entityType) ?? (new $entityType)->getMorphClass();
$query = $valueModel->newQuery()
->where('custom_field_id', $this->customField->getKey())
->where('entity_type', $morphAlias);
if ($valueColumn === 'json_value') {
$query->whereJsonContains('json_value', $normalizedValue);
} else {
$query->where($valueColumn, $normalizedValue);
}
if (FeatureManager::isEnabled(CustomFieldsFeature::SYSTEM_MULTI_TENANCY)) {
$tenantFk = config('custom-fields.database.column_names.tenant_foreign_key');
$query->where($tenantFk, TenantContextService::getCurrentTenantId());
}
if ($this->ignoreEntityId !== null) {
$query->where('entity_id', '!=', $this->ignoreEntityId);
}
return $query->exists();
}
}