diff options
Diffstat (limited to 'app/Console/Commands/updateRates.php')
-rw-r--r-- | app/Console/Commands/updateRates.php | 79 |
1 files changed, 79 insertions, 0 deletions
diff --git a/app/Console/Commands/updateRates.php b/app/Console/Commands/updateRates.php new file mode 100644 index 0000000..12830db --- /dev/null +++ b/app/Console/Commands/updateRates.php @@ -0,0 +1,79 @@ +<?php + +namespace App\Console\Commands; + +use App\Models\Rates; +use App\Models\Currency; + +use Illuminate\Console\Command; +use \GuzzleHttp\Client; + +class updateRates extends Command +{ + /** + * The name and signature of the console command. + * + * @var string + */ + protected $signature = 'rates:update'; + + /** + * The console command description. + * + * @var string + */ + protected $description = 'Pull updated rates from our API'; + + /** + * Create a new command instance. + * + * @return void + */ + public function __construct() + { + parent::__construct(); + } + + /** + * Execute the console command. + * + * @return int + */ + public function handle() + { + $client = new \GuzzleHttp\Client(); + $res = $client->get('https://api.coingecko.com/api/v3/exchange_rates', []); + + if($res->getStatusCode() != 200) { + echo "failed to make query to coingecko."; + } + + else { + + $parsed = json_decode($res->getBody(),true); + + if(array_key_exists('rates', $parsed)) { + + foreach($parsed['rates'] as $rate) { + + // grab our BTC object, since all results are relative to it. + $btc = Currency::Where('id', 1)->first(); + + // setup a Currency object if we don't have one already. + if(!$currency = Currency::where('unit', '=', $rate['unit'])->first()) { + $currency = new Currency(['name'=> $rate['name'], 'unit' => $rate['unit']]); + $currency->save(); + } + + // build rate. + $rateObj = new Rates; + $rateObj->value = $rate['value']; + $rateObj->currency_id = $currency->id; + $rateObj->relative_id = $btc->id; + $rateObj->save(); + } + } + + } + } +} |