Completed
Pull Request — master (#5)
by Dan Michael O.
01:25
created

Volume::getCover()   C

Complexity

Conditions 8
Paths 9

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 14
nc 9
nop 1
1
<?php
2
3
namespace Scriptotek\GoogleBooks;
4
5
class Volume extends Model
6
{
7
    protected static $coverSizes = [
8
        "extraLarge",
9
        "large",
10
        "medium",
11
        "small",
12
        "thumbnail",
13
        "smallThumbnail",
14
    ];
15
16
    /**
17
     * Provide a shortcut to data in 'volumeInfo', so  we can do `$volume->title`
18
     * instead of `$volume->volumeInfo->title`.
19
     *
20
     * @param  string  $key
21
     * @return mixed
22
     */
23
    public function __get($key)
24
    {
25
        return $this->get("volumeInfo.$key") ?: $this->get($key);
26
    }
27
28
    /**
29
     * Returns cover of size $preferredSize or smaller if a cover of size $preferredSize does not exist.
30
     *
31
     * @param string $preferredSize
32
     * @return mixed|null
33
     */
34
    public function getCover($preferredSize='extraLarge')
35
    {
36
        $url = null;
37
38
        if (!$this->has('volumeInfo.imageLinks')) {
39
            return null;
40
        }
41
42
        if ($this->isSearchResult() && !in_array($preferredSize, ['thumbnail', 'smallThumbnail'])) {
43
            // If we only have the brief record we got from search results, we should fetch the full one.
44
            $this->expandToFullRecord();
45
        }
46
47
        $idx = array_search($preferredSize, self::$coverSizes);
48
        if ($idx === false) {
49
            throw new \InvalidArgumentException('Invalid size: ' . $preferredSize);
50
        }
51
52
        foreach (self::$coverSizes as $n => $size) {
53
            if ($n >= $idx && $this->has("volumeInfo.imageLinks.{$size}")) {
54
                $url = $this->get("volumeInfo.imageLinks.{$size}");
55
                break;
56
            }
57
        }
58
59
        return $this->removeCoverEdge($url);
60
    }
61
62
    /**
63
     * Modify the URL to remove the cover edge.
64
     *
65
     * @param string $url
66
     * @return string
67
     */
68
    protected function removeCoverEdge($url) {
69
        if (is_null($url)) {
70
            return null;
71
        }
72
        return str_replace('&edge=curl', '&edge=none', $url);
73
    }
74
}
75