AmazonS3Resolver::isStored()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
/*
4
 * This file is part of the `liip/LiipImagineBundle` project.
5
 *
6
 * (c) https://github.com/liip/LiipImagineBundle/graphs/contributors
7
 *
8
 * For the full copyright and license information, please view the LICENSE.md
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Liip\ImagineBundle\Imagine\Cache\Resolver;
13
14
use Liip\ImagineBundle\Binary\BinaryInterface;
15
use Liip\ImagineBundle\Exception\Imagine\Cache\Resolver\NotStorableException;
16
use Psr\Log\LoggerInterface;
17
18
class AmazonS3Resolver implements ResolverInterface
19
{
20
    /**
21
     * @var \AmazonS3
22
     */
23
    protected $storage;
24
25
    /**
26
     * @var string
27
     */
28
    protected $bucket;
29
30
    /**
31
     * @var string
32
     */
33
    protected $acl;
34
35
    /**
36
     * @var array
37
     */
38
    protected $objUrlOptions;
39
40
    /**
41
     * @var LoggerInterface
42
     */
43
    protected $logger;
44
45
    /**
46
     * Constructs a cache resolver storing images on Amazon S3.
47
     *
48
     * @param \AmazonS3 $storage       The Amazon S3 storage API. It's required to know authentication information
49
     * @param string    $bucket        The bucket name to operate on
50
     * @param string    $acl           The ACL to use when storing new objects. Default: owner read/write, public read
51
     * @param array     $objUrlOptions A list of options to be passed when retrieving the object url from Amazon S3
52
     */
53
    public function __construct(\AmazonS3 $storage, $bucket, $acl = \AmazonS3::ACL_PUBLIC, array $objUrlOptions = [])
54
    {
55
        $this->storage = $storage;
56
        $this->bucket = $bucket;
57
        $this->acl = $acl;
58
        $this->objUrlOptions = $objUrlOptions;
59
    }
60
61
    public function setLogger(LoggerInterface $logger)
62
    {
63
        $this->logger = $logger;
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function isStored($path, $filter)
70
    {
71
        return $this->objectExists($this->getObjectPath($path, $filter));
72
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77
    public function resolve($path, $filter)
78
    {
79
        return $this->getObjectUrl($this->getObjectPath($path, $filter));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getObjectU...tPath($path, $filter)); (CFResponse) is incompatible with the return type declared by the interface Liip\ImagineBundle\Imagi...olverInterface::resolve of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    public function store(BinaryInterface $binary, $path, $filter)
86
    {
87
        $objectPath = $this->getObjectPath($path, $filter);
88
89
        $storageResponse = $this->storage->create_object($this->bucket, $objectPath, [
90
            'body' => $binary->getContent(),
91
            'contentType' => $binary->getMimeType(),
92
            'length' => mb_strlen($binary->getContent()),
93
            'acl' => $this->acl,
94
        ]);
95
96
        if (!$storageResponse->isOK()) {
97
            $this->logError('The object could not be created on Amazon S3.', [
98
                'objectPath' => $objectPath,
99
                'filter' => $filter,
100
                's3_response' => $storageResponse,
101
            ]);
102
103
            throw new NotStorableException('The object could not be created on Amazon S3.');
104
        }
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110
    public function remove(array $paths, array $filters)
111
    {
112
        if (empty($paths) && empty($filters)) {
113
            return;
114
        }
115
116
        if (empty($paths)) {
117
            if (!$this->storage->delete_all_objects($this->bucket, sprintf('/%s/i', implode('|', $filters)))) {
118
                $this->logError('The objects could not be deleted from Amazon S3.', [
119
                    'filters' => implode(', ', $filters),
120
                    'bucket' => $this->bucket,
121
                ]);
122
            }
123
124
            return;
125
        }
126
127
        foreach ($filters as $filter) {
128
            foreach ($paths as $path) {
129
                $objectPath = $this->getObjectPath($path, $filter);
130
                if (!$this->objectExists($objectPath)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->objectExists($objectPath) of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
131
                    continue;
132
                }
133
134
                if (!$this->storage->delete_object($this->bucket, $objectPath)->isOK()) {
135
                    $this->logError('The objects could not be deleted from Amazon S3.', [
136
                        'filter' => $filter,
137
                        'bucket' => $this->bucket,
138
                        'path' => $path,
139
                    ]);
140
                }
141
            }
142
        }
143
    }
144
145
    /**
146
     * Sets a single option to be passed when retrieving an objects URL.
147
     *
148
     * If the option is already set, it will be overwritten.
149
     *
150
     * @see \AmazonS3::get_object_url() for available options
151
     *
152
     * @param string $key   The name of the option
153
     * @param mixed  $value The value to be set
154
     *
155
     * @return AmazonS3Resolver $this
156
     */
157
    public function setObjectUrlOption($key, $value)
158
    {
159
        $this->objUrlOptions[$key] = $value;
160
161
        return $this;
162
    }
163
164
    /**
165
     * Returns the object path within the bucket.
166
     *
167
     * @param string $path   The base path of the resource
168
     * @param string $filter The name of the imagine filter in effect
169
     *
170
     * @return string The path of the object on S3
171
     */
172
    protected function getObjectPath($path, $filter)
173
    {
174
        return str_replace('//', '/', $filter.'/'.$path);
175
    }
176
177
    /**
178
     * Returns the URL for an object saved on Amazon S3.
179
     *
180
     * @param string $path
181
     *
182
     * @return string
183
     */
184
    protected function getObjectUrl($path)
185
    {
186
        return $this->storage->get_object_url($this->bucket, $path, 0, $this->objUrlOptions);
187
    }
188
189
    /**
190
     * Checks whether an object exists.
191
     *
192
     * @param string $objectPath
193
     *
194
     * @throws \S3_Exception
195
     *
196
     * @return bool
197
     */
198
    protected function objectExists($objectPath)
199
    {
200
        return $this->storage->if_object_exists($this->bucket, $objectPath);
201
    }
202
203
    /**
204
     * @param mixed $message
205
     */
206
    protected function logError($message, array $context = [])
207
    {
208
        if ($this->logger) {
209
            $this->logger->error($message, $context);
210
        }
211
    }
212
}
213