Passed
Push — master ( 9aef17...9e5266 )
by Gabriel
05:26
created

initHasAcceptsMediaWithValidation()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2.0078

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 2
eloc 7
nc 1
nop 0
dl 0
loc 12
ccs 7
cts 8
cp 0.875
crap 2.0078
rs 10
c 2
b 1
f 0
1
<?php
2
3
namespace ByTIC\MediaLibrary\Collections\Traits;
4
5
use ByTIC\MediaLibrary\Validation\Constraints\AbstractConstraint;
6
use ByTIC\MediaLibrary\Validation\Constraints\ConstraintInterface;
7
use ByTIC\MediaLibrary\Validation\Validators\AbstractValidator;
8
9
/**
10
 * Trait HasAcceptsMediaTrait.
11
 *
12
 * @method AbstractValidator getValidator();
13
 * @method ConstraintInterface|AbstractConstraint  getConstraint();
14
 */
15
trait HasAcceptsMediaTrait
16
{
17
    /** @var callable */
18
    public $acceptsMedia;
19
20 16
    protected function initHasAcceptsMedia()
21
    {
22 16
        if (method_exists($this, 'getValidator')) {
23 16
            $this->initHasAcceptsMediaWithValidation();
24
25 16
            return;
26
        }
27
        $this->initHasAcceptsMediaEmpty();
28
    }
29
30 16
    protected function initHasAcceptsMediaWithValidation()
31
    {
32 16
        $this->acceptsMedia(function ($file) {
33 2
            $validator = $this->getValidator();
34 2
            $constraint = $this->getConstraint();
35
36 2
            $violations = $validator->validate($file, $constraint);
37 2
            if ($violations->count() < 1) {
38 2
                return true;
39
            }
40
41
            return $violations;
42 16
        });
43 16
    }
44
45
    protected function initHasAcceptsMediaEmpty()
46
    {
47
        $this->acceptsMedia(function () {
48
            return true;
49
        });
50
    }
51
52
    /**
53
     * @param callable $acceptsFile
54
     *
55
     * @return HasAcceptsMediaTrait
56
     */
57 16
    public function acceptsMedia(callable $acceptsFile): self
58
    {
59 16
        $this->acceptsMedia = $acceptsFile;
60
61 16
        return $this;
62
    }
63
}
64