xref: /plugin/doi/Resolver/IsbnGoogleBooksResolver.php (revision 307c69801b7d8b027f4d0b7119b53e92e2931cb6)
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
34        $result['authors'] = $data['authors'] ?? [];
35
36        $published = $data['publishedDate'] ?? '';
37        if (preg_match('/\b(\d{4})\b/', $published, $m)) {
38            $result['published'] = $m[1];
39        }
40
41        $result['publisher'] = $data['publisher'] ?? '';
42
43        return $result;
44    }
45
46    /** @inheritdoc */
47    protected function fetchData($id)
48    {
49        $http = new DokuHTTPClient();
50        $json = $http->get('https://www.googleapis.com/books/v1/volumes?q=isbn:' . $id);
51        if (!$json) throw new \Exception('Could not fetch data from Google Books. ' . $http->error);
52        $data = json_decode($json, true);
53        if (!isset($data['items'])) throw new \Exception('No ISBN results found at Google Books.');
54        return $data['items'][0]; // first entry
55    }
56}
57