xref: /plugin/doi/Resolver/IsbnOpenLibraryResolver.php (revision 17101be411563598a3f2f83cf104a5211ddaee03)
1307c6980SAndreas Gohr<?php
2307c6980SAndreas Gohr
3307c6980SAndreas Gohrnamespace dokuwiki\plugin\doi\Resolver;
4307c6980SAndreas Gohr
5307c6980SAndreas Gohruse dokuwiki\HTTP\DokuHTTPClient;
6307c6980SAndreas Gohr
7307c6980SAndreas Gohr/**
8307c6980SAndreas Gohr * ISBN resolver using the Open Library API
9307c6980SAndreas Gohr */
10307c6980SAndreas Gohrclass IsbnOpenLibraryResolver extends AbstractIsbnResolver
11307c6980SAndreas Gohr{
12307c6980SAndreas Gohr    /** @inheritdoc */
13307c6980SAndreas Gohr    public function getData($id)
14307c6980SAndreas Gohr    {
15307c6980SAndreas Gohr        $message = $this->fetchCachedData($id);
16307c6980SAndreas Gohr        $result = $this->defaultResult;
17307c6980SAndreas Gohr
18307c6980SAndreas Gohr        $result['url'] = $message['info_url'];
19*17101be4SAndreas Gohr        $result['image'] = $message['thumbnail_url'] ?? '';
20307c6980SAndreas Gohr        $message = $message['details'];
21307c6980SAndreas Gohr
22307c6980SAndreas Gohr        $result['id'] = $message['isbn_13'][0] ?? $message['isbn_10'][0] ?? '';
23307c6980SAndreas Gohr        $result['title'] = $message['full_title'] ?? $message['title'] ?? $id;
249f8980aeSAndreas Gohr        if(empty($result['title'])) $result['title'] = $id;
25307c6980SAndreas Gohr
26307c6980SAndreas Gohr        $result['authors'] = array_map(function ($author) {
27307c6980SAndreas Gohr            return $author['name'];
28307c6980SAndreas Gohr        }, $message['authors'] ?? []);
29307c6980SAndreas Gohr
30307c6980SAndreas Gohr        $published = $message['publish_date'] ?? '';
31307c6980SAndreas Gohr        if (preg_match('/\b(\d{4})\b/', $published, $m)) {
32307c6980SAndreas Gohr            $result['published'] = $m[1];
33307c6980SAndreas Gohr        }
34307c6980SAndreas Gohr        $result['publisher'] = $message['publishers'][0] ?? '';
35307c6980SAndreas Gohr
36307c6980SAndreas Gohr        return $result;
37307c6980SAndreas Gohr    }
38307c6980SAndreas Gohr
39307c6980SAndreas Gohr    /** @inheritdoc */
40307c6980SAndreas Gohr    protected function fetchData($id)
41307c6980SAndreas Gohr    {
42307c6980SAndreas Gohr        $http = new DokuHTTPClient();
43307c6980SAndreas Gohr        $json = $http->get('https://openlibrary.org/api/books?jscmd=details&format=json&bibkeys=ISBN:' . $id);
44307c6980SAndreas Gohr        if (!$json) throw new \Exception('Could not fetch data from Open Library. ' . $http->error);
45307c6980SAndreas Gohr        $data = json_decode($json, true);
46307c6980SAndreas Gohr        if (!count($data)) throw new \Exception('No ISBN results found at Open Library.');
47307c6980SAndreas Gohr        return array_shift($data); // first entry
48307c6980SAndreas Gohr    }
49307c6980SAndreas Gohr}
50