Issues (35)

src/Traits/CMSNicetiesTraitForValidation.php (1 issue)

1
<?php
2
3
namespace Sunnysideup\CMSNiceties\Traits;
4
5
use SilverStripe\ORM\ValidationResult;
6
7
// use SilverStripe\Forms\GridField\GridFieldArchiveAction;
8
9
trait CMSNicetiesTraitForValidation
10
{
11
    public function validateForUniqueValues(ValidationResult $result): ValidationResult
12
    {
13
        foreach ($this->Config()->get('indexes') as $index) {
0 ignored issues
show
It seems like Config() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

13
        foreach ($this->/** @scrutinizer ignore-call */ Config()->get('indexes') as $index) {
Loading history...
14
            $isUniqueEntry = isset($index['type']) && 'unique' === $index['type'];
15
            if ($isUniqueEntry) {
16
                $fields = $index['columns'] ?? [];
17
                if (count($fields) > 0) {
18
                    $filter = [];
19
                    foreach ($fields as $field) {
20
                        $filter[$field] = $this->{$field};
21
                    }
22
23
                    $id = (empty($this->ID) ? 0 : $this->ID);
24
                    // https://stackoverflow.com/questions/63227834/return-self-for-the-return-type-of-a-function-inside-a-php-trait
25
                    $exists = self::get()
26
                        ->filter($filter)
27
                        ->exclude(['ID' => $id])
28
                        ->exists()
29
                    ;
30
                    if ($exists) {
31
                        $result->addError(
32
                            _t(
33
                                self::class . '.' . $index['type'] . '_UNIQUE',
34
                                $index['type'] . ' needs to be unique'
35
                            ),
36
                            'UNIQUE_' . self::class . '.' . implode('_', $fields)
37
                        );
38
                    }
39
                }
40
            }
41
        }
42
43
        return $result;
44
    }
45
}
46