This repository has been archived by the owner on Apr 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FetchCommand.php
110 lines (89 loc) · 2.78 KB
/
FetchCommand.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
use GuzzleHttp\Client;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
*
*/
class FetchCommand extends Command
{
public function configure()
{
$this->setName('crossref:fetch')
->addArgument('output')
->setDescription('Fetch all journal article metadata from Crossref');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$outputFile = $input->getArgument('output');
$outputHandle = fopen($outputFile, 'w');
$client = new Client([
//'debug' => true
]);
$headers = [
'Accept' => 'application/json',
'Accept-Encoding' => 'gzip,deflate',
'User-Agent' => 'crossref-dois/0.1 (+https://github.com/hubgit/crossref-dois/)',
];
// https://api.crossref.org/works?filter=type:journal-article&cursor=*
$filters = [
'type' => 'journal-article'
];
$filter = implode(',', array_map(function ($key) use ($filters) {
return $key . ':' . $filters[$key];
}, array_keys($filters)));
$params = [
'filter' => $filter,
'cursor' => '*',
'rows' => 1000,
];
$progress = new ProgressBar($output);
$progressStarted = false;
do {
$response = $client->get('https://api.crossref.org/works', [
//'debug' => true,
'connect_timeout' => 10,
'timeout' => 120,
'query' => $params,
'headers' => $headers,
]);
$data = json_decode($response->getBody(), true);
if (!$progressStarted) {
$progress->start($data['message']['total-results']);
$progressStarted = true;
}
$items = $this->parseResponse($data);
foreach ($items as $item) {
fwrite($outputHandle, json_encode($item) . "\n");
}
$params['cursor'] = $data['message']['next-cursor'];
$progress->advance(count($items));
} while ($params['cursor']);
$progress->finish();
}
/**
* @param array $data
*
* @throws Exception
*
* @return array
*/
private function parseResponse(array $data)
{
if (!$data) {
throw new \Exception('No data');
}
if ($data['status'] !== 'ok') {
throw new \Exception('Not ok');
}
return $data['message']['items'];
}
}