PHP code example of tetthys / crypto-price

1. Go to this page and download the library: Download tetthys/crypto-price library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tetthys / crypto-price example snippets


use Tetthys\CryptoPrice\Providers\CallableCryptoPriceProvider;
use Tetthys\CryptoPrice\Services\CryptoPriceService;

$provider = new CallableCryptoPriceProvider(
    fn(string $symbol) => match (strtoupper($symbol)) {
        'BTC' => '98765.4321',
        'ETH' => '3456.78',
        'XMR' => '150.50',
        default => throw new RuntimeException("Unknown symbol: {$symbol}")
    }
);

$service = new CryptoPriceService($provider);

echo $service->usd('BTC'); // "98765.4321"
echo $service->cryptoToUsd('0.015', 'BTC'); // "1481.48"
echo $service->usdToCrypto('1000', 'BTC');  // "0.01012345"

public function getUsdPrice(string $symbol): string;

$service = new CryptoPriceService($provider);

$usd  = $service->cryptoToUsd('0.005', 'BTC'); // "493.82"
$btc  = $service->usdToCrypto('100', 'BTC');   // "0.0010132"
$spot = $service->usd('BTC');                  // "98765.4321"

$provider = new CallableCryptoPriceProvider(
    fn(string $symbol) => ['BTC' => '98765.43', 'ETH' => '3456.78'][$symbol] ?? '0'
);

use App\Support\CryptoPrice\CoinMarketCapProvider;
use Tetthys\CryptoPrice\Services\CryptoPriceService;

$provider = new CoinMarketCapProvider(apiKey: env('COINMARKETCAP_API_KEY'));
$service  = new CryptoPriceService($provider);

echo $service->cryptoToUsd('0.5', 'ETH');

$this->app->singleton(CryptoPriceProviderInterface::class, fn () =>
    new CoinMarketCapProvider(env('COINMARKETCAP_API_KEY'))
);

$this->app->bind(CryptoPriceService::class, fn ($app) =>
    new CryptoPriceService($app->make(CryptoPriceProviderInterface::class))
);

use Tetthys\CryptoPrice\Providers\CallableCryptoPriceProvider;
use Tetthys\CryptoPrice\Services\CryptoPriceService;

$mock = new CallableCryptoPriceProvider(fn($s) => match ($s) {
    'BTC' => '10000', 'ETH' => '1000', default => '1'
});

$svc = new CryptoPriceService($mock);
expect($svc->cryptoToUsd('0.5', 'BTC'))->toBe('5000.00');