1<?php
2
3namespace dokuwiki\plugin\doi\Resolver;
4
5use dokuwiki\HTTP\DokuHTTPClient;
6
7/**
8 * ISBN resolver using Google Books API
9 */
10class IsbnGoogleBooksResolver extends AbstractIsbnResolver
11{
12
13    /** @inheritdoc */
14    public function getData($id)
15    {
16        $data = $this->fetchCachedData($id);
17        $data = $data['volumeInfo'];
18        $result = $this->defaultResult;
19
20        $result['url'] = $data['canonicalVolumeLink'];
21        foreach ($data['industryIdentifiers'] as $identifier) {
22            if ($identifier['type'] === 'ISBN_13') {
23                $result['id'] = $identifier['identifier'];
24                break;
25            }
26            if ($identifier['type'] === 'ISBN_10') {
27                $result['id'] = $identifier['identifier'];
28            }
29        }
30
31        $result['title'] = $data['title'];
32        if (isset($data['subtitle'])) $result['title'] .= ': ' . $data['subtitle'];
33        if(empty($result['title'])) $result['title'] = $id;
34
35        $result['authors'] = $data['authors'] ?? [];
36
37        $published = $data['publishedDate'] ?? '';
38        if (preg_match('/\b(\d{4})\b/', $published, $m)) {
39            $result['published'] = $m[1];
40        }
41
42        $result['publisher'] = $data['publisher'] ?? '';
43
44        $result['image'] = $data['imageLinks']['thumbnail'] ?? '';
45
46        if($result['image']) {
47            $result['image'] .= '?.jpg'; // force jpg extension
48        }
49
50        return $result;
51    }
52
53    /** @inheritdoc */
54    protected function fetchData($id)
55    {
56        $http = new DokuHTTPClient();
57        $json = $http->get('https://www.googleapis.com/books/v1/volumes?q=isbn:' . $id);
58        if (!$json) throw new \Exception('Could not fetch data from Google Books. ' . $http->error);
59        $data = json_decode($json, true);
60        if (!isset($data['items'])) throw new \Exception('No ISBN results found at Google Books.');
61        return $data['items'][0]; // first entry
62    }
63}
64