repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Data/Objects/Reviews/Review.php
src/Data/Objects/Reviews/Review.php
<?php namespace AugmentedSteam\Server\Data\Objects\Reviews; class Review implements \JsonSerializable { public function __construct( public ?int $score, public ?string $verdict, public string $url ) {} /** * @return array<string, mixed> */ #[\Override] public function jsonSerialize(): array { return [ "score" => $this->score, "verdict" => $this->verdict, "url" => $this->url ]; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Data/Providers/HLTBProvider.php
src/Data/Providers/HLTBProvider.php
<?php declare(strict_types=1); namespace AugmentedSteam\Server\Data\Providers; use AugmentedSteam\Server\Data\Interfaces\AppData\HLTBProviderInterface; use AugmentedSteam\Server\Data\Objects\HLTB; use AugmentedSteam\Server\Endpoints\EndpointBuilder; use AugmentedSteam\Server\Lib\Loader\SimpleLoader; class HLTBProvider implements HLTBProviderInterface { public function __construct( private readonly SimpleLoader $loader, private readonly EndpointBuilder $endpoints ) {} public function fetch(int $appid): ?HLTB { $endpoint = $this->endpoints->getHLTB($appid); $response = $this->loader->get($endpoint); if (!empty($response)) { $body = $response->getBody()->getContents(); if (!empty($body)) { $json = json_decode($body, true, flags: JSON_THROW_ON_ERROR); if (is_array($json)) { /** * @var array{ * id: int, * main: ?int, * extra: ?int, * complete: ?int * } $json */ $hltb = new HLTB(); $hltb->story = $json['main'] === 0 ? null : (int)floor($json['main'] / 60); $hltb->extras = $json['extra'] === 0 ? null : (int)floor($json['extra'] / 60); $hltb->complete = $json['complete'] === 0 ? null : (int)floor($json['complete'] / 60); $hltb->url = "https://howlongtobeat.com/game/{$json['id']}"; return $hltb; } } } return null; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Data/Providers/PlayersProvider.php
src/Data/Providers/PlayersProvider.php
<?php declare(strict_types=1); namespace AugmentedSteam\Server\Data\Providers; use AugmentedSteam\Server\Data\Interfaces\AppData\PlayersProviderInterface; use AugmentedSteam\Server\Data\Objects\Players; use AugmentedSteam\Server\Endpoints\EndpointBuilder; use AugmentedSteam\Server\Lib\Loader\SimpleLoader; class PlayersProvider implements PlayersProviderInterface { public function __construct( private readonly SimpleLoader $loader, private readonly EndpointBuilder $endpoints ) {} public function fetch(int $appid): Players { $endpoint = $this->endpoints->getPlayers($appid); $response = $this->loader->get($endpoint); $players = new Players(); if (!is_null($response)) { $body = $response->getBody()->getContents(); $json = json_decode($body, true, flags: JSON_THROW_ON_ERROR); if (is_array($json)) { /** * @var array{ * current: int, * day: int, * peak: int * } $json */ $players->current = $json['current']; $players->peakToday = $json['day']; $players->peakAll = $json['peak']; } } return $players; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Data/Providers/EarlyAccessProvider.php
src/Data/Providers/EarlyAccessProvider.php
<?php namespace AugmentedSteam\Server\Data\Providers; use AugmentedSteam\Server\Data\Interfaces\EarlyAccessProviderInterface; use AugmentedSteam\Server\Endpoints\EndpointBuilder; use AugmentedSteam\Server\Lib\Loader\SimpleLoader; class EarlyAccessProvider implements EarlyAccessProviderInterface { public function __construct( private readonly SimpleLoader $loader, private readonly EndpointBuilder $endpoints ) {} /** * @return list<int> */ public function fetch(): array { $response = $this->loader->get($this->endpoints->getEarlyAccess()); $appids = []; if (!is_null($response)) { $appids = json_decode($response->getBody()->getContents(), true, flags: JSON_THROW_ON_ERROR); if (!is_array($appids) || !array_is_list($appids)) { $appids = []; } } return $appids; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Data/Providers/TwitchProvider.php
src/Data/Providers/TwitchProvider.php
<?php declare(strict_types=1); namespace AugmentedSteam\Server\Data\Providers; use AugmentedSteam\Server\Data\Interfaces\TwitchProviderInterface; use AugmentedSteam\Server\Data\Objects\TwitchStream; use AugmentedSteam\Server\Endpoints\EndpointBuilder; use AugmentedSteam\Server\Lib\Loader\SimpleLoader; class TwitchProvider implements TwitchProviderInterface { public function __construct( private readonly SimpleLoader $loader, private readonly EndpointBuilder $endpoints ) {} public function fetch(string $channel): ?TwitchStream { $url = $this->endpoints->getTwitchStream($channel); $response = $this->loader->get($url); if (is_null($response)) { return null; } $body = $response->getBody()->getContents(); /** * @var array{ * user_name: string, * title: string, * thumbnail_url: string, * viewer_count: int, * game: string * } $json */ $json = json_decode($body, true, flags: JSON_THROW_ON_ERROR); if (!is_array($json)) { return null; } $stream = new TwitchStream(); $stream->userName = $json['user_name']; $stream->title = $json['title']; $stream->thumbnailUrl = $json['thumbnail_url']; $stream->viewerCount = $json['viewer_count']; $stream->game = $json['game']; return $stream; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Data/Providers/ExfglsProvider.php
src/Data/Providers/ExfglsProvider.php
<?php declare(strict_types=1); namespace AugmentedSteam\Server\Data\Providers; use AugmentedSteam\Server\Data\Interfaces\ExfglsProviderInterface; use AugmentedSteam\Server\Endpoints\EndpointBuilder; use AugmentedSteam\Server\Lib\Loader\SimpleLoader; class ExfglsProvider implements ExfglsProviderInterface { public function __construct( private readonly SimpleLoader $loader, private readonly EndpointBuilder $endpoints ) {} public function fetch(int $appid): bool { $endpoint = $this->endpoints->getExfgls(); $response = $this->loader->post($endpoint, json_encode([$appid])); if (is_null($response)) { throw new \Exception(); } /** * @var array<string, bool> $data */ $data = json_decode($response->getBody()->getContents(), true, flags: JSON_THROW_ON_ERROR); if (!is_array($data)) { throw new \Exception(); } return array_key_exists((string)$appid, $data) && $data[(string)$appid]; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Data/Providers/WSGFProvider.php
src/Data/Providers/WSGFProvider.php
<?php declare(strict_types=1); namespace AugmentedSteam\Server\Data\Providers; use AugmentedSteam\Server\Data\Interfaces\AppData\WSGFProviderInterface; use AugmentedSteam\Server\Data\Objects\WSGF; use AugmentedSteam\Server\Endpoints\EndpointBuilder; use AugmentedSteam\Server\Lib\Loader\SimpleLoader; class WSGFProvider implements WSGFProviderInterface { public function __construct( private readonly SimpleLoader $loader, private readonly EndpointBuilder $endpoints ) {} public function fetch(int $appid): ?WSGF { $endpoint = $this->endpoints->getWSGF($appid); $response = $this->loader->get($endpoint); if (!empty($response)) { $body = $response->getBody()->getContents(); if (!empty($body)) { $json = json_decode($body, true, flags: JSON_THROW_ON_ERROR); if (is_array($json)) { /** * @var array{ * url: string, * wide: string, * ultrawide: string, * multi_monitor: string, * "4k": string * } $json */ $wsgf = new WSGF(); $wsgf->path = $json['url']; $wsgf->wideScreenGrade = $json['wide']; $wsgf->ultraWideScreenGrade = $json['ultrawide']; $wsgf->multiMonitorGrade = $json['multi_monitor']; $wsgf->grade4k = $json['4k']; return $wsgf; } } } return null; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Data/Providers/RatesProvider.php
src/Data/Providers/RatesProvider.php
<?php declare(strict_types=1); namespace AugmentedSteam\Server\Data\Providers; use AugmentedSteam\Server\Data\Interfaces\RatesProviderInterface; use AugmentedSteam\Server\Endpoints\EndpointBuilder; use AugmentedSteam\Server\Lib\Loader\SimpleLoader; class RatesProvider implements RatesProviderInterface { public function __construct( private readonly SimpleLoader $loader, private readonly EndpointBuilder $endpoints ) {} /** * @return list<array{ * from: string, * to: string, * rate: float * }> */ public function fetch(): array { $endpoint = $this->endpoints->getRates(); $response = $this->loader->get($endpoint); if (!is_null($response)) { $data = json_decode($response->getBody()->getContents(), true, flags: JSON_THROW_ON_ERROR); if (is_array($data)) { return $data; // @phpstan-ignore-line } } return []; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Data/Providers/SteamRepProvider.php
src/Data/Providers/SteamRepProvider.php
<?php declare(strict_types=1); namespace AugmentedSteam\Server\Data\Providers; use AugmentedSteam\Server\Data\Interfaces\SteamRepProviderInterface; use AugmentedSteam\Server\Endpoints\EndpointBuilder; use AugmentedSteam\Server\Lib\Loader\SimpleLoader; class SteamRepProvider implements SteamRepProviderInterface { public function __construct( private readonly SimpleLoader $loader, private readonly EndpointBuilder $endpoints ) {} /** * @return ?list<string> */ public function getReputation(int $steamId): ?array { $url = $this->endpoints->getSteamRep($steamId); $response = $this->loader->get($url); if (is_null($response)) { return null; } $body = $response->getBody()->getContents(); $json = json_decode($body, true, flags: JSON_THROW_ON_ERROR); if (is_array($json) && is_array($json['steamrep'] ?? null) && is_array($json['steamrep']['reputation'] ?? null) && is_string($json['steamrep']['reputation']['full'] ?? null) ) { $reputation = $json['steamrep']['reputation']['full']; if (!empty($reputation)) { return explode(",", $reputation); } } return null; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Data/Providers/PricesProvider.php
src/Data/Providers/PricesProvider.php
<?php declare(strict_types=1); namespace AugmentedSteam\Server\Data\Providers; use AugmentedSteam\Server\Data\Interfaces\PricesProviderInterface; use AugmentedSteam\Server\Data\Objects\Prices; use AugmentedSteam\Server\Endpoints\EndpointBuilder; use AugmentedSteam\Server\Lib\Redis\ERedisKey; use AugmentedSteam\Server\Lib\Redis\RedisClient; use Ds\Set; use GuzzleHttp\Client; class PricesProvider implements PricesProviderInterface { const int CachableIdsLimit = 10; const int OverviewTTL = 5*60; const int GidsTTL = 6*60*60; public function __construct( private readonly Client $guzzle, private readonly RedisClient $redis, private readonly EndpointBuilder $endpoints ) {} /** * @param list<string> $steamIds * @return array<string, string> SteamId:GID */ private function fetchIdMap(array $steamIds): array { $key = ERedisKey::Gids->value; /** @var array<string, string> $result */ $result = []; $toFetch = new Set($steamIds); $cached = $this->redis->hmget($key, $steamIds); foreach($cached as $i => $gid) { $id = $steamIds[$i]; if (!empty($gid)) { $result[$id] = $gid; $toFetch->remove($id); } } if (count($toFetch) > 0) { $endpoint = $this->endpoints->getSteamIdLookup(); $response = $this->guzzle->post($endpoint, [ "body" => json_encode($toFetch->toArray()), "headers" => [ "content-type" => "application/json", "accept" => "application/json" ] ]); if ($response->getStatusCode() != 200) { return []; } $json = json_decode($response->getBody()->getContents(), true, flags: JSON_THROW_ON_ERROR); if (!is_array($json)) { return []; } if (!empty($json)) { $this->redis->hmset($key, $json); $this->redis->hexpire($key, self::GidsTTL, array_keys($json), "NX"); } foreach($json as $id => $gid) { $result[$id] = $gid; } } return $result; } /** * @param list<int> $shops * @param list<string> $gids * @return array<mixed> */ private function fetchOverview(string $country, array $shops, array $gids, bool $withVouchers): array { $endpoint = $this->endpoints->getPrices($country, $shops, $withVouchers); $response = $this->guzzle->post($endpoint, [ "body" => json_encode($gids), "headers" => [ "content-type" => "application/json", "accept" => "application/json" ] ]); if ($response->getStatusCode() !== 200) { return []; } $json = json_decode($response->getBody()->getContents(), true, flags: JSON_THROW_ON_ERROR); if (!is_array($json)) { return []; } return $json; } /** * @param list<string> $steamIds * @param list<int> $shops * @return ?Prices */ public function fetch( array $steamIds, array $shops, string $country, bool $withVouchers ): ?Prices { $region = match($country) { // covered "FR", "US", "GB", "CA", "BR", "AU", "TR", "CN", "IN", "KR", "JP", "ID", "TW" => $country, // eu "AL", "AD", "AT", "BE", "DK", "FI", "IE", "LI", "LU", "MK", "NL", "SE", "CH", "DE", "BA", "BG", "HR", "CY", "CZ", "GR", "HU", "IT", "MT", "MC", "ME", "NO", "PL", "PT", "RO", "SM", "RS", "SK", "SI", "ES", "VA", "EE", "LV", "LT" => "FR", // fallback default => "US" }; $key = ERedisKey::PriceOverview->value; $field = md5(json_encode([$steamIds, $shops, $region, $withVouchers], flags: JSON_THROW_ON_ERROR)); if (count($steamIds) <= self::CachableIdsLimit) { $gzcached = $this->redis->hget($key, $field); if (!empty($gzcached)) { $cached = gzuncompress($gzcached); if ($cached) { return Prices::fromJson($cached); } } } $map = array_filter($this->fetchIdMap($steamIds)); if (empty($map)) { return null; } $gids = array_values($map); $overview = $this->fetchOverview($country, $shops, $gids, $withVouchers); if (empty($overview)) { return null; } /** * @var array{ * prices: list<array<mixed>>, * bundles: list<array<mixed>> * } $overview */ $gidMap = array_flip($map); $prices = new Prices(); $prices->prices = []; $prices->bundles = $overview['bundles']; /** * @var array{ * id: string, * current: array<string, mixed>, * lowest: array<string, mixed>, * bundled: number, * urls: array{game: string} * } $game */ foreach($overview['prices'] as $game) { $gid = $game['id']; $steamId = $gidMap[$gid]; $prices->prices[$steamId] = [ "current" => $game['current'], "lowest" => $game['lowest'], "bundled" => $game['bundled'], "urls" => [ "info" => $game['urls']['game']."info/", "history" => $game['urls']['game']."history/", ] ]; } $gz = gzcompress(json_encode($prices, flags: JSON_THROW_ON_ERROR)); if ($gz) { $this->redis->hset($key, $field, $gz); $this->redis->hexpire($key, self::OverviewTTL, [$field], "NX"); } return $prices; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Data/Providers/ReviewsProvider.php
src/Data/Providers/ReviewsProvider.php
<?php declare(strict_types=1); namespace AugmentedSteam\Server\Data\Providers; use AugmentedSteam\Server\Data\Interfaces\AppData\ReviewsProviderInterface; use AugmentedSteam\Server\Data\Objects\Reviews\Review; use AugmentedSteam\Server\Data\Objects\Reviews\Reviews; use AugmentedSteam\Server\Endpoints\EndpointBuilder; use AugmentedSteam\Server\Lib\Loader\SimpleLoader; class ReviewsProvider implements ReviewsProviderInterface { public function __construct( private readonly SimpleLoader $loader, private readonly EndpointBuilder $endpoints ) {} public function fetch(int $appid): Reviews { $endpoint = $this->endpoints->getReviews($appid); $response = $this->loader->get($endpoint); $reviews = new Reviews(); if (!is_null($response)) { $body = $response->getBody()->getContents(); $json = json_decode($body, true, flags: JSON_THROW_ON_ERROR); if (is_array($json)) { if (!empty($json['metauser']) && is_array($json['metauser'])) { /** * @var array{ * score?: int, * verdict?: string, * url: string * } $review */ $review = $json['metauser']; $reviews->metauser = new Review( $review['score'] ?? null, $review['verdict'] ?? null, $review['url'] ); } if (!empty($json['opencritic']) && is_array($json['opencritic'])) { /** * @var array{ * score?: int, * verdict?: string, * url: string * } $review */ $review = $json['opencritic']; $reviews->opencritic = new Review( $review['score'] ?? null, $review['verdict'] ?? null, $review['url'] ); } } } return $reviews; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Data/Providers/SteamPeekProvider.php
src/Data/Providers/SteamPeekProvider.php
<?php namespace AugmentedSteam\Server\Data\Providers; use AugmentedSteam\Server\Data\Interfaces\AppData\SteamPeekProviderInterface; use AugmentedSteam\Server\Data\Objects\SteamPeak\SteamPeekGame; use AugmentedSteam\Server\Data\Objects\SteamPeak\SteamPeekResults; use AugmentedSteam\Server\Endpoints\EndpointBuilder; use AugmentedSteam\Server\Lib\Loader\SimpleLoader; use GuzzleHttp\Exception\ClientException; use Psr\Log\LoggerInterface; class SteamPeekProvider implements SteamPeekProviderInterface { public function __construct( private readonly SimpleLoader $loader, private readonly EndpointBuilder $endpoints, private readonly LoggerInterface $logger ) {} public function fetch(int $appid): ?SteamPeekResults { $endpoint = $this->endpoints->getSteamPeek($appid); try { $response = $this->loader->get($endpoint, throw: true); } catch (ClientException $e) { if ($e->getResponse()->getStatusCode() !== 404) { \Sentry\captureException($e); } return null; } if (!is_null($response)) { $json = json_decode($response->getBody()->getContents(), true, flags: JSON_THROW_ON_ERROR); if (is_array($json) && is_array($json['response'] ?? null)) { $response = $json['response']; if (!empty($response['success']) && $response['success'] === 1 && !empty($response['results']) ) { $this->logger->info((string)$appid); $results = new SteamPeekResults(); $results->games = array_values(array_map(function(array $a) { $game = new SteamPeekGame(); $game->title = $a['title']; $game->appid = intval($a['appid']); $game->rating = floatval($a['sprating']); $game->score = floatval($a['score']); return $game; }, $response['results'])); return $results; } } } $this->logger->error((string)$appid); return null; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Environment/Container.php
src/Environment/Container.php
<?php namespace AugmentedSteam\Server\Environment; use AugmentedSteam\Server\Config\BrightDataConfig; use AugmentedSteam\Server\Config\CoreConfig; use AugmentedSteam\Server\Controllers\AppController; use AugmentedSteam\Server\Controllers\DLCController; use AugmentedSteam\Server\Controllers\EarlyAccessController; use AugmentedSteam\Server\Controllers\MarketController; use AugmentedSteam\Server\Controllers\PricesController; use AugmentedSteam\Server\Controllers\ProfileController; use AugmentedSteam\Server\Controllers\ProfileManagementController; use AugmentedSteam\Server\Controllers\RatesController; use AugmentedSteam\Server\Controllers\SimilarController; use AugmentedSteam\Server\Controllers\TwitchController; use AugmentedSteam\Server\Data\Interfaces\AppData\HLTBProviderInterface; use AugmentedSteam\Server\Data\Interfaces\AppData\PlayersProviderInterface; use AugmentedSteam\Server\Data\Interfaces\AppData\ReviewsProviderInterface; use AugmentedSteam\Server\Data\Interfaces\AppData\SteamPeekProviderInterface; use AugmentedSteam\Server\Data\Interfaces\AppData\WSGFProviderInterface; use AugmentedSteam\Server\Data\Interfaces\EarlyAccessProviderInterface; use AugmentedSteam\Server\Data\Interfaces\ExfglsProviderInterface; use AugmentedSteam\Server\Data\Interfaces\PricesProviderInterface; use AugmentedSteam\Server\Data\Interfaces\RatesProviderInterface; use AugmentedSteam\Server\Data\Interfaces\SteamRepProviderInterface; use AugmentedSteam\Server\Data\Interfaces\TwitchProviderInterface; use AugmentedSteam\Server\Data\Managers\Market\MarketIndex; use AugmentedSteam\Server\Data\Managers\Market\MarketManager; use AugmentedSteam\Server\Data\Managers\SteamRepManager; use AugmentedSteam\Server\Data\Managers\UserManager; use AugmentedSteam\Server\Data\Providers\EarlyAccessProvider; use AugmentedSteam\Server\Data\Providers\ExfglsProvider; use AugmentedSteam\Server\Data\Providers\HLTBProvider; use AugmentedSteam\Server\Data\Providers\PlayersProvider; use AugmentedSteam\Server\Data\Providers\PricesProvider; use AugmentedSteam\Server\Data\Providers\RatesProvider; use AugmentedSteam\Server\Data\Providers\ReviewsProvider; use AugmentedSteam\Server\Data\Providers\SteamPeekProvider; use AugmentedSteam\Server\Data\Providers\SteamRepProvider; use AugmentedSteam\Server\Data\Providers\TwitchProvider; use AugmentedSteam\Server\Data\Providers\WSGFProvider; use AugmentedSteam\Server\Endpoints\EndpointBuilder; use AugmentedSteam\Server\Endpoints\EndpointsConfig; use AugmentedSteam\Server\Endpoints\KeysConfig; use AugmentedSteam\Server\Lib\Cache\Cache; use AugmentedSteam\Server\Lib\Cache\CacheInterface; use AugmentedSteam\Server\Lib\Loader\Proxy\ProxyFactory; use AugmentedSteam\Server\Lib\Loader\Proxy\ProxyFactoryInterface; use AugmentedSteam\Server\Lib\Loader\SimpleLoader; use AugmentedSteam\Server\Lib\Logging\LoggerFactory; use AugmentedSteam\Server\Lib\Logging\LoggerFactoryInterface; use AugmentedSteam\Server\Lib\Logging\LoggingConfig; use AugmentedSteam\Server\Lib\Money\CurrencyConverter; use AugmentedSteam\Server\Lib\OpenId\Session; use AugmentedSteam\Server\Lib\Redis\RedisClient; use AugmentedSteam\Server\Lib\Redis\RedisConfig; use GuzzleHttp\Client as GuzzleClient; use IsThereAnyDeal\Config\Config; use IsThereAnyDeal\Database\DbConfig; use IsThereAnyDeal\Database\DbDriver; use IsThereAnyDeal\Database\DbFactory; use Laminas\Diactoros\ResponseFactory; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use function DI\create; use function DI\get; class Container implements ContainerInterface { private static Container $instance; public static function init(Config $config): void { self::$instance = new Container($config); } public static function getInstance(): Container { return self::$instance; } private readonly Config $config; private readonly \DI\Container $diContainer; public function __construct(Config $config) { $this->config = $config; $this->diContainer = (new \DI\ContainerBuilder()) ->addDefinitions($this->definitions()) // ->enableCompilation() // ->writeProxiesToFile() ->useAutowiring(false) ->useAttributes(false) ->build(); } /** * @template T * @param class-string<T> $id * @return T */ public function get(string $id): mixed { return $this->diContainer->get($id); } public function has(string $id): bool { return $this->diContainer->has($id); } /** * @return array<string, mixed> */ private function definitions(): array { return [ // config CoreConfig::class => fn(ContainerInterface $c) => $this->config->getConfig(CoreConfig::class), DbConfig::class => fn(ContainerInterface $c) => $this->config->getConfig(DbConfig::class), RedisConfig::class => fn(ContainerInterface $c) => $this->config->getConfig(RedisConfig::class), LoggingConfig::class => fn(ContainerInterface $c) => $this->config->getConfig(LoggingConfig::class), KeysConfig::class => fn(ContainerInterface $c) => $this->config->getConfig(KeysConfig::class), EndpointsConfig::class => fn(ContainerInterface $c) => $this->config->getConfig(EndpointsConfig::class), BrightDataConfig::class => fn(ContainerInterface $c) => $this->config->getConfig(BrightDataConfig::class), // db DbDriver::class => fn(ContainerInterface $c) => (new DbFactory()) ->getDatabase($c->get(DbConfig::class), "main"), // @phpstan-ignore-line RedisClient::class => create(RedisClient::class) ->constructor(get(RedisConfig::class)), // libraries GuzzleClient::class => create(GuzzleClient::class), SimpleLoader::class => create() ->constructor(get(GuzzleClient::class)), CacheInterface::class => create(Cache::class) ->constructor(get(DbDriver::class)), Session::class => fn(ContainerInterface $c) => new Session( $c->get(DbDriver::class), // @phpstan-ignore-line $c->get(CoreConfig::class)->getHost() // @phpstan-ignore-line ), EndpointBuilder::class => create(EndpointBuilder::class) ->constructor( get(EndpointsConfig::class), get(KeysConfig::class) ), CurrencyConverter::class => create(CurrencyConverter::class) ->constructor(get(DbDriver::class)), // factories ResponseFactoryInterface::class => create(ResponseFactory::class), LoggerFactoryInterface::class => create(LoggerFactory::class) ->constructor( get(LoggingConfig::class), LOGS_DIR ), ProxyFactoryInterface::class => create(ProxyFactory::class) ->constructor(get(BrightDataConfig::class)), // providers SteamRepProviderInterface::class => create(SteamRepProvider::class) ->constructor( get(SimpleLoader::class), get(EndpointBuilder::class) ), WSGFProviderInterface::class => fn(ContainerInterface $c) => new WSGFProvider( $c->get(SimpleLoader::class), // @phpstan-ignore-line $c->get(EndpointBuilder::class), // @phpstan-ignore-line ), SteampeekProviderInterface::class => fn(ContainerInterface $c) => new SteamPeekProvider( $c->get(SimpleLoader::class), // @phpstan-ignore-line $c->get(EndpointBuilder::class), // @phpstan-ignore-line $c->get(LoggerFactoryInterface::class)->logger("steampeek") // @phpstan-ignore-line ), EarlyAccessProviderInterface::class => create(EarlyAccessProvider::class) ->constructor( get(SimpleLoader::class), get(EndpointBuilder::class) ), PricesProviderInterface::class => create(PricesProvider::class) ->constructor( get(GuzzleClient::class), get(RedisClient::class), get(EndpointBuilder::class) ), TwitchProviderInterface::class => create(TwitchProvider::class) ->constructor( get(SimpleLoader::class), get(EndpointBuilder::class) ), PlayersProviderInterface::class => create(PlayersProvider::class) ->constructor( get(SimpleLoader::class), get(EndpointBuilder::class) ), ReviewsProviderInterface::class => create(ReviewsProvider::class) ->constructor( get(SimpleLoader::class), get(EndpointBuilder::class) ), RatesProviderInterface::class => create(RatesProvider::class) ->constructor( get(SimpleLoader::class), get(EndpointBuilder::class) ), HLTBProviderInterface::class => create(HLTBProvider::class) ->constructor( get(SimpleLoader::class), get(EndpointBuilder::class) ), ExfglsProviderInterface::class => create(ExfglsProvider::class) ->constructor( get(SimpleLoader::class), get(EndpointBuilder::class) ), // managers MarketManager::class => create() ->constructor(get(DbDriver::class)), MarketIndex::class => create() ->constructor(get(DbDriver::class)), UserManager::class => create() ->constructor(get(DbDriver::class)), SteamRepManager::class => create() ->constructor( get(DbDriver::class), get(SteamRepProviderInterface::class) ), // controllers RatesController::class => create() ->constructor( get(CurrencyConverter::class) ), EarlyAccessController::class => create() ->constructor( get(CacheInterface::class), get(EarlyAccessProviderInterface::class) ), DLCController::class => create() ->constructor( get(DbDriver::class) ), MarketController::class => create() ->constructor( get(CurrencyConverter::class), get(MarketIndex::class), get(MarketManager::class), ), ProfileManagementController::class => create() ->constructor( get(Session::class), get(MarketManager::class), get(UserManager::class), ), ProfileController::class => create() ->constructor( get(UserManager::class), get(SteamRepManager::class) ), AppController::class => create() ->constructor( get(CacheInterface::class), get(WSGFProviderInterface::class), get(ExfglsProviderInterface::class), get(HLTBProviderInterface::class), get(ReviewsProviderInterface::class), get(PlayersProviderInterface::class) ), SimilarController::class => create() ->constructor( get(CacheInterface::class), get(SteamPeekProviderInterface::class) ), PricesController::class => create() ->constructor( get(PricesProviderInterface::class) ), TwitchController::class => create() ->constructor( get(CacheInterface::class), get(TwitchProviderInterface::class), ) ]; } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
IsThereAnyDeal/AugmentedSteam_Server
https://github.com/IsThereAnyDeal/AugmentedSteam_Server/blob/8a46ed2ae10106c1d4f0ec516aa04f1762093007/src/Environment/Lock.php
src/Environment/Lock.php
<?php declare(strict_types=1); namespace AugmentedSteam\Server\Environment; class Lock { private string $path; public function __construct(string $name) { $this->path = TEMP_DIR . "/locks/" . basename($name, ".lock") . ".lock"; } public function isLocked(int $seconds): bool { clearstatcache(); if (file_exists($this->path)) { $timestamp = (int)file_get_contents($this->path); return $timestamp + $seconds >= time(); } return false; } public function lock(): void { $dir = dirname($this->path); if (!file_exists($dir)) { mkdir($dir); } file_put_contents($this->path, time()); } public function unlock(): void { clearstatcache(); if (file_exists($this->path)) { unlink($this->path); } } public function tryLock(int $seconds): void { if ($this->isLocked($seconds)) { if (php_sapi_name() == "cli") { echo "Locked by " . basename($this->path); } die(); } $this->lock(); } }
php
MIT
8a46ed2ae10106c1d4f0ec516aa04f1762093007
2026-01-05T04:53:50.744931Z
false
ihmily/music-api
https://github.com/ihmily/music-api/blob/5e22638f23624ddb20c8f993ea4a4401688d44b5/netease.php
netease.php
<?php /** * @Author:Hmily * @Date:2023-05-20 * @Function:网易云音乐解析 * @Github:https://github.com/ihmily **/ header('Access-Control-Allow-Origin:*'); header('content-type: application/json;'); $msg = $_GET['msg']; // 需要搜索的歌名 $n = $_GET['n']; // 你要获取下载链接的序号 $type = empty($_GET['type']) ? 'song': $_GET['type']; // 解析类型 $count_limit = empty($_GET['count']) ? 10 : $_GET['count']; // 列表数量(默认10个) $page_limit = empty($_GET['page']) ? 1 : $_GET['page']; // 页数(默认第一页) $offset_limit = (($page_limit -1)*$count_limit); // 偏移数 $id = $_GET['id']; // 歌曲id或者歌单id switch ($type) { case 'song': if(empty($msg)){ exit(json_encode(array('code'=>200,'text'=>'请输入要解析的歌名'),448)); } get_netease_song($msg,$offset_limit,$count_limit,$n); break; case 'songid': if(!empty($_GET['id'])){ $song_url='http://music.163.com/song/media/outer/url?id='.$_GET['id']; // 构造网易云歌曲下载链接 $song_url = get_redirect_url($song_url); // 歌曲直链 exit(json_encode(array('code'=>200,'text'=>'解析成功','type'=>'歌曲解析','now'=>date("Y-m-d H:i:s"),'song_url'=>$song_url),448)); } exit(json_encode(array('code'=>200,'text'=>'解析失败,请检查歌曲id值是否正确','type'=>'歌曲解析'),448)); break; case 'random': $album_data=get_album_songs($_GET['id']); get_random_song($album_data); break; default: exit(json_encode(array('code'=>200,'text'=>'请求参数不存在'.$type),448)); } function get_netease_song($msg,$offset_limit,$count_limit,$n){ // 网易云歌曲列表接口 $url = "https://s.music.163.com/search/get/?src=lofter&type=1&filterDj=false&limit=".$count_limit."&offset=".$offset_limit."&s=".urlencode($msg); $json_str=get_curl($url); $json_data = json_decode($json_str,true); $song_list = $json_data['result']['songs']; $data_list=array(); if ($n !=''){ $song_info = $song_list[$n]; $song_url = 'http://music.163.com/song/media/outer/url?id='.$song_info['id']; // 构造网易云歌曲下载链接 $song_url = get_redirect_url($song_url); // 歌曲直链 $data_list=[ "id" => $song_info['id'], "name" => $song_info['name'], "singername" => $song_info['artists'][0]['name'], "page" => $song_info['page'], "song_url" => $song_url ]; }else{ // 未选择第几个歌曲,显示歌曲列表 foreach ($song_list as $song ){ $data=[ "id" => $song['id'], "name" => $song['name'], "singername" => $song['artists'][0]['name'] ]; array_push($data_list, $data); } } exit(json_encode(array('code'=>200,'text'=>'解析成功','type'=>'歌曲解析','now'=>date("Y-m-d H:i:s"),'data'=>$data_list),448)); } // 随机输出歌单内的一首歌 function get_random_song($album_data){ $json_str = $album_data; $json_data = json_decode($json_str,true); $playlist = $json_data['playlist']; $id = $playlist['id']; $name = $playlist['name']; $description = $playlist['description']; $trackIds = $playlist['trackIds']; $random_number = rand(0, count($trackIds)-1); $random_id = $trackIds[$random_number]['id']; $song_url = 'http://music.163.com/song/media/outer/url?id='.$random_id; // 构造网易云歌曲下载链接 $song_url = get_redirect_url($song_url); // 歌曲直链 $data_list = [ "id" => $id, "album_name" => $name, "album_description" => $description, "song_id" => $random_id, "song_url" => $song_url ]; exit(json_encode(array('code'=>200,'text'=>'解析成功','type'=>'歌单随机歌曲','now'=>date("Y-m-d H:i:s"),'data'=>$data_list),448)); } // 通过歌单id 解析歌单的方式 // ['热歌榜':'3778678','原创榜':2884035,'新歌榜':3779629,'飙升榜':19723756,'云音乐说唱榜':19723756] function get_album_songs($id){ $id = empty($id)?3778678:$id; // 如果歌单id为空,则解析热歌榜歌单的歌曲 $post_data = http_build_query(array('s'=>'100','id' =>$id,'n'=>'100','t'=>'100')); $url = "http://music.163.com/api/v6/playlist/detail"; $json_str = post_curl($url,$post_data); // exit($json_str); return $json_str; } //CURL函数 function get_curl($url,$headers=array(),$cookies=''){ $default_headers=array("User-Agent:Mozilla/6.0 (Linux; Android 11; SAMSUNG SM-G973U) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/14.2 Chrome/87.0.4280.141 Mobile Safari/537.36"); $headers = empty($headers)?$default_headers:$headers; $curl=curl_init((string)$url); curl_setopt($curl,CURLOPT_HEADER,false); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($curl, CURLOPT_ENCODING, ""); curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); curl_setopt($curl,CURLOPT_HTTPHEADER,$headers); curl_setopt($curl, CURLOPT_COOKIE, $cookies); curl_setopt($curl,CURLOPT_TIMEOUT,20); $data = curl_exec($curl); // var_dump($data); curl_close($curl); return $data; } function post_curl($post_url,$post_data,$headers=array(),$cookies='') { $default_headers=array("User-Agent:Mozilla/6.0 (Linux; Android 11; SAMSUNG SM-G973U) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/14.2 Chrome/87.0.4280.141 Mobile Safari/537.36"); $headers = empty($headers)?$default_headers:$headers; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $post_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_COOKIE, $cookies); curl_setopt($curl, CURLOPT_NOBODY, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLINFO_HEADER_OUT, TRUE); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); curl_setopt($curl,CURLOPT_TIMEOUT,20); $data = curl_exec($curl); // var_dump($data); curl_close($curl); return $data; } // 获取下载链接重定向链接 function get_redirect_url($url,$headers=array()) { $default_headers=array("User-Agent:Mozilla/6.0 (Linux; Android 11; SAMSUNG SM-G973U) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/14.2 Chrome/87.0.4280.141 Mobile Safari/537.36"); $headers = empty($headers)?$default_headers:$headers; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_NOBODY, 1); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl,CURLOPT_TIMEOUT,20); $ret = curl_exec($curl); curl_close($curl); preg_match("/Location: (.*?)\r\n/iU",$ret,$location); return $location[1]; }
php
MIT
5e22638f23624ddb20c8f993ea4a4401688d44b5
2026-01-05T04:54:03.223901Z
false
ihmily/music-api
https://github.com/ihmily/music-api/blob/5e22638f23624ddb20c8f993ea4a4401688d44b5/kuwo.php
kuwo.php
<?php /** * @Author:Hmily * @Date:2023-06-23 * @Function:酷我音乐解析 * @Github:https://github.com/ihmily **/ header('Access-Control-Allow-Origin:*'); header('content-type: application/json;'); $headers = array( 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0', 'Accept: application/json, text/plain, */*', 'Referer: https://kuwo.cn', 'Secret: 10373b58aee58943f95eaf17d38bc9cf50fbbef8e4bf4ec6401a3ae3ef8154560507f032', ); $cookies='Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1687520303,1689840209; _ga=GA1.2.2021483490.1666455184; _ga_ETPBRPM9ML=GS1.2.1689840210.4.1.1689840304.60.0.0; Hm_Iuvt_cdb524f42f0ce19b169b8072123a4727=NkA4TadJGeBWwmP2mNGpYRrM8f62K8Cm; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1689840223; _gid=GA1.2.1606176174.1689840209; _gat=1'; $msg = $_GET['msg'];//需要搜索的歌名 $n = $_GET['n'];//选择(序号) $type = empty($_GET['type']) ? 'song': $_GET['type']; $page_limit = empty($_GET['page']) ? 1 : $_GET['page'];//页数(默认第一页) $count_limit = empty($_GET['count']) ? 20 : $_GET['count'];//列表数量(默认10个) switch ($type) { case '': exit(json_encode(array('code'=>200,'text'=>'解析失败,请输入要解析的歌曲或者MV名称'),448)); break; case 'mv': $data_list=get_kuwo_mv($msg,$page_limit,$count_limit,$n,$headers,$cookies); exit(json_encode(array('code'=>200,'text'=>'解析成功','type'=>'MV解析','now'=>date("Y-m-d H:i:s"),'data'=>$data_list),448)); break; case 'song': get_kuwo_song($msg,$page_limit,$count_limit,$n,$headers,$cookies); break; case 'rid': if(!empty($_GET['id'])){ $song_data=get_mp3_data($_GET['id'],$headers,$cookies); exit(json_encode($song_data,448)); } exit(json_encode(array('code'=>200,'text'=>'解析失败,请检查歌曲rid值是否正确','type'=>'歌曲解析'),448)); break; case 'mid': if(!empty($_GET['id'])){ $mv_data=get_mv_data($_GET['id'],$headers,$cookies); if(!empty(($mv_data))){ exit(json_encode($mv_data,448)); } } exit(json_encode(array('code'=>200,'text'=>'解析失败,请检查MV mid值是否正确','type'=>'MV解析'),448)); break; default: exit(json_encode(array('code'=>200,'text'=>'请求参数不存在'),448)); } function get_kuwo_song($msg,$page_limit,$count_limit,$n,$headers,$cookies){ // 歌曲搜索接口 $url="http://kuwo.cn/api/www/search/searchMusicBykeyWord?key=".urlencode($msg)."&pn=".$page_limit."&rn=".$count_limit."&httpsStatus=1"; $json_str=get_curl($url,$headers,$cookies); $json_data = json_decode($json_str,true); $info_list=$json_data['data']['list']; $data_list=array(); if ($n !=''){ $info = $info_list[$n]; // 获取歌曲mp3链接 $song_rid = $info['rid']; if($song_rid !=""){ $json_data2 = get_mp3_data($song_rid,$headers,$cookies); $song_url = empty($json_data2['data'])?"付费歌曲暂时无法获取歌曲下载链接":$json_data2['data']['url']; } $data_list=[ "name" => $info['name'], "singername" => $info['artist'], "duration" => gmdate("i:s", $info['duration']), "file_size" => null, // 将字节转换为MB并保留两位小数, "song_url" => $song_url, "mv_url" => get_mv_data($song_rid,$headers,$cookies)['data']['url'], "album_img" => $info['pic'], ]; }else{ // 未选择第几个歌曲,显示歌曲列表 foreach ($info_list as $info ){ $data=[ "name" => $info['name'], "singername" => $info['artist'], "duration" => gmdate("i:s", $info['duration']), "rid" => $info['rid'] ]; array_push($data_list, $data); } } exit(json_encode(array('code'=>200,'text'=>'解析成功','type'=>'歌曲解析','now'=>date("Y-m-d H:i:s"),'data'=>$data_list),448)); } function get_kuwo_mv($msg,$page_limit,$count_limit,$n,$headers,$cookies){ // 歌曲搜索接口 $url="http://www.kuwo.cn/api/www/search/searchMvBykeyWord?key=".urlencode($msg)."&pn=".$page_limit."&rn=".$count_limit."&httpsStatus=1"; $json_str=get_curl($url,$headers,$cookies); // exit($json_str); $json_data = json_decode($json_str,true); $info_list=$json_data['data']['mvlist']; $data_list=array(); if ($n !=''){ $info = $info_list[$n]; $json_data2 = get_mv_data($info['id'],$headers,$cookies); $mv_url = $json_data2['data']['url']; $data_list=[ "name" => $info['name'], "singername" => $info['artist'], "duration" => gmdate("i:s", $info['duration']), "file_size" => null, // 将字节转换为MB并保留两位小数, "mv_url" => $mv_url, "cover_url" => $info['pic'], "publish_date" => null ]; }else{ // 未选择第几个歌曲,显示歌曲列表 foreach ($info_list as $info ){ $data=[ "name" => $info['name'], "singername" => $info['artist'], "duration" => gmdate("i:s", $info['duration']), "cover_url" => $info['pic'], ]; array_push($data_list, $data); } } return $data_list; } // 获取歌曲数据 function get_mp3_data($song_rid,$headers,$cookies){ $url = 'http://kuwo.cn/api/v1/www/music/playUrl?mid='.$song_rid.'&type=music&httpsStatus=1'; $json_str=get_curl($url,$headers,$cookies); // exit($json_str2); $json_data = json_decode($json_str,true); return $json_data; } // 获取MV视频数据 function get_mv_data($mv_mid,$headers,$cookies){ // 获取MV视频 $url = 'http://www.kuwo.cn/api/v1/www/music/playUrl?mid='.$mv_mid.'&type=mv&httpsStatus=1'; $json_str=get_curl($url,$headers,$cookies); $json_data = json_decode($json_str,true); return $json_data; } function get_response_headers($url) { // 设置 CURL 请求的 URL 和一些选项 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, true); // 发送请求并获取响应和响应头信息 $response = curl_exec($ch); $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $header = substr($response, 0, $header_size); // 打印响应头信息 // echo $header; // 关闭 CURL 请求 curl_close($ch); return $header; } //CURL函数 function get_curl($url,$headers=array(),$cookies=''){ $default_headers=array("User-Agent:Mozilla/6.0 (Linux; Android 11; SAMSUNG SM-G973U) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/14.2 Chrome/87.0.4280.141 Mobile Safari/537.36"); $headers = empty($headers)?$default_headers:$headers; $curl=curl_init((string)$url); curl_setopt($curl,CURLOPT_HEADER,false); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($curl, CURLOPT_ENCODING, ""); curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); curl_setopt($curl,CURLOPT_HTTPHEADER,$headers); curl_setopt($curl, CURLOPT_COOKIE, $cookies); curl_setopt($curl,CURLOPT_TIMEOUT,20); $data = curl_exec($curl); // var_dump($data); curl_close($curl); return $data; }
php
MIT
5e22638f23624ddb20c8f993ea4a4401688d44b5
2026-01-05T04:54:03.223901Z
false
ihmily/music-api
https://github.com/ihmily/music-api/blob/5e22638f23624ddb20c8f993ea4a4401688d44b5/kugou.php
kugou.php
<?php /** * @Author:Hmily * @Date:2023-05-28 * @Function:酷狗音乐解析 * @Github:https://github.com/ihmily **/ header('Access-Control-Allow-Origin:*'); header('content-type: application/json;'); $msg = $_GET['msg'];//需要搜索的歌名 $n = $_GET['n'];//选择(序号) $type = empty($_GET['type']) ? 'song': $_GET['type']; $page_limit = empty($_GET['page']) ? 1 : $_GET['page'];//页数(默认第一页) $count_limit = empty($_GET['count']) ? 10 : $_GET['count'];//列表数量(默认10个) switch ($type) { case '': exit(json_encode(array('code'=>200,'text'=>'解析失败,请输入要解析的歌名'),448)); break; case 'mv': $data_list=get_kugou_mv($msg,$page_limit,$count_limit,$n); exit(json_encode(array('code'=>200,'text'=>'解析成功','type'=>'MV解析','now'=>date("Y-m-d H:i:s"),'data'=>$data_list),448)); break; case 'song': get_kugou_song($msg,$page_limit,$count_limit,$n); break; case 'shash': if(!empty($_GET['hash'])){ $song_data=get_mp3_data($_GET['hash']); exit(json_encode($song_data,448)); } exit(json_encode(array('code'=>200,'text'=>'解析失败,请检查歌曲hash值是否正确','type'=>'歌曲解析'),448)); break; case 'mhash': if(!empty($_GET['hash'])){ $mv_data=get_mv_data($_GET['hash']); if(!empty(($mv_data))){ exit(json_encode($mv_data,448)); } } exit(json_encode(array('code'=>200,'text'=>'解析失败,请检查MV hash值是否正确','type'=>'MV解析'),448)); break; default: exit(json_encode(array('code'=>200,'text'=>'请求参数不存在'),448)); } function get_kugou_mv($msg,$page_limit,$count_limit,$n){ // MV搜索接口1 // $url = 'http://mvsearch.kugou.com/mv_search?page='.$page_limit.'&pagesize='.$count_limit.'&userid=-1&clientver=&platform=WebFilter&tag=em&filter=10&iscorrection=1&privilege_filter=0&keyword='.urlencode($msg); // MV搜索接口2 $url = "https://mobiles.kugou.com/api/v3/search/mv?format=json&keyword=".urlencode($msg)."&page=".$page_limit."&pagesize=".$count_limit."&showtype=1"; // $jsonp_str=get_curl($url,array('User-Agent:'.$user_agent)); // $json_str = preg_replace('/^\w+\((.*)\)$/', '$1', $jsonp_str); $json_str=get_curl($url); $json_data = json_decode($json_str,true); $info_list=$json_data['data']['info']; $data_list=array(); if ($n !=''){ $info = $info_list[$n]; $json_data2 = get_mv_data($info['hash']); $mvdata_list = $json_data2['mvdata']; $mvdata = null; if (array_key_exists('sq', $mvdata_list)) { $mvdata = $mvdata_list['sq']; } else if (array_key_exists('le', $mvdata_list)) { $mvdata = $mvdata_list['le']; } else if (array_key_exists('rq', $mvdata_list)) { $mvdata = $mvdata_list['rq']; } $data_list=[ "name" => $info['filename'], "singername" => $info['singername'], "duration" => gmdate("i:s", $info['duration']), "file_size" => round($mvdata['filesize'] / (1024 * 1024), 2).' MB', // 将字节转换为MB并保留两位小数, "play_count" => $json_data['play_count'], "like_count" => $json_data['like_count'], "comment_count" => $json_data['comment_count'], "collect_count" => $json_data['collect_count'], "mv_url" => $mvdata['downurl'], "cover_url" => str_replace('/{size}', '', $info['imgurl']), "publish_date" => $json_data['publish_date'] ]; }else{ // 未选择第几个歌曲,显示歌曲列表 foreach ($info_list as $info ){ $data=[ "name" => $info['filename'], "singername" => $info['singername'], "duration" => gmdate("i:s", $info['duration']), "cover_url" => str_replace('/{size}', '', $info['imgurl']) ]; array_push($data_list, $data); } } return $data_list; } function get_kugou_song($msg,$page_limit,$count_limit,$n){ // 歌曲搜索接口 $url = "https://mobiles.kugou.com/api/v3/search/song?format=json&keyword=".urlencode($msg)."&page=".$page_limit."&pagesize=".$count_limit."&showtype=1"; // $jsonp_str=get_curl($url,array('User-Agent:'.$user_agent)); // $json_str = preg_replace('/^\w+\((.*)\)$/', '$1', $jsonp_str); $json_str=get_curl($url); $json_data = json_decode($json_str,true); $info_list=$json_data['data']['info']; $data_list=array(); if ($n !=''){ $info = $info_list[$n]; // 获取歌曲mp3链接 $song_hash = $info['hash']; if($song_hash !=""){ $json_data2 = get_mp3_data($song_hash); $song_url = empty($json_data2['error'])?$json_data2['url']:"付费歌曲暂时无法获取歌曲下载链接"; } $data_list=[ "name" => $info['filename'], "singername" => $info['singername'], "duration" => gmdate("i:s", $info['duration']), "file_size" => round($json_data2['fileSize'] / (1024 * 1024), 2).' MB', // 将字节转换为MB并保留两位小数, "song_url" => $song_url, "mv_url" => get_kugou_mv($msg,$page_limit,$count_limit,$n)['mv_url'], "album_img" => str_replace('/{size}', '', $json_data2['album_img']), ]; }else{ // 未选择第几个歌曲,显示歌曲列表 foreach ($info_list as $info ){ $data=[ "name" => $info['filename'], "singername" => $info['singername'], "duration" => gmdate("i:s", $info['duration']), "hash" => $info['hash'], "mvhash" => empty($info['mvhash'])?null:$info['mvhash'] ]; array_push($data_list, $data); } } exit(json_encode(array('code'=>200,'text'=>'解析成功','type'=>'歌曲解析','now'=>date("Y-m-d H:i:s"),'data'=>$data_list),448)); } // 获取歌曲数据 function get_mp3_data($song_hash){ $url = 'https://m.kugou.com/app/i/getSongInfo.php?hash='.$song_hash.'&cmd=playInfo'; $json_str=get_curl($url); // exit($json_str2); $json_data = json_decode($json_str,true); return $json_data; } // 获取MV视频数据 function get_mv_data($mv_hash){ // 获取MV视频 $url = 'http://m.kugou.com/app/i/mv.php?cmd=100&hash='.$mv_hash.'&ismp3=1&ext=mp4'; $json_str=get_curl($url); $json_data = json_decode($json_str,true); return $json_data; } //CURL函数 function get_curl($url,$headers=array(),$cookies=''){ $default_headers=array("User-Agent:Mozilla/6.0 (Linux; Android 11; SAMSUNG SM-G973U) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/14.2 Chrome/87.0.4280.141 Mobile Safari/537.36"); $headers = empty($headers)?$default_headers:$headers; $curl=curl_init((string)$url); curl_setopt($curl,CURLOPT_HEADER,false); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($curl, CURLOPT_ENCODING, ""); curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); curl_setopt($curl,CURLOPT_HTTPHEADER,$headers); curl_setopt($curl, CURLOPT_COOKIE, $cookies); curl_setopt($curl,CURLOPT_TIMEOUT,20); $data = curl_exec($curl); // var_dump($data); curl_close($curl); return $data; }
php
MIT
5e22638f23624ddb20c8f993ea4a4401688d44b5
2026-01-05T04:54:03.223901Z
false
ihmily/music-api
https://github.com/ihmily/music-api/blob/5e22638f23624ddb20c8f993ea4a4401688d44b5/qq.php
qq.php
<?php /** * @Author:Hmily * @Date:2023-07-20 * @Function:qq音乐解析 * @Github:https://github.com/ihmily **/ header('Access-Control-Allow-Origin:*'); header('content-type: application/json;'); $msg = $_GET['msg'];//需要搜索的歌名 $n = $_GET['n'];//选择(序号) $type = empty($_GET['type']) ? 'song': $_GET['type']; $page_limit = empty($_GET['page']) ? 1 : $_GET['page'];//页数(默认第一页) $count_limit = empty($_GET['count']) ? 20 : $_GET['count'];//列表数量(默认20个) switch ($type) { case 'song': if(empty($msg)){ exit(json_encode(array('code'=>200,'text'=>'请输入要解析的歌名'),448)); } get_qq_song($msg,$page_limit,$count_limit,$n); break; case 'songid': if(!empty($_GET['id'])){ $json_data=get_mp3_data($_GET['id']); $song_url = $json_data["songList"][0]["url"]; exit(json_encode(array('code'=>200,'text'=>'解析成功','type'=>'歌曲解析','now'=>date("Y-m-d H:i:s"),'song_url'=>$song_url),448)); } exit(json_encode(array('code'=>200,'text'=>'解析失败,请检查歌曲id值是否正确','type'=>'歌曲解析'),448)); break; default: exit(json_encode(array('code'=>200,'text'=>'请求参数不存在'.$type),448)); } function get_qq_song($msg,$page_limit,$count_limit,$n){ // 歌曲搜索接口 $post_data = '{"comm":{"_channelid":"19","_os_version":"6.2.9200-2","authst":"Q_H_L_5tvGesDV1E9ywCVIuapBeYL7IYKKtbZErLj5HeBkyXeqXtjfQYhP5tg","ct":"19","cv":"1873","guid":"B69D8BC956E47C2B65440380380B7E9A","patch":"118","psrf_access_token_expiresAt":1697829214,"psrf_qqaccess_token":"A865B8CA3016A74B1616F8919F667B0B","psrf_qqopenid":"2AEA845D18EF4BCE287B8EFEDEA1EBCA","psrf_qqunionid":"6EFC814008FAA695ADD95392D7D5ADD2","tmeAppID":"qqmusic","tmeLoginType":2,"uin":"961532186","wid":"0"},"music.search.SearchCgiService":{"method":"DoSearchForQQMusicDesktop","module":"music.search.SearchCgiService","param":{"grp":1,"num_per_page":'.$count_limit.',"page_num":'.$page_limit.',"query":"'.$msg.'","remoteplace":"txt.newclient.history","search_type":0,"searchid":"6254988708H54D2F969E5D1C81472A98609002"}}}'; $headers = array( "Content-Type: application/json; charset=UTF-8", "Charset: UTF-8", "Accept: */*", "User-Agent: Mozilla/5.0 (Linux; Android 6.0.1; OPPO R9s Plus Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36", "Host: u.y.qq.com" ); $post_url="https://u.y.qq.com/cgi-bin/musicu.fcg"; // $jsonp_str=get_curl($url,array('User-Agent:'.$user_agent)); // $json_str = preg_replace('/^\w+\((.*)\)$/', '$1', $jsonp_str); $json_str=post_curl($post_url,$post_data,$headers); // var_dump($json_str); // exit(); $json_data = json_decode($json_str,true); $info_list=$json_data["music.search.SearchCgiService"]["data"]["body"]["song"]["list"]; $data_list=array(); if ($n !=''){ $info = $info_list[$n]; // 获取歌曲mp3链接 $song_mid = $info["mid"]; if($song_mid !=""){ $json_data2 = get_mp3_data($song_mid); $song_url = $json_data2["songList"][0]["url"]; } $song_name=$info["name"]; if($song_url==""){ $song_url=null; $song_name =$song_name."[付费歌曲]"; } $data_list=[ "name" => $song_name, "singername" => $info["singer"][0]["name"], "duration" => null, "file_size" => null, // 将字节转换为MB并保留两位小数, "song_url" => $song_url, "mv_url" => null, "album_img" => "https://y.qq.com/music/photo_new/T002R300x300M000".$info["album"]["pmid"].".jpg", ]; }else{ // 未选择第几个歌曲,显示歌曲列表 foreach ($info_list as $info ){ $data=[ "name" => $info["name"], "singername" => $info["singer"][0]["name"], "duration" => null, "mid" => $info["mid"], "vid" => $info['mv']['vid']==""?null:$info['mv']['vid'], "time_public"=>$info['time_public'], "mvhash" => null ]; array_push($data_list, $data); } } exit(json_encode(array('code'=>200,'text'=>'解析成功','type'=>'歌曲解析','now'=>date("Y-m-d H:i:s"),'data'=>$data_list),448)); } // 获取歌曲数据 function get_mp3_data($song_mid){ $url="https://i.y.qq.com/v8/playsong.html?ADTAG=ryqq.songDetail&songmid=".$song_mid."&songid=0&songtype=0"; $html_str=get_curl($url); preg_match('/>window.__ssrFirstPageData__ =(.*?)<\/script/',$html_str,$json_str); // echo($json_str[1]); $json_data=json_decode($json_str[1], true); return $json_data; } // 获取MV视频数据 // function get_mv_data($mv_vid){ // // 获取MV视频 // $url = 'https://y.qq.com/n/ryqq/mv/'.$mv_vid; // $json_str=get_curl($url); // $json_data = json_decode($json_str,true); // return $json_data; // } //CURL函数 function get_curl($url,$headers=array(),$cookies=''){ $default_headers=array("User-Agent:Mozilla/6.0 (Linux; Android 11; SAMSUNG SM-G973U) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/14.2 Chrome/87.0.4280.141 Mobile Safari/537.36"); $headers = empty($headers)?$default_headers:$headers; $curl=curl_init((string)$url); curl_setopt($curl,CURLOPT_HEADER,false); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($curl, CURLOPT_ENCODING, ""); curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); curl_setopt($curl,CURLOPT_HTTPHEADER,$headers); curl_setopt($curl, CURLOPT_COOKIE, $cookies); curl_setopt($curl,CURLOPT_TIMEOUT,20); $data = curl_exec($curl); // var_dump($data); curl_close($curl); return $data; } function post_curl($post_url,$post_data,$headers,$cookies='') { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $post_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_COOKIE, $cookies); curl_setopt($curl, CURLOPT_NOBODY, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLINFO_HEADER_OUT, TRUE); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); curl_setopt($curl,CURLOPT_TIMEOUT,20); $data = curl_exec($curl); // var_dump($data); curl_close($curl); return $data; }
php
MIT
5e22638f23624ddb20c8f993ea4a4401688d44b5
2026-01-05T04:54:03.223901Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/CoinGeckoClient.php
src/CoinGeckoClient.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi; use Codenixsv\CoinGeckoApi\Api\Coins; use Codenixsv\CoinGeckoApi\Api\Contract; use Codenixsv\CoinGeckoApi\Api\Derivatives; use Codenixsv\CoinGeckoApi\Api\Events; use Codenixsv\CoinGeckoApi\Api\ExchangeRates; use Codenixsv\CoinGeckoApi\Api\Exchanges; use Codenixsv\CoinGeckoApi\Api\Finance; use Codenixsv\CoinGeckoApi\Api\Globals; use Codenixsv\CoinGeckoApi\Api\Indexes; use Codenixsv\CoinGeckoApi\Api\Ping; use Codenixsv\CoinGeckoApi\Api\Simple; use Codenixsv\CoinGeckoApi\Api\StatusUpdates; use Exception; use GuzzleHttp\Client; use Psr\Http\Message\ResponseInterface; /** * Class CoinGeckoClient * @package Codenixsv\CoinGeckoApi */ class CoinGeckoClient { protected const BASE_URI = 'https://api.coingecko.com'; /** @var Client */ private $httpClient; /** @var ResponseInterface|null */ protected $lastResponse; public function __construct(?Client $client = null) { $this->httpClient = $client ?: new Client(['base_uri' => self::BASE_URI]); } public function getHttpClient(): Client { return $this->httpClient; } /** * @return array * @throws Exception */ public function ping(): array { return (new Ping($this))->ping(); } public function simple(): Simple { return new Simple($this); } public function coins(): Coins { return new Coins($this); } public function contract(): Contract { return new Contract($this); } public function exchanges(): Exchanges { return new Exchanges($this); } public function finance(): Finance { return new Finance($this); } public function indexes(): Indexes { return new Indexes($this); } public function derivatives(): Derivatives { return new Derivatives($this); } public function statusUpdates(): StatusUpdates { return new StatusUpdates($this); } public function events(): Events { return new Events($this); } public function exchangeRates(): ExchangeRates { return new ExchangeRates($this); } public function globals(): Globals { return new Globals($this); } public function setLastResponse(ResponseInterface $response) { return $this->lastResponse = $response; } public function getLastResponse(): ?ResponseInterface { return $this->lastResponse; } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Exceptions/TransformResponseException.php
src/Exceptions/TransformResponseException.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Exception; use Exception; /** * Class TransformResponseException * @package Codenixsv\CoinGeckoApi\Exception */ class TransformResponseException extends Exception { }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Message/ResponseTransformer.php
src/Message/ResponseTransformer.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Message; use Codenixsv\CoinGeckoApi\Exception\TransformResponseException; use Psr\Http\Message\ResponseInterface; use Exception; /** * Class ResponseTransformer * @package Codenixsv\CoinGeckoApi\Message */ class ResponseTransformer { /** * @param ResponseInterface $response * @return array * @throws Exception */ public function transform(ResponseInterface $response): array { $body = (string) $response->getBody(); if (strpos($response->getHeaderLine('Content-Type'), 'application/json') === 0) { $content = json_decode($body, true); if (JSON_ERROR_NONE === json_last_error()) { return $content; } throw new TransformResponseException('Error transforming response to array. JSON_ERROR: ' . json_last_error() . ' --' . $body . '---'); } throw new TransformResponseException('Error transforming response to array. Content-Type is not application/json'); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/Api.php
src/Api/Api.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Codenixsv\CoinGeckoApi\CoinGeckoClient; use Codenixsv\CoinGeckoApi\Message\ResponseTransformer; use Exception; class Api { /** @var CoinGeckoClient */ protected $client; private $version = 'v3'; /** @var ResponseTransformer */ protected $transformer; public function __construct(CoinGeckoClient $client) { $this->client = $client; $this->transformer = new ResponseTransformer(); } /** * @param string $uri * @param array $query * @return array * @throws Exception */ public function get(string $uri, array $query = []): array { $response = $this->client->getHttpClient()->request('GET', '/api/' . $this->version . $uri, ['query' => $query]); $this->client->setLastResponse($response); return $this->transformer->transform($response); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/Derivatives.php
src/Api/Derivatives.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Exception; class Derivatives extends Api { /** * @param array $params * @return array * @throws Exception */ public function getDerivatives(array $params = []): array { return $this->get('/derivatives', $params); } /** * @param array $params * @return array * @throws Exception */ public function getExchanges(array $params = []): array { return $this->get('/derivatives/exchanges', $params); } /** * @param string $id * @param array $params * @return array * @throws Exception */ public function getExchange(string $id, $params = []): array { return $this->get('/derivatives/exchanges/' . $id, $params); } /** * @return array * @throws Exception */ public function getExchangeList(): array { return $this->get('/derivatives/exchanges/list'); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/Finance.php
src/Api/Finance.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Exception; class Finance extends Api { /** * @param array $params * @return array * @throws Exception */ public function getPlatforms(array $params = []): array { return $this->get('/finance_platforms', $params); } /** * @param array $params * @return array * @throws Exception */ public function getProducts(array $params = []): array { return $this->get('/finance_products', $params); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/Events.php
src/Api/Events.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Exception; class Events extends Api { /** * @param array $params * @return array * @throws Exception */ public function getEvents(array $params = []): array { return $this->get('/events', $params); } /** * @return array * @throws Exception */ public function getCountries(): array { return $this->get('/events/countries'); } /** * @return array * @throws Exception */ public function getTypes(): array { return $this->get('/events/types'); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/Globals.php
src/Api/Globals.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Exception; class Globals extends Api { /** * @return array * @throws Exception */ public function getGlobal(): array { return $this->get('/global'); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/StatusUpdates.php
src/Api/StatusUpdates.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Exception; class StatusUpdates extends Api { /** * @param array $params * @return array * @throws Exception */ public function getStatusUpdates(array $params = []): array { return $this->get('/status_updates', $params); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/Contract.php
src/Api/Contract.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Exception; class Contract extends Api { /** * @param string $id * @param string $contractAddress * @return array * @throws Exception */ public function getContract(string $id, string $contractAddress): array { return $this->get('/coins/' . $id . '/contract/' . $contractAddress); } /** * @param string $id * @param string $contractAddress * @param string $vsCurrency * @param string $days * @return array * @throws Exception */ public function getMarketChart(string $id, string $contractAddress, string $vsCurrency, string $days): array { $params = ['days' => $days, 'vs_currency' => $vsCurrency]; return $this->get('/coins/' . $id . '/contract/' . $contractAddress . '/market_chart', $params); } /** * @param string $id * @param string $contractAddress * @param string $vsCurrency * @param string $from * @param string $to * @return array * @throws Exception */ public function getMarketChartRange( string $id, string $contractAddress, string $vsCurrency, string $from, string $to ): array { $params['vs_currency'] = $vsCurrency; $params['from'] = $from; $params['to'] = $to; return $this->get('/coins/' . $id . '/contract/' . $contractAddress . '/market_chart/range', $params); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/ExchangeRates.php
src/Api/ExchangeRates.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Exception; class ExchangeRates extends Api { /** * @return array * @throws Exception */ public function getExchangeRates(): array { return $this->get('/exchange_rates'); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/Ping.php
src/Api/Ping.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Exception; class Ping extends Api { /** * @return array * @throws Exception */ public function ping(): array { return $this->get('/ping'); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/Simple.php
src/Api/Simple.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Exception; class Simple extends Api { /** * @param string $ids * @param string $vsCurrencies * @param array $params * @return array * @throws Exception */ public function getPrice(string $ids, string $vsCurrencies, array $params = []): array { $params['ids'] = $ids; $params['vs_currencies'] = $vsCurrencies; return $this->get('/simple/price', $params); } /** * @param string $id * @param string $contractAddresses * @param string $vsCurrencies * @param array $params * @return array * @throws Exception */ public function getTokenPrice( string $id, string $contractAddresses, string $vsCurrencies, array $params = [] ): array { $params['contract_addresses'] = $contractAddresses; $params['vs_currencies'] = $vsCurrencies; return $this->get('/simple/token_price/' . $id, $params); } /** * @return array * @throws Exception */ public function getSupportedVsCurrencies() { return $this->get('/simple/supported_vs_currencies'); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/Indexes.php
src/Api/Indexes.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Exception; class Indexes extends Api { /** * @param array $params * @return array * @throws Exception */ public function getIndexes(array $params = []): array { return $this->get('/indexes', $params); } /** * @param string $id * @return array * @throws Exception */ public function getIndex(string $id): array { return $this->get('/indexes/' . $id); } /** * @return array * @throws Exception */ public function getList(): array { return $this->get('/indexes/list'); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/Coins.php
src/Api/Coins.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Exception; class Coins extends Api { /** * @return array * @throws Exception */ public function getList(): array { return $this->get('/coins/list'); } /** * @param string $vsCurrency * @param array $params * @return array * @throws Exception */ public function getMarkets(string $vsCurrency, array $params = []): array { $params['vs_currency'] = $vsCurrency; return $this->get('/coins/markets', $params); } /** * @param string $id * @param array $params * @return array * @throws Exception */ public function getCoin(string $id, array $params = []): array { return $this->get('/coins/' . $id, $params); } /** * @param string $id * @param array $params * @return array * @throws Exception */ public function getTickers(string $id, array $params = []): array { return $this->get('/coins/' . $id . '/tickers', $params); } /** * @param string $id * @param string $date * @param array $params * @return array * @throws Exception */ public function getHistory(string $id, string $date, array $params = []): array { $params['date'] = $date; return $this->get('/coins/' . $id . '/history', $params); } /** * @param string $id * @param string $vsCurrency * @param string $days * @return array * @throws Exception */ public function getMarketChart(string $id, string $vsCurrency, string $days): array { $params['vs_currency'] = $vsCurrency; $params['days'] = $days; return $this->get('/coins/' . $id . '/market_chart', $params); } /** * @param string $id * @param string $vsCurrency * @param string $from * @param string $to * @return array * @throws Exception */ public function getMarketChartRange(string $id, string $vsCurrency, string $from, string $to): array { $params['vs_currency'] = $vsCurrency; $params['from'] = $from; $params['to'] = $to; return $this->get('/coins/' . $id . '/market_chart/range', $params); } /** * @param string $id * @param array $params * @return array * @throws Exception */ public function getStatusUpdates(string $id, array $params = []): array { return $this->get('/coins/' . $id . '/status_updates', $params); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/src/Api/Exchanges.php
src/Api/Exchanges.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Api; use Exception; class Exchanges extends Api { /** * @param array $params * @return array * @throws Exception */ public function getExchanges(array $params = []): array { return $this->get('/exchanges', $params); } /** * @return array * @throws Exception */ public function getList(): array { return $this->get('/exchanges/list'); } /** * @param string $id * @return array * @throws Exception */ public function getExchange(string $id): array { return $this->get('/exchanges/' . $id); } /** * @param string $id * @param array $params * @return array * @throws Exception */ public function getTickers(string $id, array $params = []): array { return $this->get('/exchanges/' . $id . '/tickers', $params); } /** * @param string $id * @param array $params * @return array * @throws Exception */ public function getStatusUpdates(string $id, array $params = []): array { return $this->get('/exchanges/' . $id . '/status_updates', $params); } /** * @param string $id * @param string $days * @return array * @throws Exception */ public function getVolumeChart(string $id, string $days): array { return $this->get('/exchanges/' . $id . '/volume_chart', ['days' => $days]); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/CoinGeckoClientTest.php
tests/CoinGeckoClientTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests; use Codenixsv\CoinGeckoApi\Api\Coins; use Codenixsv\CoinGeckoApi\Api\Contract; use Codenixsv\CoinGeckoApi\Api\Derivatives; use Codenixsv\CoinGeckoApi\Api\Events; use Codenixsv\CoinGeckoApi\Api\ExchangeRates; use Codenixsv\CoinGeckoApi\Api\Exchanges; use Codenixsv\CoinGeckoApi\Api\Finance; use Codenixsv\CoinGeckoApi\Api\Globals; use Codenixsv\CoinGeckoApi\Api\Indexes; use Codenixsv\CoinGeckoApi\Api\Simple; use Codenixsv\CoinGeckoApi\Api\StatusUpdates; use Codenixsv\CoinGeckoApi\CoinGeckoClient; use GuzzleHttp\Client; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; class CoinGeckoClientTest extends TestCase { public function testGetBaseClient() { $client = new CoinGeckoClient(); $this->assertInstanceOf(Client::class, $client->getHttpClient()); } public function testPing() { $client = new CoinGeckoClient(); $this->assertIsArray($client->ping()); } public function testSimple() { $client = new CoinGeckoClient(); $this->assertInstanceOf(Simple::class, $client->simple()); } public function testCoins() { $client = new CoinGeckoClient(); $this->assertInstanceOf(Coins::class, $client->coins()); } public function testContract() { $client = new CoinGeckoClient(); $this->assertInstanceOf(Contract::class, $client->contract()); } public function testExchanges() { $client = new CoinGeckoClient(); $this->assertInstanceOf(Exchanges::class, $client->exchanges()); } public function testFinance() { $client = new CoinGeckoClient(); $this->assertInstanceOf(Finance::class, $client->finance()); } public function testIndexes() { $client = new CoinGeckoClient(); $this->assertInstanceOf(Indexes::class, $client->indexes()); } public function testDerivatives() { $client = new CoinGeckoClient(); $this->assertInstanceOf(Derivatives::class, $client->derivatives()); } public function testStatusUpdates() { $client = new CoinGeckoClient(); $this->assertInstanceOf(StatusUpdates::class, $client->statusUpdates()); } public function testEvents() { $client = new CoinGeckoClient(); $this->assertInstanceOf(Events::class, $client->events()); } public function testExchangeRates() { $client = new CoinGeckoClient(); $this->assertInstanceOf(ExchangeRates::class, $client->exchangeRates()); } public function testGlobals() { $client = new CoinGeckoClient(); $this->assertInstanceOf(Globals::class, $client->globals()); } public function testGetLastResponseIsNull() { $client = new CoinGeckoClient(); $this->assertNull($client->getLastResponse()); } public function testSetLastResponse() { $client = new CoinGeckoClient(); $response = $this->createMock(ResponseInterface::class); $client->setLastResponse($response); $this->assertInstanceOf(ResponseInterface::class, $client->getLastResponse()); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Message/ResponseTransformerTest.php
tests/Message/ResponseTransformerTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Message; use Codenixsv\CoinGeckoApi\Exception\TransformResponseException; use Codenixsv\CoinGeckoApi\Message\ResponseTransformer; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; class ResponseTransformerTest extends TestCase { public function testTransform() { $transformer = new ResponseTransformer(); $data = ['foo' => 'bar']; $response = new Response(200, ['Content-Type' => 'application/json'], json_encode($data)); $this->assertEquals($data, $transformer->transform($response)); } public function testTransformWithEmptyBody() { $transformer = new ResponseTransformer(); $data = []; $response = new Response(200, ['Content-Type' => 'application/json'], json_encode($data)); $this->assertEquals($data, $transformer->transform($response)); } public function testTransformThrowTransformResponseException() { $transformer = new ResponseTransformer(); $response = new Response(200, ['Content-Type' => 'application/json'], ''); $this->expectException(TransformResponseException::class); $transformer->transform($response); } public function testTransformWithIncorrectContentType() { $transformer = new ResponseTransformer(); $data = []; $response = new Response(200, ['Content-Type' => 'application/javascript'], json_encode($data)); $this->expectException(TransformResponseException::class); $this->assertEquals($data, $transformer->transform($response)); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/ExchangesTest.php
tests/Api/ExchangesTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use Codenixsv\CoinGeckoApi\Api\Exchanges; use Codenixsv\CoinGeckoApi\CoinGeckoClient; class ExchangesTest extends ApiTestCase { public function testGetExchanges() { $this->createApi()->getExchanges(); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/exchanges', $request->getUri()->__toString()); } public function testGetList() { $this->createApi()->getList(); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/exchanges/list', $request->getUri()->__toString()); } public function testGetExchange() { $this->createApi()->getExchange('binance'); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/exchanges/binance', $request->getUri()->__toString()); } public function testGetTickers() { $this->createApi()->getTickers('binance', ['coin_ids' => '0x,bitcoin']); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/exchanges/binance/tickers?coin_ids=0x%2Cbitcoin', $request->getUri()->__toString() ); } public function testGetStatusUpdates() { $this->createApi()->getStatusUpdates('binance'); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/exchanges/binance/status_updates', $request->getUri()->__toString()); } public function testGetVolumeChart() { $this->createApi()->getVolumeChart('binance', '1'); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/exchanges/binance/volume_chart?days=1', $request->getUri()->__toString()); } private function createApi(): Exchanges { return new Exchanges(new CoinGeckoClient($this->getMockClient())); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/StatusUpdatesTest.php
tests/Api/StatusUpdatesTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use Codenixsv\CoinGeckoApi\Api\StatusUpdates; use Codenixsv\CoinGeckoApi\CoinGeckoClient; class StatusUpdatesTest extends ApiTestCase { public function testGlobal() { $api = new StatusUpdates(new CoinGeckoClient($this->getMockClient())); $api->getStatusUpdates(); $this->assertEquals('/api/v3/status_updates', $this->getLastRequest()->getUri()->__toString()); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/IndexesTest.php
tests/Api/IndexesTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use Codenixsv\CoinGeckoApi\Api\Indexes; use Codenixsv\CoinGeckoApi\CoinGeckoClient; class IndexesTest extends ApiTestCase { public function testGetIndexes() { $this->createApi()->getIndexes(); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/indexes', $request->getUri()->__toString()); } public function testGetIndex() { $this->createApi()->getIndex('BAT'); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/indexes/BAT', $request->getUri()->__toString()); } public function testGetList() { $this->createApi()->getList(); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/indexes/list', $request->getUri()->__toString()); } private function createApi(): Indexes { return new Indexes(new CoinGeckoClient($this->getMockClient())); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/ExchangeRatesTest.php
tests/Api/ExchangeRatesTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use Codenixsv\CoinGeckoApi\Api\ExchangeRates; use Codenixsv\CoinGeckoApi\CoinGeckoClient; class ExchangeRatesTest extends ApiTestCase { public function testGetExchangeRates() { $api = new ExchangeRates(new CoinGeckoClient($this->getMockClient())); $api->getExchangeRates(); $this->assertEquals('/api/v3/exchange_rates', $this->getLastRequest()->getUri()->__toString()); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/FinanceTest.php
tests/Api/FinanceTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use Codenixsv\CoinGeckoApi\Api\Finance; use Codenixsv\CoinGeckoApi\CoinGeckoClient; class FinanceTest extends ApiTestCase { public function testGetPlatforms() { $this->createApi()->getPlatforms(); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/finance_platforms', $request->getUri()->__toString()); } public function testGetProducts() { $this->createApi()->getProducts(); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/finance_products', $request->getUri()->__toString()); } private function createApi(): Finance { return new Finance(new CoinGeckoClient($this->getMockClient())); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/CoinsTest.php
tests/Api/CoinsTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use Codenixsv\CoinGeckoApi\Api\Coins; use Codenixsv\CoinGeckoApi\CoinGeckoClient; class CoinsTest extends ApiTestCase { public function testGetList() { $this->createApi()->getList(); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/coins/list', $request->getUri()->__toString() ); } public function testGetMarkets() { $this->createApi()->getMarkets('usd', ['per_page' => 10, 'sparkline' => 'true']); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/coins/markets?per_page=10&sparkline=true&vs_currency=usd', $request->getUri()->__toString() ); } public function testGetCoin() { $this->createApi()->getCoin('bitcoin', ['tickers' => 'false', 'market_data' => 'false']); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/coins/bitcoin?tickers=false&market_data=false', $request->getUri()->__toString() ); } public function testGetTickers() { $this->createApi()->getTickers('bitcoin'); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/coins/bitcoin/tickers', $request->getUri()->__toString() ); } public function testGetHistory() { $this->createApi()->getHistory('bitcoin', '30-12-2017'); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/coins/bitcoin/history?date=30-12-2017', $request->getUri()->__toString() ); } public function testGetMarketChart() { $this->createApi()->getMarketChart('bitcoin', 'usd', 'max'); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=max', $request->getUri()->__toString() ); } public function testGetMarketChartRange() { $this->createApi()->getMarketChartRange('bitcoin', 'usd', '1392577232', '1422577232'); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/coins/bitcoin/market_chart/range?vs_currency=usd&from=1392577232&to=1422577232', $request->getUri()->__toString() ); } public function testGetStatusUpdates() { $this->createApi()->getStatusUpdates('0x'); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/coins/0x/status_updates', $request->getUri()->__toString() ); } private function createApi(): Coins { return new Coins(new CoinGeckoClient($this->getMockClient())); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/ApiTestCase.php
tests/Api/ApiTestCase.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use GuzzleHttp\Client; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; class ApiTestCase extends TestCase { private $transactions = []; private $mockClient = null; protected function getLastRequest(): ?RequestInterface { if (($count = count($this->transactions)) === 0) { return null; } return $this->transactions[$count - 1]['request'] ?? null; } protected function getMockClient() { $mock = new MockHandler([ new Response(200, ['Content-Type' => 'application/json'], json_encode(['fo' => 'bar'])), ]); $handlerStack = HandlerStack::create($mock); $handlerStack->push(Middleware::history($this->transactions)); $this->mockClient = new Client(['handler' => $handlerStack]); return $this->mockClient; } protected function tearDown(): void { $this->mockClient = null; $this->transactions = []; } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/ContractTest.php
tests/Api/ContractTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use Codenixsv\CoinGeckoApi\Api\Contract; use Codenixsv\CoinGeckoApi\CoinGeckoClient; class ContractTest extends ApiTestCase { public function testGetContract() { $this->createApi()->getContract('ethereum', '0xE41d2489571d322189246DaFA5ebDe1F4699F498'); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/coins/ethereum/contract/0xE41d2489571d322189246DaFA5ebDe1F4699F498', $request->getUri()->__toString() ); } public function testGetMarketChart() { $this->createApi()->getMarketChart('ethereum', '0xE41d2489571d322189246DaFA5ebDe1F4699F498', 'usd', '1'); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/coins/ethereum/contract/0xE41d2489571d322189246DaFA5ebDe1F4699F498/market_chart' . '?days=1&vs_currency=usd', $request->getUri()->__toString() ); } public function testGetMarketChartRange() { $this->createApi()->getMarketChartRange( 'ethereum', '0xE41d2489571d322189246DaFA5ebDe1F4699F498', 'usd', '11392577232', ' 1422577232' ); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/coins/ethereum/contract/0xE41d2489571d322189246DaFA5ebDe1F4699F498/market_chart/range?' . 'vs_currency=usd&from=11392577232&to=%201422577232', $request->getUri()->__toString() ); } private function createApi(): Contract { return new Contract(new CoinGeckoClient($this->getMockClient())); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/PingTest.php
tests/Api/PingTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use Codenixsv\CoinGeckoApi\Api\Ping; use Codenixsv\CoinGeckoApi\CoinGeckoClient; class PingTest extends ApiTestCase { public function testPing() { $api = new Ping(new CoinGeckoClient($this->getMockClient())); $api->ping(); $this->assertEquals('/api/v3/ping', $this->getLastRequest()->getUri()->__toString()); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/DerivativesTest.php
tests/Api/DerivativesTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use Codenixsv\CoinGeckoApi\Api\Derivatives; use Codenixsv\CoinGeckoApi\CoinGeckoClient; class DerivativesTest extends ApiTestCase { public function testGetDerivatives() { $this->createApi()->getDerivatives(); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/derivatives', $request->getUri()->__toString()); } public function testGetExchanges() { $this->createApi()->getExchanges(); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/derivatives/exchanges', $request->getUri()->__toString()); } public function testGetExchange() { $this->createApi()->getExchange('binance_futures'); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/derivatives/exchanges/binance_futures', $request->getUri()->__toString()); } public function testGetExchangeList() { $this->createApi()->getExchangeList(); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/derivatives/exchanges/list', $request->getUri()->__toString()); } private function createApi(): Derivatives { return new Derivatives(new CoinGeckoClient($this->getMockClient())); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/SimpleTest.php
tests/Api/SimpleTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use Codenixsv\CoinGeckoApi\Api\Simple; use Codenixsv\CoinGeckoApi\CoinGeckoClient; class SimpleTest extends ApiTestCase { public function testGetPrice() { $this->createApi()->getPrice('0x,bitcoin', 'usd,rub'); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/simple/price?ids=0x%2Cbitcoin&vs_currencies=usd%2Crub', $request->getUri()->__toString() ); } public function testGetTokenPrice() { $api = $this->createApi(); $api->getTokenPrice('ethereum', '0xE41d2489571d322189246DaFA5ebDe1F4699F498', 'usd,rub'); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/simple/token_price/ethereum?contract_addresses' . '=0xE41d2489571d322189246DaFA5ebDe1F4699F498&vs_currencies=usd%2Crub', $request->getUri()->__toString() ); } public function testGetSupportedVsCurrencies() { $this->createApi()->getSupportedVsCurrencies(); $request = $this->getLastRequest(); $this->assertEquals( '/api/v3/simple/supported_vs_currencies', $request->getUri()->__toString() ); } private function createApi(): Simple { return new Simple(new CoinGeckoClient($this->getMockClient())); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/EventsTest.php
tests/Api/EventsTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use Codenixsv\CoinGeckoApi\Api\Events; use Codenixsv\CoinGeckoApi\CoinGeckoClient; class EventsTest extends ApiTestCase { public function testGetEvents() { $this->createApi()->getEvents(); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/events', $request->getUri()->__toString()); } public function testGetCountries() { $this->createApi()->getCountries(); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/events/countries', $request->getUri()->__toString()); } public function testGetTypes() { $this->createApi()->getTypes(); $request = $this->getLastRequest(); $this->assertEquals('/api/v3/events/types', $request->getUri()->__toString()); } private function createApi(): Events { return new Events(new CoinGeckoClient($this->getMockClient())); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
codenix-sv/coingecko-api
https://github.com/codenix-sv/coingecko-api/blob/53996fc09eb903d08a80fbeb7bc8c4f24553c144/tests/Api/GlobalsTest.php
tests/Api/GlobalsTest.php
<?php declare(strict_types=1); namespace Codenixsv\CoinGeckoApi\Tests\Api; use Codenixsv\CoinGeckoApi\Api\Globals; use Codenixsv\CoinGeckoApi\CoinGeckoClient; class GlobalsTest extends ApiTestCase { public function testGlobal() { $api = new Globals(new CoinGeckoClient($this->getMockClient())); $api->getGlobal(); $this->assertEquals('/api/v3/global', $this->getLastRequest()->getUri()->__toString()); } }
php
MIT
53996fc09eb903d08a80fbeb7bc8c4f24553c144
2026-01-05T04:54:14.425104Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/app/controllers/Welcome.php
app/controllers/Welcome.php
<?php class Welcome extends GPController { public function index() { GP::view('welcome_view'); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/app/models/StubModel.php
app/models/StubModel.php
<?php /** * This stub is here so that git keeps track of this folder. Feel free to delete */ final class StubModel extends GPNode { }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/app/views/welcome_view.php
app/views/welcome_view.php
<html> <head> <title>Welcome page</title> <style type="text/css"> .box { border: solid black 1px; width: 500px; margin:100px auto 0 auto; padding: 10px; text-align: center; } .header { color: blue; } </style> </head> <body> <div class="box"> <h2 class="header">Welcome to the GraPHP framework</h2> <div> This is a work in progress, contribute on <a href="https://github.com/mikeland86/graphp" target="_blank">github</a> </div> </div> </body> </html>
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/app/libraries/StubLibrary.php
app/libraries/StubLibrary.php
<?php /** * This stub is here so that git keeps track of this folder. Feel free to delete */ final class StubLibrary extends GPObject { }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/model/GPEdgeType.php
graphp/model/GPEdgeType.php
<?php class GPEdgeType extends GPObject { private $fromType; private $to; private $name; private $storageKey; private $singleNodeName; private $inverse; private $type; public function __construct($to, $name = '', $storage_key = '') { $this->to = $to; $this->name = $name ? $name : $to; $this->storageKey = $storage_key; } public function setFromClass($from_class) { $this->fromType = $from_class::getType(); } public function getType() { if (!$this->type) { $this->type = STRUtils::to64BitInt($this->getStorageKey()); } return $this->type; } public function getName() { return strtolower($this->name); } public function getTo() { return $this->to; } public function getToType() { $to = $this->to; return $to::getType(); } public function getFromType() { return $this->fromType; } public function setSingleNodeName($name) { $this->singleNodeName = $name; return $this; } public function getSingleNodeName() { return strtolower($this->singleNodeName); } public function inverse($inverse) { $this->inverse = $inverse; $inverse->inverse = $this; $inverse->fromType = $this->getToType(); return $this; } public function getInverse() { return $this->inverse; } private function getStorageKey() { if ($this->storageKey) { return $this->storageKey; } return $this->fromType.$this->getToType().$this->name; } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/model/GPBatch.php
graphp/model/GPBatch.php
<?php final class GPBatch extends GPObject { private $nodes = []; private $classes = []; private $lazy; private $lazyEdges = []; private $lazyForce = false; public function __construct(array $nodes, $lazy) { $this->nodes = $nodes; $this->classes = array_unique(array_map( function($node) { return get_class($node); }, $nodes )); $this->lazy = $lazy; } public function delete() { GPNode::batchDelete($this->nodes); } public function save() { GPNode::batchSave($this->nodes); return $this; } public function __call($method, $args) { if (substr_compare($method, 'forceLoad', 0, 9) === 0) { if ($this->lazy) { $this->lazyForce = true; } return $this->handleLoad(mb_substr($method, 5), $args, true); } if (substr_compare($method, 'load', 0, 4) === 0) { return $this->handleLoad($method, $args); } throw new GPException( 'Method '.$method.' not found in '.get_called_class() ); } public function load() { Assert::true($this->lazy, 'Cannot call load on non lazy batch loader'); GPNode::batchLoadConnectedNodes( $this->nodes, $this->lazyEdges, $this->lazyForce ); $this->lazyEdges = []; $this->lazyForce = false; return $this; } public function getConnectedNodeCount(array $edges) { if (!$this->nodes) { return []; } $results = GPDatabase::get()->getConnectedNodeCount($this->nodes, $edges); foreach ($results as $from_node_id => $rows) { $results[$from_node_id] = ipull($rows, 'c', 'type'); } return $results; } private function handleLoad($method, $args, $force = false) { if (!$this->nodes) { return $this; } if (substr_compare($method, 'IDs', -3) === 0) { if ($this->lazy) { throw new GPException('Lazy ID loading is not supported'); } else { GPNode::batchLoadConnectedNodes( $this->nodes, $this->getEdges(mb_substr($method, 4, -3)), $force, true ); } } else { if ($this->lazy) { $this->lazyEdges += mpull($this->getEdges(mb_substr($method, 4)), null, 'getType'); } else { GPNode::batchLoadConnectedNodes( $this->nodes, $this->getEdges(mb_substr($method, 4)), $force ); } } return $this; } private function getEdges($edge_name) { $edges = array_filter(array_map( function($class) use ($edge_name) { return $class::isEdgeType($edge_name) ? $class::getEdgeType($edge_name) : null; }, $this->classes )); Assert::truthy($edges, $edge_name.' is not a valid edge name.'); return $edges; } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/model/GPNodeMap.php
graphp/model/GPNodeMap.php
<?php class GPNodeMap extends GPObject { private static $inverseMap = []; private static $map = []; private static function getMap() { if (!self::$map) { self::$map = is_readable(self::buildPath()) ? include self::buildPath() : null; } return self::$map ?: []; } private static function getInverseMap() { if (!self::$inverseMap) { self::$inverseMap = array_flip(self::getMap()); } return self::$inverseMap; } /** * getClass * * @param mixed $type Description. * * @access public * @static * * @return mixed Value. */ public static function getClass($type) { if (!idx(self::getMap(), $type)) { self::regenMap(); } return idxx(self::getMap(), $type); } public static function isNode($node_name) { $map = self::getInverseMap(); if (!idx($map, $node_name)) { self::regenMap(); $map = self::getInverseMap(); } return array_key_exists($node_name, $map); } public static function regenAndGetAllTypes() { self::regenMap(); return self::getMap(); } public static function addToMapForTest($class) { GPEnv::assertTestEnv(); self::$map[$class::getType()] = $class; } private static function regenMap() { $app_folder = GPConfig::get()->app_folder; self::$map = []; self::$inverseMap = []; $file = "<?php\nreturn [\n"; $model_map = new GPFileMap(ROOT_PATH.$app_folder.'/models', 'models'); foreach ($model_map->getAllFileNames() as $class) { $file .= ' '.$class::getType().' => \''.$class."',\n"; self::$map[$class::getType()] = $class; self::$inverseMap[$class] = $class::getType(); } $file .= "];\n"; $file_path = self::buildPath(); $does_file_exist = file_exists($file_path); file_put_contents($file_path, $file); if (!$does_file_exist) { // File was just created, make sure to make it readable chmod($file_path, 0666); } } private static function buildPath() { return '/tmp/maps/'.GPConfig::get()->app_folder.'_node'; } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/model/GPNodeMagicMethods.php
graphp/model/GPNodeMagicMethods.php
<?php trait GPNodeMagicMethods { private static $methodCache = []; // Magic API: // // getX() should only work if the node has a GPDataType with the name x // returned by getDataTypeImpl() or if the node has a GPEdgeType with that // name that has previously loaded. Calling getX on an unloaded edge will // throw. // // setY() should only work if y is defined in data_types. (Not for edges) // // unsetZ() should only work if z is defined in data_types. // // addFoo() should only work if Foo is a defined edge for that node. // // getOneFoo Is like getFoo for edges but returns only the first result. // // remove[edge_type]($node) should remove edge to that node // removeAll[edge_type] should remove all edges of that type // // load[edge_type] called to load edges (and end nodes) of that type // load[edge_type]IDs called to load edges (and end ids) of that type // // save() must be called for all set, add and remove operations to be // performed // public function __call($method, $args) { $cache_key = get_class($this).$method; if (array_key_exists($cache_key, self::$methodCache)) { return call_user_func(self::$methodCache[$cache_key], $this); } if (substr_compare($method, 'get', 0, 3) === 0) { return $this->handleGet(mb_substr($method, 3), $args); } if (substr_compare($method, 'is', 0, 2) === 0) { $name = mb_substr($method, 2); $type = static::getDataTypeByName($name); if ($type && $type->getType() === GPDataType::GP_BOOL) { return $this->handleGet(mb_substr($method, 2), $args); } } if (substr_compare($method, 'set', 0, 3) === 0) { Assert::equals( count($args), 1, GPErrorText::wrongArgs(get_called_class(), $method, 1, count($args)) ); return $this->setDataX(strtolower(mb_substr($method, 3)), idx0($args)); } if (substr_compare($method, 'add', 0, 3) === 0) { $edge = static::getEdgeType(mb_substr($method, 3)); return $this->addPendingConnectedNodes($edge, make_array(idx0($args))); } if (substr_compare($method, 'removeAll', 0, 9) === 0) { $edge = static::getEdgeType(mb_substr($method, 9)); return $this->addPendingRemovalAllNodes($edge); } if (substr_compare($method, 'remove', 0, 6) === 0) { $edge = static::getEdgeType(mb_substr($method, 6)); return $this->addPendingRemovalNodes($edge, make_array(idx0($args))); } if (substr_compare($method, 'forceLoad', 0, 9) === 0) { return $this->handleLoad(mb_substr($method, 5), $args, true); } if (substr_compare($method, 'load', 0, 4) === 0) { return $this->handleLoad($method, $args); } if (substr_compare($method, 'unset', 0, 3) === 0) { return $this->unsetDataX(strtolower(mb_substr($method, 5))); } throw new GPException( 'Method '.$method.' not found in '.get_called_class() ); } private function handleGet($name, $args) { $lower_name = strtolower($name); // Default to checking data first. $type = static::getDataTypeByName($lower_name); if ($type) { self::$methodCache[get_class($this).'get'.$name] = function($that) use ($type, $lower_name) { return $that->getData($lower_name, $type->getDefault()); }; return $this->getData($lower_name, $type->getDefault()); } if (substr_compare($name, 'One', 0, 3, true) === 0) { $name = str_ireplace('One', '', $name); $one = true; } if (substr_compare($name, 'IDs', -3) === 0) { $name = str_ireplace('IDs', '', $name); $ids_only = true; } else if (substr_compare($name, 'ID', -2) === 0) { $name = str_ireplace('ID', '', $name); $ids_only = true; } $name = strtolower($name); $edge = static::getEdgeType($name); if ($edge) { if ($name === $edge->getSingleNodeName()) { $one = true; } if (empty($ids_only)) { $result = $this->getConnectedNodes([$edge]); } else { $result = $this->getConnectedIDs([$edge]); } $nodes = idx($result, $edge->getType(), []); return empty($one) ? $nodes : idx0($nodes); } else { throw new GPException( 'Getter did not match any data or edge', 1 ); } } private function handleLoad($method, $args, $force = false) { $limit = null; $offset = 0; if (count($args) === 1) { $limit = idx0($args); } else if (count($args) === 2) { list($limit, $offset) = $args; } if (substr_compare($method, 'IDs', -3) === 0) { $edge_name = mb_substr($method, 4, -3); $edge = static::getEdgeType($edge_name); return $this->loadConnectedIDs([$edge], $force, $limit, $offset); } else { $edge_name = mb_substr($method, 4); $edge = static::getEdgeType($edge_name); return $this->loadConnectedNodes([$edge], $force, $limit, $offset); } } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/model/GPNode.php
graphp/model/GPNode.php
<?php abstract class GPNode extends GPObject { use GPNodeLoader; use GPNodeMagicMethods; use GPBatchLoader; use GPNodeEdgeCreator; private $data, $id, $updated, $created, // array([edge_type] => [array of nodes indexed by id]) $connectedNodeIDs = [], $connectedNodes = [], $pendingConnectedNodes = [], $pendingRemovalNodes = [], $pendingRemovalAllNodes = [], $pendingRemovalAllInverseNodes = [], $nodesWithInverse = []; protected static $data_types = [], $edge_types = [], $edge_types_by_type = []; public function __construct(array $data = []) { $this->data = []; foreach ($data as $key => $value) { $this->data[strtolower($key)] = $value; } } public function getID() { return (int) $this->id; } public function isSaved(): bool { return $this->getID() > 0; } public function getUpdated() { return $this->updated; } public function getCreatedTimestamp() { return $this->created; } public static function getType() { return STRUtils::to64BitInt(static::getStorageKey()); } public static function getStorageKey() { return 'node_'.get_called_class(); } public function setDataX($key, $value) { $data_type = self::getDataTypeByName($key); if ($data_type === null) { throw new GPException( '\''.$key.'\' is not a declared data type on '.get_class($this). '. Possible data types are ['. implode(', ', mpull(self::getDataTypes(), 'getName')).']' ); } $data_type->assertValueIsOfType($value); return $this->setData($key, $value); } public function setData($key, $value) { $this->data[strtolower($key)] = $value; return $this; } public function setDataArray(array $data): self { $this->data = $data; return $this; } public function getDataX($key) { $type = self::getDataTypeByName($key); Assert::truthy($type); return $this->getData($key, $type->getDefault()); } public function getData($key, $default = null) { return idx($this->data, strtolower($key), $default); } public function getDataArray() { return $this->data; } public function getJSONData() { return json_encode($this->data); } public function getIndexedData() { $keys = array_keys(mfilter(self::getDataTypes(), 'isIndexed')); return array_select_keys($this->data, $keys); } public function unsetDataX($key) { Assert::truthy(self::getDataTypeByName($key)); return $this->unsetData($key); } public function unsetData($key) { unset($this->data[strtolower($key)]); return $this; } public function unsafeSave() { GPDatabase::get()->beginUnguardedWrites(); $ret = $this->save(); GPDatabase::get()->endUnguardedWrites(); return $ret; } public function save() { $db = GPDatabase::get(); $db->startTransaction(); if ($this->id) { $db->updateNodeData($this); } else { $this->id = $db->insertNode($this); $this->updated = date('Y-m-d H-i-s'); self::$cache[$this->id] = $this; } $db->updateNodeIndexedData($this); $db->saveEdges($this, $this->pendingConnectedNodes); $db->deleteEdges($this, $this->pendingRemovalNodes); $db->deleteAllEdges($this, $this->pendingRemovalAllNodes); $db->deleteAllInverseEdges($this, $this->pendingRemovalAllInverseNodes); batch($this->nodesWithInverse)->save(); $db->commit(); $this->pendingConnectedNodes = []; $this->pendingRemovalNodes = []; $this->pendingRemovalAllNodes = []; $this->pendingRemovalAllInverseNodes = []; $this->nodesWithInverse = []; return $this; } public function addPendingConnectedNodes(GPEdgeType $edge, array $nodes) { if ($edge->getInverse()) { $this->nodesWithInverse += mpull($nodes, null, 'getID'); foreach ($nodes as $node) { $node->addPendingNodes( 'pendingConnectedNodes', $edge->getInverse(), [$this] ); } } return $this->addPendingNodes('pendingConnectedNodes', $edge, $nodes); } public function addPendingRemovalNodes(GPEdgeType $edge, array $nodes) { if ($edge->getInverse()) { $this->nodesWithInverse += mpull($nodes, null, 'getID'); foreach ($nodes as $key => $node) { $node->addPendingNodes( 'pendingRemovalNodes', $edge->getInverse(), [$this] ); } } return $this->addPendingNodes('pendingRemovalNodes', $edge, $nodes); } public function addPendingRemovalAllNodes($edge) { if ($edge->getInverse()) { // This can be slow :( there is no index on (to_node_id, type) $this->pendingRemovalAllInverseNodes[$edge->getInverse()->getType()] = $edge->getInverse()->getType(); } $this->pendingRemovalAllNodes[$edge->getType()] = $edge->getType(); return $this; } private function addPendingNodes($var, GPEdgeType $edge, array $nodes) { Assert::equals( count($nodes), count(mfilter(array_filter($nodes), 'getID')), 'You can\'t add nodes that have not been saved' ); Assert::allEquals( mpull($nodes, 'getType'), $edge->getToType(), 'Trying to add nodes of the wrong type. '. json_encode(mpull($nodes, 'getType')).' != '.$edge->getToType() ); if (!array_key_exists($edge->getType(), $this->$var)) { $this->{$var}[$edge->getType()] = []; } $this->{$var}[$edge->getType()] = array_merge_by_keys( $this->{$var}[$edge->getType()], mpull($nodes, null, 'getID') ); return $this; } private function loadConnectedIDs( array $edges, $force = false, $limit = null, $offset = 0 ) { $types = mpull($edges, 'getType', 'getType'); if ($force) { array_unset_keys($this->connectedNodeIDs, $types); } $already_loaded = array_select_keys($this->connectedNodeIDs, $types); $to_load_types = array_diff_key($types, $this->connectedNodeIDs); $ids = GPDatabase::get()->getConnectedIDs( $this, $to_load_types, $limit, $offset); $this->connectedNodeIDs = array_merge_by_keys( $this->connectedNodeIDs, $ids + $already_loaded ); return $this; } private function getConnectedIDs(array $edges) { $types = mpull($edges, 'getType'); return array_select_keysx($this->connectedNodeIDs, $types); } public function loadConnectedNodes( array $edges, $force = false, $limit = null, $offset = 0 ) { $ids = $this ->loadConnectedIDs($edges, $force, $limit, $offset) ->getConnectedIDs($edges); $nodes = GPNode::multiGetByID(array_flatten($ids)); foreach ($ids as $edge_type => & $ids_for_edge_type) { foreach ($ids_for_edge_type as $key => $id) { $ids_for_edge_type[$key] = $nodes[$id]; } } $this->connectedNodes = array_merge_by_keys($this->connectedNodes, $ids); return $this; } public function getConnectedNodes(array $edges) { $types = mpull($edges, 'getType'); return array_select_keysx( $this->connectedNodes, $types, function() use ($edges) { $ids = array_keys($this->connectedNodes); throw new GPException( GPErrorText::missingEdges($edges, $this, $ids), 1 ); } ); } public function getConnectedNodeCount(array $edges) { $results = GPDatabase::get()->getConnectedNodeCount([$this], $edges); return ipull(idx($results, $this->getID(), []), 'c', 'type'); } private function isLoaded($edge_or_edges) { $edges = make_array($edge_or_edges); $types = mpull($edges, 'getType'); return count(array_select_keys($this->connectedNodes, $types)) === count($types); } protected static function getEdgeTypesImpl() { return []; } public function delete() { unset(self::$cache[$this->getID()]); GPDatabase::get()->deleteNodes([$this]); } final public static function getEdgeTypes() { $class = get_called_class(); if (!isset(static::$edge_types[$class])) { $edges = static::getEdgeTypesImpl(); foreach ($edges as $edge) { $edge->setFromClass(get_called_class()); } static::$edge_types[$class] = mpull($edges, null, 'getName') + mpull($edges, null, 'getSingleNodeName'); unset(static::$edge_types[$class]['']); static::$edge_types_by_type[$class] = mpull($edges, null, 'getType'); foreach ($edges as $edge) { if (!array_key_exists($edge->getTo(), static::$edge_types)) { $to = $edge->getTo(); $to::getEdgeTypes(); } } } return static::$edge_types[$class]; } final public static function getEdgeType($name) { $name = strtolower($name); if (!array_key_exists($name, self::getEdgeTypes())) { throw new GPException(GPErrorText::missingEdgeType( get_called_class(), $name, self::getEdgeTypes() )); } return self::getEdgeTypes()[$name]; } final public static function isEdgeType($name) { return (bool) idx(self::getEdgeTypes(), strtolower($name)); } final public static function getEdgeTypeByType($type) { $class = get_called_class(); isset(static::$edge_types_by_type[$class]) ?: self::getEdgeTypes(); return idxx(static::$edge_types_by_type[$class], $type); } final public static function getEdgeTypesByType() { self::getEdgeTypes(); return static::$edge_types_by_type[get_called_class()]; } protected static function getDataTypesImpl() { return []; } final public static function getDataTypes() { $class = get_called_class(); if (!array_key_exists($class, self::$data_types)) { self::$data_types[$class] = mpull(static::getDataTypesImpl(), null, 'getName'); } return self::$data_types[$class]; } final public static function getDataTypeByName($name) { $data_types = self::getDataTypes(); return idx($data_types, strtolower($name)); } } function batch(/*array of nodes, single nodes, arrays of arrays of nodes*/) { return new GPBatch(array_flatten(func_get_args()), false /*lazy*/); } function lazy(/*array of nodes, single nodes, arrays of arrays of nodes*/) { return new GPBatch(array_flatten(func_get_args()), true /*lazy*/); }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/model/GPDataType.php
graphp/model/GPDataType.php
<?php class GPDataType extends GPObject { use GPDataTypeCreator; const GP_INT = 'is_int'; const GP_NODE_ID = 'is_int'; const GP_FLOAT = 'is_float'; const GP_NUMBER = 'is_numeric'; const GP_ARRAY = 'is_array'; const GP_STRING = 'is_string'; const GP_BOOL = 'is_bool'; const GP_ANY = 'is_any'; private $name; private $type; private $isIndexed; private $default; public function __construct( $name, $type = self::GP_ANY, $is_indexed = false, $default = null ) { $this->name = strtolower($name); $this->type = $type; $this->isIndexed = $is_indexed; $this->default = $default; } public function assertValueIsOfType($value) { self::assertConstValueExists($this->type); if ($this->type === self::GP_ANY) { return true; } if (!call_user_func($this->type, $value)) { throw new Exception( 'Value '.$value.' is not of type '.mb_substr($this->type, 3) ); } return true; } public function getName() { return $this->name; } public function getIndexedType() { Assert::true($this->isIndexed()); return STRUtils::to64BitInt($this->name); } public function isIndexed() { return $this->isIndexed; } public function getType() { return $this->type; } public function getDefault() { return $this->default; } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/model/GPNodeLoader.php
graphp/model/GPNodeLoader.php
<?php trait GPNodeLoader { private static $cache = []; public static function createFromType($type, array $data = []) { $class = GPNodeMap::getClass($type); return new $class($data); } private static function nodeFromArray(array $data) { $class = GPNodeMap::getClass($data['type']); $node = new $class(json_decode($data['data'], true)); $node->id = $data['id']; $node->updated = $data['updated']; $node->created = $data['created']; return $node; } public static function getByID($id) { if (!array_key_exists($id, self::$cache)) { $node_data = get_called_class() === GPNode::class ? GPDatabase::get()->getNodeByID($id) : GPDatabase::get()->getNodeByIDType($id, self::getType()); if ($node_data === null) { return null; } self::$cache[$id] = self::nodeFromArray($node_data); } if ( get_called_class() !== GPNode::class && self::$cache[$id]->getType() !== self::getType() ) { return null; } return self::$cache[$id]; } public static function multiGetByID(array $ids) { $ids = key_by_value($ids); $to_fetch = array_diff_key($ids, self::$cache); $node_datas = get_called_class() === GPNode::class ? GPDatabase::get()->multigetNodeByIDType($to_fetch) : GPDatabase::get()->multigetNodeByIDType($to_fetch, self::getType()); foreach ($node_datas as $node_data) { self::$cache[$node_data['id']] = self::nodeFromArray($node_data); } $nodes = array_select_keys(self::$cache, $ids); if (get_called_class() === GPNode::class) { return $nodes; } $type = self::getType(); return array_filter( $nodes, function($node) use ($type) { return $node->getType() === $type; } ); } public static function __callStatic($name, array $arguments) { $only_one = false; $len = mb_strlen($name); if ( strpos($name, 'getBy') === 0 && strpos($name, 'Range') === ($len - 5) ) { $type_name = strtolower(mb_substr($name, 5, $len - 10)); $range = true; } else if (substr_compare($name, 'getBy', 0, 5) === 0) { $type_name = strtolower(mb_substr($name, 5)); } else if (substr_compare($name, 'getOneBy', 0, 8) === 0) { $type_name = strtolower(mb_substr($name, 8)); $only_one = true; } else if (substr_compare($name, 'getAllWith', 0, 10) === 0) { $type_name = strtolower(mb_substr($name, 10)); $get_all_with_type = true; } if (isset($type_name)) { $class = get_called_class(); $data_type = static::getDataTypeByName($type_name); Assert::truthy($data_type, $name.' is not a method on '.$class); if (isset($range)) { $required_args = 2; } else if (isset($get_all_with_type)) { $required_args = 0; } else { $required_args = 1; } Assert::truthy( count($arguments) >= $required_args, GPErrorText::wrongArgs($class, $name, $required_args, count($arguments)) ); if ($arguments) { $arg = idx0($arguments); foreach (make_array($arg) as $val) { $data_type->assertValueIsOfType($val); } } if (isset($range)) { array_unshift($arguments, $data_type->getIndexedType()); $results = self::getByIndexDataRange($arguments); } else if (isset($get_all_with_type)) { $results = self::getByIndexDataAll($data_type->getIndexedType()); } else { $results = self::getByIndexData($data_type->getIndexedType(), $arg); } return $only_one ? idx0($results) : $results; } throw new GPException('Method '.$name.' not found in '.get_called_class()); } public static function getAll($limit = GPDatabase::LIMIT, $offset = 0) { $node_datas = GPDatabase::get()->getAllByType(static::getType(), $limit, $offset); foreach ($node_datas as $node_data) { if (!isset(self::$cache[$node_data['id']])) { self::$cache[$node_data['id']] = self::nodeFromArray($node_data); } } return array_select_keys(self::$cache, ipull($node_datas, 'id')); } public static function clearCache() { self::$cache = []; } public static function unsetFromCache($id) { unset(self::$cache[$id]); } private static function getByIndexDataAll($data_type) { $node_ids = GPDatabase::get()->getNodeIDsByTypeDataAll($data_type); return self::multiGetByID($node_ids); } private static function getByIndexData($data_type, $data) { $db = GPDatabase::get(); $node_ids = $db->getNodeIDsByTypeData($data_type, make_array($data)); return self::multiGetByID($node_ids); } private static function getByIndexDataRange($args) { $ids = GPDatabase::get()->getNodeIDsByTypeDataRange( $args[0], $args[1], $args[2], idx($args, 3, GPDatabase::LIMIT), idx($args, 4, 0)); return self::multiGetByID($ids); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/model/GPBatchLoader.php
graphp/model/GPBatchLoader.php
<?php trait GPBatchLoader { public static function batchSave(array $nodes) { $db = GPDatabase::get(); $db->startTransaction(); foreach ($nodes as $node) { $node->save(); } $db->commit(); } public static function batchDelete(array $nodes) { $db = GPDatabase::get(); $db->startTransaction(); foreach ($nodes as $node) { $node->delete(); } $db->commit(); } /** * Deletes nodes, but ignores overriden delete() methods. More efficient but * won't do fancy recursive deletes. */ public static function simpleBatchDelete(array $nodes) { GPDatabase::get()->deleteNodes($nodes); array_unset_keys(self::$cache, mpull($nodes, 'getID')); } public static function batchLoadConnectedNodes( array $nodes, array $edge_types, $force = false, $ids_only = false ) { $nodes = mpull($nodes, null, 'getID'); $raw_edge_types = mpull($edge_types, 'getType'); if (!$force) { $names = mpull($edge_types, 'getName'); foreach ($nodes as $key => $node) { $valid_edge_types = array_select_keys( $node::getEdgeTypesByType(), $raw_edge_types ); if ($node->isLoaded($valid_edge_types)) { unset($nodes[$key]); } } } $ids = GPDatabase::get()->multiGetConnectedIDs($nodes, $raw_edge_types); if (!$ids_only) { $to_nodes = GPNode::multiGetByID(array_flatten($ids)); } foreach ($ids as $from_id => $type_ids) { $loaded_nodes_for_type = []; if (!$ids_only) { foreach ($type_ids as $edge_type => $ids_for_edge_type) { $loaded_nodes_for_type[$edge_type] = array_select_keys( $to_nodes, $ids_for_edge_type ); } } $nodes[$from_id]->connectedNodeIDs = array_merge_by_keys($nodes[$from_id]->connectedNodeIDs, $type_ids); if (!$ids_only) { $nodes[$from_id]->connectedNodes = array_merge_by_keys( $nodes[$from_id]->connectedNodes, $loaded_nodes_for_type ); } } foreach ($nodes as $id => $node) { $types_for_node = $node::getEdgeTypes(); foreach ($edge_types as $type) { if ( !array_key_exists($id, $ids) && !array_key_exists($type->getType(), $nodes[$id]->connectedNodes) && array_key_exists($type->getName(), $types_for_node) ) { $nodes[$id]->connectedNodeIDs[$type->getType()] = []; if (!$ids_only) { $nodes[$id]->connectedNodes[$type->getType()] = []; } } } } } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/model/traits/GPNodeEdgeCreator.php
graphp/model/traits/GPNodeEdgeCreator.php
<?php trait GPNodeEdgeCreator { public static function edge(string $name = null) { return new GPEdgeType(get_called_class(), $name ?: STR::pluralize(get_called_class())); } public static function singleEdge(string $single_name = null, string $plural_name = null) { $defaulted_single_name = $single_name ?: get_called_class(); $defaulted_plural_name = $plural_name ?: STR::pluralize($defaulted_single_name); return (new GPEdgeType(get_called_class(), $defaulted_plural_name)) ->setSingleNodeName($defaulted_single_name); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/model/traits/GPDataTypeCreator.php
graphp/model/traits/GPDataTypeCreator.php
<?php trait GPDataTypeCreator { public static function array($name, ...$args) { return new GPDataType($name, GPDataType::GP_ARRAY, ...$args); } public static function string($name, ...$args) { return new GPDataType($name, GPDataType::GP_STRING, ...$args); } public static function bool($name, ...$args) { return new GPDataType($name, GPDataType::GP_BOOL, ...$args); } public static function int($name, ...$args) { return new GPDataType($name, GPDataType::GP_INT, ...$args); } public static function float($name, ...$args) { return new GPDataType($name, GPDataType::GP_FLOAT, ...$args); } public static function number($name, ...$args) { return new GPDataType($name, GPDataType::GP_NUMBER, ...$args); } public static function any($name, ...$args) { return new GPDataType($name, GPDataType::GP_ANY, ...$args); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/tests/GPBatchTest.php
graphp/tests/GPBatchTest.php
<?php class GPTestBatchModel extends GPNode { public static $customDelete = false; protected static function getDataTypesImpl() { return [ new GPDataType('name', GPDataType::GP_STRING, true), new GPDataType('age', GPDataType::GP_INT), ]; } protected static function getEdgeTypesImpl() { return [ new GPEdgeType(GPTestBatchModel2::class), ]; } public function delete() { parent::delete(); self::$customDelete = true; } } class GPTestBatchModel2 extends GPNode { protected static function getEdgeTypesImpl() { return [ new GPEdgeType(GPTestBatchModel3::class), new GPEdgeType(GPTestBatchModel4::class), ]; } } class GPTestBatchModel3 extends GPNode {} class GPTestBatchModel4 extends GPNode {} class GPBatchTest extends GPTest { public static function setUpBeforeClass(): void { GPDatabase::get()->beginUnguardedWrites(); GPNodeMap::addToMapForTest(GPTestBatchModel::class); GPNodeMap::addToMapForTest(GPTestBatchModel2::class); GPNodeMap::addToMapForTest(GPTestBatchModel3::class); GPNodeMap::addToMapForTest(GPTestBatchModel4::class); } public function testBatchSave() { $m1 = new GPTestBatchModel(); $m2 = new GPTestBatchModel(); batch($m1, $m2)->save(); $this->assertNotEmpty($m1->getID()); $this->assertNotEmpty($m2->getID()); } public function testBatchDelete() { GPTestBatchModel::$customDelete = false; $m1 = new GPTestBatchModel(); $m2 = new GPTestBatchModel(); batch($m1, $m2)->save(); $this->assertNotEmpty($m1->getID()); $this->assertNotEmpty($m2->getID()); batch($m1, $m2)->delete(); $results = GPNode::multiGetByID([$m1->getID(), $m2->getID()]); $this->assertEmpty($results); $this->assertTrue(GPTestBatchModel::$customDelete); } public function testSimpleBatchDelete() { GPTestBatchModel::$customDelete = false; $m1 = new GPTestBatchModel(); $m2 = new GPTestBatchModel(); batch([$m1, $m2])->save(); $this->assertNotEmpty($m1->getID()); $this->assertNotEmpty($m2->getID()); GPNode::simpleBatchDelete([$m1, $m2]); $results = GPNode::multiGetByID([$m1->getID(), $m2->getID()]); $this->assertEmpty($results); $this->assertFalse(GPTestBatchModel::$customDelete); } public function testBatchLoad() { $m1 = new GPTestBatchModel(); $m2 = new GPTestBatchModel2(); $m3 = new GPTestBatchModel3(); $m4 = new GPTestBatchModel4(); batch($m1, $m2, $m3, $m4)->save(); $m1->addGPTestBatchModel2($m2); $m2->addGPTestBatchModel3($m3); $m2->addGPTestBatchModel4($m4); batch($m1, $m2)->save(); batch($m1, $m2, $m3) ->loadGPTestBatchModel2() ->loadGPTestBatchModel3() ->loadGPTestBatchModel4(); $this->assertNotEmpty($m1->getGPTestBatchModel2()); $this->assertNotEmpty($m2->getGPTestBatchModel3()); $this->assertNotEmpty($m2->getGPTestBatchModel4()); } public function testBatchLazyLoad() { $m1 = new GPTestBatchModel(); $m2 = new GPTestBatchModel2(); $m3 = new GPTestBatchModel3(); $m4 = new GPTestBatchModel4(); batch($m1, $m2, $m3, $m4)->save(); $m1->addGPTestBatchModel2($m2); $m2->addGPTestBatchModel3($m3); $m2->addGPTestBatchModel4($m4); batch($m1, $m2)->save(); lazy($m1, $m2, $m3) ->loadGPTestBatchModel2() ->loadGPTestBatchModel3() ->loadGPTestBatchModel4() ->load(); $this->assertNotEmpty($m1->getGPTestBatchModel2()); $this->assertNotEmpty($m2->getGPTestBatchModel3()); $this->assertNotEmpty($m2->getGPTestBatchModel4()); } public function testErrorBatchLoad() { $this->expectException(GPException::class); $m1 = new GPTestBatchModel(); $m2 = new GPTestBatchModel2(); batch($m1, $m2)->loadBogus(); } public static function tearDownAfterClass(): void { GPNode::simpleBatchDelete(GPTestBatchModel::getAll()); GPNode::simpleBatchDelete(GPTestBatchModel2::getAll()); GPNode::simpleBatchDelete(GPTestBatchModel3::getAll()); GPNode::simpleBatchDelete(GPTestBatchModel4::getAll()); GPDatabase::get()->endUnguardedWrites(); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/tests/GPLoadByRangeTest.php
graphp/tests/GPLoadByRangeTest.php
<?php class GPTestRangeModel extends GPNode { protected static function getDataTypesImpl() { return [ GPDataType::string('firstName', true), GPDataType::int('age', true), GPDataType::string('sex', true), ]; } } class GPLoadByRangeTest extends GPTest { public static function setUpBeforeClass(): void { GPDatabase::get()->beginUnguardedWrites(); GPNodeMap::addToMapForTest(GPTestRangeModel::class); } public function testLoadByNameRange() { $m1 = (new GPTestRangeModel())->setfirstName('Andres')->save(); $m2 = (new GPTestRangeModel())->setfirstName('Bibi')->save(); $m3 = (new GPTestRangeModel())->setfirstName('Charlotte')->save(); $results = GPTestRangeModel::getByFirstNameRange('Andres', 'zzz'); $this->assertEquals(array_values($results), [$m1, $m2, $m3]); $results = GPTestRangeModel::getByFirstNameRange('Bibis', 'zzz'); $this->assertEquals(array_values($results), [$m3]); } public function testLoadByAgeRangeWithLimit() { $m1 = (new GPTestRangeModel())->setAge(50)->save(); $m2 = (new GPTestRangeModel())->setAge(26)->save(); $m3 = (new GPTestRangeModel())->setAge(22)->save(); $results = GPTestRangeModel::getByAgeRange(22, 50, 1); $this->assertEquals(array_values($results), [$m1]); $results = GPTestRangeModel::getByAgeRange(22, 50, 1, 1); $this->assertEquals(array_values($results), [$m2]); $results = GPTestRangeModel::getByAgeRange(22, 50, 3, 0); $this->assertEquals(array_values($results), [$m1, $m2, $m3]); } public function testgetAllWith() { $m1 = (new GPTestRangeModel())->setSex('M')->save(); $m2 = (new GPTestRangeModel())->save(); $m3 = (new GPTestRangeModel())->setSex('F')->save(); $results = GPTestRangeModel::getAllWithSex(); $this->assertEquals(array_values($results), [$m1, $m3]); } public static function tearDownAfterClass(): void { batch(GPTestRangeModel::getAll())->delete(); GPDatabase::get()->endUnguardedWrites(); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/tests/GPEdgeTest.php
graphp/tests/GPEdgeTest.php
<?php class GPTestModel1 extends GPNode { protected static function getEdgeTypesImpl() { return [ (new GPEdgeType(GPTestModel2::class))->setSingleNodeName('Foo'), ]; } } class GPTestModel2 extends GPNode { } class GPEdgeTest extends GPTest { public static function setUpBeforeClass(): void { GPDatabase::get()->beginUnguardedWrites(); GPNodeMap::addToMapForTest(GPTestModel1::class); GPNodeMap::addToMapForTest(GPTestModel2::class); } public function testAddingAndGetting() { $model1 = (new GPTestModel1())->save(); $model2 = (new GPTestModel2())->save(); $model1->addGPTestModel2($model2)->save(); $model1->loadGPTestModel2(); $this->assertEquals($model1->getOneGPTestModel2(), $model2); $this->assertEquals( $model1->getGPTestModel2(), [$model2->getID() => $model2] ); } public function testAddingAndGettingSingle() { $model1 = (new GPTestModel1())->save(); $model2 = (new GPTestModel2())->save(); $model1->addGPTestModel2($model2)->save(); $model1->loadGPTestModel2(); $this->assertEquals($model1->getFoo(), $model2); $this->assertEquals( $model1->getGPTestModel2(), [$model2->getID() => $model2] ); } public function testAddingWrongType() { $this->expectException(GPException::class); $model1 = (new GPTestModel1())->save(); $model2 = (new GPTestModel1())->save(); $model1->addGPTestModel2($model2)->save(); } public function testAddngBeforeSaving() { $this->expectException(GPException::class); $model1 = (new GPTestModel1())->save(); $model2 = new GPTestModel2(); $model1->addGPTestModel2($model2)->save(); } public function testAddingAndGettingIDs() { $model1 = (new GPTestModel1())->save(); $model2 = (new GPTestModel2())->save(); $model1->addGPTestModel2($model2)->save(); $model1->loadGPTestModel2IDs(); $this->assertEquals($model1->getOneGPTestModel2IDs(), $model2->getID()); $this->assertEquals( $model1->getGPTestModel2IDs(), [$model2->getID() => $model2->getID()] ); } public function testEdgeRemoval() { $model1 = (new GPTestModel1())->save(); $model2 = (new GPTestModel2())->save(); $model3 = (new GPTestModel2())->save(); $model1->addGPTestModel2([$model2, $model3])->save(); $model1->loadGPTestModel2(); $model1->removeGPTestModel2($model2)->save(); // force loading should reset the edges $model1->forceLoadGPTestModel2(); $this->assertEquals( $model1->getGPTestModel2(), [$model3->getID() => $model3] ); } public function testAllEdgeRemoval() { $model1 = (new GPTestModel1())->save(); $model2 = (new GPTestModel2())->save(); $model3 = (new GPTestModel2())->save(); $model1->addGPTestModel2([$model2, $model3])->save(); $model1->loadGPTestModel2(); $model1->removeAllGPTestModel2()->save(); // force loading should reset the edges $model1->forceLoadGPTestModel2(); $this->assertEmpty($model1->getGPTestModel2()); } public static function tearDownAfterClass(): void { GPNode::simpleBatchDelete(GPTestModel1::getAll()); GPNode::simpleBatchDelete(GPTestModel2::getAll()); GPDatabase::get()->endUnguardedWrites(); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/tests/GPTestLimitLoadTest.php
graphp/tests/GPTestLimitLoadTest.php
<?php class GPTestLimitLoadModel extends GPNode { protected static function getEdgeTypesImpl() { return [ new GPEdgeType(GPTestLimitLoadModel2::class), ]; } } class GPTestLimitLoadModel2 extends GPNode {} class GPTestLimitLoadTest extends GPTest { public static function setUpBeforeClass(): void { GPDatabase::get()->beginUnguardedWrites(); GPNodeMap::addToMapForTest(GPTestLimitLoadModel::class); GPNodeMap::addToMapForTest(GPTestLimitLoadModel2::class); } public function testLimitLoad() { $m1 = new GPTestLimitLoadModel(); $m21 = new GPTestLimitLoadModel2(); $m22 = new GPTestLimitLoadModel2(); $m23 = new GPTestLimitLoadModel2(); batch($m1, $m21, $m22, $m23)->save(); $m1->addGPTestLimitLoadModel2([$m21, $m22, $m23])->save(); $m1->loadGPTestLimitLoadModel2(1); $this->assertEquals(count($m1->getGPTestLimitLoadModel2()), 1); $m1->forceLoadGPTestLimitLoadModel2(); $this->assertEquals(count($m1->getGPTestLimitLoadModel2()), 3); } public function testLimitLoadIDs() { $m1 = new GPTestLimitLoadModel(); $m21 = new GPTestLimitLoadModel2(); $m22 = new GPTestLimitLoadModel2(); $m23 = new GPTestLimitLoadModel2(); batch($m1, $m21, $m22, $m23)->save(); $m1->addGPTestLimitLoadModel2([$m21, $m22, $m23])->save(); $m1->loadGPTestLimitLoadModel2IDs(1); $this->assertEquals(count($m1->getGPTestLimitLoadModel2IDs()), 1); } public function testLimitOffsetLoad() { $m1 = new GPTestLimitLoadModel(); $m21 = new GPTestLimitLoadModel2(); $m22 = new GPTestLimitLoadModel2(); $m23 = new GPTestLimitLoadModel2(); batch($m1, $m21, $m22, $m23)->save(); $m1->addGPTestLimitLoadModel2([$m21, $m22, $m23])->save(); $m1->loadGPTestLimitLoadModel2(2, 1); $this->assertEquals(count($m1->getGPTestLimitLoadModel2()), 2); $this->assertEquals(idx0($m1->getGPTestLimitLoadModel2()), $m22); $this->assertEquals(last($m1->getGPTestLimitLoadModel2()), $m21); $m1->forceLoadGPTestLimitLoadModel2(); $this->assertEquals(count($m1->getGPTestLimitLoadModel2()), 3); } public static function tearDownAfterClass(): void { batch(GPTestLimitLoadModel::getAll())->delete(); batch(GPTestLimitLoadModel2::getAll())->delete(); GPDatabase::get()->endUnguardedWrites(); GPDatabase::get()->dispose(); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/tests/GPModelTest.php
graphp/tests/GPModelTest.php
<?php class GPTestModel extends GPNode { protected static function getDataTypesImpl() { return [ new GPDataType('name', GPDataType::GP_STRING, true), new GPDataType('age', GPDataType::GP_INT), new GPDataType('currency', GPDataType::GP_STRING, false, 'USD'), ]; } } class GPTestOtherModel extends GPNode {} class GPNodeTest extends GPTest { public static function setUpBeforeClass(): void { GPDatabase::get()->beginUnguardedWrites(); GPNodeMap::addToMapForTest(GPTestModel::class); } public function testCreate() { $model = new GPTestModel(); $this->assertEmpty($model->getID()); $model->save(); $this->assertNotEmpty($model->getID()); } public function testLoadByID() { $model = new GPTestModel(); $this->assertEmpty($model->getID()); $model->save(); $model::clearCache(); $this->assertNotEmpty(GPTestModel::getByID($model->getID())); // And from cache $this->assertNotEmpty(GPTestModel::getByID($model->getID())); } public function testLoadByIDWrongModel() { $model = new GPTestModel(); $this->assertEmpty($model->getID()); $model->save(); $model::clearCache(); $this->assertEmpty(GPTestOtherModel::getByID($model->getID())); // And from cache GPTestModel::getByID($model->getID()); $this->assertEmpty(GPTestOtherModel::getByID($model->getID())); } public function testMultiLoadByID() { $model = new GPTestModel(); $model2 = new GPTestModel(); batch($model, $model2)->save(); $model->save(); $model::clearCache(); $this->assertEquals( mpull( GPTestModel::multiGetByID([$model->getID(), $model2->getID()]), 'getID' ), mpull([$model, $model2], 'getID', 'getID') ); // And from cache $this->assertEquals( mpull( GPTestModel::multiGetByID([$model->getID(), $model2->getID()]), 'getID' ), mpull([$model, $model2], 'getID', 'getID') ); } public function testMultiLoadByIDWrongModel() { $model = new GPTestModel(); $model2 = new GPTestModel(); batch($model, $model2)->save(); $model->save(); $model::clearCache(); $this->assertEmpty( GPTestOtherModel::multiGetByID([$model->getID(), $model2->getID()]) ); // And from cache GPTestModel::getByID($model->getID()); $this->assertEmpty( GPTestOtherModel::multiGetByID([$model->getID(), $model2->getID()]) ); $this->assertNotEmpty(GPTestModel::multiGetByID([$model->getID()])); } public function testLoadByName() { $name = 'Weirds Name'; $model = new GPTestModel(['name' => $name]); $this->assertEmpty($model->getID()); $model->save(); $model::clearCache(); $this->assertNotEmpty(GPTestModel::getByName($name)); // From cache $this->assertNotEmpty(GPTestModel::getByName($name)); } public function testLoadByNameAfterUnset() { $name = 'Weirderer Name'; $model = new GPTestModel(['name' => $name]); $this->assertEmpty($model->getID()); $model->save(); $model::clearCache(); $loaded_model = GPTestModel::getOneByName($name); $this->assertNotEmpty($loaded_model); $loaded_model->unsetName(); $loaded_model->save(); $model::clearCache(); $this->assertEmpty(GPTestModel::getOneByName($name)); } public function testLoadByAge() { $this->expectException(GPException::class); $model = new GPTestModel(['name' => 'name', 'age' => 18]); $this->assertEmpty($model->getID()); $model->save(); GPTestModel::getByAge(18); } public function testGetData() { $model = new GPTestModel(['name' => 'Foo', 'age' => 18]); $this->assertEquals($model->getName(), 'Foo'); $this->assertEquals($model->getAge(), 18); $model->save(); $model::clearCache(); $loaded_model = GPTestModel::getByID($model->getID()); $this->assertEquals( $model->getDataArray(), ['name' => 'Foo', 'age' => 18] ); } public function testSetData() { $model = new GPTestModel(); $model->setName('Bar'); $model->setAge(25); $this->assertEquals( $model->getDataArray(), ['name' => 'Bar', 'age' => 25] ); } public function testDefaultData() { $model = new GPTestModel(); $this->assertEquals($model->getCurrency(), 'USD'); $this->assertNull($model->getAge()); } public static function tearDownAfterClass(): void { GPNode::simpleBatchDelete(GPTestModel::getAll()); GPDatabase::get()->endUnguardedWrites(); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/tests/GPEdgeCountTest.php
graphp/tests/GPEdgeCountTest.php
<?php class GPTestCountModel1 extends GPNode { protected static function getEdgeTypesImpl() { return [ (new GPEdgeType(GPTestCountModel2::class))->setSingleNodeName('Foo'), ]; } } class GPTestCountModel2 extends GPNode { } class GPEdgeCountTest extends GPTest { public static function setUpBeforeClass(): void { GPDatabase::get()->beginUnguardedWrites(); GPNodeMap::addToMapForTest(GPTestCountModel1::class); GPNodeMap::addToMapForTest(GPTestCountModel2::class); } public function testCorrectCount() { $nodes = []; foreach (range(1, 10) as $key => $value) { $nodes[] = (new GPTestCountModel2())->save(); } $n1 = (new GPTestCountModel1())->save(); $n1->addGPTestCountModel2($nodes)->save(); $count = $n1->getConnectedNodeCount( [GPTestCountModel1::getEdgeType(GPTestCountModel2::class)]); $this->assertEquals(idx0($count), 10); } public function testBatchCorrectCount() { $nodes = []; foreach (range(1, 10) as $key => $value) { $nodes[] = (new GPTestCountModel2())->save(); } $n1 = (new GPTestCountModel1())->save(); $n12 = (new GPTestCountModel1())->save(); $n1->addGPTestCountModel2($nodes)->save(); $n12->addGPTestCountModel2(array_slice($nodes, 5))->save(); $count = batch($n1, $n12)->getConnectedNodeCount( [GPTestCountModel1::getEdgeType(GPTestCountModel2::class)]); $this->assertEquals(idx0($count[$n1->getID()]), 10); $this->assertEquals(idx0($count[$n12->getID()]), 5); } public static function tearDownAfterClass(): void { GPNode::simpleBatchDelete(GPTestCountModel1::getAll()); GPNode::simpleBatchDelete(GPTestCountModel2::getAll()); GPDatabase::get()->endUnguardedWrites(); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/tests/GPBatchLoaderTest.php
graphp/tests/GPBatchLoaderTest.php
<?php class GPTestBatchLoaderModel extends GPNode { public static $customDelete = false; protected static function getDataTypesImpl() { return [ new GPDataType('name', GPDataType::GP_STRING, true), new GPDataType('age', GPDataType::GP_INT), ]; } protected static function getEdgeTypesImpl() { return [ new GPEdgeType(GPTestBatchLoaderModel2::class), ]; } public function delete() { parent::delete(); self::$customDelete = true; } } class GPTestBatchLoaderModel2 extends GPNode { protected static function getEdgeTypesImpl() { return [ new GPEdgeType(GPTestBatchLoaderModel3::class), new GPEdgeType(GPTestBatchLoaderModel4::class), ]; } } class GPTestBatchLoaderModel3 extends GPNode {} class GPTestBatchLoaderModel4 extends GPNode {} class GPBatchLoaderTest extends GPTest { public static function setUpBeforeClass(): void { GPDatabase::get()->beginUnguardedWrites(); GPNodeMap::addToMapForTest(GPTestBatchLoaderModel::class); GPNodeMap::addToMapForTest(GPTestBatchLoaderModel2::class); GPNodeMap::addToMapForTest(GPTestBatchLoaderModel3::class); GPNodeMap::addToMapForTest(GPTestBatchLoaderModel4::class); } public function testBatchSave() { $m1 = new GPTestBatchLoaderModel(); $m2 = new GPTestBatchLoaderModel(); GPNode::batchSave([$m1, $m2]); $this->assertNotEmpty($m1->getID()); $this->assertNotEmpty($m2->getID()); } public function testBatchDelete() { GPTestBatchLoaderModel::$customDelete = false; $m1 = new GPTestBatchLoaderModel(); $m2 = new GPTestBatchLoaderModel(); GPNode::batchSave([$m1, $m2]); $this->assertNotEmpty($m1->getID()); $this->assertNotEmpty($m2->getID()); GPNode::batchDelete([$m1, $m2]); $results = GPNode::multiGetByID([$m1->getID(), $m2->getID()]); $this->assertEmpty($results); $this->assertTrue(GPTestBatchLoaderModel::$customDelete); } public function testSimpleBatchDelete() { GPTestBatchLoaderModel::$customDelete = false; $m1 = new GPTestBatchLoaderModel(); $m2 = new GPTestBatchLoaderModel(); GPNode::batchSave([$m1, $m2]); $this->assertNotEmpty($m1->getID()); $this->assertNotEmpty($m2->getID()); GPNode::simpleBatchDelete([$m1, $m2]); $results = GPNode::multiGetByID([$m1->getID(), $m2->getID()]); $this->assertEmpty($results); $this->assertFalse(GPTestBatchLoaderModel::$customDelete); } public function testBatchLoad() { $m1 = new GPTestBatchLoaderModel(); $m2 = new GPTestBatchLoaderModel2(); $m3 = new GPTestBatchLoaderModel3(); $m4 = new GPTestBatchLoaderModel4(); GPNode::batchSave([$m1, $m2, $m3, $m4]); $m1->addGPTestBatchLoaderModel2($m2); $m2->addGPTestBatchLoaderModel3($m3); $m2->addGPTestBatchLoaderModel4($m4); GPNode::batchSave([$m1, $m2]); GPNode::batchLoadConnectedNodes( [$m1, $m2, $m3], array_merge( GPTestBatchLoaderModel::getEdgeTypes(), GPTestBatchLoaderModel2::getEdgeTypes() ) ); $this->assertNotEmpty($m1->getGPTestBatchLoaderModel2()); $this->assertNotEmpty($m2->getGPTestBatchLoaderModel3()); $this->assertNotEmpty($m2->getGPTestBatchLoaderModel4()); } public static function tearDownAfterClass(): void { GPNode::simpleBatchDelete(GPTestBatchLoaderModel::getAll()); GPNode::simpleBatchDelete(GPTestBatchLoaderModel2::getAll()); GPNode::simpleBatchDelete(GPTestBatchLoaderModel3::getAll()); GPNode::simpleBatchDelete(GPTestBatchLoaderModel4::getAll()); GPDatabase::get()->endUnguardedWrites(); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/tests/bootstrap.php
graphp/tests/bootstrap.php
<?php // This is used to bootstrap the framework without routing. // It is useful for tests and other require() cases. // For cli, you can use public/index.php and provide a controller and method // as arguments. define('ROOT_PATH', __DIR__.'/../../'); date_default_timezone_set('UTC'); try { require_once ROOT_PATH.'graphp/core/GPLoader.php'; GPRouter::init(); } catch (Exception $e) { echo ' There was an exception: <br />'; echo $e->getMessage().'<br />'; echo str_replace("\n", '<br />', $e->getTraceAsString()).'<br /><br />'; // Propagate exception so that it gets logged throw $e; }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/tests/GPEdgeInverseTest.php
graphp/tests/GPEdgeInverseTest.php
<?php class GPEdgeInverseTestModel1 extends GPNode { protected static function getEdgeTypesImpl() { return [ (new GPEdgeType(GPEdgeInverseTestModel2::class)) ->inverse(GPEdgeInverseTestModel2::getEdgeType( GPEdgeInverseTestModel1::class )), ]; } } class GPEdgeInverseTestModel2 extends GPNode { protected static function getEdgeTypesImpl() { return [ (new GPEdgeType(GPEdgeInverseTestModel1::class)), ]; } } class GPEdgeInverseTest extends GPTest { public static function setUpBeforeClass(): void { GPDatabase::get()->beginUnguardedWrites(); GPNodeMap::addToMapForTest(GPEdgeInverseTestModel1::class); GPNodeMap::addToMapForTest(GPEdgeInverseTestModel2::class); } public function testAddingAndGetting() { $model1 = (new GPEdgeInverseTestModel1())->save(); $model2 = (new GPEdgeInverseTestModel2())->save(); $model1->addGPEdgeInverseTestModel2($model2)->save(); $model2->loadGPEdgeInverseTestModel1(); $this->assertEquals($model2->getOneGPEdgeInverseTestModel1(), $model1); $this->assertEquals( $model2->getGPEdgeInverseTestModel1(), [$model1->getID() => $model1] ); } public function testEdgeRemoval() { $model1 = (new GPEdgeInverseTestModel1())->save(); $model2 = (new GPEdgeInverseTestModel2())->save(); $model3 = (new GPEdgeInverseTestModel2())->save(); $model1->addGPEdgeInverseTestModel2([$model2, $model3])->save(); $model1->loadGPEdgeInverseTestModel2(); $model1->removeGPEdgeInverseTestModel2($model2)->save(); // force loading should reset the edges $model2->forceLoadGPEdgeInverseTestModel1(); $model3->forceLoadGPEdgeInverseTestModel1(); $this->assertEquals($model2->getGPEdgeInverseTestModel1(), []); $this->assertEquals( $model3->getGPEdgeInverseTestModel1(), [$model1->getID() => $model1] ); } public function testAllEdgeRemoval() { $model1 = (new GPEdgeInverseTestModel1())->save(); $model2 = (new GPEdgeInverseTestModel2())->save(); $model3 = (new GPEdgeInverseTestModel2())->save(); $model1->addGPEdgeInverseTestModel2([$model2, $model3])->save(); $model1->loadGPEdgeInverseTestModel2(); $model1->removeAllGPEdgeInverseTestModel2()->save(); // force loading should reset the edges $model1->forceLoadGPEdgeInverseTestModel2(); $model2->forceLoadGPEdgeInverseTestModel1(); $model3->forceLoadGPEdgeInverseTestModel1(); $this->assertEmpty($model1->getGPEdgeInverseTestModel2()); $this->assertEmpty($model2->getGPEdgeInverseTestModel1()); $this->assertEmpty($model3->getGPEdgeInverseTestModel1()); } public static function tearDownAfterClass(): void { GPNode::simpleBatchDelete(GPEdgeInverseTestModel1::getAll()); GPNode::simpleBatchDelete(GPEdgeInverseTestModel2::getAll()); GPDatabase::get()->endUnguardedWrites(); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/tests/GPControllerHandlerTest.php
graphp/tests/GPControllerHandlerTest.php
<?php class TestController extends GPController { public function foo($var) { } } class GPControllerHandlerTest extends GPTest { public function testURI() { $index = GPConfig::get()->use_index_php ? '/index.php' : ''; $uri = TestController::URI()->foo('abc'); $this->assertEquals($uri, $index.'/testcontroller/foo/abc'); } public function testShortURI() { $index = GPConfig::get()->use_index_php ? '/index.php' : ''; $uri = TestController::URI(); $this->assertEquals($uri, $index.'/testcontroller/'); } public function testBadURI() { $this->expectException(GPException::class); $uri = TestController::URI()->bar('abc'); } public function testURL() { $index = GPConfig::get()->use_index_php ? '/index.php' : ''; $domain = GPConfig::get()->domain; $uri = TestController::URL()->foo('abc'); $this->assertEquals($uri, $domain.$index.'/testcontroller/foo/abc'); } public function testShortURL() { $index = GPConfig::get()->use_index_php ? '/index.php' : ''; $domain = GPConfig::get()->domain; $uri = TestController::URL(); $this->assertEquals($uri, $domain.$index.'/testcontroller/'); } public function testRedirect() { $handler = TestController::redirect(); $this->assertTrue($handler instanceof GPRedirectControllerHandler); $handler->disableDestructRedirect(); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/utils/arrays.php
graphp/utils/arrays.php
<?php /** * idxx * * @param mixed \array Description. * @param mixed $key Description. * * @access public * * @return mixed Value. */ function idxx(array $array, $key, $message = '') { if (!array_key_exists($key, $array)) { throw new GPException( $message ?: $key.' not in array: '.json_encode($array) ); } return $array[$key]; } /** * Returns first element in array. null if array is empty. * @param array $array * @return mixed First element of array or false is array is empty */ function idx0(array $array) { if (count($array) === 0) { return null; } return reset($array); } function array_merge_by_keys() { $result = []; foreach (func_get_args() as $array) { foreach ($array as $key => $value) { $result[$key] = $value; } } return $result; } function key_by_value(array $array) { $result = []; foreach ($array as $key => $value) { $result[$value] = $value; } return $result; } function array_concat_in_place(& $arr1, $arr2) { foreach ($arr2 as $key => $value) { $arr1[] = $value; } } function array_concat(array $arr1 /*array2, ...*/) { $args = func_get_args(); foreach ($args as $key => $arr2) { if ($key !== 0) { foreach ($arr2 as $key => $value) { $arr1[] = $value; } } } return $arr1; } function array_flatten(array $array) { $result = []; foreach ($array as $key => $value) { if (is_array($value)) { array_concat_in_place($result, array_flatten($value)); } else { $result[] = $value; } } return $result; } function make_array($val) { return is_array($val) ? $val : [$val]; } function array_select_keysx(array $dict, array $keys, $custom_error = null) { $result = []; foreach ($keys as $key) { if (array_key_exists($key, $dict)) { $result[$key] = $dict[$key]; } else { if (is_callable($custom_error)) { $custom_error(); } else { throw new GPException('Missing key '.$key.' in '.json_encode($dict), 1); } } } return $result; } function array_unset_keys(array & $array, array $keys) { foreach ($keys as $key) { unset($array[$key]); } } function array_append(array $array, $elem, $key = null) { if ($key === null) { $array[] = $elem; } else { $array[$key] = $elem; } return $array; } function array_key_by_value(array $array) { $new_array = []; foreach ($array as $key => $value) { $new_array[$value] = $value; } return $new_array; }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/utils/STRUtils.php
graphp/utils/STRUtils.php
<?php class STRUtils { public static function to64BitInt($string) { $hash = substr(md5($string), 17); // truncate to 64 bits return (int) base_convert($hash, 16, 10); // base 10 } /** * Basic HTML escaping for user input * @param string $str String to be escaped. * @return string */ public static function esc($str) { $str = mb_convert_encoding($str, 'UTF-8', 'UTF-8'); return htmlspecialchars($str, ENT_QUOTES, 'UTF-8'); } public static function startsWith($haystack, $needle) { // search backwards starting from haystack length characters from the end return $needle === "" || strrpos($haystack, $needle, - strlen($haystack)) !== false; } public static function endsWith($haystack, $needle) { // search forward starting from end minus needle length characters return $needle === "" || ( ($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false ); } public static function pluralize(string $singular, string $plural = null) { if ($plural !== null) { return $plural; } $last_letter = strtolower($singular[strlen($singular) - 1]); switch ($last_letter) { case 'y': return substr($singular, 0, -1).'ies'; case 's': return $singular.'es'; default: return $singular.'s'; } } } class_alias('STRUtils', 'STR');
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/utils/Assert.php
graphp/utils/Assert.php
<?php class Assert extends GPObject { public static function true($var, $message = '') { if ($var !== true) { throw new GPException( $message ?: 'Failed asserting that '.$var.' is true - ' ); } } public static function truthy($var, $message = '') { if (!$var) { throw new GPException( $message ?: 'Failed asserting that '.$var.' is true - ' ); } } public static function false($var, $message = '') { if ($var !== false) { throw new GPException( $message ?: 'Failed asserting that '.$var.' is false - ' ); } } public static function equals($var, $val, $message = '') { if ($var !== $val) { throw new GPException( $message ?: 'Failed asserting that '.$var.' is equal to '.$val.' - ' ); } } public static function inArray($idx, array $array, $message = '') { if (!array_key_exists($idx, $array)) { throw new GPException($message ?: $idx.' not in '.json_encode($array)); } } public static function allEquals(array $vars, $val, $message = '') { foreach ($vars as $var) { if ($var !== $val) { throw new GPException( $message ?: 'Failed asserting that '.json_encode($var).' is equal to '.$val.' - ' ); } } } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/lib/GPRouteGenerator.php
graphp/lib/GPRouteGenerator.php
<?php class GPRouteGenerator extends GPObject { private $path; private $controller; private $method; private $args; public function __construct($uri = '') { $this->path = explode('/', parse_url($uri)['path']); } public static function createFromParts($controller, $method = 'index', ...$args) { $route_generator = new GPRouteGenerator(); $route_generator->controller = $controller; $route_generator->method = $method; $route_generator->args = $args; return $route_generator; } public function getPath() { return $this->path; } public function getController() { return $this->controller; } public function getMethod() { return $this->method; } public function getArgs() { return $this->args; } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/lib/GPProfiler.php
graphp/lib/GPProfiler.php
<?php final class GPProfiler { private static $enabled = false; private static $queryData = []; private static $marks = []; public static function enable() { if (self::$enabled) { return; } self::$enabled = true; self::$marks[] = [ 'uri' => idx($_SERVER, 'REQUEST_URI', ''), 'name' => 'enabled', 'microtime' => microtime(true), ]; PhutilServiceProfiler::getInstance()->addListener('GPProfiler::format'); } public static function getQueryData() { return self::$queryData; } public static function getMarks() { return self::$marks; } public static function format($type, $id, $data) { $data['id'] = $id; $data['stage'] = $type; self::$queryData[] = $data; } public static function mark($name = '') { if (!self::$enabled) { return; } $name = $name ?: 'Mark '.count(self::$marks); self::$marks[] = ['name' => $name, 'microtime' => microtime(true)]; $count = count(self::$marks); self::$marks[$count - 1]['duration'] = self::$marks[$count - 1]['microtime'] - self::$marks[$count - 2]['microtime']; } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPURLControllerHandler.php
graphp/core/GPURLControllerHandler.php
<?php final class GPURLControllerHandler extends GPURIControllerHandler { public function handle($method, array $args) { return GPConfig::get()->domain.parent::handle($method, $args); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPLibrary.php
graphp/core/GPLibrary.php
<?php class GPLibrary extends GPController { public function isAllowed(string $method): bool { if (GP::isCLI()) { return true; } return false; } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPConfig.php
graphp/core/GPConfig.php
<?php class GPConfig extends GPObject { private static $configs = []; private $config; private $name; public static function get($name = 'general') { if (!isset(self::$configs[$name])) { self::$configs[$name] = new GPConfig($name); } return self::$configs[$name]; } protected function __construct($name) { $this->name = $name; $this->config = require_once ROOT_PATH.'config/'.$name.'.php'; } public function toArray() { return $this->config; } public function __get($name) { if (isset($this->config[$name])) { return $this->config[$name]; } throw new Exception($name.' is not in '.$this->name.' config', 1); } public static function from_file($file) { $path = ROOT_PATH.'config/'.$file; if (is_readable($path)) { return include_once($path); } return []; } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPRouter.php
graphp/core/GPRouter.php
<?php class GPRouter extends GPObject { private static $routes; private static $parts; private static $controller; private static $method; public static function init() { self::$routes = require_once ROOT_PATH.'config/routes.php'; self::$parts = self::getParts(); } public static function route() { if (is_array(self::$parts)) { $generator = GPRouteGenerator::createFromParts(...self::$parts); } else if (idx(class_parents(self::$parts), GPRouteGenerator::class)) { $generator = new self::$parts($_SERVER['REQUEST_URI']); } else { throw new GPException('Unrecognized route value'); } $controller_name = $generator->getController(); if (!class_exists($controller_name)) { GP::return404(); } self::$controller = new $controller_name(); self::$method = $generator->getMethod(); if (!method_exists(self::$controller, self::$method)) { GP::return404(); } if (!self::$controller->isAllowed(self::$method)) { GP::return404(); } self::$controller->init(); call_user_func_array([self::$controller, self::$method], $generator->getArgs()); } public static function getController() { return self::$controller; } public static function getMethod() { return self::$method; } private static function getParts() { if (GP::isCLI()) { global $argv; $uri = idx($argv, 1, ''); } else { $uri = $_SERVER['REQUEST_URI']; } $uri = str_replace('index.php', '', $uri); $uri = preg_replace(['/\?.*/', '#[/]+$#'], '', $uri); if (!$uri && isset(self::$routes['__default__'])) { return self::$routes['__default__']; } foreach (array_keys(self::$routes) as $regex) { $matches = []; if (preg_match('#'.$regex.'#', $uri, $matches)) { $parts = self::$routes[$regex]; if (is_array($parts)) { array_concat_in_place($parts, array_slice($matches, 1)); } return $parts; } } return array_values(array_filter( explode('/', $uri), function($part) { return mb_strlen($part) > 0; // Stupid PHP filters out '0' } )); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPObject.php
graphp/core/GPObject.php
<?php class GPObject { private static $classConstants = []; private static $classConstantsFlip = []; public static function assertConstValueExists($name) { idxx(self::getClassConstantsFlip(), $name); } public static function getClassConstants() { if (!array_key_exists(get_called_class(), self::$classConstants)) { self::initClassConstants(); } return self::$classConstants[get_called_class()]; } public static function getClassConstantsFlip() { if (!array_key_exists(get_called_class(), self::$classConstantsFlip)) { self::initClassConstants(); } return self::$classConstantsFlip[get_called_class()]; } private static function initClassConstants() { $refl = new ReflectionClass(get_called_class()); self::$classConstants[get_called_class()] = $refl->getConstants(); self::$classConstantsFlip[get_called_class()] = array_flip(self::$classConstants[get_called_class()]); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPTest.php
graphp/core/GPTest.php
<?php use PHPUnit\Framework\TestCase; abstract class GPTest extends TestCase { public function __construct() { parent::__construct(); GPEnv::isTest(); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPDatabase.php
graphp/core/GPDatabase.php
<?php class GPDatabase extends GPObject { public const LIMIT = 100; private const NODE_SELECT = 'SELECT id, type, data, UNIX_TIMESTAMP(created) AS created, UNIX_TIMESTAMP(updated) AS updated'; private static $dbs = []; private $connection; private $guard; private $nestedTransactions = 0; private static $viewLock = 0; private static $skipWriteGuard = false; public static function get($name = 'database') { if (!isset(self::$dbs[$name])) { self::$dbs[$name] = new GPDatabase($name); } return self::$dbs[$name]; } public function __construct($config_name) { $this->guard = new AphrontWriteGuard(function() { if (GP::isCLI() || self::$skipWriteGuard) { return; } if (idx($_SERVER, 'REQUEST_METHOD') !== 'POST') { throw new Exception( 'You can only write to the database on post requests. If you need to make writes on get request, use GPDatabase::get()->beginUnguardedWrites()', 1 ); } if (!GPSecurity::isCSFRTokenValid(idx($_POST, 'csrf'))) { throw new Exception( 'The request did not have a valid csrf token. This may be an attack or you may have forgetten to include it in a post request that does writes', 1 ); } }); $config = GPConfig::get($config_name); $this->connection = new AphrontMySQLiDatabaseConnection($config->toArray()); } public function getConnection() { Assert::equals( self::$viewLock, 0, 'Tried to access DB while view lock is on' ); Assert::truthy($this->connection, 'DB Connection no longer exists'); return $this->connection; } public function beginUnguardedWrites() { AphrontWriteGuard::beginUnguardedWrites(); } public function endUnguardedWrites() { AphrontWriteGuard::endUnguardedWrites(); } public function skipWriteGuard() { self::$skipWriteGuard = true; } public function startTransaction() { if ($this->nestedTransactions === 0) { queryfx($this->getConnection(), 'START TRANSACTION;'); } $this->nestedTransactions++; } public function commit() { $this->nestedTransactions--; if ($this->nestedTransactions === 0) { queryfx($this->getConnection(), 'COMMIT;'); } } public function insertNode(GPNode $node) { queryfx( $this->getConnection(), 'INSERT INTO node (type, data) VALUES (%d, %s)', $node::getType(), $node->getJSONData() ); return $this->getConnection()->getInsertID(); } public function updateNodeData(GPNode $node) { queryfx( $this->getConnection(), 'UPDATE node SET data = %s WHERE id = %d', $node->getJSONData(), $node->getID() ); } public function getNodeByID($id) { return queryfx_one( $this->getConnection(), self::NODE_SELECT.' FROM node WHERE id = %d;', $id ); } public function getNodeByIDType($id, $type) { return queryfx_one( $this->getConnection(), self::NODE_SELECT.' FROM node WHERE id = %d AND type = %d;', $id, $type ); } public function multigetNodeByIDType(array $ids, $type = null) { if (!$ids) { return []; } $type_fragment = $type ? 'AND type = %d;' : ';'; $args = array_filter([$ids, $type]); return queryfx_all( $this->getConnection(), self::NODE_SELECT.' FROM node WHERE id IN (%Ld) '.$type_fragment, ...$args ); } public function getNodeIDsByTypeDataAll(int $type): array { return ipull(queryfx_all( $this->getConnection(), 'SELECT node_id FROM node_data WHERE type = %d;', $type ), 'node_id'); } public function getNodeIDsByTypeData($type, array $data) { if (!$data) { return []; } return ipull(queryfx_all( $this->getConnection(), 'SELECT node_id FROM node_data WHERE type = %d AND data IN (%Ls);', $type, $data ), 'node_id'); } public function getNodeIDsByTypeDataRange( $type, $start, $end, $limit, $offset ) { return ipull(queryfx_all( $this->getConnection(), 'SELECT node_id FROM node_data WHERE '. 'type = %d AND data >= %s AND data <= %s ORDER BY updated ASC LIMIT %d, %d;', $type, $start, $end, $offset, $limit ), 'node_id'); } public function updateNodeIndexedData(GPNode $node) { $values = []; $parts = []; foreach ($node->getIndexedData() as $name => $val) { $parts[] = '(%d, %d, %s)'; $values[] = $node->getID(); $values[] = $node::getDataTypeByName($name)->getIndexedType(); $values[] = $val; } $this->startTransaction(); $result = queryfx( $this->getConnection(), 'DELETE FROM node_data WHERE node_id = %d', $node->getID() ); if ($parts) { queryfx( $this->getConnection(), 'INSERT INTO node_data (node_id, type, data) VALUES '. implode(',', $parts).' ON DUPLICATE KEY UPDATE data = VALUES(data);', ...$values ); } $this->commit(); } private function getEdgeParts(GPNode $from_node, array $array_of_arrays) { $values = []; $parts = []; foreach ($array_of_arrays as $edge_type => $to_nodes) { foreach ($to_nodes as $to_node) { $parts[] = '(%d, %d, %d)'; array_push($values, $from_node->getID(), $to_node->getID(), $edge_type); } } return [$parts, $values]; } public function saveEdges(GPNode $from_node, array $array_of_arrays) { list($parts, $values) = $this->getEdgeParts($from_node, $array_of_arrays); if (!$parts) { return; } queryfx( $this->getConnection(), 'INSERT IGNORE INTO edge (from_node_id, to_node_id, type) VALUES '. implode(',', $parts).';', ...$values ); } public function deleteEdges(GPNode $from_node, array $array_of_arrays) { list($parts, $values) = $this->getEdgeParts($from_node, $array_of_arrays); if (!$parts) { return; } queryfx( $this->getConnection(), 'DELETE FROM edge WHERE (from_node_id, to_node_id, type) IN ('. implode(',', $parts).');', ...$values ); } public function deleteAllEdges(GPNode $node, array $edge_types) { return $this->deleteAllEdgesInternal($node, $edge_types, 'from_node_id'); } public function deleteAllInverseEdges(GPNode $node, array $edge_types) { return $this->deleteAllEdgesInternal($node, $edge_types, 'to_node_id'); } private function deleteAllEdgesInternal( GPNode $node, array $edge_types, $col ) { $values = []; $parts = []; foreach ($edge_types as $edge_type) { $parts[] = '(%d, %d)'; array_push($values, $node->getID(), $edge_type); } if (!$parts) { return; } queryfx( $this->getConnection(), 'DELETE FROM edge WHERE ('.$col.', type) IN ('. implode(',', $parts).');', ...$values ); } public function getConnectedIDs( GPNode $from_node, array $types, $limit = null, $offset = 0 ) { return idx( $this->multiGetConnectedIDs([$from_node], $types, $limit, $offset), $from_node->getID(), array_fill_keys($types, []) ); } public function multiGetConnectedIDs( array $from_nodes, array $types, $limit = null, $offset = 0 ) { if (!$types || !$from_nodes) { return []; } $args = [mpull($from_nodes, 'getID'), $types]; if ($limit !== null) { $args[] = $offset; $args[] = $limit; } $results = queryfx_all( $this->getConnection(), 'SELECT from_node_id, to_node_id, type FROM edge '. 'WHERE from_node_id IN (%Ld) AND type IN (%Ld) ORDER BY updated DESC'. ($limit === null ? '' : ' LIMIT %d, %d').';', ...$args ); $ordered = []; foreach ($results as $result) { if (!array_key_exists($result['from_node_id'], $ordered)) { $ordered[$result['from_node_id']] = array_fill_keys($types, []); } $ordered[$result['from_node_id']][$result['type']][$result['to_node_id']] = $result['to_node_id']; } return $ordered; } public function getConnectedNodeCount(array $nodes, array $edges) { $results = queryfx_all( $this->getConnection(), 'SELECT from_node_id, type, count(1) as c FROM edge '. 'WHERE from_node_id IN (%Ld) AND type IN (%Ld) group by from_node_id, '. 'type;', mpull($nodes, 'getID'), mpull($edges, 'getType') ); return igroup($results, 'from_node_id'); } public function getAllByType($type, $limit, $offset) { return queryfx_all( $this->getConnection(), self::NODE_SELECT.' FROM node WHERE type = %d ORDER BY updated DESC LIMIT %d, %d;', $type, $offset, $limit ); } public function getTypeCounts() { return queryfx_all( $this->getConnection(), 'SELECT type, COUNT(1) AS count FROM node GROUP BY type;' ); } public function deleteNodes(array $nodes) { if (!$nodes) { return; } queryfx( $this->getConnection(), 'DELETE FROM node WHERE id IN (%Ld);', mpull($nodes, 'getID') ); } public static function incrementViewLock() { self::$viewLock++; } public static function decrementViewLock() { self::$viewLock--; } public function dispose() { if ($this->guard->isGuardActive()) { $this->guard->dispose(); } if ($this->connection) { $this->connection->close(); $this->connection = null; } } public static function disposeAll() { foreach (self::$dbs as $db) { $db->dispose(); } } public function __destruct() { $this->dispose(); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPRequestData.php
graphp/core/GPRequestData.php
<?php class GPRequestData extends GPObject { private $data; public function __construct(array $data) { $this->data = $data; } public function getData() { return $this->data; } public function getInt($key, $default = null) { $val = $this->get($key, 'is_numeric'); return $val !== null ? (int) $val : $default; } public function getString($key, $default = null) { $val = $this->get($key, 'is_string'); return $val !== null ? $val : $default; } public function getNumeric($key, $default = null) { $val = $this->get($key, 'is_numeric'); return $val !== null ? $val : $default; } public function getArray($key, $default = null) { $val = $this->get($key, 'is_array'); return $val !== null ? $val : $default; } public function getExists($key) { return array_key_exists($key, $this->data); } public function get($key, callable $validator = null) { $value = idx($this->data, $key); if ($validator === null || $validator($value)) { return $value; } return null; } public function serialize() { return json_encode($this->data); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPController.php
graphp/core/GPController.php
<?php class GPController extends GPObject { protected $post; protected $get; private static $coreHandlers = [ 'async' => true, 'redirect' => true, 'uri' => true, 'url' => true, ]; public function init() { $post_json_data = (array) json_decode(file_get_contents('php://input'), true); $this->post = new GPRequestData(array_merge_by_keys($_POST, $post_json_data)); $this->get = new GPRequestData($_GET); } public function __call($method_name, $args) { return self::handleStatic($method_name, $args); } public static function __callStatic($method_name, $args) { return self::handleStatic($method_name, $args); } public function __destruct() { GPDatabase::disposeAll(); } private static function handleStatic($method_name, $args) { $handler = $method_name.GPConfig::get()->handler_suffix; if ( !idx(self::$coreHandlers, strtolower($method_name)) && is_subclass_of($handler, GPControllerHandler::class) ) { return $handler::get(get_called_class()); } $core_handler = 'GP'.$method_name.GPConfig::get()->handler_suffix; if (is_subclass_of($core_handler, GPControllerHandler::class)) { return $core_handler::get(get_called_class()); } if (GPEnv::isDevEnv()) { echo 'Method "'.$method_name.'" is not in '.get_called_class(); } GP::return404(); } /** * Override this to limit access to individual methods or the entire controller * @param string * @return boolean */ public function isAllowed(string $method): bool { return true; } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPEnv.php
graphp/core/GPEnv.php
<?php final class GPEnv extends GPObject { private static $isTestEnv = false; public static function isTest() { self::$isTestEnv = true; } public static function isTestEnv() { return self::$isTestEnv; } public static function assertTestEnv() { Assert::true(self::isTestEnv()); } public static function isDevEnv() { return GPConfig::get()->is_dev; } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPErrorText.php
graphp/core/GPErrorText.php
<?php final class GPErrorText extends GPObject { public static function missingEdges($edges, GPNode $obj, array $loaded_ids) { $to_load = mpull($edges, 'getName'); $possible = array_values(mpull($obj::getEdgeTypes(), 'getName')); $loaded = array_values(mpull( array_select_keys($obj::getEdgeTypes(), $loaded_ids), 'getName' )); if (array_intersect($to_load, $possible) === $to_load) { return 'Unloaded edges on '.get_class($obj).': '. json_encode(array_diff($to_load, $loaded)). ' You must load connected nodes before you can use them.'; } return 'One or more of '.json_encode($to_load).' has either not been loaded or '. 'does not exist on '.get_class($obj).'. Possible edges are '. json_encode($possible).' and loaded edge types are '.json_encode($loaded); } public static function wrongArgs($class, $method, $expected, $actual) { return $class.'::'.$method.' expected '.$expected.' arguments, got '.$actual; } public static function missingEdgeType($class, $edge_name, $possible_edges) { return $class.' does not have an edge "'.$edge_name.'". Possible edges'. ' are: '.json_encode(array_keys($possible_edges)); } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPAsyncControllerHandler.php
graphp/core/GPAsyncControllerHandler.php
<?php class GPAsyncControllerHandler extends GPURIControllerHandler { private $handled = false; public function handle($method, array $args) { $this->handled = true; $uri = parent::handle($method, $args); $log = ini_get('error_log') ?: '/dev/null'; execx('php '.ROOT_PATH.'public/index.php %s >> '.$log.' 2>&1 &', $uri); } public function __destruct() { if (!$this->handled) { $this->handle('', []); } } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPLoader.php
graphp/core/GPLoader.php
<?php // We load a couple of things up front. Everything else gets loaded on demand. class GPException extends Exception {} require_once ROOT_PATH.'graphp/utils/arrays.php'; require_once ROOT_PATH.'graphp/core/GPObject.php'; require_once ROOT_PATH.'graphp/core/GPFileMap.php'; require_once ROOT_PATH.'graphp/core/GPConfig.php'; require_once ROOT_PATH.'third_party/libphutil/src/__phutil_library_init__.php'; class GPLoader extends GPObject { private static $map = null; private static $viewData = []; private static $globalViewData = []; public static function init() { spl_autoload_register('GPLoader::GPAutoloader'); if (!is_writable('/tmp/maps')) { mkdir('/tmp/maps'); chmod('/tmp/maps', 0777); } } private static function getMap() { if (self::$map === null) { $app_folder = GPConfig::get()->app_folder; self::$map = new GPFileMap( [ ROOT_PATH.$app_folder.'/models', ROOT_PATH.'graphp', ROOT_PATH.$app_folder.'/libraries', ROOT_PATH.$app_folder.'/controllers', ], 'file_map' ); } return self::$map; } private static function GPAutoloader($class_name) { $path = self::getMap()->getPath($class_name); if ($path) { require_once $path; } } public static function view($view_name, array $_data = [], $return = false) { if (GPConfig::get()->disallow_view_db_access) { GPDatabase::incrementViewLock(); } $file = ROOT_PATH.GPConfig::get()->app_folder.'/views/'.$view_name.'.php'; if (!file_exists($file)) { throw new GPException('View "'.$view_name.'"" not found'); } $new_data = array_diff_key($_data, self::$viewData); $replaced_data = array_intersect_key(self::$viewData, $_data); self::$viewData = array_merge_by_keys(self::$viewData, $_data); ob_start(); extract(self::$globalViewData); extract(self::$viewData); require $file; // Return $viewData to the previous state to avoid view data bleeding. self::$viewData = array_merge_by_keys( array_diff_key(self::$viewData, $new_data), $replaced_data ); if (GPConfig::get()->disallow_view_db_access) { GPDatabase::decrementViewLock(); } if ($return) { $buffer = ob_get_contents(); @ob_end_clean(); return $buffer; } ob_end_flush(); } public static function viewWithLayout( $view, $layout, array $data = [], array $layout_data = [] ) { if (array_key_exists('content', $layout_data)) { throw new GPException('Key: \'content\' cannot be int layout_data'); } $layout_data['content'] = GP::view($view, $data, true); GP::view($layout, $layout_data); } public static function isCLI() { return php_sapi_name() === 'cli'; } public static function isAjax() { return filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest'; } public static function isJSONRequest() { return idx($_SERVER, 'CONTENT_TYPE') === 'application/json'; } public static function return404() { GPDatabase::get()->dispose(); http_response_code(404); $config = GPConfig::get(); if (GP::isAjax() || GP::isJSONRequest()) { GP::ajax(['error_code' => 404, 'error' => 'Resource Not Found']); } else if ($config->redirect_404) { header('Location: '.$config->redirect_404, true); } else if ($config->view_404 && $config->layout_404) { GP::viewWithLayout($config->view_404, $config->layout_404); } else if ($config->view_404) { GP::view($config->view_404); } else { echo '404'; } die(); } public static function return403() { GPDatabase::get()->dispose(); http_response_code(403); if (GP::isAjax() || GP::isJSONRequest()) { GP::ajax(['error_code' => 403, 'error' => 'Forbidden']); } else { echo 'Forbidden'; } die(); } public static function ajax(array $data) { header('Expires: 0'); header( 'Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0' ); header('Pragma: no-cache'); header('Content-type: application/json'); echo json_encode($data); GP::exit(); } public static function exit() { GPDatabase::disposeALl(); exit(); } public static function addGlobal($key, $val) { self::$globalViewData[$key] = $val; } } class_alias('GPLoader', 'GP'); // To instanciate a new GPLoader we need to call this once. GP::init();
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPFileMap.php
graphp/core/GPFileMap.php
<?php class GPFileMap extends GPObject { private $map = []; private $dir; private $name; public function __construct($dirs, $name) { $this->dirs = make_array($dirs); $this->name = $name; $map = is_readable($this->buildPath()) ? include $this->buildPath() : null; $this->map = $map ?: []; } public function getPath($file) { $file = strtolower($file); if (!isset($this->map[$file]) || !file_exists($this->map[$file])) { $this->regenMap(); } return idx($this->map, $file); } public function regenMap() { $this->map = []; foreach ($this->dirs as $dir) { $dir_iter = new RecursiveDirectoryIterator($dir); $iter = new RecursiveIteratorIterator($dir_iter); foreach ($iter as $key => $file) { if ($file->getExtension() === 'php') { list($name) = explode('.', $file->getFileName()); $this->map[strtolower($name)] = $key; } } } $this->writeMap(); } public function getAllFileNames() { $this->regenMap(); return array_keys($this->map); } private function writeMap() { $map_file = "<?php\nreturn [\n"; foreach ($this->map as $file => $path) { $map_file .= ' \''.$file.'\' => \''.$path."',\n"; } $map_file .= "];\n"; $file_path = $this->buildPath(); $does_file_exist = file_exists($file_path); file_put_contents($file_path, $map_file); if (!$does_file_exist) { // File was just created, make sure to make it readable chmod($file_path, 0666); } } private function buildPath() { return '/tmp/maps/'.GPConfig::get()->app_folder.'_'.$this->name; } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPURIControllerHandler.php
graphp/core/GPURIControllerHandler.php
<?php class GPURIControllerHandler extends GPControllerHandler implements JsonSerializable { public function handle($method, array $args) { $index = GPConfig::get()->use_index_php ? '/index.php' : ''; return $index.'/'.strtolower($this->controller).'/'.$method. ($args ? '/'.implode('/', $args) : ''); } public function __toString() { return $this->handle('', []); } public function jsonSerialize() { return (string) $this; } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPControllerHandler.php
graphp/core/GPControllerHandler.php
<?php /** * Controller handlers give you an easy way of extending controller * functionality and syntax without having to modify any core code. This makes * controller addons and extensions plug and play. Some basic extensions will be * included: URI, URL, Async, redirect * * Some creative uses could be: * -> Return if user has access to controller/method * -> Return API endpoint of method * -> Return endpoint as a manipulatable object * -> Return annotations for given controller method */ abstract class GPControllerHandler extends GPObject { protected $controller; public function __construct($controller) { $this->controller = $controller; } // Override to implement handler functionality abstract protected function handle($method, array $args); // Override for more complicated functionality/caching public static function get($controller) { return new static($controller); } public function __call($method, array $args) { $this->validateMethod($method); return $this->handle($method, $args); } protected function validateMethod($method) { if ($method) { if ( !method_exists($this->controller, $method) || !(new ReflectionMethod($this->controller, $method))->isPublic() ) { throw new GPException( $this->controller.' does not have a public method '.$method ); } } } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPRedirectControllerHandler.php
graphp/core/GPRedirectControllerHandler.php
<?php class GPRedirectControllerHandler extends GPURIControllerHandler { private $handled = false; public function handle($method, array $args) { $this->handled = true; // The autoloader will not work if PHP is shutting down. if (class_exists('GPDatabase', false)) { GPDatabase::disposeAll(); } $uri = parent::handle($method, $args); header('Location: '.$uri, true, 307); die(); } public function disableDestructRedirect() { $this->handled = true; } /** * This will redirect when the handler is destroyed allowing for shorter code * like: * MyController::redirect(); * instead of * MyController::redirect()->index(); */ public function __destruct() { if (!$this->handled) { $this->handle('', []); } } }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPSession.php
graphp/core/GPSession.php
<?php class GPSession extends GPObject { const UID = 'uid'; private static $config; private static $session; public static function init() { self::$config = GPConfig::get(); $json_with_hash = idx($_COOKIE, self::$config->cookie_name, ''); $json = '[]'; if ($json_with_hash) { if (!GPSecurity::hmacVerify($json_with_hash, self::$config->salt)) { self::destroy(); throw new Exception('Cookie hash missmatch. Possible attack', 1); } $json = mb_substr($json_with_hash, 64, null, '8bit'); } self::$session = json_decode($json, true); if (!self::get(self::UID)) { self::set(self::UID, base64_encode(microtime().mt_rand())); } } public static function get($key, $default = null) { return idx(self::$session, $key, $default); } public static function set($key, $val) { self::$session[$key] = $val; self::updateCookie(); } public static function delete($key) { unset(self::$session[$key]); self::updateCookie(); } public static function destroy() { if (GP::isCLI()) { return; } setcookie( self::$config->cookie_name, '', 0, '/', self::$config->cookie_domain ); } private static function updateCookie() { if (GP::isCLI()) { return; } $json = json_encode(self::$session); $json_with_hash = GPSecurity::hmacSign($json, self::$config->salt); if (strlen($json_with_hash) > 4093) { throw new Exception( 'Your session cookie is too large. That may break in some browsers. Consider storing large info in the DB.', 1 ); } $result = setcookie( self::$config->cookie_name, $json_with_hash, time() + self::$config->cookie_exp, '/', self::$config->cookie_domain ); if (!$result) { throw new Exception( 'Error setting session cookie, make sure not to print any content prior to setting cookie', 1 ); } } } GPSession::init();
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/graphp/core/GPSecurity.php
graphp/core/GPSecurity.php
<?php class GPSecurity extends GPObject { const EXPIRATION = 86400; private static $config; private static $token; public static function init() { self::$config = GPConfig::get(); } public static function getNewCSRFToken() { $time = time(); $id = GPSession::get(GPSession::UID); return self::hmacSign($time, self::$config->salt.$id); } public static function csrf() { if (self::$token === null) { self::$token = self::getNewCSRFToken(); } return '<input name="csrf" type="hidden" value="'.self::$token.'" />'; } public static function isCSFRTokenValid($token) { $timestamp = mb_substr($token, 64, null, '8bit'); if ($timestamp < time() - self::EXPIRATION) { return false; } $id = GPSession::get(GPSession::UID); return self::hmacVerify($token, self::$config->salt.$id); } public static function hmacSign($message, $key) { return hash_hmac('sha256', $message, $key).$message; } public static function hmacVerify($bundle, $key) { $msgMAC = mb_substr($bundle, 0, 64, '8bit'); $message = self::hmacGetMessage($bundle); // For PHP 5.5 compat if (function_exists('hash_equals')) { return hash_equals( hash_hmac('sha256', $message, $key), $msgMAC ); } return hash_hmac('sha256', $message, $key) === $msgMAC; } public static function hmacGetMessage($bundle) { return mb_substr($bundle, 64, null, '8bit'); } } GPSecurity::init();
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/public/index.php
public/index.php
<?php define('ROOT_PATH', __DIR__.'/../'); date_default_timezone_set('UTC'); try { require_once ROOT_PATH.'graphp/core/GPLoader.php'; GPRouter::init(); GPRouter::route(); } catch (Exception $e) { $error = [ 'There was an exception:', $e->getMessage(), $e->getTraceAsString(), ]; if (GPEnv::isDevEnv()) { echo str_replace("\n", '<br>', implode('<br>', $error)); throw $e; } error_log(implode("\n", $error)); }
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/config/database.php
config/database.php
<?php return [ 'host' => '127.0.0.1', 'database' => 'graphp', 'user' => 'graphp', 'pass' => 'graphp', 'port' => 0, ];
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false
mikeland73/graphp
https://github.com/mikeland73/graphp/blob/5f55bbb2eae1e058f83e831baaaec728a9c10dfd/config/general.php
config/general.php
<?php return [ 'is_dev' => true, 'domain' => 'localhost', 'use_index_php' => true, // To avoid this, you need to configure your server 'handler_suffix' => 'ControllerHandler', // Security 'salt' => 'CHANGE THIS TO ANY RANDOM STRING', 'admin_enabled' => true, 'cookie_exp' => '1209600', // Two weeks in seconds 'cookie_domain' => '', 'cookie_name' => 'session', 'view_404' => '', 'layout_404' => '', 'app_folder' => 'app', // This will automatically drop the DB before the first view is rendered 'disallow_view_db_access' => false, ];
php
MIT
5f55bbb2eae1e058f83e831baaaec728a9c10dfd
2026-01-05T04:54:31.965184Z
false