nextcloud-app-radio/lib/Service/SearchService.php

60 lines
1.3 KiB
PHP
Raw Normal View History

2020-10-18 09:41:18 +00:00
<?php
declare(strict_types=1);
namespace OCA\Radio\Service;
use Exception;
use OCP\Http\Client\IClientService;
use Psr\Log\LoggerInterface;
use function array_filter;
use function array_map;
use function json_decode;
use function mb_strpos;
use function mb_strtolower;
class SearchService {
/** @var IClientService */
private $clientService;
/** @var LoggerInterface */
private $logger;
public function __construct(IClientService $clientService,
LoggerInterface $logger) {
$this->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));
});
}
}