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

HasAcceptsMediaTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 68.18%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 17
c 2
b 1
f 0
dl 0
loc 47
ccs 15
cts 22
cp 0.6818
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A initHasAcceptsMediaEmpty() 0 4 1
A initHasAcceptsMedia() 0 8 2
A acceptsMedia() 0 5 1
A initHasAcceptsMediaWithValidation() 0 12 2
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