Repository navigation
Expand file tree
/
Copy pathRunSpiderCommand.php
More file actions
196 lines (155 loc) · 6.57 KB
/
Copy pathRunSpiderCommand.php
File metadata and controls
196 lines (155 loc) · 6.57 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
<?php
declare(strict_types=1);
/*
* Copyright (c) 2022 Ne-Lexa <alexey@nelexa.ru>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* @see https://github.com/Ne-Lexa/roach-php-bundle
*/
namespace Nelexa\RoachPhpBundle\Command;
use RoachPHP\Roach;
use RoachPHP\Spider\Configuration\Overrides;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\OutputStyle;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\SerializerInterface;
final class RunSpiderCommand extends Command
{
/** @var array<class-string<\RoachPHP\Spider\SpiderInterface>, array<string>> */
private array $spiderNames;
public function __construct(private ServiceLocator $serviceLocator, private SerializerInterface $serializer)
{
/** @var array<class-string<\RoachPHP\Spider\SpiderInterface>> $providedServices */
$providedServices = $this->serviceLocator->getProvidedServices();
$this->spiderNames = $this->buildSpiderNameAliases($providedServices);
parent::__construct();
}
protected function configure(): void
{
$this
->setName('roach:run')
->setDescription('Run the provided spider');
$spiderArgDescription = "Spider class name\nSupport spiders:\n";
foreach ($this->spiderNames as $className => $aliases) {
$spiderArgDescription .= '[*] <comment>' . $className . '</comment> or aliases <info>'
. implode('</info>, <info>', $aliases)
. '</info>' . \PHP_EOL;
}
$this
->addArgument('spider', InputArgument::OPTIONAL, rtrim($spiderArgDescription))
->addOption('delay', 't', InputOption::VALUE_OPTIONAL, 'The delay (in seconds) between requests.')
->addOption('concurrency', 'p', InputOption::VALUE_OPTIONAL, 'The number of concurrent requests.')
->addOption('output', 'o', InputOption::VALUE_OPTIONAL, 'Save to JSON file')
;
}
/**
* @param array<class-string<\RoachPHP\Spider\SpiderInterface>> $services
*
* @return array<class-string<\RoachPHP\Spider\SpiderInterface>, array<string>>
*/
private function buildSpiderNameAliases(array $services): array
{
$aliasServices = [];
foreach ($services as $className) {
$aliases = [];
if (($lastPosDelim = strrpos($className, '\\')) !== false) {
$shortClassName = substr($className, $lastPosDelim + 1);
$aliases[] = $shortClassName;
} else {
$shortClassName = $className;
}
$snakeCaseClass = strtolower(ltrim(preg_replace('/[A-Z]([A-Z](?![a-z]))*/', '_$0', $shortClassName), '_'));
$aliases[] = $snakeCaseClass;
if (preg_match('~^(.*?)_spider$~', $snakeCaseClass, $matches)) {
$aliases[] = $matches[1];
}
$aliasServices[$className] = $aliases;
}
return $aliasServices;
}
protected function interact(InputInterface $input, OutputInterface $output): void
{
$spiderName = $input->getArgument('spider');
if ($spiderName === null) {
$spiderName = $this->selectSpiderClassName(new SymfonyStyle($input, $output));
$input->setArgument('spider', $spiderName);
}
}
private function selectSpiderClassName(OutputStyle $io): string
{
return (string) $io->choice('Choose a spider class', array_values($this->serviceLocator->getProvidedServices()));
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$outputFilename = $input->getOption('output');
$spiderName = $input->getArgument('spider');
$spiderClassName = $this->findSpiderClass($spiderName);
if ($spiderClassName === null) {
\assert($spiderName !== null);
$io = new SymfonyStyle($input, $output);
$io->error('Unknown spider ' . $spiderName);
return self::FAILURE;
}
$delay = $input->getOption('delay');
if ($delay !== null) {
$delay = max(0, (int) $delay);
}
$concurrency = $input->getOption('concurrency');
if ($concurrency !== null) {
$concurrency = max(1, (int) $concurrency);
}
$overrides = new Overrides(
concurrency: $concurrency,
requestDelay: $delay,
);
if ($outputFilename !== null) {
$collectData = Roach::collectSpider($spiderClassName, $overrides);
if (!$this->saveCollectData($collectData, $outputFilename, $io)) {
return self::FAILURE;
}
} else {
Roach::startSpider($spiderClassName, $overrides);
}
return self::SUCCESS;
}
/**
* @return class-string<\RoachPHP\Spider\SpiderInterface>|null
*/
private function findSpiderClass(?string $spiderName): ?string
{
if ($spiderName !== null) {
foreach ($this->spiderNames as $className => $aliases) {
if ($className === $spiderName || \in_array($spiderName, $aliases, true)) {
return $className;
}
}
}
return null;
}
private function saveCollectData(array $collectData, string $outputFilename, SymfonyStyle $io): bool
{
$content = $this->serializer->serialize($collectData, 'json', [
JsonEncode::OPTIONS => \JSON_UNESCAPED_UNICODE | \JSON_PRETTY_PRINT | \JSON_UNESCAPED_LINE_TERMINATORS | \JSON_UNESCAPED_SLASHES | \JSON_THROW_ON_ERROR,
]);
$dirname = \dirname($outputFilename);
if (!is_dir($dirname) && !mkdir($dirname, 0755, true) && !is_dir($dirname)) {
$io->error(sprintf('Directory "%s" was not created', $dirname));
return false;
}
if (file_put_contents($outputFilename, $content) === false) {
$io->error(sprintf('An error occurred while saving output to file %s', $dirname));
return false;
}
$io->success(sprintf('Collected data successfully saved to file %s', $outputFilename));
return true;
}
}