Completed
Push — 1.1 ( d166b0...e7f438 )
by Patrick
11:31 queued 07:46
created

UploadableFile::enable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
1
<?php
2
3
namespace LaravelDoctrine\Fluent\Extensions\Gedmo;
4
5
use Gedmo\Exception\InvalidMappingException;
6
use Gedmo\Uploadable\Mapping\Driver\Fluent as UploadableDriver;
7
use LaravelDoctrine\Fluent\Buildable;
8
use LaravelDoctrine\Fluent\Builders\Field;
9
use LaravelDoctrine\Fluent\Extensions\ExtensibleClassMetadata;
10
11
class UploadableFile implements Buildable
12
{
13
    /**
14
     * @var ExtensibleClassMetadata
15
     */
16
    private $classMetadata;
17
18
    /**
19
     * @var string
20
     */
21
    private $fieldName;
22
23
    /**
24
     * @var string
25
     */
26
    private $type;
27
28
    /**
29
     * @var array
30
     */
31
    private static $validTypes = ['Path', 'Name', 'Size', 'MimeType'];
32
33
    /**
34
     * UploadableFile constructor.
35
     *
36
     * @param ExtensibleClassMetadata $classMetadata
37
     * @param string                  $fieldName
38
     * @param string                  $type
39
     */
40
    public function __construct(ExtensibleClassMetadata $classMetadata, $fieldName, $type = 'Name')
41
    {
42
        $this->validateType($type);
43
44
        $this->classMetadata = $classMetadata;
45
        $this->fieldName     = $fieldName;
46
        $this->type          = "file{$type}Field";
47
    }
48
49
    /**
50
     * Enable the UploadableFile extension.
51
     *
52
     * @return void
53
     */
54
    public static function enable()
55
    {
56
        foreach (self::$validTypes as $type) {
57
            Field::macro("asFile$type", function (Field $builder) use ($type) {
58
                return new static($builder->getClassMetadata(), $builder->getName(), $type);
59
            });
60
        }
61
    }
62
63
    /**
64
     * Execute the build process
65
     */
66
    public function build()
67
    {
68
        $this->classMetadata->appendExtension(UploadableDriver::EXTENSION_NAME, [
69
            $this->type => $this->fieldName,
70
        ]);
71
    }
72
73
    /**
74
     * Validate the given type of file field.
75
     *
76
     * @param string $type
77
     *
78
     * @return void
79
     */
80
    private function validateType($type)
81
    {
82
        if (!in_array($type, self::$validTypes)) {
83
            throw new InvalidMappingException(
84
                'Invalid uploadable field type reference. Must be one of: ' . implode(', ', self::$validTypes)
85
            );
86
        }
87
    }
88
}
89