Completed
Push — master ( a81ea2...e23c5c )
by Gabriel
03:24
created

HasAcceptsMediaTrait::initHasAcceptsMedia()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 8
ccs 4
cts 5
cp 0.8
crap 2.032
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 13
    protected function initHasAcceptsMedia()
21
    {
22 13
        if (method_exists($this, 'getValidator')) {
23 13
            $this->initHasAcceptsMediaWithValidation();
24
25 13
            return;
26
        }
27
        $this->initHasAcceptsMediaEmpty();
28
    }
29
30 13
    protected function initHasAcceptsMediaWithValidation()
31
    {
32
        $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 13
        });
43 13
    }
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 13
    public function acceptsMedia(callable $acceptsFile): self
58
    {
59 13
        $this->acceptsMedia = $acceptsFile;
60
61 13
        return $this;
62
    }
63
}
64