|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Command\Todos; |
| 4 | + |
| 5 | +use App\Command\BaseController; |
| 6 | + |
| 7 | +class ListController extends BaseController |
| 8 | +{ |
| 9 | + public $baseApi = 'https://jsonplaceholder.typicode.com/todos'; |
| 10 | + |
| 11 | + public function handle(): void |
| 12 | + { |
| 13 | + // if (empty($this->hasParam('page')) || empty($this->hasParam('limit'))) { |
| 14 | + // $this->getPrinter()->error("Please, inform the name of Pokemon you want to fetch info."); |
| 15 | + // $this->getPrinter()->error("Usage: ./minicli demo todos page=\"1\" limit=\"5\" "); |
| 16 | + // return; |
| 17 | + // } |
| 18 | + |
| 19 | + $page = $this->getParam('page') ?? 1; |
| 20 | + $limit = $this->getParam('limit') ?? 5; |
| 21 | + |
| 22 | + $this->getPrinter()->info('Showing todos'); |
| 23 | + $this->getPrinter()->newline(); |
| 24 | + $this->getPrinter()->display("Page: $page, Limit: $limit"); |
| 25 | + $this->fetchPokemonInfo($page, $limit); |
| 26 | + } |
| 27 | + |
| 28 | + public function fetchPokemonInfo(string $page, string $limit): void |
| 29 | + { |
| 30 | + $pokemonInfo = $this->get($this->baseApi . "?_page=$page&_limit=$limit"); |
| 31 | + |
| 32 | + if (is_string($pokemonInfo)) { |
| 33 | + $this->printPokemonTableInfo($pokemonInfo); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + public function printPokemonTableInfo(string $info): void |
| 38 | + { |
| 39 | + try { |
| 40 | + $rows = json_decode($info, true); |
| 41 | + |
| 42 | + $headers = ['User ID', 'ID', 'Title', 'Completed']; |
| 43 | + |
| 44 | + $this->view('table', ['headers' => $headers, 'rows' => $rows]); |
| 45 | + |
| 46 | + } catch (\Throwable $th) { |
| 47 | + if ($this->getApp()->config->debug) { |
| 48 | + $this->getPrinter()->error("An error occurred:"); |
| 49 | + $this->getPrinter()->error($th->getMessage()); |
| 50 | + } |
| 51 | + return; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + public function get($url): string|bool |
| 56 | + { |
| 57 | + $ch = curl_init($url); |
| 58 | + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
| 59 | + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); |
| 60 | + |
| 61 | + $response = curl_exec($ch); |
| 62 | + curl_close($ch); |
| 63 | + |
| 64 | + return $response; |
| 65 | + } |
| 66 | +} |
0 commit comments