Completed
Pull Request — master (#129)
by jelmer
05:00
created

AbstractImage::getAbsolutePath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
1
<?php
2
3
namespace SumoCoders\FrameworkCoreBundle\Entity;
4
5
use DateTime;
6
use Doctrine\ORM\Mapping as ORM;
7
use JsonSerializable;
8
use Symfony\Component\Validator\Constraints as Assert;
9
use Symfony\Component\HttpFoundation\File\UploadedFile;
10
11
/**
12
 * @ORM\MappedSuperclass
13
 * @ORM\HasLifecycleCallbacks
14
 */
15
abstract class AbstractImage implements JsonSerializable
16
{
17
    const FALLBACK_IMAGE = null;
18
19
    /**
20
     * @var int
21
     * @ORM\Id
22
     * @ORM\Column(type="integer")
23
     * @ORM\GeneratedValue(strategy="AUTO")
24
     */
25
    protected $id;
26
27
    /**
28
     * @var string
29
     * @ORM\Column(type="string", length=255, nullable=true)
30
     */
31
    protected $alt = null;
32
33
    /**
34
     * @var string
35
     * @ORM\Column(type="string", length=255, nullable=true)
36
     */
37
    protected $path = null;
38
39
    /**
40
     * @var UploadedFile
41
     * @Assert\File(
42
     *     maxSize = "5M",
43
     *     mimeTypes = {"image/jpeg", "image/gif", "image/png"},
44
     *     mimeTypesMessage = "file.invalid_mime_type"
45
     * )
46
     */
47
    private $file;
48
49
    /**
50
     * @var string
51
     */
52
    private $oldPath;
53
54
    /**
55
     * @var DateTime
56
     * @ORM\Column(type="datetime")
57
     */
58
    private $updatedAt;
59
60
    /**
61
     * @return int
62
     */
63
    public function getId()
64
    {
65
        return $this->id;
66
    }
67
68
    /**
69
     * @return string
70
     */
71
    public function getAlt()
72
    {
73
        return $this->alt;
74
    }
75
76
    /**
77
     * @return string
78
     */
79
    public function getPath()
80
    {
81
        return $this->path;
82
    }
83
84
    /**
85
     * @param string $alt
86
     *
87
     * @return self
88
     */
89
    public function setAlt($alt)
90
    {
91
        $this->alt = $alt;
92
93
        return $this;
94
    }
95
96
    /**
97
     * @return null|string
98
     */
99
    public function getAbsolutePath()
100
    {
101
        return $this->path === null
102
            ? null
103
            : $this->getUploadRootDir() . '/' . $this->path;
104
    }
105
106
    /**
107
     * @return null|string
108
     */
109
    public function getWebPath()
110
    {
111
        $file = $this->getAbsolutePath();
112
        if (is_file($file) && file_exists($file)) {
113
            return '/' . $this->getUploadDir() . '/' . $this->path;
114
        }
115
116
        return static::FALLBACK_IMAGE;
117
    }
118
119
    /**
120
     * @return string
121
     */
122
    protected function getUploadRootDir()
123
    {
124
        // the absolute directory path where uploaded
125
        // documents should be saved
126
        return __DIR__ . '/../../../../web/' . $this->getUploadDir();
127
    }
128
129
    /**
130
     * the dir in the web folder where the image needs to be uploaded.
131
     *
132
     * @return string
133
     */
134
    abstract protected function getUploadDir();
135
136
    /**
137
     * Sets file.
138
     *
139
     * @param UploadedFile $file
140
     */
141
    public function setFile(UploadedFile $file = null)
142
    {
143
        $this->updatedAt = new DateTime();
144
145
        $this->file = $file;
146
        // check if we have an old image path
147
        if (isset($this->path)) {
148
            // store the old name to delete after the update
149
            $this->oldPath = $this->path;
150
            $this->path = null;
151
        }
152
    }
153
154
    /**
155
     * Get file.
156
     *
157
     * @return UploadedFile
158
     */
159
    public function getFile()
160
    {
161
        return $this->file;
162
    }
163
164
    /**
165
     * @ORM\PrePersist()
166
     * @ORM\PreUpdate()
167
     */
168
    public function preUpload()
169
    {
170
        $this->updatedAt = new DateTime();
171
172
        if ($this->getFile() !== null) {
173
            // do whatever you want to generate a unique name
174
            $filename = sha1(uniqid(mt_rand(), true));
175
            $this->path = $filename . '.' . $this->getFile()->guessExtension();
176
        }
177
    }
178
179
    /**
180
     * @ORM\PostPersist()
181
     * @ORM\PostUpdate()
182
     */
183
    public function upload()
184
    {
185
        if ($this->getFile() === null) {
186
            return;
187
        }
188
189
        // if there is an error when moving the file, an exception will
190
        // be automatically thrown by move(). This will properly prevent
191
        // the entity from being persisted to the database on error
192
        $this->getFile()->move($this->getUploadRootDir(), $this->path);
193
194
        // check if we have an old image
195
        if (isset($this->oldPath)) {
196
            // delete the old image
197
            $oldFile = $this->getUploadRootDir() . '/' . $this->oldPath;
198
            if (is_file($oldFile) && file_exists($oldFile)) {
199
                unlink($oldFile);
200
            }
201
            // clear the $this->oldPath image path
202
            $this->oldPath = null;
203
        }
204
        $this->file = null;
205
    }
206
207
    /**
208
     * @ORM\PostRemove()
209
     */
210
    public function removeUpload()
211
    {
212
        $file = $this->getAbsolutePath();
213
        if (is_file($file) && file_exists($file)) {
214
            unlink($file);
215
        }
216
    }
217
218
    /**
219
     * Returns a string representation of the child.
220
     *
221
     * @return string
222
     */
223
    public function __toString()
224
    {
225
        return (string) $this->getWebPath();
226
    }
227
228
    /**
229
     * @return null|string
230
     */
231
    public function getFallbackImage()
232
    {
233
        return static::FALLBACK_IMAGE;
234
    }
235
236
    /**
237
     * {@inheritdoc}
238
     */
239
    public function jsonSerialize()
240
    {
241
        return [
242
            'url' => (string) $this->getWebPath(),
243
            'alt' => $this->getAlt(),
244
        ];
245
    }
246
}
247