ImageUploader   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 8
c 2
b 0
f 1
lcom 1
cbo 1
dl 0
loc 61
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A remove() 0 4 1
B upload() 0 23 5
A expandPath() 0 9 1
1
<?php
2
3
namespace DoS\ResourceBundle\Uploader;
4
5
use Gaufrette\Filesystem;
6
use DoS\ResourceBundle\Model\ImageInterface;
7
8
class ImageUploader implements ImageUploaderInterface
9
{
10
    protected $filesystem;
11
12
    public function __construct(Filesystem $filesystem)
13
    {
14
        $this->filesystem = $filesystem;
15
    }
16
17
    /**
18
     * @param ImageInterface $image
19
     */
20
    public function upload(ImageInterface $image)
21
    {
22
        if (!$image->hasFile()) {
23
            return;
24
        }
25
26
        // remove older path
27
        if (null !== $image->getPath() && $this->filesystem->has($image->getPath())) {
28
            $this->remove($image->getPath());
29
        }
30
31
        do {
32
            $hash = md5(uniqid(mt_rand(), true));
33
            $path = $this->expandPath($hash.'.'.$image->getFile()->getExtension());
34
        } while ($this->filesystem->has($path));
35
36
        $image->setPath($path);
37
38
        $this->filesystem->write(
39
            $image->getPath(),
40
            file_get_contents($image->getFile()->getPathname())
41
        );
42
    }
43
44
    /**
45
     * @param $path
46
     *
47
     * @return bool
48
     */
49
    public function remove($path)
50
    {
51
        return $this->filesystem->delete($path);
52
    }
53
54
    /**
55
     * @param $path
56
     *
57
     * @return string
58
     */
59
    private function expandPath($path)
60
    {
61
        return sprintf(
62
            '%s/%s/%s',
63
            substr($path, 0, 2),
64
            substr($path, 2, 2),
65
            substr($path, 4)
66
        );
67
    }
68
}
69