From 7cddb4ccfac4e06101529da062a4dd71f9f97411 Mon Sep 17 00:00:00 2001 From: Jonas Heinrich Date: Sun, 18 Oct 2020 11:41:18 +0200 Subject: [PATCH] fix global search provider --- lib/Command/Search.php | 51 ++++++++++++++++++++++++++++++ lib/Service/SearchService.php | 59 +++++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 lib/Command/Search.php create mode 100644 lib/Service/SearchService.php diff --git a/lib/Command/Search.php b/lib/Command/Search.php new file mode 100644 index 0000000..c33f776 --- /dev/null +++ b/lib/Command/Search.php @@ -0,0 +1,51 @@ +searchService = $searchService; + } + + /** + * @return void + */ + protected function configure() { + $this->setName('radio:search'); + $this->setDescription('Search for radio stations'); + + $this->addArgument("term", InputArgument::OPTIONAL); + } + + protected function execute(InputInterface $input, OutputInterface $output): int { + $radioStations = $this->searchService->findRadioStations( + $input->getArgument("term") + ); + + $output->writeln("Found radio stations"); + foreach ($radioStations as $radioStation) { + $output->writeln("* $radioStation"); + } + + return 0; + } +} diff --git a/lib/Service/SearchService.php b/lib/Service/SearchService.php new file mode 100644 index 0000000..21c7745 --- /dev/null +++ b/lib/Service/SearchService.php @@ -0,0 +1,59 @@ +clientService = $clientService; + $this->logger = $logger; + } + + public function findRadioStations(?string $term = null): array { + $this->logger->debug('searching radio stations'); + + $client = $this->clientService->newClient(); + + try { + $response = $client->get("https://cat-fact.herokuapp.com/facts?animal_type=cat"); + } catch (Exception $e) { + $this->logger->error("Could not search for radio stations. Please check connection to radio-browser API."); + + throw $e; + } + + $body = $response->getBody(); + $parsed = json_decode($body, true); + + $mapped = array_map(function(array $radioStation) { + return $radioStation['text']; + }, $parsed['all']); + + if (empty($term)) { + return $mapped; + } + + return array_filter($mapped, function(string $radioStation) use ($term) { + return mb_strpos(mb_strtolower($radioStation), mb_strtolower($term)); + }); + } + +}