Completed
Push — master ( 7888b2...3ffd2a )
by Dan Michael O.
02:27
created

CachedImage::store()   C

Complexity

Conditions 7
Paths 14

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 31
rs 6.7272
cc 7
eloc 18
nc 14
nop 1
1
<?php
2
3
namespace Colligator;
4
5
use Intervention\Image\Image;
6
use Intervention\Image\ImageManager;
7
use League\Flysystem\AdapterInterface;
8
use League\Flysystem\Config as FlysystemConfig;
9
10
class CachedImage
11
{
12
    public $sourceUrl;
13
    public $maxHeight;
14
    protected $_metadata;
15
16
    public function __construct($url, $maxHeight = 0, AdapterInterface $filesystem = null, ImageManager $imageManager = null)
17
    {
18
        $this->sourceUrl = $url;
19
        $this->maxHeight = intval($maxHeight);
20
        $this->filesystem = $filesystem ?: \Storage::disk('s3')->getAdapter();
21
        $this->imageManager = $imageManager ?: app('Intervention\Image\ImageManager');
22
        $maxAge = 3153600; // 30 days
23
        $this->fsConfig = new FlysystemConfig([
24
            'CacheControl' => 'max-age=' . $maxAge . ', public',
25
        ]);
26
    }
27
28
    public function getMetadata()
29
    {
30
        if (is_null($this->_metadata)) {
31
            $data = $this->filesystem->read($this->basename());
32
            $contents = strval($data['contents']);
33
            $img = $this->imageManager->make($contents);
34
            $this->setMetadata($contents, $img);
35
        }
36
37
        return $this->_metadata;
38
    }
39
40
    protected function setMetadata($file, Image $img)
41
    {
42
        $this->_metadata = [
43
            'size'   => strlen($file),
44
            'width'  => $img->width(),
45
            'height' => $img->height(),
46
            'mime'   => $img->mime(),
47
        ];
48
    }
49
50
    public function width()
51
    {
52
        return $this->getMetadata()['width'];
53
    }
54
55
    public function height()
56
    {
57
        return $this->getMetadata()['height'];
58
    }
59
60
    public function mime()
61
    {
62
        return $this->getMetadata()['mime'];
63
    }
64
65
    public function size()
66
    {
67
        return $this->getMetadata()['size'];
68
    }
69
70
    public function basename()
71
    {
72
        return sha1($this->sourceUrl . $this->maxHeight);
73
    }
74
75
    /**
76
     * Retrieves the content of an URL.
77
     *
78
     * @return string
79
     */
80
    public function download()
81
    {
82
        // TODO: Use flysystem-http-downloader instead, but needs update
83
        // https://github.com/indigophp/flysystem-http-downloader/pull/2
84
        return file_get_contents($this->sourceUrl);
85
    }
86
87
    /**
88
     * Store a file in cache.
89
     *
90
     * @throws \ErrorException
91
     *
92
     * @return CachedImage
93
     */
94
    public function store($data = null)
95
    {
96
        if (is_null($data)) {
97
            $data = $this->download();
98
        }
99
        if (!$data) {
100
            throw new \ErrorException('[CoverCache] Failed to download ' . $this->sourceUrl);
101
        }
102
103
        $img = $this->imageManager->make($data);
104
        if ($this->maxHeight && $img->height() > $this->maxHeight) {
105
            \Log::debug('[CachedImage] Resizing from ' . $img->height() . ' to ' . $this->maxHeight);
106
            $img->heighten($this->maxHeight);
107
            $data = strval($img->encode('jpg'));
108
        }
109
110
        if ($img->width() / $img->height() > 1.4) {
111
            throw new \ErrorException('[CoverCache] Not accepting images with w/h ratio > 1.4: ' . $this->sourceUrl);
112
        }
113
114
        $this->setMetadata($data, $img);
115
116
        \Log::debug('[CachedImage] Storing image as ' . $img->width() . ' x ' . $img->height() . ', ' . strlen($data) . ' bytes');
117
        if (!$this->filesystem->write($this->basename(), $data, $this->fsConfig)) {
118
            throw new \ErrorException('[CoverCache] Failed to upload to S3: ' . $this->sourceUrl);
119
        }
120
121
        \Log::debug('[CachedImage] Wrote cached version of ' . $this->sourceUrl . ' as ' . $this->basename());
122
123
        return $this;
124
    }
125
126
    /**
127
     * Return a representation with height no more than $maxHeight.
128
     *
129
     * @param string $maxHeight
130
     *
131
     * @throws \ErrorException
132
     *
133
     * @return CachedImage
134
     */
135
    public function thumb($maxHeight)
136
    {
137
        return \CoverCache::put($this->sourceUrl, $maxHeight);
138
    }
139
}
140