Completed
Push — master ( 3e2e82...d39141 )
by Mark
01:15
created

Unsplash::toArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace MarkSitko\LaravelUnsplash;
4
5
use Exception;
6
use Illuminate\Support\Facades\Storage;
7
use Illuminate\Support\Str;
8
use MarkSitko\LaravelUnsplash\API\UnsplashAPI;
9
use MarkSitko\LaravelUnsplash\Http\HttpClient;
10
use MarkSitko\LaravelUnsplash\Models\UnsplashAsset;
11
12
class Unsplash extends HttpClient
13
{
14
    use UnsplashAPI;
15
16
    /**
17
     * Accepted url keys from response.
18
     */
19
    const PHOTO_KEYS = [
20
        'raw',
21
        'full',
22
        'regular',
23
        'small',
24
        'thumb',
25
    ];
26
27
    /**
28
     * Storage disk to store photos.
29
     */
30
    protected $storage;
31
32
    /**
33
     * Guzzle response.
34
     */
35
    protected $response;
36
37
    /**
38
     * Storage disk to store photos.
39
     */
40
    protected $storeInDatabase;
41
42
    /**
43
     * Creates a new instance of Unsplash.
44
     *
45
     * @return MarkSitko\LaravelUnsplash\Unsplash
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
46
     */
47
    public function __construct()
48
    {
49
        parent::__construct();
50
51
        $this->initalizeConfiguration();
52
53
        return $this;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
54
    }
55
56
    /**
57
     * Checks if the accessed property exists as a method
58
     * if exists, call the get() method and return the complete response.
59
     */
60
    public function __get($param)
61
    {
62
        if (method_exists($this, $param)) {
63
            return $this->$param()->get();
64
        }
65
    }
66
67
    /**
68
     * Returns the full http response.
69
     *
70
     * @return GuzzleHttp\Psr7\Response
71
     */
72
    public function get()
73
    {
74
        $this->buildResponse();
75
76
        return $this->response;
77
    }
78
79
    /**
80
     * Returns the http response body.
81
     *
82
     * @return object
83
     */
84
    public function toJson()
85
    {
86
        $this->buildResponse();
87
88
        return json_decode($this->response->getBody()->getContents());
89
    }
90
91
    /**
92
     * Returns the http response body.
93
     *
94
     * @return array
95
     */
96
    public function toArray()
97
    {
98
        $this->buildResponse();
99
100
        return json_decode($this->response->getBody()->getContents(), true);
101
    }
102
103
    /**
104
     * Returns the http response body as collection.
105
     *
106
     * @return \Illuminate\Support\Collection
107
     */
108
    public function toCollection()
109
    {
110
        $this->buildResponse();
111
112
        return collect(json_decode($this->response->getBody()->getContents(), true));
113
    }
114
115
    /**
116
     * Stores the retrieving photo in the storage.
117
     *
118
     * @param string $name If no name is provided, a random 24 Charachter name will be generated
119
     * @param string $key  Defines the size of the retrieving photo
120
     *
121
     * @return string The stored photo name
122
     */
123
    public function store($name = null, $key = 'small')
124
    {
125
        $response = $this->toArray();
126
        if (!array_key_exists('urls', $response)) {
127
            throw new Exception('Photo can not be stored. Certainly the "urls" key is missing or you try to store an photo while retrieving multiple photos.');
128
        }
129
130
        if (!in_array($key, self::PHOTO_KEYS)) {
131
            throw new Exception("Your provided key \"{$key}\" is an undefined accessor.");
132
        }
133
134
        $name = $name ?? Str::random(24);
135
        $image = file_get_contents($response['urls'][$key]);
136
137
        while ($this->storage->exists("{$name}.jpg")) {
138
            $name = Str::random(24);
139
        }
140
141
        $this->storage->put("{$name}.jpg", $image);
142
143
        if ($this->storeInDatabase) {
144
            return UnsplashAsset::create([
145
                'unsplash_id' => $response['id'],
146
                'name' => "{$name}.jpg",
147
                'author' => $response['user']['name'],
148
                'author_link' => $response['user']['links']['html'],
149
            ]);
150
        }
151
152
        return $name;
153
    }
154
155
    /**
156
     * Builds the http request.
157
     *
158
     * @return MarkSitko\LaravelUnsplash\Unsplash
159
     */
160
    protected function buildResponse()
161
    {
162
        $verb = $this->apiCall['verb'] ?? 'get';
163
        $this->response = $this->client->$verb("{$this->apiCall['endpoint']}?{$this->getQuery()}");
164
165
        return $this;
166
    }
167
168
    /**
169
     * Initalize storage.
170
     *
171
     * @return MarkSitko\LaravelUnsplash\Unsplash
172
     */
173
    private function initalizeConfiguration()
0 ignored issues
show
Bug introduced by
Consider using a different method name as you override a private method of the parent class.

Overwriting private methods is generally fine as long as you also use private visibility. It might still be preferable for understandability to use a different method name.

Loading history...
174
    {
175
        $this->storage = Storage::disk(config('unsplash.disk', 'local'));
176
        $this->storeInDatabase = config('unsplash.store_in_database', false);
177
178
        return $this;
179
    }
180
}
181