1+ <?php
2+
3+ namespace App \Jobs ;
4+
5+ use App \Models \Article ;
6+ use Illuminate \Contracts \Queue \ShouldQueue ;
7+ use Illuminate \Foundation \Bus \Dispatchable ;
8+ use Illuminate \Foundation \Queue \Queueable ;
9+ use Illuminate \Queue \InteractsWithQueue ;
10+ use Illuminate \Queue \SerializesModels ;
11+ use Illuminate \Support \Facades \Http ;
12+
13+ final class SyncArticleImage implements ShouldQueue
14+ {
15+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
16+
17+ public function __construct (public Article $ article )
18+ {
19+ //
20+ }
21+
22+ public function handle (): void
23+ {
24+ $ imageData = $ this ->fetchUnsplashImageDataFromId ($ this ->article );
25+
26+ if (! is_null ($ imageData )) {
27+ $ this ->article ->hero_image_url = $ imageData ['image_url ' ];
28+ $ this ->article ->hero_image_author_name = $ imageData ['author_name ' ];
29+ $ this ->article ->hero_image_author_url = $ imageData ['author_url ' ];
30+ $ this ->article ->save ();
31+ }
32+ }
33+
34+ protected function fetchUnsplashImageDataFromId (Article $ article ): ?array
35+ {
36+ $ response = Http::retry (3 , 100 , throw: false )
37+ ->withToken (config ('services.unsplash.access_key ' ), 'Client-ID ' )
38+ ->get ("https://api.unsplash.com/photos/ {$ article ->hero_image_id }" );
39+
40+ if ($ response ->failed ()) {
41+ $ article ->hero_image_id = null ;
42+ $ article ->save ();
43+
44+ return null ;
45+ }
46+
47+ $ response = $ response ->json ();
48+
49+ // Trigger as Unsplash download...
50+ Http::retry (3 , 100 , throw: false )
51+ ->withToken (config ('services.unsplash.access_key ' ), 'Client-ID ' )
52+ ->get ($ response ['links ' ]['download_location ' ]);
53+
54+ return [
55+ 'image_url ' => $ response ['urls ' ]['raw ' ],
56+ 'author_name ' => $ response ['user ' ]['name ' ],
57+ 'author_url ' => $ response ['user ' ]['links ' ]['html ' ],
58+ ];
59+ }
60+ }
0 commit comments