-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathGeocodeCommand.php
94 lines (74 loc) · 2.58 KB
/
GeocodeCommand.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
<?php
declare(strict_types=1);
/*
* This file is part of the BazingaGeocoderBundle package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
namespace Bazinga\GeocoderBundle\Command;
use Geocoder\ProviderAggregator;
use Geocoder\Query\GeocodeQuery;
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;
/**
* @author Markus Bachmann <[email protected]>
*/
class GeocodeCommand extends Command
{
private ProviderAggregator $geocoder;
public function __construct(ProviderAggregator $geocoder)
{
$this->geocoder = $geocoder;
parent::__construct();
}
protected function configure(): void
{
$this
->setName('geocoder:geocode')
->setDescription('Geocode an address or a ip address')
->addArgument('address', InputArgument::REQUIRED, 'The address')
->addOption('provider', null, InputOption::VALUE_OPTIONAL)
->setHelp(<<<'HELP'
The <info>geocoder:geocoder</info> command will fetch the latitude
and longitude from the given address.
You can force a provider with the "provider" option.
<info>php bin/console geocoder:geocoder "Eiffel Tower" --provider=yahoo</info>
HELP
);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
if ($input->getOption('provider')) {
$this->geocoder->using($input->getOption('provider'));
}
$results = $this->geocoder->geocodeQuery(GeocodeQuery::create($input->getArgument('address')));
$data = $results->first()->toArray();
$max = 0;
foreach ($data as $key => $value) {
$length = strlen($key);
if ($max < $length) {
$max = $length;
}
}
$max += 2;
foreach ($data as $key => $value) {
$key = $this->humanize($key);
$output->writeln(sprintf(
'<comment>%s</comment>: %s',
str_pad($key, $max, ' ', STR_PAD_RIGHT),
is_array($value) ? json_encode($value) : $value
));
}
return 0;
}
private function humanize(string $text): string
{
$text = preg_replace('/([A-Z][a-z]+)|([A-Z][A-Z]+)|([^A-Za-z ]+)/', ' \1', $text);
return ucfirst(strtolower($text));
}
}