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        return $result;
45    }
46
47    /** @inheritdoc */
48    protected function fetchData($id)
49    {
50        $http = new DokuHTTPClient();
51        $json = $http->get('https://www.googleapis.com/books/v1/volumes?q=isbn:' . $id);
52        if (!$json) throw new \Exception('Could not fetch data from Google Books. ' . $http->error);
53        $data = json_decode($json, true);
54        if (!isset($data['items'])) throw new \Exception('No ISBN results found at Google Books.');
55        return $data['items'][0]; // first entry
56    }
57}
58