text
stringlengths
2
104M
meta
dict
<?php namespace Rehike\SignInV2\Parser\Exception; use Rehike\Exception\AbstractException; class UnfinishedParsingException extends AbstractException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\SignInV2\Exception; use Rehike\Exception\AbstractException; class FailedSwitcherRequestException extends AbstractException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Version; /** * Control the retrival of version information. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class VersionController { /** * Array storing the version information. * * This is obtained from the .version file in root, * or .git if it is available. * * @var mixed[] */ public static $versionInfo = []; /** * Initialise the Version subsystem. * * @return void */ public static function init() { static $hasRun = false; if ($hasRun) return true; if ($dg = DotGit::canUse()) { self::$versionInfo = DotGit::getInfo(); self::$versionInfo += ["supportsDotGit" => true]; } if ($dv = DotVersion::canUse()) { self::$versionInfo += DotVersion::getInfo(); } if ($dg || $dv) { $hasRun = true; return true; } return false; } /** * Attempt to get all relevant information about the current version. * * @return void */ public static function getVersion() { $semanticVersion = \Rehike\Constants\VERSION; $initStatus = self::init(); if ($initStatus && @self::$versionInfo["currentRevisionId"]) { $semanticVersion .= "." . (string)self::$versionInfo["currentRevisionId"]; } return $semanticVersion; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Version; /** * Get version information from the .git folder if it exists * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class DotGit { /** * Determine if the version system can be used. * * @return bool */ public static function canUse() { return is_dir(".git"); } /** * Get the active Git branch. * * @return string */ public static function getBranch() { $headFile = @file_get_contents(".git/HEAD"); if (false == $headFile) return null; return trim(str_replace(["ref:", "refs/heads/", " ",], "", $headFile)); } /** * Get the latest possible commit hash. * * @return string */ public static function getCommit($branch) { $branchFile = @file_get_contents(".git/refs/heads/{$branch}"); if (false == $branchFile) return null; return trim($branchFile); } /** * Return an info array that can be merged with the DotVersion * format. * * @return string[] */ public static function getInfo() { if (!self::canUse()) return []; // Add nothing at all $response = []; if ($branch = self::getBranch()) $response += ["branch" => $branch]; if ($commit = self::getCommit($branch)) $response += ["currentHash" => $commit]; return $response; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Version; /** * Get version information from the .version file * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class DotVersion { /** * Determine if the version system can be used. * * @return bool */ public static function canUse() { return file_exists(".version"); } /** * Return info from the .version file. * * @return string[] */ public static function getInfo() { if (!self::canUse()) return []; // Add nothing $versionFile = file_get_contents(".version"); $json = json_decode($versionFile); if (null == $json) { return []; } return (array)$json; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\ErrorHandler; use Throwable; use Rehike\ErrorHandler\ErrorPage\{ AbstractErrorPage, FatalErrorPage, UncaughtExceptionPage, UnhandledPromisePage }; use YukisCoffee\CoffeeRequest\Exception\UnhandledPromiseException; /** * Implements a general error handler for Rehike. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ final class ErrorHandler { // These are aliases which look pretty in code later on, that's all! public const handleUncaughtException = self::class."::handleUncaughtException"; public const handleShutdown = self::class."::handleShutdown"; private static AbstractErrorPage $pageModel; public static function getErrorPageModel(): AbstractErrorPage { return self::$pageModel; } public static function handleUncaughtException(Throwable $e): void { if (class_exists("YukisCoffee\\CoffeeRequest\\Util\\PromiseResolutionTracker", false)) { // Disable promise resolution tracker because it may trigger additional // error messages on top of our own. \YukisCoffee\CoffeeRequest\Util\PromiseResolutionTracker::disable(); } /* * BUG (kirasicecreamm): Unhandled Promises are not compatible with the custom * error page yet because they are triggered during the cleanup at the end of * the script. * * The Promise system itself will need to be modified to account for this. */ if ($e instanceof UnhandledPromiseException) { self::$pageModel = new UnhandledPromisePage($e); } else { self::$pageModel = new UncaughtExceptionPage($e); } self::renderErrorTemplate(); exit(); } public static function handleShutdown(): void { $e = error_get_last(); if ($e != null && isset($e["type"]) && self::isErrorFatal($e["type"])) { self::$pageModel = new FatalErrorPage($e); self::renderErrorTemplate(); exit(); } } private static function renderErrorTemplate(): void { static $hasRendered = false; if ($hasRendered) return; while (ob_get_level() != 0) { ob_end_clean(); } ob_start(); require "includes/fatal_templates/fatal_error_page.html.php"; ob_end_flush(); $hasRendered = true; } private static function isErrorFatal(int $errorType): bool { return match ($errorType) { E_ERROR => true, E_CORE_ERROR => true, E_COMPILE_ERROR => true, E_PARSE => true, E_USER_ERROR => true, default => false }; } } register_shutdown_function(ErrorHandler::handleShutdown); set_exception_handler(ErrorHandler::handleUncaughtException);
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\ErrorHandler\ErrorPage; use Rehike\FileSystem; /** * Represents the page for a fatal PHP error. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class FatalErrorPage extends AbstractErrorPage { private string $type; private string $file; private ?string $message; public function __construct(array $phpError) { $this->type = $this->serializeType($phpError["type"] ?? 0); $this->message = $phpError["message"] ?? null; if ($phpError["file"] && $phpError["line"]) { $this->file = FileSystem::getRehikeRelativePath($phpError["file"]) . ":" . $phpError["line"]; } else if ($phpError["file"]) { $this->file = FileSystem::getRehikeRelativePath($phpError["file"]); } else { $this->file = "Unknown file"; } } public function getTitle(): string { return "Fatal error"; } /** * Get a user-friendly string representing the top of PHP error that * occurred. */ public function getType(): string { return $this->type; } /** * Get the file and line on which PHP reports the error occurred. */ public function getFile(): string { return $this->file; } /** * Check if I have a message to display! */ public function hasMessage(): bool { return null != $this->message; } /** * Get the message for the error, or an empty string if there is none. */ public function getMessage(): string { return $this->message ?? ""; } /** * Get a user-friendly string describing the meaning of a given PHP error * type. */ private function serializeType(int $errorType): string { return match ($errorType) { E_ERROR => "PHP engine runtime error (E_ERROR)", E_WARNING => "PHP engine runtime warning (E_WARNING)", E_PARSE => "PHP compiler parse error (E_PARSE)", E_NOTICE => "PHP engine runtime notice (E_NOTICE)", E_CORE_ERROR => "PHP engine error (E_CORE_ERROR)", E_CORE_WARNING => "PHP engine warning (E_CORE_WARNING)", E_COMPILE_ERROR => "PHP compiler error (E_COMPILE_ERROR)", E_COMPILE_WARNING => "PHP compiler warning (E_COMPILE_WARNING)", E_USER_ERROR => "Runtime error (E_USER_ERROR)", E_USER_WARNING => "Runtime warning (E_USER_WARNING)", E_USER_NOTICE => "Runtime notice (E_USER_NOTICE)", E_STRICT => "E_STRICT", E_RECOVERABLE_ERROR => "Recoverable error (E_RECOVERABLE_ERROR)", E_DEPRECATED => "PHP engine deprecation warning (E_DEPRECATED)", E_USER_DEPRECATED => "Deprecation warning (E_USER_DEPRECATED)", E_ALL => "E_ALL", default => "Unknown type" }; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\ErrorHandler\ErrorPage; use Rehike\Logging\Common\FormattedString; use Rehike\Logging\ExceptionLogger; use Throwable; /** * Represents the error page for an unhandled Promise. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class UnhandledPromisePage extends UncaughtExceptionPage { public function getTitle(): string { return "Unhandled Promise"; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\ErrorHandler\ErrorPage; use Rehike\Logging\Common\FormattedString; use Rehike\Logging\ExceptionLogger; use Throwable; /** * Represents the error page for an uncaught exception. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class UncaughtExceptionPage extends AbstractErrorPage { private FormattedString $exceptionLog; public function __construct(Throwable $e) { $this->exceptionLog = ExceptionLogger::getFormattedException($e); } public function getTitle(): string { return "Uncaught exception"; } /** * Get the exception log. */ public function getExceptionLog(): FormattedString { return $this->exceptionLog; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\ErrorHandler\ErrorPage; /** * Represents an abstract error page model. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ abstract class AbstractErrorPage { /** * Get the title of the error page type. */ abstract public function getTitle(): string; }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Logging; use Rehike\FileSystem; use Rehike\Logging\Common\FormattedString; use Throwable; /** * Formats printable exception logs that are more advanced than the default PHP * implementation. * * The log format returned by this class are very similar to Java's exception * logs. Most of the implementation is inspired by this post: * https://www.php.net/manual/en/exception.gettraceasstring.php#114980 * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class ExceptionLogger { // Disallow instantiation private function __construct() {} /** * Reformat a given exception in the custom format. */ public static function getFormattedException(Throwable $e): FormattedString { $output = new FormattedString; $exceptions = self::getExceptionChain($e); $visitedTraces = []; foreach ($exceptions as $index => $currentException) { if ($index != 0) { $output->addText("\n"); $output->addTaggedText("Thrown by ", "thrown_by"); } self::formatException( $currentException, $output, $visitedTraces, $index != 0 // first one should not be truncated ); } return $output; } private static function getExceptionChain(Throwable $e): array { // Always just add the initial exception since it will never be a // previous one: $out = [$e]; // Work through the object nest and flatten it into the above array: $currentException = $e->getPrevious(); while (null != $currentException) { $out[] = $currentException; $currentException = $currentException->getPrevious(); } return $out; } private static function formatException( Throwable $e, FormattedString $out, array &$visitedTraces, bool $truncateLog = true ): void { $trace = $e->getTrace(); $file = FileSystem::getRehikeRelativePath($e->getFile()); $line = $e->getLine(); $skipArgs = false; $out->addTaggedText(get_class($e), "exception_class"); $out->addText(": "); $out->addTaggedText($e->getMessage(), "exception_message"); while (true) { $out->addText("\n"); $currentPos = "$file:$line"; // If the log should be truncated, which we want to do with ones other // than the first log, then truncate: if ($truncateLog && in_array($currentPos, $visitedTraces)) { $out->addTaggedText( sprintf( " ... %d more", count($trace) + 1 ), "more_exceptions" ); break; } $out->addTaggedText(" at ", "at_text"); if (count($trace) > 0 && array_key_exists("class", $trace[0])) { $tmpClassName = $trace[0]["class"]; // Parse class name to prettify identifiers for anonymous classes: if (preg_match( "/@anonymous(.*?)\\$([a-zA-Z0-9]+)/", $tmpClassName, $tmpClassNameMatches )) { // Remove text $tmpClassName = str_replace( $tmpClassNameMatches[1], "", $tmpClassName ); $tmpClassName = str_replace( "@anonymous$", "@anonymous(#", $tmpClassName ); $tmpClassName .= ")"; $anonymizedPath = FileSystem::getRehikeRelativePath( $tmpClassNameMatches[1] ); $tmpClassName .= "<$anonymizedPath>"; } $out->addTaggedText($tmpClassName, "class_name"); if (array_key_exists("function", $trace[0])) { $out->addTaggedText("::", "double_colon_operator"); $out->addTaggedText($trace[0]["function"], "method_name"); } } else if (count($trace) > 0 && array_key_exists("function", $trace[0])) { $out->addTaggedText($trace[0]["function"], "function_name"); } else { // Arguments should not be shown on main, as a stylistic choice. $skipArgs = true; $out->addTaggedText("{main}", "function_name"); } if (!$skipArgs) { $out->addTaggedText("(", "args_parentheses"); if (count($trace) > 0 && array_key_exists("args", $trace[0])) { $numArgs = count($trace[0]["args"]); foreach ($trace[0]["args"] as $i => $arg) { switch (gettype($arg)) { case "string": $tmpStringText = str_replace("\"", "\\\"", $arg); if (strlen($tmpStringText) > 255) { $tmpStringText = substr($tmpStringText, 0, 255 - 3) . "..."; } $out->addTaggedText( "\"" . $tmpStringText . "\"", "args_type_string" ); break; case "integer": case "double": $out->addTaggedText( $arg, "args_type_number" ); break; case "array": $out->addTaggedText( "array<" . count($arg) . '>', "args_type_array" ); break; case "object": $out->addTaggedText( get_class($arg), "args_type_object" ); break; case "resource": $out->addTaggedText( "<resource>", "args_type_resource" ); break; case "resource (closed)": $out->addTaggedText( "<resource (closed)>", "args_type_resource" ); break; case "NULL": $out->addTaggedText( "null", "args_type_null" ); break; default: $out->addTaggedText( "<unknown type>", "args_type_unknown" ); break; } if ($i != $numArgs - 1) { $out->addTaggedText(", ", "args_comma"); } } } $out->addTaggedText(")", "args_parentheses"); } $out->addTaggedText("(", "file_line_parentheses"); $out->addTaggedText($currentPos, "file_line"); $out->addTaggedText(")", "file_line_parentheses"); $visitedTraces[] = $currentPos; if (count($trace) <= 0) { break; } $file = array_key_exists("file", $trace[0]) ? FileSystem::getRehikeRelativePath($trace[0]["file"]) : "{unknown}"; $line = array_key_exists("file", $trace[0]) && array_key_exists("line", $trace[0]) && $trace[0]["line"] ? $trace[0]["line"] : null; array_shift($trace); } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Logging\Common; /** * A simple formatted string system for the logger. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class FormattedString { /** * Contains arrays of each run of the formatted string. */ private array $runs = []; /** * Get every run of the formatted string as necessary. */ public function getRuns(): array { return $this->runs; } /** * Get the formatted string as raw text. */ public function getRawText(): string { $out = ""; foreach ($this->runs as $run) { $out .= $run["text"] ?? ""; } return $out; } /** * Manually add a run with custom metadata to the formatted string. */ public function addRun(string $text, array $metadata): void { $this->runs[] = $metadata + ["text" => $text]; } /** * Add regular text to the formatted string. */ public function addText(string $text): void { $this->runs[] = [ "text" => $text ]; } /** * Add text with a metadata tag to the run. * * This can be used for displaying the text with certain markup effects. */ public function addTaggedText(string $text, string $tag): void { $this->runs[] = [ "text" => $text, "tag" => $tag ]; } /** * Add a navigation link to the formatted string. */ public function addNavigationText(string $text, string $href): void { $this->runs[] = [ "text" => $text, "endpoint" => $href ]; } /** * Remove a run from the formatted string. * * @return bool True on success or false on failure. */ public function removeRun(int $index): bool { if ($index < 0 || $index > count($this->runs)) { return false; } array_splice($this->runs, $index, 1); return true; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Player; use Rehike\Player\Exception\CacherException; /** * Manage caching and player information storage. * * In order to make the player retrival process more * efficient, necessary information is stored rather than * queried from the server each time it is requested. * * However, server-side variables change all the time, so * this storage cannot be permanent. Cache should persist * for a maximum of 24 hours. * * Much of this library is copied from Rehike's FileSystem * module in order to retain portability. Unfortunately, * that does mean some code redundancy. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class Cacher { /** * Get the current cached contents. * * @return string */ public static function get() { $root = PlayerCore::$cacheDestDir; $name = PlayerCore::$cacheDestName; $path = "$root/$name.json"; if (file_exists($path)) { $result = json_decode(file_get_contents($path)); if (null != $result && time() < $result->expire) return $result->content; // file contents else throw new CacherException( "Failed to get cached contents from file \"$path\" " . "(or cache has expired)" ); } else { throw new CacherException( "Cache file \"$path\" does not exist" ); } } /** * Create or update the cache file with the current * information. * * @param object $object * @return void */ public static function write($object) { $root = PlayerCore::$cacheDestDir; $name = PlayerCore::$cacheDestName; $path = "$root/$name.json"; $expire = PlayerCore::$cacheMaxTime; try { return self::writeJson($path, self::expireWrap($expire, $object)); } catch (CacherException $e) { throw $e; } } /** * Wrap an object in an expirable container. * * @param int $duration * @param object $object * @return object */ public static function expireWrap($duration, $object) { $expireTime = time() + $duration; return (object)[ "expire" => $expireTime, "content" => $object ]; } /** * Serialise an object and write it to the path. * * @param string $path * @param object|array $object * * @return void */ public static function writeJson($path, $object) { try { if (is_array($object)) $object = (object)$object; $object = json_encode($object, JSON_PRETTY_PRINT); return self::writeRaw($path, $object); } catch (CacherException $e) { throw $e; } } /** * Write a raw string to a file path. * * @param string $path * @param string $contents * @param bool $recursive * @param bool $append * * @return void */ public static function writeRaw($path, $contents, $recursive = true, $append = false) { // Make sure all folders leading to the path exist if the // recursive option is enabled. if ($recursive) { $folder = self::getFolder($path); if (!is_dir($folder)) { self::mkdir($folder, 0777, true); } } // Determine fopen mode from append value $fopenMode = $append ? "a" : "w"; // Use fopen to write the file $fh = @\fopen($path, $fopenMode); $status = @\fwrite($fh, $contents); // Validate if (false == $fh || false == $status) { throw new CacherException("Failed to write file \"$path\""); } \fclose($fh); } /** * Get the containing folder of a file path. * * @param string $path * @return string */ public static function getFolder($path) { // Convert the path to account for Windows separation. $path = str_replace("\\", "/", $path); // Split the path by the separator $root = explode("/", $path); // Remove the last item (the filename) array_splice($root, count($root) - 1, 1); // Rejoin $root = implode("/", $root); return $root; } /** * An error-checked mkdir wrapper. * * @return void */ public static function mkdir($dirname, $mode = 0777, $recursive = false) { $status = @\mkdir($dirname, $mode, $recursive); if (false == $status) { throw new CacherException( "Failed to create directory \"$dirname\"" ); } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Player; use ReflectionClass; use BadMethodCallException; /** * Implements base configuration behaviours for PlayerCore. * * This essentially implements a set of "set" functions for * configuring the static properties of a class. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ abstract class Configurable { public static function __callStatic($name, $args) { if ("get" == substr($name, 0, 3)) { return self::_getBehaviour( self::_transformName("get", $name) ); } else if ("set" == substr($name, 0, 3)) { return self::_setBehaviour( self::_transformName("set", $name), $args[0] ); } else { throw new BadMethodCallException( "Method $name does not exist on " . get_called_class() ); } } /** * Set a list of properties from an array. * * @param string[] $arr * @return void */ protected static function configFromArray($arr) { $reflection = new ReflectionClass(get_called_class()); // Get a list of the static properties so that I can // compare them. $props = $reflection->getStaticProperties(); foreach ($arr as $key => $value) { if (!isset($props[$key])) continue; self::_setBehaviour($key, $value); } } /** * Transform property names for individual function * calls (getters/setters). * * @param string $prefix * @param string $name * @return string */ private static function _transformName($prefix, $name) { $name = str_replace($prefix, "", $name, 1); $name = lcfirst($name); return $name; } /** * Implements the standard "getter" behaviour. * * @param ReflectionClass $reflection * @param string $name * * @return mixed */ private static function _getBehaviour($name) { return static::$$name; } /** * Implements the standard "setter" behaviour. * * @param ReflectionClass $reflection * @param string $name * @param mixed $value * * @return void */ private static function _setBehaviour($name, $value) { static::$$name = $value; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Player; use Rehike\Player\Exception\UpdaterException; /** * Retrieve information about the current player. * * Two important variables must be retrieved in order to properly * use the YouTube player, no matter the circumstances. These are * the URL of the JS program itself and the "signature timestamp", * which is used to prevent custom applications like this. oops! * * This process involves two separate web requests, so it's useful * to cache the result for some reasonable amount of time instead * of requerying each subsequent visit. * * @author Daylin Cooper <[email protected]> * @author Taniko Yamamoto <[email protected]> */ class PlayerUpdater { /** * The URL for the YouTube player JS can only be found * on certain pages, such as watch or embed pages. However, * the JS binary remains the same between both. * * As such, in order to get the JS URL, we need to query * some such YouTube URL. * * Any embed URL works perfectly fine, no matter how invalid. * In fact, https://www.youtube.com/embed with no additional * parameters works perfectly fine and returns the JS URL, * but I want the requests to look legitimate. * * So the URL provided by default is that of "Me at the zoo", a * very important video in YouTube's history, one that receives * plenty of views, and one that's very likely never going anywhere. * * @var string */ protected static $sourceUrl = "https://www.youtube.com/embed/jNQXAC9IVRw"; /** * Request all necessary player information for the latest * version. * * @return object */ public static function requestPlayerInfo() { $html = self::requestAppHtml(); // Attempt to get application URLs from the // response. $jsUrl = self::extractApplicationUrl($html); $cssUrl = self::extractApplicationCss($html); $embedJsUrl = self::extractEmbedUrl($html); // Now get the sts from the application itself. $js = self::requestApplication(self::unrelativize($jsUrl)); $sts = self::extractSts($js); // Pack these up and return: return (object)[ "baseJsUrl" => $jsUrl, "baseCssUrl" => $cssUrl, "embedJsUrl" => $embedJsUrl, "signatureTimestamp" => $sts ]; } /** * Get the YouTube Player JS application URL. * * These vary with VFL hash (base position) and localisation, * otherwise they are very uniform URLs. * * Since YouTube changed their static URL system circa 2020, these * assets are not stored permanently (i.e. these might expire mid-use * if the cache duration is too long). * * @return string */ public static function requestAppHtml() { $response = Network::request(self::$sourceUrl); return $response; } /** * Download the player application so that the * signature timestamp can be extracted from it. * * @param string $playerUrl * @return string */ public static function requestApplication($playerUrl) { return Network::request($playerUrl); } /** * Extract the player application URL from a HTML response. * * @param string $html * @return string */ public static function extractApplicationUrl($html) { $status = preg_match(PlayerCore::$playerJsRegex, $html, $matches); if (false != $status) { return $matches[0]; } else { throw new UpdaterException("Failed to extract application URL"); } } /** * Extract the URL of the player CSS from a HTML response. * * @param string $html * @return string */ public static function extractApplicationCss($html) { $status = preg_match(PlayerCore::$playerCssRegex, $html, $matches); if (false != $status) { return $matches[0]; } else { throw new UpdaterException("Failed to get application CSS endpoint"); } } /** * Extract the player embed JS URL from a HTML response. * * @param string $html * @return string */ public static function extractEmbedUrl($html) { $status = preg_match(PlayerCore::$embedJsRegex, $html, $matches); if (false != $status) { return $matches[0]; } else { throw new UpdaterException("Failed to extract application URL"); } } /** * Extract the signature timestamp of a player application. * * Signature timestamp, or STS, is a security key that YouTube * includes to prevent unauthorised access to stream URLs. This * is, funnily enough, useless if you have the player request * the video itself, but for many other cases it is required. * * Without the signature timestamp, the streams will fail to * download or be severely throttled to the point where watching * the video is impossible. * * STS is synchronised between the player source code and the * InnerTube player API, making it necessary to also forward this * value to that if you're intending on using the API directly. * * @param string $player Source code of the player application. * @return string */ public static function extractSts($player) { // Pretty lazy code here, but it works preg_match(PlayerCore::$stsRegex, $player, $matches); if (isset($matches[1])) { return (int)$matches[1]; } else { throw new UpdaterException( "Failed to get signature timestamp of player" ); } } /** * Make a relative URL (path) not relative. * * @param string $url * @param string $base to prepend * @return string */ public static function unrelativize($path, $base = "https://www.youtube.com") { if ("/" == $path[0]) { return $base . $path; } else { return $path; } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Player; use YukisCoffee\CoffeeRequest\CoffeeRequest; use YukisCoffee\CoffeeRequest\Enum\PromiseStatus; /** * A wrapper class for networking. * * This allows portability of this portion of Rehike for freer * reuse in other projects, without them having to include YukisCoffee * modules. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class Network { const COFFEEREQUEST_LIBRARY = "YukisCoffee\\CoffeeRequest\\CoffeeRequest"; private static $mode = "curl"; private static $coffeeRequest; /** * Initialise the class * * @return void */ public static function init() { self::determineMode(); } /** * Perform a network request. * * @param string $url * @return string */ public static function request($url) { switch (self::$mode) { case "curl": return self::curlRequest($url); case "coffee": return self::coffeeRequest($url); } } /** * Perform a network request using the CoffeeRequest library. * * This is used within Rehike itself or when CoffeeRequest is * otherwise available. * * @param string $url * @return string */ protected static function coffeeRequest($url) { $p = CoffeeRequest::request($url); do { CoffeeRequest::run(); } while (PromiseStatus::PENDING == $p->status); return $p->result; } /** * Perform a network request using CURL. * * This is used as a fallback when CoffeeRequest is not * available, such as when used by a third party project. * * @param string $url * @return string */ protected static function curlRequest($url) { $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_POST => false, CURLOPT_RETURNTRANSFER => true ]); $response = curl_exec($ch); curl_close($ch); return $response; } /** * Set the internal request method. * * The available options are * - coffee (for CoffeeRequest) * - curl (for cURL) * * @return void */ protected static function determineMode() { if (self::coffeeAvailable()) { self::$mode = "coffee"; } else { self::$mode = "curl"; } } /** * Check the availability of CoffeeRequest. * * @return bool */ protected static function coffeeAvailable() { return class_exists(self::COFFEEREQUEST_LIBRARY); } } Network::init();
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Player; use Rehike\Player\{ Exception\CacherException, Exception\UpdaterException }; /** * A portable library for retrieving and using the YouTube player * in PHP. * * PlayerCore makes getting the YouTube player and using it easy! * * However, it only serves as a wrapper for getting the player * application itself. You still need all that fun frontend configuration * (luckily, if you're making a custom YouTube frontend like Rehike, that's * already covered!) * * This also can't easily be used for older versions of the YouTube * player. That is, any old version at all. YouTube has security * mechanisms in place to limit access to their streams, including * signatures and encryption. PlayerCore currently cannot extract * the decryption algorithm from the player JS, so the use of older * players is limited. * * Still, this serves as a vital component of the Rehike project and it's * made open to the public for anyone to use, whether that be for similar * or completely different purposes. * * @author Daylin Cooper <[email protected]> * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers * * @license Unlicense * @version 3.0 */ class PlayerCore extends Configurable { static $playerJsRegex = "#/s/player/[a-zA-Z0-9/\-_.]*base.js#"; static $playerCssRegex = "#/s/player/[a-zA-Z0-9/\-_.]*(www-player|www-player-webp|player-rtl).css#"; static $embedJsRegex = "#/s/player/[a-zA-Z0-9/\-_.]*www-embed-player.js#"; static $stsRegex = "/signatureTimestamp:?\s*([0-9]*)/"; static $cacheDestDir = "cache"; static $cacheDestName = "player_cache"; // .json static $cacheMaxTime = 18000; // 5 hours in seconds /** * Set configuration from an array. * * The format is a simple associative array with * key => value pairs representing the static properties * of this class. * * The base Configurable behaviour will handle parsing this * data and updating the static properties to be this way, * otherwise they are handled as constants by the PHP * compiler. * * @param string[] $array * @return void */ public static function configure($array) { self::configFromArray($array); } /** * The main function: get the necessary player information! * * @return PlayerInfo */ public static function getInfo() { // Try getting information from the cacher: try { return PlayerInfo::from(Cacher::get()); } catch (CacherException $e) { /* * If the cache is unavailable (doesn't exist, * expired, etc.) then request the data from * YouTube's servers. * * This function does also throw an exception, but * it should be treated as fatal since there's nothing * else to do here. */ $remoteInfo = PlayerUpdater::requestPlayerInfo(); // Attempt to write this to cache: // (and if it fails, do nothing) try { Cacher::write($remoteInfo); } catch (CacherException $e) {} // If everything went right, then return the remote info: return PlayerInfo::from($remoteInfo); } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Player; use Reflectionobject; /** * Implements the player information schema. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class PlayerInfo { /** * The URL of the player's base JS module. * * @var string */ public $baseJsUrl; /** * The URL of the player's base stylesheet, required * in order for it to display properly in a HTML document. * * @var string */ public $baseCssUrl; /** * A valued used to protect video streams. This is required for * playback on the client. * * @var int */ public $signatureTimestamp; /** * The URL of the player's embed JS module. * * @var string */ public $embedJsUrl; /** * PHP does not have native object casting (whyyyyyyyyy) * * I stole most of this from a Stack Overflow function: * https://stackoverflow.com/a/9812023 * * @param object $obj * @return PlayerInfo */ public static function from($obj) { $casted = new self(); $sourceReflection = new ReflectionObject($obj); $destinationReflection = new ReflectionObject($casted); $sourceProps = $sourceReflection->getProperties(); foreach ($sourceProps as $prop) { $prop->setAccessible(true); $name = $prop->getName(); $value = $prop->getValue($obj); if ($destinationReflection->hasProperty($name)) { $propDest = $destinationReflection->getProperty($name); $propDest->setAccessible(true); $propDest->setValue($casted,$value); } else { $casted->$name = $value; } } return $casted; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Player\Exception; class CacherException extends BaseException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Player\Exception; class UpdaterException extends BaseException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Player\Exception; // Define separately based on the presence of CoffeeException. if (class_exists("YukisCoffee\\CoffeeException", true)) { abstract class BaseException extends \YukisCoffee\CoffeeException {} } else { abstract class BaseException extends \Exception {} }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Signin; use Rehike\FileSystem as FS; /** * Time constants, relative to time() output which is * UNIX timestamp in seconds. */ const SECONDS = 1; const MINUTES = 60; const HOURS = 60 * MINUTES; const DAYS = 24 * HOURS; const WEEKS = 7 * DAYS; /** * Implements the cache manager for the Rehike Signin component. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class Cacher { /** * Stores the path to the signin cache file. * * @var string */ const CACHE_FILE = "cache/signin_cache.json"; /** * Get the cache file if it exists and is valid. * * If the cache file is invalid, then this method will * return false, in order to allow assignment within an * if statement. * * @return object|false */ public static function getCache() { if (FS::fileExists(self::CACHE_FILE)) { try { $object = self::readCacheFile(); $expiration = @$object->expire ?? 0; if (time() > $expiration) return false; if (null != $object) return $object; else return false; } catch (\Throwable $e) { return false; } } } /** * Read and parse the cache file, if possible. * * If the data is invalid, then this function will * return null. * * @return object|null */ protected static function readCacheFile() { $content = FS::getFileContents(self::CACHE_FILE); $object = json_decode($content); // Validate if (false == $object) return null; return $object; } /** * Write a new cache file from a provided responses array. * * @param string[] $responses * @param bool $noCheck */ public static function writeCache($responses, $noCheck = false) { if (!FS::fileExists(self::CACHE_FILE) || $noCheck) { $session = AuthManager::getUniqueSessionCookie(); $data = (object)[ "expire" => time() + (1 * WEEKS), "responseCache" => (object)[ $session => (object)$responses ] ]; FS::writeFile(self::CACHE_FILE, json_encode($data)); } else { return self::updateCache($responses); } } /** * Update the cache in order to add new data. * * @param string[] $addedResponses * @return void */ public static function updateCache($addedResponses) { $data = self::readCacheFile(); if (null == $data) return self::writeCache($addedResponses, true); $session = AuthManager::getUniqueSessionCookie(); @$data->expire += (1 * DAYS); @$data->responseCache->{$session} = $addedResponses; // Rewrite the file now FS::writeFile(self::CACHE_FILE, json_encode($data)); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Signin; /** * Implements the Rehike Signin API. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class API { /** * Check if the current session is signed in. * * @return bool */ public static function isSignedIn() { return AuthManager::$isSignedIn; } /** * Get account information from the private AuthManager. */ public static function getInfo() { return AuthManager::$info; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Signin; use YukisCoffee\CoffeeRequest\CoffeeRequest; use YukisCoffee\CoffeeRequest\Promise; use YukisCoffee\CoffeeRequest\Network\Request; use YukisCoffee\CoffeeRequest\Network\Response; use Rehike\Network; use Rehike\FileSystem as FS; /** * Treat this as private. Use the API please. * * This handles most of the internal behaviour. I'm too lazy * to clean it up. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class AuthManager { /** * Stores the value returned by the public API method self::shouldAuth(). * * @internal * @var bool */ private static $shouldAuth = false; /** * Stores the user's SAPISID; a login cookie used to authenticate each * individual request. * * During the authentication process, this is hashed, resulting in an * SAPISIDHASH value. * * @var string */ private static $sapisid; /** * Stores the current account's GAIA ID. * * This is used internally in some places, as well as is used to identify * the Google account as a whole. * * @var string */ private static $currentGaiaId = ""; /** * Stores the current signin state. * * This isn't guaranteed. If an error occurs while attempting to get * authentication data, the signin request will be rejected and this will * remain false. * * @var bool */ public static $isSignedIn = false; /** * Stores the resulting information from a signin request. * * @var ?array */ public static $info = null; public static function __initStatic() { self::init(); } public static function init() { self::$shouldAuth = self::determineShouldAuth(); } /** * Provide the global context ($yt) for internal use. * * @param object $yt Global context * @return void */ public static function use(&$yt) { // Merge data into main variable sent to the // templater and whatnot. // Also tell the request manager to use this too. if (self::shouldAuth()) { Network::useAuthService(); $data = self::getSigninData(); if (self::$isSignedIn) { $yt->signin = ["isSignedIn" => true] + $data; return; } } $yt->signin = ["isSignedIn" => false]; } /** * Get if authentication is available. * * @return bool */ public static function shouldAuth() { return self::$shouldAuth; } /** * Used internally as a one-time determination of the authentication's * availability. * * @return bool */ private static function determineShouldAuth() { // Determined by the presence of SAPISID cookie. if (isset($_COOKIE) && isset($_COOKIE["SAPISID"])) { self::$sapisid = $_COOKIE["SAPISID"]; return true; } return false; } /** * Get the contents of the authentication HTTP header. This will generate * a new SAPISIDHASH. * * @param string $origin * @return string */ public static function getAuthHeader($origin = "https://www.youtube.com") { $sapisid = self::$sapisid; $time = time(); $sha1 = sha1("{$time} {$sapisid} {$origin}"); return "SAPISIDHASH {$time}_{$sha1}"; } /** * Get the current user's GAIA ID. * * @return string */ public static function getGaiaId() { return self::$currentGaiaId; } /** * Retrieve signin data from the server or cache. * * @return array */ public static function getSigninData() { if (null != self::$info) { return self::$info; } else if ($cache = Cacher::getCache()) { $sessionId = self::getUniqueSessionCookie(); if ($data = @$cache->responseCache->{$sessionId}) { self::$info = self::processSwitcherData( $data->switcher ); Network::useAuthGaiaId(); self::processMenuData(self::$info, $data->menu); return self::$info; } } // This is the fallback in all other cases. self::$info = self::requestSigninData(); return self::$info; } /** * Request signin data from the server. * * @return array */ public static function requestSigninData() { /** @var string */ $switcher = null; /** @var string */ $menu = null; $info = null; Network::urlRequest( "https://www.youtube.com/getAccountSwitcherEndpoint", Network::getDefaultYoutubeOpts() )->then(function($response) use (&$switcher, &$info) { $switcher = $response->getText(); $info = self::processSwitcherData($switcher); Network::useAuthGaiaId(); return Network::innertubeRequest("account/account_menu", [ "deviceTheme" => "DEVICE_THEME_SUPPORTED", "userInterfaceTheme" => "USER_INTERFACE_THEME_DARK" ]); })->then(function($response) use (&$menu) { $menu = $response->getText(); }); // This call blocks the thread until the requests are done. Network::run(); self::processMenuData($info, $menu); $responses = [ "switcher" => &$switcher, "menu" => &$menu ]; Cacher::writeCache($responses); return $info; } /** * Generate a new signin data array from the getAccountSwitcherEndpoint * response. * * @param string $switcher getAccountSwitcherEndpoint response * @return array */ public static function processSwitcherData($switcher) { $info = Switcher::parseResponse($switcher); self::$currentGaiaId = &$info["activeChannel"]["gaiaId"]; // Since no errors were thrown, assume everything // works. self::$isSignedIn = true; return $info; } /** * Modify the switcher endpoint's data to add the UCID obtained from the * menu data. * * @param array $info Reference to the data to modify. * @param string $menu Response of the account_menu endpoint. */ public static function processMenuData(&$info, $menu) { // UCID must be retrieved here to work with GAIA id $info["ucid"] = self::getUcid(json_decode($menu)); } /** * Get the UCID of the active channel. * * @param object $menu * @return string */ public static function getUcid($menu) { if ($items = @$menu->actions[0]->openPopupAction->popup ->multiPageMenuRenderer->sections[0]->multiPageMenuSectionRenderer ->items ) { foreach ($items as $item) { $item = @$item->compactLinkRenderer; if ("ACCOUNT_BOX" == @$item->icon->iconType) { return $item->navigationEndpoint->browseEndpoint->browseId ?? null; } } } return ""; } /** * Get the unique session cookie (if it exists) * * @return string (even "null" as a string) */ public static function getUniqueSessionCookie() { if (isset($_COOKIE["LOGIN_INFO"])) { return $_COOKIE["LOGIN_INFO"]; } else { return "null"; } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Signin; /** * A really nasty switcher parser, wrote by Taniko circa March 2022. * * Needless to say, it's one of the messier Rehike modules. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class Switcher { /** * Parse a getAccountSwitcherEndpoint response. * * @param string $response Raw response (not JSON decoded). * @return array Associative array of wrappers. */ public static function parseResponse($response) { $response = json_decode(substr($response, 4, strlen($response))); $info = [ "googleAccount" => self::getGoogAccInfo($response), "activeChannel" => self::getActiveChannel($response), "channelPicker" => self::getChannels($response) ]; return $info; } /** * Get Google account information from the header. * * @param object $data Decoded from the response. * @return array Associative array of parsed data. */ public static function getGoogAccInfo($data) { $header = $data->data->actions[0]->getMultiPageMenuAction-> menu->multiPageMenuRenderer->sections[0]->accountSectionListRenderer-> header->googleAccountHeaderRenderer; return [ "email" => $header->email->simpleText, "name" => $header->name->simpleText ]; } /** * Get the available channels on a Google account. * * @param object $data Decoded from the response. * @return array Iterative array of channel information. */ public static function getChannels($data) { $items = $data->data->actions[0]->getMultiPageMenuAction-> menu->multiPageMenuRenderer->sections[0]->accountSectionListRenderer-> contents[0]->accountItemSectionRenderer->contents; $channels = []; for ($i = 0, $c = count($items); $i < $c; $i++) if (isset($items[$i]->accountItem)) { $channels[] = self::accountItem($items[$i]->accountItem); } return $channels; } /** * Get information about the active channel. * * @param object $data Decoded from the response. * @return ?array Channel item data */ public static function getActiveChannel($data) { $channels = self::getChannels($data); foreach ($channels as $index => $channel) { if ($channel["selected"]) { return $channel; } } return null; } /** * Parse information about an account item. * * @param object $account From the original response. * @return array Parsed associative array. */ public static function accountItem($account) { if (isset($account->serviceEndpoint->selectActiveIdentityEndpoint->supportedTokens)) foreach ($account->serviceEndpoint->selectActiveIdentityEndpoint->supportedTokens as $token) { if (isset($token->pageIdToken)) { $gaiaId = $token->pageIdToken->pageId; } elseif (isset($token->accountSigninToken)) { $switchUrl = $token->accountSigninToken->signinUrl; } } return [ "name" => $account->accountName->simpleText, "photo" => $account->accountPhoto->thumbnails[0]->url, "byline" => $account->accountByline->simpleText, "selected" => $account->isSelected, "hasChannel" => $account->hasChannel ?? false, "gaiaId" => $gaiaId ?? "", "switchUrl" => $switchUrl ?? "" ]; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Exception; use YukisCoffee\CoffeeException; abstract class AbstractException extends CoffeeException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Exception\i18n; use Rehike\Exception\AbstractException; class I18nUnsupportedFileException extends AbstractException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Exception\FileSystem; use Rehike\Exception\AbstractException; class FsWriteFileException extends AbstractException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Exception\FileSystem; use Rehike\Exception\AbstractException; class FsFileDoesNotExistException extends AbstractException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Exception\FileSystem; use Rehike\Exception\AbstractException; class FsFileReadFailureException extends AbstractException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Exception\FileSystem; use Rehike\Exception\AbstractException; class FsMkdirException extends AbstractException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Exception\Network; use Rehike\Exception\AbstractException; class InnertubeFailedRequestException extends AbstractException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Boot; use Rehike\{ YtApp, TemplateManager, ControllerV2\Core as ControllerV2, Debugger\Debugger, Signin\AuthManager, RehikeConfigManager }; /** * Manages the global app state for Rehike during boot. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ final class YtStateManager { /** * Initialise and get the global state. */ public static function init(): YtApp { $yt = new YtApp(); self::bindToEverything($yt); return $yt; } /** * Bind the global state to everything that needs it. */ protected static function bindToEverything(YtApp $yt): void { TemplateManager::registerGlobalState($yt); ControllerV2::registerStateVariable($yt); Debugger::init($yt); /* * TODO: This should be removed when V1 is deprecated. */ if (RehikeConfigManager::getConfigProp("experiments.useSignInV2") !== true) { AuthManager::use($yt); } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Boot; use Rehike\{ Debugger\Debugger }; /** * Main bootstrapper insertion point for Rehike. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ final class Bootloader { /** * Start a new Rehike session. */ public static function startSession(): void { self::boot(); self::postboot(); self::shutdown(); } /** * Sets up everything necessary to load a Rehike page. */ private static function boot(): void { self::runInitTasks(); $yt = YtStateManager::init(); self::runSetupTasks(); } /** * Manages main application behaviour after the initial boot process is * done. */ private static function postboot(): void { require "router.php"; } /** * Ran after all page logic is done. */ private static function shutdown(): void { Debugger::shutdown(); } /** * Runs all initialisation tasks. * * These are early-stage configuration tasks that later "setup" tasks * may be dependent upon. These do not have access to the global state. */ private static function runInitTasks(): void { Tasks::initNetwork(); Tasks::initResourceConstants(); Tasks::initConfigManager(); } /** * Runs all setup tasks. * * These are late-stage configuration tasks that have access to Rehike's * global state. */ private static function runSetupTasks(): void { Tasks::setupTemplateManager(); Tasks::setupI18n(); Tasks::setupControllerV2(); Tasks::setupPlayer(); Tasks::setupVisitorData(); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Boot; use YukisCoffee\CoffeeRequest\CoffeeRequest; use Rehike\{ ContextManager, TemplateManager, i18n, YtApp, Network, Async\Concurrency, ControllerV2\Core as ControllerV2, Player\PlayerCore, Misc\RehikeUtilsDelegate, Misc\ResourceConstantsStore, RehikeConfigManager, Util\Nameserver\Nameserver, Util\Base64Url }; /** * Implements boot tasks for Rehike. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ final class Tasks { public static function initNetwork(): void { CoffeeRequest::setResolve([ Nameserver::get("www.youtube.com", "1.1.1.1", 443)->serialize() ]); } public static function initResourceConstants(): void { ResourceConstantsStore::init(); } public static function initConfigManager(): void { RehikeConfigManager::loadConfig(); } public static function setupTemplateManager(): void { $utilsDelegate = new RehikeUtilsDelegate(); $constants = ResourceConstantsStore::get(); TemplateManager::addGlobal("rehike", $utilsDelegate); TemplateManager::addGlobal("ytConstants", $constants); TemplateManager::addGlobal("PIXEL", $constants->pixelGif); } public static function setupI18n(): void { i18n::setDefaultLanguage("en"); i18n::newNamespace("main/regex") ->registerFromFolder("i18n/regex"); i18n::newNamespace("main/misc") ->registerFromFolder("i18n/misc"); i18n::newNamespace("main/guide") ->registerFromFolder("i18n/guide"); $msgs = i18n::newNamespace("main/global") ->registerFromFolder("i18n/global"); // Also expose common messages to the global variable. YtApp::getInstance()->msgs = $msgs->getStrings()[$msgs->getLanguage()]; } public static function setupControllerV2(): void { ControllerV2::setRedirectHandler( require "includes/spf_redirect_handler.php" ); } public static function setupPlayer(): void { PlayerCore::configure([ "cacheMaxTime" => 18000, // 5 hours (in seconds) "cacheDestDir" => "cache", "cacheDestName" => "player_cache" // .json ]); } public static function setupVisitorData(): void { // Obtain the info from the user if it exists, otherwise // request it and store that. if (isset($_COOKIE["VISITOR_INFO1_LIVE"])) { $visitor = $_COOKIE["VISITOR_INFO1_LIVE"]; } else { // Hacky algo to get it from the server: $request = Network::urlRequest("https://www.youtube.com"); $response = Concurrency::awaitSync($request); // Find the configuration set property that contains the visitor // data string. preg_match("/ytcfg\.set\(({.*?})\);/", $response, $matches); $ytcfg = json_decode(@$matches[1]); $visitor = $ytcfg->INNERTUBE_CONTEXT->client->visitorData; // Very hackily extract the cookie string from the encoded base64 // protobuf string YouTube gives. $visitor = Base64Url::decode($visitor); $visitor = substr($visitor, 2); $visitor = explode("(", $visitor)[0]; setcookie("VISITOR_INFO1_LIVE", $visitor); } ContextManager::setVisitorData($visitor); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Misc; use Rehike\RehikeConfigManager; use Rehike\Version\VersionController; use Rehike\Util\ParsingUtils; use stdClass; /** * Defines the `rehike` variable exposed to Twig-land. * * This implements unique properties directly on the class. The child * class will implement all alias properties. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ abstract class RehikeUtilsDelegateBase extends stdClass { /** * Stores the current Rehike configuration. */ public object $config; /** * Provides version information about the current Rehike setup. */ public object $version; /** * Initialise all utilities. */ public function __construct() { $this->config = RehikeConfigManager::loadConfig(); $this->version = (object)VersionController::$versionInfo; $this->version->semanticVersion = VersionController::getVersion(); } /** * Alias for ParsingUtils::getText() for templating use. */ public static function getText(mixed $source): string { return ParsingUtils::getText($source) ?? ""; } /** * Alias for ParsingUtils::getUrl() for templating use. */ public static function getUrl(mixed $source): string { return ParsingUtils::getUrl($source) ?? ""; } /** * Alias for ParsingUtils::getThumb() for templating use. */ public static function getThumb(?object $obj, int $height = 0): string { if (null == $obj) return "//i.ytimg.com"; return ParsingUtils::getThumb($obj, $height) ?? "//i.ytimg.com/"; } /** * Alias for ParsingUtils::getThumbnailOverlay() for templating use. */ public static function getThumbnailOverlay(object $array, string $name): ?object { return ParsingUtils::getThumbnailOverlay($array, $name); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Misc; /** * Stores resource constants locations for resource routing in Rehike. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class ResourceConstantsStore { public static object $constants; public static function init(): void { self::$constants = include "includes/resource_constants.php"; } public static function get(): object { return self::$constants; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Misc; use Rehike\Util\{ Base64, CasingUtils, ResourceUtils, ParsingUtils }; /** * Defines the `rehike` variable exposed to Twig-land. * * This class implements all alises to other utility classes. The parent * class handles unique properties and all methods. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class RehikeUtilsDelegate extends RehikeUtilsDelegateBase { public Base64 $base64; public CasingUtils $casing; public ResourceUtils $resource; public ParsingUtils $parsing; public function __construct() { parent::__construct(); // When abandoning support for PHP 8.0, these may be coalesced into // the constructor arguments. $this->casing = new CasingUtils(); $this->base64 = new Base64(); $this->resource = new ResourceUtils(); $this->parsing = new ParsingUtils(); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Async; use Rehike\Async\Concurrency\AsyncFunction; use YukisCoffee\CoffeeRequest\Promise; use YukisCoffee\CoffeeRequest\Loop; use YukisCoffee\CoffeeRequest\Enum\PromiseStatus; use Generator; /** * Implements a Generator-based Promise abstraction. * * This allows similar syntax to async functions in C# and ECMAScript by * using generators as a hack. * * In fact, the hack is reminiscent of a technique used to emulate async * functions in ES6, when generators were available but async functions * were not. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class Concurrency { public static function __initStatic() { \YukisCoffee\CoffeeRequest\Debugging\PromiseStackTrace::registerSkippedFile(__FILE__); \YukisCoffee\CoffeeRequest\Debugging\PromiseStackTrace::registerSkippedFile(ASYNC_FUNCTION_FILE); } /** * Declares an async function. * * This is an abstraction for Promises using PHP's native generator * functionality. It functions very similarly to async functions in * C# or ECMAScript 7. The main difference is it relies on an anonymous * function still, and uses the `yield` keyword rather than `await`. * * For API compatiblity with standard Promises, all async functions * return a Promise which will resolve or reject with the internal * Generator it uses. * * It's recommended to `use function Rehike\Async\async;` and use the * shorthand function, rather than using this class directly. * * Usage example: * * function requestExample(string $url): Promise//<Response> * { * return Concurrency::async(function() use (&$myPromises) { * echo "Making network request..."; * * $result = yield Network::request($url); * * if (200 == $result->status) * { * return $result; * } * else * { * throw new NetworkFailedExeception($result); * } * }); * } * * This is like the following C# code: * * async Task<Response> requestExample(string url) * { * System.Console.WriteLine("Making network request..."); * * Response result = await Network.request(url); * * if (200 == result.status) * { * return result; * } * else * { * throw new NetworkFailedException(result); * } * } * * or the following TypeScript code: * * async function requestExample(url: string): Promise<Response> * { * console.log("Making network request..."); * * let result = await Network.request(url); * * if (200 == request.status) * { * return result; * } * else * { * throw new NetworkFailedException(result); * } * } * * Notice that both languages also return their respective wrapper * type for all asynchronous functions. This is for API-compatibility * with other approaches. It is also important to keep in consideration! * * PHP developers who are unfamiliar with asynchronous design may think * that an async function returns the type it returns, but it simply * provides syntax to work with Promises in a synchronous manner. * Remember that *ANY* function which needs to use the result of an * asynchronous function must also do so asynchronously, either by using * Promise::then() or implementing its body in an async stream. * * @template T * @param callable<T> $cb * @return Promise<T> */ public static function async/*<T>*/(callable/*<T>*/ $cb): Promise/*<T>*/ { /* * Capture the result of the callback provided. * * All anonymous functions are Closure objects, including those * that have the `yield` keyword. They only become Generator objects * after being ran for the first time. * * As such, a check is needed immediately after this. */ $result = $cb(); if ($result instanceof Generator) { $async = new AsyncFunction($result); // Run the Generator for the first time. This will handle // the first `yield` expression and move on to the next. $async->run(); return $async->getPromise(); } else { // Return a Promise that instantly resolves with the result // of the callback. return new Promise(fn($r) => $r($result)); } } /** * Synchronously get the result of a Promise (or throw an exeception). * * As this is blocking, using this will have none of the benefits of an * asynchronous design. * * This should be used rarely, and only for critical code. */ public static function awaitSync(Promise $p): mixed { $result = null; // Registers the base handlers for the Promise. $p->then(function ($r) use (&$result) { $result = $r; })->catch(function ($e) { throw $e; }); do { Loop::run(); } while (PromiseStatus::PENDING == $p->status); return $result; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Async; // Hack for IDE hover behaviour. if(false){class Promise extends \YukisCoffee\CoffeeRequest\Promise {}} // We want a true copy such that: // (new Rehike\Async\Promise()) instanceof YukisCoffee\CoffeeRequest\Promise // so a class alias is preferred here. class_alias("YukisCoffee\\CoffeeRequest\\Promise", "Rehike\\Async\\Promise");
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Async; use Rehike\Async\Pubsub\Topic; /** * A simple publish/subscribe messaging system. * * PHP generally isn't asynchronous, so something this typically isn't * necessary, however Rehike does use an asynchronous design and this is * helpful in wrapping that. JS programmers may find this API familiar, * however. * * This is a very simple pattern. Subscribing to a topic with a callback adds * that callback to a queue internally, which is then called when the topic * gets published. * * A topic is a simple string that acts as a unique ID for that particular * queue action. * * Using this, code can be queued for later, which preserves the flow and * structure of source code while making it wait for another task to continue * elsewhere. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class Pubsub { /** * An array of topics. * * @var Topic[] */ private static array $topics = []; /** * Subscribe to a topic. */ public static function subscribe(string $id, callable $cb): void { self::getTopicById($id)->subscribe($cb); } /** * Unsubscribe from a topic. */ public static function unsubscribe(string $id, callable $cb): void { self::getTopicById($id)->unsubscribe($cb); } /** * Publish a topic. */ public static function publish(string $id, mixed $extraData = null): void { self::getTopicById($id)->publish($extraData); } /** * Remove a topic. */ public static function clear(string $id): void { self::getTopicById($id)->clear(); } /** * Get a topic by its ID. */ private static function getTopicById(string $id): Topic { foreach (self::$topics as $topic) { if ($id == $topic->id) { return $topic; } } // Otherwise it doesn't exist, so add it. $topic = new Topic($id); self::$topics[] = $topic; return $topic; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Async\Pubsub; use Closure; /** * Implements a pubsub topic handler. * * @internal * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class Topic { public string $id; /** * @var callable[] */ private array $listeners = []; public function __construct(string $id) { $this->id = $id; } /** * Subscribe to this topic. */ public function subscribe(callable $cb): void { $this->listeners[] = $cb; } /** * Unsubscribe from this topic. */ public function unsubscribe(callable $cb): void { if ($index = array_search($cb, $this->listeners)) { array_splice($this->listeners, $index, 1); } } /** * Publish this topic. * * This will notify all subscriptions. * * @param mixed $extraData */ public function publish(mixed $extraData = null): void { foreach ($this->listeners as $cb) { $cb($extraData); } } /** * Clear all subscriptions from this topic. */ public function clear(): void { $this->listeners = []; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Async\Concurrency; use Generator, Exception; use Rehike\Async\Promise; /** * Represents an async function in execution. * * Async functions work in Rehike by using generator functions that yield * promises within them. This class implements the logic necessary to * capture the Promise and send back the value of the Promise. * * @internal * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class AsyncFunction { /** * The generator is the backend of the whole thing. * * Generators are a perfect to emulate async functions since their * yield functionality is pretty much identical to await. * * Most notably, you can capture the result of a yield expression, use * it, and then replace it with a completely different variable. */ private Generator $generator; /** * A Promise for the completion of the async function. * * This enables API compatibility with Promise-based code, i.e. you * can `myAsyncFunction()->then("handleAsyncResult")`. When the async * function returns or throws, this Promise will be resolved or rejected * respectively. */ private Promise $ownPromise; public static function __initStatic() { \YukisCoffee\CoffeeRequest\Debugging\PromiseStackTrace::registerSkippedFile(__FILE__); } public function __construct(Generator $g) { $this->generator = $g; $this->ownPromise = new Promise(); } /** * Get a Promise representing the state of the async function. * * This will resolve or reject accordingly with the value returned * or thrown by the async function. */ public function getPromise(): Promise { return $this->ownPromise; } /** * Run the async function for one iteration. * * This progresses the internal Generator and captures the value held * within it as long as the Generator has not yet returned. * * If the Generator has returned, then it will resolve this function's * Promise and message the return status to all internal listeners. * Likewise for rejection. */ public function run(): void { // A valid generator is one that has not returned. if ($this->generator->valid()) { try { /* * Capture the value of the generator *and then progress * it*. * * Those unfamiliar with PHP's generator implementation may * be a little confused with this behaviour. Whenever you * try to get the current value of the generator, it will * return that value and then run the generator again. * * That's also why this function never explicitly calls * Generator::next(). */ $value = $this->generator->current(); } catch (Exception $e) { // Capture the exception thrown by the Generator and carry // it over to the internal Promise. $this->ownPromise->reject($e); } } else // has returned { $result = $this->generator->getReturn(); $this->ownPromise->resolve($result); return; } // Obviously, an async function must take in a Promise. if ($value instanceof Promise) { $value->then($this->getThenHandler()); } else { throw new \Exception( "An async function must take in a Promise." ); } } /** * Get a then handler for the internal Promise. * * Only one handler is ever needed, which is this closure. This relies * on the Promise messaging system to send the value of the current * Promise back to the generator and then rerun it. */ protected function getThenHandler(): callable { return function (mixed $value) { $this->generator->send($value); $this->run(); }; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\Async\Concurrency; use Rehike\Async\Promise; /** * A nice debugging tool I made because I was having an issue with an error * being swallowed. * * @static * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ final class AntiSwallowedErrorHelper { private static int $pendingResolutionCount = 0; private static array $pendingResolutions = []; private static array $sources = []; private static object $shutdownHelper; public static function __initStatic() { self::$shutdownHelper = new class() { public function __destruct() { AntiSwallowedErrorHelper::_handleShutdown(); } }; } /** * Report a pending resolution. */ public static function reportPendingResolution(Promise $function, array $source): void { self::$pendingResolutionCount++; self::$pendingResolutions[] = $function; self::$sources[] = $source; } public static function resolvePendingResolution(Promise $function): void { self::$pendingResolutionCount--; if ($pos = array_search($function, self::$pendingResolutions)) { array_splice(self::$pendingResolutions, $pos, 1); array_splice(self::$sources, $pos, 1); } } public static function _handleShutdown() { if (self::$pendingResolutionCount > 0) { // Throw out the current output buffer because it isn't wanted. do { ob_end_clean(); } while (ob_get_level() > 0); $index = count(self::$pendingResolutions) - 1; $promise = self::$pendingResolutions[$index]; $source = self::$sources[$index]; $reflection = new \ReflectionClass($promise); $name = $reflection->getName(); $file = $source["file"]; $line = $source["line"]; throw new \Exception( "Unresolved promise ($name) in async function ending at $file:$line." ); } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\ConfigManager; // Prereq coffeeexception class DumpFileException extends \YukisCoffee\CoffeeException {};
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\ConfigManager; // Prereq coffeeexception class LoadConfigException extends \YukisCoffee\CoffeeException {};
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\ConfigManager; // Prereq coffeeexception class FilePathException extends \YukisCoffee\CoffeeException {};
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\ConfigManager; use YukisCoffee\PropertyAtPath; /** * An abstract ConfigManager */ class ConfigManager { /** @var array (because PHP limitations) */ public static $defaultConfig = []; /** @var array (because PHP limitation) */ public static $types = []; /** @var string */ protected static $file = 'config.json'; /** @var object|null */ protected static $config; /** * Dump a config file. * * @abstract * @return void */ protected static function dump($file, $cfg) { try { $stream = fopen($file, "w"); fwrite($stream, $cfg); fclose($stream); } catch (\Throwable $e) { throw DumpFileException::from($e); } } /** * Dump the active config and override * the active file. * * @return void */ public static function dumpConfig() { return static::dump( static::$file, json_encode(static::$config, JSON_PRETTY_PRINT) ); } /** * Dump the default config and override or create * the active file. * * @return void */ public static function dumpDefaultConfig() { return static::dump( static::$file, json_encode((object) static::$defaultConfig, JSON_PRETTY_PRINT) ); } /** * Set the config location * * @param string $filePath * @return void */ public static function setConfigFile($filePath) { if (!is_string($filePath)) throw new FilePathException("Type of file path must be string."); self::$file = $filePath; } /** * Get the active config * * @return object */ public static function getConfig() { return is_object(static::$config) ? static::$config : (object) static::$defaultConfig; } /** * Get the types of the configs * * @return object */ public static function getTypes() { return json_decode(json_encode(static::$types)); } /** * Get a configuration option * * This handles checking if an option is set in the * config. If it isn't, this returns null. * * @param string $path Period-delimited path of the config * @return mixed */ public static function getConfigProp($path) { $cfg = static::getConfig(); try { $value = PropertyAtPath::get($cfg, $path); } catch (\YukisCoffee\PropertyAtPathException $e) { return null; } return $value; } /** * Set a configuration option * * This handles checking if an option is set in the * config. If it isn't, this returns null. * * @param string $path Period-delimited path of the config * @param string $value New value * @return void */ public static function setConfigProp($path, $value) { try { PropertyAtPath::set(static::$config, $path, $value); } catch (\YukisCoffee\PropertyAtPathException $e) { return; } } /** * Get a configuration option's type * * This handles checking if an option is set in the * config. If it isn't, this returns null. * * @param string $path Period-delimited path of the config * @return string */ public static function getConfigType($path) { $types = static::getTypes(); try { $value = PropertyAtPath::get($types, $path); } catch(\YukisCoffee\PropertyAtPathException $e) { return null; } return $value; } /** * Set the config to be an object parsed * from the provided file name. * * @return object */ public static function loadConfig() { $file = self::$file; $object = \json_decode(file_get_contents($file)); // Throw an exception if response type is not object // This is because PHP does not throw an exception if // json_decode fails. if (!is_object($object)) throw new LoadConfigException("Failed to parse config file \"{$file}\""); // Else, set the active config used to this. static::$config = $object; return static::$config; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\UserPrefs; /** * Provides utilities for managing YouTube user preferences in Rehike. * * This processes the value of the PREF cookie and allows easy parsing of * its value. * * Most YouTube preferences set through this cookie are flags, which are * implemented efficiently through a bitmask. Other implementations are * permitted by YouTube's code, but they seem to be unused. * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ class UserPrefs { private static UserPrefs $instance; /** * The name of the cookie YouTube stores user information in. */ protected const COOKIE_NAME = "PREF"; /** * Stores parsed user preferences. */ protected array $prefs = []; public function __construct() { $cookie = self::getPrefCookie(); $this->parse($cookie); } public static function __initStatic(): void { static::$instance = new static(); } public static function getInstance(): UserPrefs { return static::$instance; } /** * Get the value of a flag. */ public function getFlag(int $flag): bool { [$index, $bitmask] = self::calcFlagVars($flag); return $this->getFlagValue("f$index", $bitmask); } /** * Set the value of a flag. */ public function setFlag(int $flag, bool $value): void { [$index, $bitmask] = self::calcFlagVars($flag); // todo finish!! } /** * Dump the changes made on the instance. */ public function dump(): string { $out = []; foreach ($this->prefs as $name => $value) { // rawurlencode to emulate JS escape $out[] = "$name=" . rawurlencode($value); } return implode("&", $out); } /** * Parse a serialised preferences string. */ protected function parse(string $cookie): void { $fields = explode("&", $cookie); foreach ($fields as $field) { $pair = explode("=", $field); // Ignore malformed input. if (isset($pair[1])) { $key = $pair[0]; $value = $pair[1]; // rawurldecode to emulate JS unescape $this->prefs[$key] = rawurldecode($value); } } } /** * Get the number of a numeric field, i.e. flags. */ protected function getNumber(int $index): ?int { if (isset($this->prefs[$index])) { return hexdec( (string)$this->prefs[$index] ); } else { return null; } } /** * Get the boolean value of a flag. * * Internally, the flag index is handled as hexadecimal and AND'd with * the bitmask. * * If the result of the AND is 0, this will return false. Otherwise * it always returns true. */ protected function getFlagValue(int $index, int $bitmask): bool { $result = ($this->getNumber($index) ?? 0) & $bitmask; return (0 != $result) ? true : false; } /** * Calculate the variables required to read or write a flag. */ protected static function calcFlagVars(int $flag): array { return [ floor($flag / 31) + 1, 1 << $flag % 31 ]; } /** * Get the PREF cookie value. */ protected static function getPrefCookie(): string { return $_COOKIE[self::COOKIE_NAME] ?? ""; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace Rehike\UserPrefs; /** * An int enum for flags. * * @enum * * @author Taniko Yamamoto <[email protected]> * @author The Rehike Maintainers */ final class Flags { }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee; interface ICoffeeException { // PHP Exception standard methods: public function getMessage(); public function getCode(); public function getFile(); public function getLine(); public function getTrace(); public function getTraceAsString(); public function __toString(); public function __construct($message = null, $code = 0); } abstract class CoffeeException extends \Exception implements ICoffeeException { // PHP is really annoying ugh... // - protected $file // - protected $line // Crash PHP 8, saying they must be typed // - protected string $file // - protected int $line // Crash PHP 7, saying they must be untyped // Fix: Remove the redefinition here and just // inherit from Exception. public $message = "Unknown exception"; private $string; protected $code = 0; private $trace; public $exceptionName; protected static $beautifulError = true; public function __construct($message = null, $code = 0) { $this->exceptionName = get_class($this); if (!$message) { $this->message = "Unknown {$this->exceptionName}"; } parent::__construct($message, $code); } /** * Create a new exception from a previously thrown * one. * * Useful for renaming exceptions. * * @param Throwable $exception * @return CoffeeException */ public static function from($exception) { $ceInstance = new static( $exception->getMessage(), $exception->getCode() ); $ceInstance->_setFile( $exception->getFile() ); $ceInstance->_setLine( $exception->getLine() ); $ceInstance->_setTrace( $exception->getTrace() ); return $ceInstance; } public function _setFile($a) { $this->file = $a; } public function _setLine($a) { $this->line = $a; } public function _setTrace($a) { $this->trace = $a; } public function __toString() { if (self::$beautifulError) { // More readable crash screen if uncaught. echo "<div class=\"yukiscoffee-uncaught-error-container\">" . "<h1>Fatal error</h1>" . "Uncaught <b>{$this->exceptionName}</b>: {$this->message}<br><br>" . "<h1>Technical info</h1>" . "<pre>" . "File: {$this->file}:{$this->line}\n\n" . "Stack trace:<div class=\"yc-stack-trace\">{$this->getTraceAsString()}</div>" . "</pre>" . "</div>" . "<style>.yukiscoffee-uncaught-error-container{padding:12px;color:#000;border:4px solid #d31010;background:#fff;font-family:arial,sans-serif}" . ".yc-stack-trace{margin-left:12px;padding-left:12px;border-left:2px solid #ccc}" . "</style>"; exit(); } else { return parent::__toString(); } } public static function enableBeautifulError($status = true) { self::$beautifulError = $status; } public static function disableBeautifulError() { return self::enableBeautifulError(false); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee; class PropertyAtPathException extends CoffeeException {} /** * PHP lacks traditional syntax for walking property paths. * String interpolation may be used for single properties, * however children of children may not be accessed. * * Or more simply, $a->{'b'} is valid, but you cannot access * $a->b->c without multiple pointers. * * This is an eval mess, be warned. * * @author Taniko Yamamoto <[email protected]> * @author Aubrey Pankow <[email protected]> * @author The Rehike Maintainers */ class PropertyAtPath { /** * Get the PHP pointer string needed * for other functions. * * @param object|array $base Parent object/array, * @param string $path JS-style period delimited path * @return string */ public static function func(&$base, string $path): string { $tree = explode(".", $path); if (is_object($base)) { $tokenL = "->{'"; $tokenR = "'}"; } else if (is_array($base)) { $tokenL = "['"; $tokenR = "']"; } else { throw new PropertyAtPathException("Argument \$base must of be of type object|array"); } $func = '$base'; $items = ""; foreach($tree as $i => $property) { $arrayCarry = ""; if (strpos($property, "[") > 0) { $arrayWorker = explode("[", $property); $property = $arrayWorker[0]; array_splice($arrayWorker, 0, 1); $arrayCarry = "[" . implode("[", $arrayWorker); } $items .= "{$tokenL}{$property}{$tokenR}{$arrayCarry}"; } $func .= $items; return $func; } /** * Get a property at a path. * * @param object|array $base Parent object/array, * @param string $path JS-style period delimited path * @return mixed */ public static function get(&$base, string $path) { $func = self::func($base, $path); if (!@eval("return isset({$func});")) { throw new PropertyAtPathException("Unknown property {$func}"); return null; } return @eval("return {$func};"); } /** * Set a property at a path. * * @param object|array $base Parent object/array, * @param string $path JS-style period delimited path * @param mixed $value Value to set the property to. * @return void */ public static function set(&$base, string $path, $value): void { $func = self::func($base, $path); @eval("{$func} = \$value;"); } /** * Unset a property at a path. * * @param object|array $base Parent object/array, * @param string $path JS-style period delimited path * @return void */ public static function unset(&$base, string $path): void { $func = self::func($base, $path); if (!@eval("return isset({$func});")) { throw new PropertyAtPathException("Unknown property {$func}"); return; } @eval("unset({$func});"); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest; use YukisCoffee\CoffeeRequest\Exception\GeneralException; use YukisCoffee\CoffeeRequest\Util\IFulfillableEvent; use YukisCoffee\CoffeeRequest\Util\NullEvent; use YukisCoffee\CoffeeRequest\Util\QueuedPromiseResolver; use YukisCoffee\CoffeeRequest\Debugging\PromiseStackTrace; /** * Implements the CoffeeRequest event loop. * * The event loop is very simple, simply checking iterating over the * registered events and calling them. Events dictate their own cuts of * the runtime, but they may yield at any time and switch execution to * another event. * * This, along with the Event API, bring to PHP a simple singlethreaded * asynchronous execution system. * * @author Taniko Yamamoto <[email protected]> */ final class Loop { /** * Stores all current events. * * @var IFulfillableEvent[] */ private static array $events = []; /** * Stores an array of QueuedPromiseResolvers to be finished upon * the end of the Event loop. * * @var QueuedPromiseResolver[] */ private static array $queuedPromises = []; /** * Stores the current pause state of the event loop. */ private static bool $isPaused = false; /** * Keeps track of the current call level. */ private static int $level = 0; // Disable instances private function __construct() {} /** * Run the event loop. * * Running the event loop will block further code execution, so * still think of this as a synchronous operation. * * Although this call may be synchronous, what happens with the * events isn't, so you can implement your own asynchronous handlers * using the Events API if need be. */ public static function run(): void { self::$level++; do { foreach (self::$events as $event) if ( !$event->isFulfilled() && $event instanceof Event ) { $event->run(); } } while (self::shouldContinueRunning()); // We can't just assume that the event is finished when this // function stops being called, as it can also be paused. if (self::isFinished()) { self::$level--; self::cleanup(); } } /** * Determine if the event loop has an event. */ public static function hasEvent(Event $e): bool { return (bool)array_search($e, self::$events); } /** * Add an event to the event loop. */ public static function addEvent(Event $e): void { self::$events[] = $e; } /** * Add an event to the event loop if it's not already there. */ public static function addEventIfNotAdded(Event $e): void { if (!self::hasEvent($e)) { self::addEvent($e); } } /** * Remove an event from the event loop. */ public static function removeEvent(IFulfillableEvent $e): void { $index = array_search($e, self::$events); if (false != $index) { array_splice(self::$events, $index, 1); } else { throw new GeneralException( "Attempted to remove a non-existent event from the loop." ); } } /** * Reports whether or not the event loop is currently paused. */ public static function isPaused(): bool { return self::$isPaused; } /** * Check if the loop is finished running. * * Unlike checking if the loop should continue running, this does * not return true if the event loop is paused. */ public static function isFinished(): bool { return self::isPaused() ? false : !self::shouldContinueRunning(); } /** * Pauses the event loop. * * When the event loop is paused, code declared outside of events * continues to execute synchronously until the event loop is * manually continued. * * Naturally, the event loop can only be paused within an event. Be * careful to continue the event loop afterwards. If you make a mistake * and the event loop is never continued, a warning will be displayed to * notify you of your probable mistake. * * This is an advanced feature that has few use cases, but it is * supported. */ public static function pause(): void { self::$isPaused = true; } /** * Continues event loop execution and unpauses the loop. */ public static function continue($autoRun = true): void { self::$isPaused = false; if ($autoRun) self::run(); } /** * Add a QueuedPromiseResolver to the queue. */ public static function addQueuedPromise(QueuedPromiseResolver $p): void { self::$queuedPromises[] = $p; } /** * Used internally to determine if the loop is still running. */ private static function shouldContinueRunning(): bool { if (self::$isPaused) return false; foreach (self::$events as &$event) { if ( !$event->isFulfilled() && $event instanceof Event ) { return true; } else if (!@$event->preventNullification) { // The event is no longer needed at all since it's // no longer accessed after being fulfilled. Might as well // clean it from memory and get it over with. $event = new NullEvent(); } } return false; } /** * Clean up the mess this made in memory. */ private static function cleanup(): void { // Rely on GC to CL34NUP memory afterwards >:] self::$events = []; // Notify the delayed promise resolutions to finish. self::finishQueuedPromises(); } /** * Finish the Promise queue after Event memory is freed. */ private static function finishQueuedPromises(): void { foreach (self::$queuedPromises as $promise) { $promise->finish(); if (self::$level == 0 && count(self::$events) > 0) { self::run(); } } // Since all queued Promise callbacks have been gotten to, // the queues aren't necessary. self::$queuedPromises = []; } } PromiseStackTrace::registerSkippedFile(__FILE__);
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest; use YukisCoffee\CoffeeRequest\Network\Request; use YukisCoffee\CoffeeRequest\Network\Response; use YukisCoffee\CoffeeRequest\Handler\NetworkHandler; use YukisCoffee\CoffeeRequest\Handler\NetworkHandlerFactory; use YukisCoffee\CoffeeRequest\Exception\GeneralException; /** * A simple asynchronous request library for PHP. * * The CoffeeRequest API should be very familiar to JavaScript developers, * as the main API mirrors fetch and internal APIs mirror JavaScript's * Events system and Promises API. * * **Currently not for production release!** * Use only in Rehike 0.7 "asynchike" development releases. * * @author Taniko Yamamoto <[email protected]> * @version 3.0 BETA */ final class CoffeeRequest { /** * The current version number. * * @see getVersion() * @var string */ private const VERSION = "3.0"; /** * Stores references to all currently running requests. * * @var Request[] */ private static array $requests = []; /** * Keeps track of the number of running requests. The requests array * is only formally cleared when all active requests are finished. */ private static int $activeRequests = 0; /** * Stores a reference to the currently used network handler. */ private static NetworkHandler $handler; /** * A list of resolution definitions. */ private static array $resolve = []; // Disable instances private function __construct() {} /** * Initialise the request manager. * * @internal */ public static function _init(): void { self::setNetworkHandler(NetworkHandlerFactory::getBest()); } /** * Set the network handler/driver. */ public static function setNetworkHandler(NetworkHandler $handler): void { if (isset(self::$handler)) { try { Loop::removeEvent(self::$handler); } catch (GeneralException $e) {} // do nothing & hope for the best } self::$handler = $handler; } /** * Send a network request. * * The network request API provided by CoffeeRequest is very * reminiscent of JavaScript's fetch API. * * @param mixed[] $opts * @return Promise<Response> */ public static function request( string $url, array $opts = [] ): Promise/*<Response>*/ { $request = new Request($url, $opts); if (self::$handler->isFulfilled()) { self::$handler->restartManager(); } self::addRequest($request); Loop::addEventIfNotAdded(self::$handler); self::$handler->addRequest($request); return $request->getPromise(); } /** * Run the event loop. */ public static function run(): void { Loop::run(); } /** * Await all currently registered requests. * * @return Promise<Response[]> */ public static function awaitAll(): Promise/*<array>*/ { // wrong $requests type, // needs to be Promise<Response>[] not Response[]!! return Promise::all(self::$requests); } /** * Get the version of CoffeeRequest. */ public static function getVersion(): string { return self::VERSION; } public static function getResolve(): array { return self::$resolve; } public static function setResolve(array $a): void { self::$resolve = $a; } /** * Report a finished request and decrement the internal counter. * * It's too expensive to take in a finished request and remove its * reference for the array, so we keep track of the number of running * Requests and cleanup only when it can be guaranteed to have no * ramifications. * * @internal */ public static function reportFinishedRequest(): void { if (self::$activeRequests > 1) { self::$activeRequests--; } else { self::cleanup(); } } private static function addRequest(Request $request): void { self::$requests[] = $request; self::$activeRequests++; } /** * Clean up when possible. */ private static function cleanup(): void { self::$activeRequests = 0; self::$requests = []; self::$handler->clearRequests(); } } CoffeeRequest::_init();
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest; use YukisCoffee\CoffeeRequest\Enum\PromiseStatus; use YukisCoffee\CoffeeRequest\Exception\UncaughtPromiseException; use YukisCoffee\CoffeeRequest\Util\PromiseAllBase; use YukisCoffee\CoffeeRequest\Util\QueuedPromiseResolver; use YukisCoffee\CoffeeRequest\Util\PromiseResolutionTracker; use YukisCoffee\CoffeeRequest\Debugging\PromiseStackTrace; use Exception; use ReflectionFunction; use ReflectionMethod; /** * A simple Promise implementation for PHP. * * Due to the lack of any native event loop in PHP, and thus the reliance * on cURL's own event loop implementation, this is essentially an * overglorified pubsub system. * * I haven't tested interoperability with proper asynchronous libraries, * i.e. Amp or ReactPHP, so I don't know how compatible this is. * * @template T * @author Taniko Yamamoto <[email protected]> */ class Promise/*<T>*/ { /** * Represents the current status of a Promise. * * @var PromiseStatus */ public int $status = PromiseStatus::PENDING; /** * The result of the Promise after it is finished. * * Although this will rarely be manually accessed upon a Promise's * resolution, its value is public for internal use and the rare * edge cases that manual access is used. * * @var T */ public /*T*/ $result; /** * The reason for rejecting the Promise, if it is rejected. * * Ditto $result for publicity. */ public Exception $reason; /** * The stack trace of the Promise at its creation. */ public PromiseStackTrace $creationTrace; /** * The stack trace of the Promise as of the last update. */ public PromiseStackTrace $latestTrace; /** * Callbacks to be ran when the promise is resolved. * * Although this is an array, only one callback can be assigned * to a Promise. Extra thens are delegated to a subpromise. * * Essentially, * $promiseA->then(getPromiseB())->then(...) * is made to be syntatic sugar for: * $promiseA->then(getPromiseB()->then(...)) * using this array. * * As such, extra thens will simply be ignored for any callback * that doesn't return a viable Promise. * * @var callable<mixed>[] */ private array $thens = []; /** * Callbacks to be ran when an error occurs. * * The same reason for being an array that apply to thens apply * to this as well. * * This is actually an associative array for ease of use, so some * indices may be skipped. Just be careful with this thing, alright? * * @var callable<Exception>|null[] */ private array $catches = []; /** * Requires the Promise to be resolved before the script ends. */ private bool $throwOnUnresolved = true; /** * Used for keeping track of the current Promise callback level. * * That means this increments before every callback and decrements * afterwards. This is used for internal checks if the program is * currently in a Promise. */ private static int $promiseCallbackLevel = 0; /** * Create a new anonymous Promise. * * A callback can optionally be provided, which will be * evaluated. * * Unlike a Deferred class's Promise, an anonymous Promise is * automatically made into an Event and added to the event loop. * * @param ?callable<void> $a */ public function __construct( ?callable/*<void>*/ $cb = null, ?array $options = null ) { $isCritical = isset($options["critical"]) ? $options["critical"] : true; if (isset($cb)) { $reflection = new ReflectionFunction($cb); if ($reflection->isGenerator()) { PromiseEvent/*<mixed>*/::fromAnonPromise( $this, $cb, $this->getResolveApi(), $this->getRejectApi() ); } else { $cb($this->getResolveApi(), $this->getRejectApi()); } } $this->throwOnUnresolved = $isCritical; $this->creationTrace = new PromiseStackTrace; $this->latestTrace = &$this->creationTrace; } /** * API function to await an array of Promises, and then * return a new Promise with its values. * * @param Promise<mixed>[]|...Promise $promises * @return Promise<mixed[]> */ public static function all(...$promises): Promise/*<array>*/ { // Allow passing an array rather than rest syntax. if (is_array($promises[0])) { $promises = $promises[0]; } return (new PromiseAllBase($promises))->getPromise(); } /** * Check if the script is currently in a Promise callback. */ public static function isCurrentlyInPromise(): bool { return self::$promiseCallbackLevel > 0; } /** * Register a function to be called upon a Promise's * resolution. * * @param callable<mixed> * @return Promise<T> */ public function then(callable/*<mixed>*/ $cb): Promise/*<T>*/ { $this->thens[] = $cb; // Enable late binding (i.e. for internal versatility) if (PromiseStatus::RESOLVED == $this->status) { self::$promiseCallbackLevel++; $cb($this->result); self::$promiseCallbackLevel--; } $this->latestTrace = new PromiseStackTrace; if ( count($this->thens) == 1 && $this->throwOnUnresolved && $this->status == PromiseStatus::PENDING ) { PromiseResolutionTracker::registerPendingPromise($this); } return $this; } /** * Register a function to be called upon an error occurring * during a Promise's resolution. * * @param callable<Exception> $cb * @return Promise<T> */ public function catch(callable/*<Exception>*/ $cb): Promise/*<T>*/ { $this->catches[$this->getCurrentThenIndex()] = $cb; // Late binding if (PromiseStatus::REJECTED == $this->status) { self::$promiseCallbackLevel++; $cb($this->reason); self::$promiseCallbackLevel--; } $this->latestTrace = new PromiseStackTrace; return $this; } /** * Resolve a Promise (and call its thens). * * @internal * @param T $data */ public function resolve(/*T*/ $data = null): void { /* * A promise's resolution should not be called if the event * loop is still running. * * Instead, it is added to a queue to be called upon the loop's * cleanup. This flattens the call stack and allows GC to get in * and clean up memory used in the events. * * Otherwise, the resolution callback would be predicated on the * event logic and it could cause a memory leak. Only the data * ultimately used by the Promise should be left behind. */ if (!Loop::isFinished()) { Loop::addQueuedPromise( new QueuedPromiseResolver( $this, PromiseStatus::RESOLVED, $data ) ); return; // Should finish here. } $this->result = $data; /* * Do nothing if the Promise already has a set status. * * This is important, as without it, a rejection call followed * by a resolution call will be handled as if it's resolved, * thus causing odd behaviour. */ if (PromiseStatus::PENDING != $this->status) return; // If there's nothing to resolve, do nothing if (($count = count($this->thens)) > 0) { self::$promiseCallbackLevel++; $result = $this->thens[0]($data); self::$promiseCallbackLevel--; // If the response itself is a Promise, bind any // further existing thens to it (this process will // repeat itself in the next resolution). if ($count > 1 && $result instanceof Promise/*<T>*/) { for ($i = 1; $i < $count; $i++) { $result->then($this->thens[$i]); } } } if ($this->throwOnUnresolved) { PromiseResolutionTracker::unregisterPendingPromise($this); } $this->setStatus(PromiseStatus::RESOLVED); } /** * Reject a Promise (error). * * @param string|Exception $e (union types are PHP 8.0+) * * @internal * @param */ public function reject($e): void { /* * A promise's rejection should not be called if the event * loop is still running. * * Instead, it is added to a queue to be called upon the loop's * cleanup. This flattens the call stack and allows GC to get in * and clean up memory used in the events. * * Otherwise, the rejection callback would be predicated on the * event logic and it could cause a memory leak. Only the data * ultimately used by the Promise should be left behind. */ if (!Loop::isFinished()) { Loop::addQueuedPromise( new QueuedPromiseResolver( $this, PromiseStatus::REJECTED, $e ) ); return; // Should finish here. } /* * Do nothing if the Promise already has a set status. * * This is important, as without it, a rejection call followed * by a resolution call will be handled as if it's resolved, * thus causing odd behaviour. */ if (PromiseStatus::PENDING != $this->status) return; if (is_string($e)) { $this->reason = new Exception($e); } else if ($e instanceof Exception) { $this->reason = $e; } // If there's nothing to reject, do nothing $current = $this->getCurrentThenIndex(); if (isset($this->catches[$current])) { self::$promiseCallbackLevel++; $this->catches[$current]($this->reason); self::$promiseCallbackLevel--; } else { throw UncaughtPromiseException::from($this->reason); } $this->setStatus(PromiseStatus::REJECTED); } /** * Get a proxy to an internal API handler here, such as resolve() * or reject(). * * @internal */ protected function getInternalApi(string $name): callable/*<mixed>*/ { return function (...$args) use ($name) { $this->{$name}(...$args); }; } /** * Get the internal resolution API. * * @see resolve() */ protected function getResolveApi(): callable/*<mixed>*/ { return $this->getInternalApi("resolve"); } /** * Get the internal rejection API. * * @see reject() */ protected function getRejectApi(): callable/*<string|Exception>*/ { return $this->getInternalApi("reject"); } /** * Set the Promise's status to a new value. * * The value is technically an int due to the current enum * implementation, however the type should always be a value * within the PromiseStatus enum. * * @param PromiseStatus $newStatus */ protected function setStatus(int $newStatus): void { $this->status = $newStatus; } /** * Get the current number of thens bound to a single Promise. * * This is used internally to determine the correct child Promise * to bind a exception handler (->catch) to. */ protected function getCurrentThenIndex(): int { return count($this->thens) - 1; } } PromiseStackTrace::registerSkippedFile(__FILE__);
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest; use YukisCoffee\CoffeeRequest\Exception\GeneralException; use YukisCoffee\CoffeeRequest\Debugging\PromiseStackTrace; use Exception; use Generator; use ReflectionFunction; /** * Implements a simple event wrapper for any event that interacts * with a Promise (i.e. most events). * * @template T * @author Taniko Yamamoto <[email protected]> */ abstract class PromiseEvent/*<T>*/ extends Event { /** @var Promise<T> */ private Promise/*<T>*/ $promise; use Deferred { getPromise as public; } public function __construct() { $this->initPromise(); } /** * Create a new PromiseEvent from a previously established Promise. * * @param Promise<T> $promise * @return PromiseEvent<T> */ public static function fromPromise(Promise/*<T>*/ $p): PromiseEvent/*<T>*/ { $self = new static/*<T>*/(); $self->promise = $p; return $self; } /** * Create a new PromiseEvent from an anonymous Promise. * * This will not accept a non-generator callback, which is handled * in Promise::__construct(). Generator functions return * Generator objects after being ran, but they are not Generators * by default and it will cause a hang. * * @internal * * @param Promise<T> $p * @param callable<Generator<T>> $cb * @param callable<T> $res Resolve API * @param callable<Exception|string> $rej Reject API * * @return PromiseEvent<T> */ public static function fromAnonPromise( Promise/*<T>*/ $p, callable/*<Generator<T>>*/ $cb, callable/*<T>*/ $res, callable/*<Exception|string>*/ $rej ): PromiseEvent/*<T>*/ { if (!(new ReflectionFunction($cb))->isGenerator()) { throw new GeneralException( "Anonymous promise must be constructed from a " . "generator. Add \"if (false) yield;\" to your function" . "or update the external handler." ); } return new class($p, $cb, $res, $rej) extends PromiseEvent/*<T>*/ { private $promise; /** * Callback hack. * * PHP actually doesn't allow class members to be typed * with callable at all, unlike C# with delegate or * TypeScript with its arrow-function-like syntax. * * @var callable<Generator<T>> */ private $onRunCb; /** @var callable<T> */ private $resolveApi; /** @var callable<Exception|string> */ private $rejectApi; /** * @param Promise<T> $p * @param Generator<T> $cb * @param callable<T> $res * @param callable<Exception|string> $rej */ final public function __construct( Promise/*<T>*/ $p, callable/*<Generator<T>>*/& $cb, callable/*<T>*/ $res, callable/*<Exception|string>*/ $rej ) { parent::__construct(); $this->promise = $p; $this->onRunCb = &$cb; // Wrap the internal Promise APIs so that they automatically // fulfill the Event upon being called. $this->resolveApi = self::wrapPromiseApi( $this, $res ); $this->rejectApi = self::wrapPromiseApi( $this, $rej ); Loop::addEvent($this); } final protected function onRun(): Generator/*<T>*/ { return ($this->onRunCb)($this->resolveApi, $this->rejectApi); } }; } /** * Wrap a Promise's API to also fulfill the event. * * This is useful for anonymous Promises, so that they don't * need to directly interface with the Event API. * * @param PromiseEvent<T> $myself * @param callable<mixed> $api * @return callable<mixed> */ protected static function wrapPromiseApi( PromiseEvent/*<T>*/ $myself, callable/*<mixed>*/ $api ): callable/*<mixed>*/ { /** @param mixed[] $args */ return function (...$args) use ($myself, $api) { $api(...$args); $myself->fulfill(); }; } } PromiseStackTrace::registerSkippedFile(__FILE__);
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest; use YukisCoffee\CoffeeRequest\Exception\GeneralException; use Exception; /** * A template for a Promise controller. * * @template T * @author Taniko Yamamoto <[email protected]> */ trait Deferred/*<T>*/ { /** @var Promise<T> */ private Promise/*<T>*/ $promise; /** * Initialise the class's Promise. */ private function initPromise(): void { $this->promise = new Promise/*<T>*/(); } /** * Get this class's Promise. * * @return Promise<T> */ private function getPromise(): Promise/*<T>*/ { if (!isset($this->promise)) { throw self::getNoPromiseException(); } return $this->promise; } /** * Resolve the Promise controlled by this class. * * @param mixed $data */ private function resolve($data = null): void { if (!isset($this->promise)) { throw self::getNoPromiseException(); } $this->promise->resolve($data); } /** * Reject the Promise controlled by this class. * * @param Exception|string $reason */ private function reject($reason): void { if (!isset($this->promise)) { throw self::getNoPromiseException(); } $this->promise->reject($reason); } /** * Thrown when a Deferred class doesn't have an initialised * Promise. */ private static function getNoPromiseException() { $class = static::class; return new GeneralException( "Deferred class $class::\$promise is not a Promise. " . "Did you forget to run initPromise()?" ); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest; use YukisCoffee\CoffeeRequest\Util\IFulfillableEvent; use YukisCoffee\CoffeeRequest\Debugging\PromiseStackTrace; use Generator; use const E_USER_WARNING; use function trigger_error; /** * Represents an asynchronous event. * * Events operate based on PHP's native generators. This allows a * function to be paused and continued at any time, meaning that an * event can be interrupted and yield control to other concurrently * running events. As such, singlethreaded asynchronity is achieved. * * By themselves, events don't really serve much of a purpose. State * cannot be easily communicated between events or to outside areas. * Events only serve as a simple proxy for functions that can be paused * and resumed within a loop. * * The Promise API exists to extend the functionality of an event. With * promises, callbacks can be bound and state can be transported, just * like a regular function. This paradigm is very reminiscent of * ECMAScript's functionality, except that our event loop is blocking and * does not necessarily let synchronous functions continue executing in * between events. * * @author Taniko Yamamoto <[email protected]> */ abstract class Event implements IFulfillableEvent { /** * Stores whether or not the event is fulfilled. * * An event ceases to be called upon being fulfilled and is * eventually culled from the event loop to free memory. */ protected bool $fulfilled = false; /** * A reference to the Generator callback of onRun(). * * All future calls to the event will progress this generator, * rather than reset it. Of course we don't wanna do that! * * @var Generator<void> */ protected Generator/*<void>*/ $generator; /** * Keeps track of the developer warning. * * @see __destruct() */ protected static bool $echoedDeveloperWarning = false; /** * Run the event. */ final public function run($reset = false): void { // If the generator is not running, then start the generator // and mark it as running. Otherwise, progress the currently // running generator. if (!isset($this->generator) || $reset) { $this->generator = $this->onRun(); // The generator must be rewinded, otherwise events have a // tendency to give results prematurely and essentially run // twice for the first call. $this->generator->rewind(); } else { $this->generator->next(); } } /** * Function to be ran every time the event is ran. * * Well, technically, only the first time the event is ran... * * This is the handler method that all children must override. * run() only implements the public API, which requires a hack * to keep the Generator running. * * @return Generator<void> */ abstract protected function onRun(): Generator/*<void>*/; /** * Check if the event is fulfilled. */ public function isFulfilled(): bool { return $this->fulfilled; } /** * End the event and mark it as resolved. */ protected function fulfill(): void { $this->fulfilled = true; } /** * Destructor hack: report programmer error! * * The idea behind this is simple: Events are managed within the * event loop, so if they are destructed while the event loop is * paused, then it is reasonable to assume the destructor was called * by the PHP script ending during its usual cleanup process. * * Thus, the programmer can be alerted of their error. */ public function __destruct() { // If this is the case, then another crash has already occurred // and it's pointless to echo. if (!class_exists("YukisCoffee\\CoffeeRequest\\Loop")) return; if ( Loop::isPaused() && !$this->isFulfilled() && !self::$echoedDeveloperWarning ) { self::$echoedDeveloperWarning = true; trigger_error( "There are currently active events, but the event loop " . "is on an endless pause in CoffeeRequest. " . "Did you forget to unpause your loop?", E_USER_WARNING ); } } } PromiseStackTrace::registerSkippedFile(__FILE__);
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Util; /** * Declares a common interface for a fulfillable event. * * @author Taniko Yamamoto <[email protected]> */ interface IFulfillableEvent { /** * Check if the event is fulfilled. */ public function isFulfilled(): bool; }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Util; use YukisCoffee\CoffeeRequest\Promise; use Closure; use YukisCoffee\CoffeeRequest\Exception\UnhandledPromiseException; /** * Tracks pending Promises and displays an error if the Promise is uncaught * within the scope. * * @static * @author Taniko Yamamoto <[email protected]> */ final class PromiseResolutionTracker { /** * An anonymous object that watches for shutdowns. */ private static object $shutdownTracker; private static int $pendingPromiseCount = 0; private static array $pendingPromises = []; private static bool $isEnabled = true; public static function initialize(): void { $shutdownFunction = Closure::fromCallable(self::class."::handleShutdown"); // An anonymous object is used for the destructor hack in order to // run code on PHP shutdown. self::$shutdownTracker = new class($shutdownFunction) { private Closure $shutdownFunction; public function __construct(Closure $shutdownFunction) { $this->shutdownFunction = $shutdownFunction; } public function __destruct() { $this->shutdownFunction->__invoke(); } }; } public static function disable(): void { self::$isEnabled = false; } public static function enable(): void { self::$isEnabled = true; } public static function registerPendingPromise(Promise $promise): void { // Save a reference to the Promise and a copy of its latest trace. self::$pendingPromises[] = [$promise, $promise->latestTrace]; self::$pendingPromiseCount++; } public static function unregisterPendingPromise(Promise $promise): void { foreach (self::$pendingPromises as $i => $pending) { if ($pending[0] == $promise) { array_splice(self::$pendingPromises, $i, 1); self::$pendingPromiseCount--; } } } private static function getLatestPromiseList(): array { return self::$pendingPromises[count(self::$pendingPromises) - 1]; } private static function handleShutdown(): void { if (!self::$isEnabled) return; if (self::$pendingPromiseCount > 0) { // Prevent it from overtaking other errors: $lastError = error_get_last(); if (in_array($lastError["type"], [E_CORE_ERROR, E_USER_ERROR, E_ERROR])) { return; } self::throwUnhandledError(); } } private static function throwUnhandledError(): void { $promiseList = self::getLatestPromiseList(); $promise = $promiseList[0]; $originTrace = $promiseList[1]; throw new UnhandledPromiseException($promise, $originTrace); } } PromiseResolutionTracker::initialize();
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Util; /** * Represents a null event in memory, i.e. one with nothing bound to it. * * This should only ever be used internally to denote a void event within * the event loop for a temporary time. * * @internal * @author Taniko Yamamoto <[email protected]> */ class NullEvent implements IFulfillableEvent { public function isFulfilled(): bool { return true; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Util; use YukisCoffee\CoffeeRequest\Promise; use YukisCoffee\CoffeeRequest\Loop; use YukisCoffee\CoffeeRequest\Enum\PromiseStatus; /** * Stores a Promise and its state to be called at a later time. * * This allows a Promise resolution or rejection to be delayed. This is used * internally by the Event Loop API for memory management. * * @author Taniko Yamamoto <[email protected]> */ class QueuedPromiseResolver { /** * Stores the Promise to queue. */ private Promise $promise; /** * Stores the state to set. * * This reuses the future-tense PromiseStatus enum. Only * RESOLVED and REJECTED may be used for this. */ private $state = PromiseStatus::RESOLVED; /** * Data to resolve or reject with. * * Naturally, this can be of any type, but it must abide by the * type constraints of the actual functions. * * @var mixed */ private $data; /** * @param PromiseStatus $state * @param mixed $data */ public function __construct(Promise $p, int $state, $data) { $this->promise = $p; $this->state = $state; $this->data = $data; } public function finish(): void { switch ($this->state) { case PromiseStatus::RESOLVED: $this->promise->resolve($this->data); return; case PromiseStatus::REJECTED: $this->promise->reject($this->data); return; } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Util; use YukisCoffee\CoffeeRequest\Promise; use YukisCoffee\CoffeeRequest\Deferred; use YukisCoffee\CoffeeRequest\Exception\PromiseAllException; use Exception; /** * Used as a base class for Promise::all() implementation. * * This is used to coalesce multiple Promises (i.e. mutually dependent ones) * into one single Promise with a response array. Compare with ECMAScript's * Promise.all(). * * Use ::getPromise() on an instance, as this is a deferred API and you * don't want to return the Promise controller. * * @internal * @author Taniko Yamamoto <[email protected]> */ class PromiseAllBase { use Deferred/*<mixed[]>*/ { getPromise as public; } /** * Stores an array of Promises to await. * * @var Promise<mixed>[] */ private array $promises = []; /** * Stores the number of Promises in the bound array. */ private int $boundPromiseCount = 0; /** * Keeps track of the number of Promise resolutions so far. * * This is used as a simple check to see if we've finished yet. */ private int $resolvedPromises = 0; /** @param Promise[] $promises */ public function __construct(array $promises) { $this->initPromise(); $this->promises = $promises; // Used to track the number of responses internally. $this->boundPromiseCount = count($promises); $this->awaitPromiseArray($promises); } /** * Handle any Promise's resolution. */ public function handlePromiseResolution(Promise $p): void { $this->resolvedPromises++; // Also check if this is the last value, and if so, resolve. // Since the number of Promises for one Promise.all aggregator // cannot change, this logic is perfectly fine to use. if ($this->resolvedPromises == $this->boundPromiseCount) { $this->resolve($this->getResult()); } } /** * Handle any Promise's rejection. * * Just like with ECMAScript's Promise.all implementation, any Promise * in the chain failing will result in the entire aggregate Promise * being rejected. */ public function handlePromiseRejection(Promise $p): void { // Find the index of the given Promise in the array. $index = (string)array_search($p, $this->promises) || "(unknown index :/)"; $message = $p->reason->getMessage(); $this->reject( new PromiseAllException( "Promise $index rejected in Promise::all() call " . "with reason \"$message\"", $p->reason // exception ) ); } /** * Get the result (contents) of each Promise after they're finished. * * @return mixed[] */ private function getResult(): array { $results = []; foreach ($this->promises as $key => $promise) { $results[$key] = $promise->result; } return $results; } /** * Await an array of Promises and return their responses in * an array following the input order. * * @param Promise[] $promises */ private function awaitPromiseArray(array $promises): void { foreach ($promises as $promise) { $promise ->then(function($result) use ($promise) { $this->handlePromiseResolution($promise); }) ->catch(function(Exception $e) use ($promise) { $this->handlePromiseRejection($promise); }) ; } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Network; use YukisCoffee\CoffeeRequest\CoffeeRequest; use YukisCoffee\CoffeeRequest\Deferred; use YukisCoffee\CoffeeRequest\Enum\RedirectPolicy; use YukisCoffee\CoffeeRequest\Enum\RequestErrorPolicy; use YukisCoffee\CoffeeRequest\Network\Response; use YukisCoffee\CoffeeRequest\Util\Nameserver; use YukisCoffee\CoffeeRequest\Util\NameserverInfo; /** * Represents a network request. * * @author Taniko Yamamoto <[email protected]> */ class Request { use Deferred/*<Response>*/ { getPromise as public; resolve as private resolvePromise; } /** * The request method to send. */ public string $method = "GET"; /** * The URL to request. */ public string $url = ""; /** * An associative array of headers. * * @var string[] */ public array $headers = []; /** * If specified, the POST body to be sent. */ public string $body; /** * If specified, the preferred encoding to request with. * * This option should be used instead of the Accept-Encoding header, * as it can better tell the request handler what to do. */ public string $preferredEncoding; /** * If specified, the redirect policy to use with the Request handler. * * @var RedirectPolicy */ public int $redirectPolicy = RedirectPolicy::FOLLOW; /** * If specified, sets the error policy to use. * * If it's throw, then any request that isn't a 2xx status will * throw an exception. If it's ignore, then the response is treated * like normal. * * @var RequestErrorPolicy */ public int $onError = RequestErrorPolicy::THROW; /** * If specified, sets the user agent of the request. * * If not specified, the user agent of the browser requesting the current * page will be used instead. */ public string $userAgent = ""; public function __construct(string $url, array $opts) { $this->initPromise(); // Unset unused-by-default properties: unset($this->body); unset($this->preferredEncoding); $this->url = $url; $this->handleOptions($opts); } /** * Resolve the request with a Response. * * @internal */ public function resolve(Response $response): void { CoffeeRequest::reportFinishedRequest(); $this->resolvePromise($response); } /** * Handle the array of options provided to construct the Request. */ private function handleOptions(array $opts): void { foreach ($opts as $name => $value) switch ($name) { case "method": $this->method = $value; break; case "headers": $this->headers = $value; break; case "redirect": $this->redirectPolicy = self::handleRedirectOpt($value); break; case "body": $this->body = $value; break; case "preferredEncoding": $this->preferredEncoding = $value; break; case "onError": $this->onError = self::handleOnErrorOpt($value); break; case "userAgent": $this->userAgent = $value; break; } } /** * Handle the redirect option. * * @param RedirectPolicy|string $value * * @return RedirectPolicy */ private function handleRedirectOpt($value): int { if (!is_string($value)) { return $value; } switch (strtolower((string)$value)) { case "follow": return RedirectPolicy::FOLLOW; break; case "manual": return RedirectPolicy::MANUAL; break; } } /** * Handle the redirect option. * * @param RequestErrorPolicy|string $value * * @return RedirectPolicy */ private function handleOnErrorOpt($value): int { if (!is_string($value)) { return $value; } switch (strtolower((string)$value)) { case "throw": return RequestErrorPolicy::THROW; break; case "ignore": return RequestErrorPolicy::IGNORE; break; } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Network; use ArrayAccess; use Iterator; use ReturnTypeWillChange; // PHP 8.1+ use function reset; use function current; use function key; use function next; /** * Implements an array for accessing HTTP headers. * * This is very similar to the Controller v2 RequestMetadata structure * used by the Rehike project, except this is also iterable using foreach * loops. * * @author Taniko Yamamoto <[email protected]> */ class ResponseHeaders implements ArrayAccess, Iterator { /** * Bound array that stores definitions. * * @var mixed[] */ private array $boundArray = []; public function __construct(array $baseArray) { $this->boundArray = $baseArray; } /** * Attempt to get a property on the class if it is readable. */ public function __get($var) { // Headers are case-insensitive. $lowercaseName = strtolower($var); // Converted from camelCase to hyphen-case $hyphenCaseName = strtolower( preg_replace("/(?<!^)[A-Z]/", "-$0", $var) ); // And to snake_case $snake_case_name = str_replace("_", "-", $var); // Then check if the raw name is accessible in the object if (isset($this->boundArray[$lowercaseName])) { return $this->boundArray[$lowercaseName]; } // Otherwise, check if the camelCase name is accessible // in the object. else if (isset($this->boundArray[$hyphenCaseName])) { return $this->boundArray[$hyphenCaseName]; } // If that's not the case, check if it's snake_case else if (isset($this->boundArray[$snake_case_name])) { return $this->boundArray[$snake_case_name]; } // Finally, if none of those are set, return an empty string else { return ""; } } public function __isset($var) { return "" != $this->__get($var); } public function __set($a, $b) { $this->offsetSet(null, null); // inherit warning } /* * Array access functions * * In order to maintain compatibility with both PHP 7.x and * PHP 8.1, the ReturnTypeWillChange attribute is required on all * methods. * * This is to avoid a conflict where PHP 8.1 requires strict type * signatures on methods and PHP 7.x doesn't even support them at * all. */ #[ReturnTypeWillChange] public function offsetExists($offset) { return isset($this->boundArray[$offset]); } #[ReturnTypeWillChange] public function offsetSet($offset, $value) { trigger_error("RequestMetadata->headers is read only.", E_USER_WARNING); } #[ReturnTypeWillChange] public function offsetUnset($offset) { $this->offsetSet(null, null); // inherit warning } #[ReturnTypeWillChange] public function offsetGet($offset) { return isset($this->boundArray[$offset]) ? $this->boundArray[$offset] : null ; } #[ReturnTypeWillChange] public function rewind() { return reset($this->boundArray); } #[ReturnTypeWillChange] public function current() { return current($this->boundArray); } #[ReturnTypeWillChange] public function key() { return key($this->boundArray); } #[ReturnTypeWillChange] public function next() { return next($this->boundArray); } #[ReturnTypeWillChange] public function valid() { return key($this->boundArray) !== null; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Network; use YukisCoffee\CoffeeRequest\Exception\GeneralException; use YukisCoffee\CoffeeRequest\Exception\RequestFailedResponseCodeException; use YukisCoffee\CoffeeRequest\Enum\RequestErrorPolicy; use function json_decode; /** * Represents a network response. * * @author Taniko Yamamoto <[email protected]> */ class Response { /** * A reference to the source request. */ public Request $sourceRequest; /** * The response status. */ public int $status = 0; /** * An array of HTTP headers sent back from the server with the * response. */ public ResponseHeaders $headers; /** * The response as a string (byte array). */ private string $content = ""; public function __construct( Request $source, int $status, string $content, array $headers ) { if ( RequestErrorPolicy::THROW == $source->onError && $status < 200 && $status > 399 ) { throw new RequestFailedResponseCodeException( "Request to $source->url failed with response code of $status." ); } $this->sourceRequest = $source; $this->status = $status; $this->content = $content; $this->headers = new ResponseHeaders($headers); } /** * Get a text representation of the response. */ public function getText(): string { return $this->content; } /** * Get the response decoded as JSON. */ public function getJson(): object|array { /* * TODO (kirasicecreamm): Slow validation method. * * This should be cleaned up eventually and replaced with a more * efficient one. Of keen interest is the json_validate() function, * which is slated to be released in PHP 8.3. * * As a bleeding edge feature, it may be implemented as an * alternative path for use in the target language runtime only, * and the slower method used here will be kept for previous * versions. * * https://wiki.php.net/rfc/json_validate */ if ($a = @json_decode($this->content)) { return $a; } else { throw new GeneralException( "Response content is not valid JSON." ); } } public function __toString(): string { return $this->getText(); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Test; use YukisCoffee\CoffeeRequest\Event; use Generator; class TestEvent extends Event { public function onRun(): Generator/*<void>*/ { for ($i = 0; $i < 15; $i++) { echo "$i "; yield; } $this->fulfill(); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php spl_autoload_register(function($className) { $className = str_replace("\\", "/", $className); include explode("CoffeeRequest/", str_replace("\\", "/", __DIR__))[0] . str_replace("YukisCoffee", "", $className) . ".php" ; });
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php require "autoloader.php"; // Test events and promises use YukisCoffee\CoffeeRequest\Event; use YukisCoffee\CoffeeRequest\Promise; use YukisCoffee\CoffeeRequest\Deferred; use YukisCoffee\CoffeeRequest\Loop; use YukisCoffee\CoffeeRequest\Test\{ HelloWorldEvent, TestEvent }; class MyPromiser { use Deferred/*<string>*/ { getPromise as public; } private Event $e; public function __construct() { $this->initPromise(); $this->castEvent(); } public function castEvent(): void { $this->e = (new class extends Event { private Promise $p; public function onRun(): Generator/*<void>*/ { $endTime = time() + 5; // seconds while (time() < $endTime) { yield; } $this->p->resolve("Promise finished."); $this->fulfill(); } public function bindPromise(Promise $p): Event { $this->p = $p; return $this; } })->bindPromise($this->getPromise()); Loop::addEvent($this->e); } } $promiser = new MyPromiser(); $promise = $promiser->getPromise(); $promise->then(function($result): void { echo "\n\n" . $result; }); Loop::addEvent(new HelloWorldEvent()); Loop::run();
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php require "autoloader.php"; // Test events use YukisCoffee\CoffeeRequest\Event; use YukisCoffee\CoffeeRequest\Loop; use YukisCoffee\CoffeeRequest\Test\{ HelloWorldEvent, TestEvent }; function sayHello() { echo "\nHello world!\n"; } Loop::addEvent(new class extends Event { public function onRun(): Generator/*<void>*/ { yield; for ($i = 0; $i < 2; $i++) Loop::pause(); yield; sayHello(); $this->fulfill(); } }); Loop::run(); echo "hi\n"; Loop::continue(); echo "Manual continuing of the loop\n"; Loop::continue(); echo "\nDone!";
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php require "autoloader.php"; // Anonymous promises use YukisCoffee\CoffeeRequest\CoffeeRequest; use YukisCoffee\CoffeeRequest\Promise; function request(): Promise/*<Response>*/ { return CoffeeRequest::request("http://127.0.0.3/"); } function promiseTest(): Promise/*<void>*/ { return new Promise(function($r): Generator/*<void>*/ { $endTime = time() + 2; while (time() < $endTime) { yield; } $r("test"); }); } Promise::all([request(), request(), promiseTest()])->then(function($responses){ var_dump($responses); }); CoffeeRequest::run();
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Test; use YukisCoffee\CoffeeRequest\Event; use Generator; class HelloWorldEvent extends Event { public function onRun(): Generator/*<void>*/ { if (false) yield; echo "Hello world"; $this->fulfill("Hello world!"); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php require "autoloader.php"; // Anonymous promises use YukisCoffee\CoffeeRequest\Event; use YukisCoffee\CoffeeRequest\Promise; use YukisCoffee\CoffeeRequest\Deferred; use YukisCoffee\CoffeeRequest\Loop; use YukisCoffee\CoffeeRequest\Test\{ HelloWorldEvent, TestEvent }; function testPromise(): Promise/*<string>*/ { return new Promise/*<string>*/(function ($resolve, $reject): Generator/*<void>*/ { yield; $reject("Hello world!"); $resolve("This will never be sent."); }); } /* * Non-generator anon Promises are handled synchronously. This is because * it's hard to create a Generator from a standard anonymous function. * * I could just limit the programmer ability to only Generators, but this * is more versatile and may have some use. */ function syncPromise(): Promise/*<string>*/ { return new Promise/*<string>*/(function ($resolve, $reject): void { $resolve( "This should echo first, since it runs synchronously " . "before the event loop even starts." ); }); } function lastPromise(): Promise/*<string>*/ { return new Promise/*<string>*/(function ($resolve, $reject): Generator/*<void>*/ { yield; $resolve("Promises are pretty cool."); }); } testPromise() ->then(function (string $result): void { // This should never run because the Promise is rejected // before it is resolved. echo "\n\n" . $result; }) ->catch(function (Exception $e): void { // This, on the other hand, should run and echo the Exception's // message. echo "\n\n" . $e->getMessage(); }) ; // This should run first syncPromise()->then(function (string $result): void { echo "\n\n" . $result; }); // This should still run last since the event was registered last. lastPromise()->then(function (string $result): void { echo "\n\n" . $result; }); Loop::run();
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php require "autoloader.php"; // Test events use YukisCoffee\CoffeeRequest\Event; use YukisCoffee\CoffeeRequest\Loop; use YukisCoffee\CoffeeRequest\Test\{ HelloWorldEvent, TestEvent }; function sayHello() { echo "\nHello world!\n"; } class PlaceholderEvent extends Event { public function onRun(): Generator/*<void>*/ { yield; for ($i = 0; $i < 2; $i++) Loop::pause(); yield; sayHello(); $this->fulfill(); } } Loop::addEvent(new PlaceholderEvent()); Loop::addEvent(new PlaceholderEvent()); Loop::addEvent(new PlaceholderEvent()); Loop::addEvent(new PlaceholderEvent()); Loop::run(); echo "hi\n"; //Loop::continue(); echo "Manual continuing of the loop\n"; //Loop::continue(); echo "\nDone!";
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php require "autoloader.php"; // Anonymous promises use YukisCoffee\CoffeeRequest\CoffeeRequest; CoffeeRequest::request("http://127.0.0.3/")->then(function ($r) { echo $r::class; echo "\n\n"; var_dump($r); }); CoffeeRequest::run();
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php require "autoloader.php"; // Test events use YukisCoffee\CoffeeRequest\Loop; use YukisCoffee\CoffeeRequest\Test\{ HelloWorldEvent, TestEvent }; Loop::addEvent(new TestEvent()); Loop::addEvent(new HelloWorldEvent()); echo "Loop is starting\n\n"; Loop::run(); echo "\n\nLoop is finished";
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Helper; use YukisCoffee\CoffeeRequest\Helper\SingletonUtils as Utils; use Exception; /** * A singleton that can be instantiated, just as a regular class. * * Class instances created through this class are also proxied, so * the same API considerations (make singletons final) that apply * to static-only singletons apply to instanceable ones too. * * @template T * @author Taniko Yamamoto <[email protected]> */ abstract class InstanceableSingleton/*<T>*/ extends Singleton/*<T>*/ { /** * Refers to the current proxy instance's true instance. * * $instance still refers to static::$instance. * * @var T */ private $thisInstance; /** * As these are constructable, there needs to be a public * constructor. */ public function __construct(...$args) { $T = static::T; $this->thisInstance = new $T(...$args); } /** @return mixed */ public function &__get(string $name) { } /** @param mixed $value */ public function __set(string $name, $value): void { } /** * @param mixed[] $args * @return mixed */ public function __call(string $name, $args) { $T = static::T; try { return Utils/*<T>*/::call($T, self::$instance, $name, $args); } catch (Exception $e) { // This must be elevated to the caller's scope. throw $e; } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Helper; use YukisCoffee\CoffeeRequest\Helper\SingletonUtils as Utils; use Exception; /** * Statically proxy an instance class. * * This is used in cases where the advantages of an instance class are * desired, but the instance must be accessed globally instead. * * Basically MyClass::hello() will correspond to (new MyClass())->hello(), * except that the anonymous instance is permanent. * * These singletons are simple, only proxying methods. If a variable * property needs to be accessed, the instance can be accessed through * the $instance property. For example: * * <code> * MyClass::$instance->myProperty = 1; * </code> * * A general API consideration you should make is marking any Singleton * class as final, as to prevent a misextension. Since they're proxy * classes, they don't truly implement the properties of the classes * that they proxy. * * @template T * @author Taniko Yamamoto <[email protected]> */ abstract class Singleton/*<T>*/ { /** * Type of the bound singleton. * * For ease of access, this can generally point to the ::class * pseudo-const of any existing class, i.e. stdClass::class. * * This is also the closest PHP currently gets to true generics. * * @var string * @internal */ protected const T = stdClass::class; /** * Stores the parent class for static use. * * @var T */ public static $instance; /** * A singleton proxy should not be constructable. * * Protected inherits this non-constructability to child classes * too, unless they explicitly override the protected constructor * with a public one. */ protected function __construct() {} /** * Initialise the singleton for the first time. */ private static function initSingleton(): void { $T = static::T; // Cannot use a constant as an interpolated class constructor! self::$instance = new $T(); } /** * Call a method on the bound instance. * * @param mixed[] args * @return mixed */ public static function __callStatic(string $name, array $args) { $T = static::T; if (!(self::$instance instanceof $T)) { self::initSingleton(); } try { return Utils/*<T>*/::call($T, self::$instance, $name, $args, true); } catch (Exception $e) { // This must be elevated to the caller's scope. throw $e; } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Helper; use YukisCoffee\CoffeeRequest\Exception\MethodPrivacyException; use ReflectionClass; use ReflectionMethod; /** * Implements common utilities to the singleton classes. * * This better allows code reuse within the classes internally, * as it doesn't override method names on child classes. * * @template T * @internal * @author Taniko Yamamoto <[email protected]> */ final class SingletonUtils/*<T>*/ { /** Utils class should not be constructable! */ private function __construct() {} /** * A public class member. This is the default. */ public const PRIVACY_PUBLIC = 0; /** * A protected class member. */ public const PRIVACY_PROTECTED = 1; /** * A private class member. */ public const PRIVACY_PRIVATE = 2; /** * Call a method on an instance. * * @param string<T> $class Type name of the class. * @param T $instance * @param mixed[] $args * @return mixed */ public static function call( /*string<T>*/ $class, /*T*/ $instance, string $name, array $args, bool $static = false ) { $classRef = new ReflectionClass($instance); $sameClass = ($instance::class == $class); $method = $classRef->getMethod($name); switch (self::getMethodPrivacy($method)) { case self::PRIVACY_PRIVATE; if (!$sameClass) { throw new MethodPrivacyException( "Call to private method $class::$name()" ); } // Do not break case self::PRIVACY_PROTECTED: if (!($instance instanceof $class)) { throw new MethodPrivacyException( "Call to protected method $class::$name()" ); } // Both private and protected members require // this prior to PHP 8.0, but no check is required $method->setAccessible(true); } if ($static && $method->isStatic()) { $method->invoke(null, $args); } else { $method->invoke($instance, $args); } } /** * Get the privacy of a method. */ public static function getMethodPrivacy(ReflectionMethod $m): int { switch (true) { case $m->isPrivate(): return self::PRIVACY_PRIVATE; case $m->isProtected(): return self::PRIVACY_PROTECTED; default: return self::PRIVACY_PUBLIC; } } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Handler; use YukisCoffee\CoffeeRequest\Event; /** * This is a factory class that is used internally to determine * the best default network handler to use. * * @author Taniko Yamamoto <[email protected]> */ class NetworkHandlerFactory { /** * Determine the best type of factory to use by analysing a * specific configuration. */ public static function getBest(): NetworkHandler { switch (true) { case self::isCurlSupported(): return self::getCurl(); default: return self::getNull(); } } /** * Return the cURL-based handler. */ public static function getCurl(): CurlHandler { return new CurlHandler(); } /** * Determine if the cURL extension is installed on the system. */ public static function isCurlSupported(): bool { return function_exists("\curl_init"); } /** * Return a null handler in the event there's no supported * handler installed to use. */ public static function getNull(): NullHandler { return new NullHandler(); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Handler; use YukisCoffee\CoffeeRequest\Attributes\Override; use YukisCoffee\CoffeeRequest\Exception\NoSupportedHandlerException; use YukisCoffee\CoffeeRequest\Network\Request; use Generator; /** * Implements a "null" handler to be used in the event no * available handler is possible. * * This may only throw an error notifying the user of a lack of * any supported interface. * * @author Taniko Yamamoto <[email protected]> */ final class NullHandler extends NetworkHandler { #[Override] public function addRequest(Request $r): void { throw new NoSupportedHandlerException(); } #[Override] public function clearRequests(): void {} /** @return Generator<void> */ public function onRun(): Generator/*<void>*/ { if (false) yield; $this->fulfill(); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Handler; use YukisCoffee\CoffeeRequest\Attributes\Override; use YukisCoffee\CoffeeRequest\Handler\NetworkHandler; use YukisCoffee\CoffeeRequest\Handler\Curl\EventLoopRunner; use YukisCoffee\CoffeeRequest\Handler\Curl\RequestTransformer; use YukisCoffee\CoffeeRequest\Handler\Curl\RequestWrapper; use YukisCoffee\CoffeeRequest\Network\Request; use YukisCoffee\CoffeeRequest\Network\Response; /** * Implements a cURL-compatible network handler for CoffeeRequest. * * The cURL handler uses curl_multi integration with PHP in order to * perform a network request. This already operates asynchronously, but * most PHP-land uses are blocking. * * @author Taniko Yamamoto <[email protected]> */ class CurlHandler extends NetworkHandler { // This must be implemented through a hack as it has conditional // behaviour depending on the PHP version. use EventLoopRunner; /** * Stores all active requests. * * @var RequestWrapper[] */ private array $requests = []; #[Override] public function addRequest(Request $request): void { $this->requests[] = $this->convertRequest($request); } #[Override] public function clearRequests(): void { $this->requests = []; } /** * Convert a Request to a cURL handle. */ protected function convertRequest(Request $request): RequestWrapper { return RequestTransformer::convert($request); } /** * Convert a cURL response to a CoffeeRequest Response object. */ protected function makeResponse( int $status, string $raw, RequestWrapper $wrapper, ): Response { return new Response( $wrapper->instance, $status, $raw, $wrapper->responseHeaders ); } /** * Resolve a Request with a Response. */ protected function sendResponse(Request $request, Response $response): void { $request->resolve($response); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Handler; use YukisCoffee\CoffeeRequest\Event; use YukisCoffee\CoffeeRequest\Attributes\Override; use YukisCoffee\CoffeeRequest\Network\Request; use YukisCoffee\CoffeeRequest\Network\Response; /** * A template for all network handlers. * * @author Taniko Yamamoto <[email protected]> */ abstract class NetworkHandler extends Event { /** * Used internally to prevent the event loop from nullifying this * event when it's reported as fulfilled. */ public bool $preventNullification = true; /** * Add a request to the request manager. */ abstract public function addRequest(Request $request): void; /** * Clear all requests from the request manager. */ abstract public function clearRequests(): void; /** * Called in order to restart the manager when needed by the request * manager. * * This is required in order for the event to run more than once, as * otherwise it is never gotten to again once it finishes its job. */ public function restartManager(): void { unset($this->generator); $this->fulfilled = false; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Handler\Curl; use YukisCoffee\CoffeeRequest\Network\Request; use CurlHandle; /** * A structure that stores a cURL handle and the original Request object * for easy internal use. * * @author Taniko Yamamoto <[email protected]> */ class RequestWrapper { /** * The request itself, which may feature additional metadata * not used by cURL but used by CoffeeRequest. */ public Request $instance; /** * The cURL handle opened for the request. * * @var CurlHandle|resource */ public $handle; /** * An array of response headers. * * This is a hacky solution, but it's required in order to work around * CURLOPT_HEADERFUNCTION being declared as part of the request. The * data store here will be coalesced into the Response later. * * @var string[] */ public array $responseHeaders = []; public function __construct(Request $r, &$h) { $this->instance = $r; $this->handle = &$h; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Handler\Curl; use YukisCoffee\CoffeeRequest\Attributes\Override; use YukisCoffee\CoffeeRequest\Attributes\RequireMember; use const PHP_VERSION_ID; use Generator; use Fiber; // PHP 8.1 use function usleep; // cURL imports: use function curl_multi_init; use function curl_multi_add_handle; use function curl_multi_exec; use function curl_multi_select; use function curl_multi_getcontent; use function curl_multi_remove_handle; use function curl_multi_close; use function curl_getinfo; use function curl_close; use const CURLM_OK; use const CURLINFO_HTTP_CODE; if (false/*PHP_VERSION_ID >= 81000*/) { //===================================================================== // PHP 8.1+ implementation, leverages Fibers //===================================================================== #[RequireMember("requests")] #[RequireMember("makeResponse(int, string)")] #[RequireMember("sendResponse(Request, Response)")] trait EventLoopRunner // implements Event::onRun() { private array $normalItems = []; private array $fiberItems = []; #[Override] public function onRun(): Generator/*<void>*/ { yield; } } // EventLoopRunner } else { //===================================================================== // PHP 7 and 8.0 implementation //===================================================================== #[RequireMember("requests")] #[RequireMember("makeResponse(int, string)")] #[RequireMember("sendResponse(Request, Response)")] trait EventLoopRunner // implements Event::onRun() { #[Override] public function onRun(): Generator/*<void>*/ { // Defined in CurlHandler $requests = &$this->requests; if (count($requests) == 0) { $this->fulfil(); return; } $mh = curl_multi_init(); // Register all queued requests in the handle array foreach ($requests as $request) { curl_multi_add_handle($mh, $request->handle); } do { $status = curl_multi_exec($mh, $active); if ($active) { usleep(1); yield; } } while ($active && CURLM_OK == $status); // Report each of the responses. foreach ($requests as $request) { $response = $this->makeResponse( curl_getinfo($request->handle, CURLINFO_HTTP_CODE), curl_multi_getcontent($request->handle), $request ); $this->sendResponse($request->instance, $response); curl_multi_remove_handle($mh, $request->handle); curl_close($request->handle); } curl_multi_close($mh); $this->fulfill(); } } // EventLoopRunner } // PHP_VERSION_ID >= 81000
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Handler\Curl; use YukisCoffee\CoffeeRequest\Enum\RedirectPolicy; use YukisCoffee\CoffeeRequest\Network\Request; use YukisCoffee\CoffeeRequest\Util\NameserverInfo; use YukisCoffee\CoffeeRequest\CoffeeRequest; // cURL imports: use CurlHandle; use const CURLOPT_RETURNTRANSFER; use const CURLOPT_ENCODING; use const CURLOPT_POSTFIELDS; use const CURLOPT_HTTPHEADER; use const CURLOPT_CUSTOMREQUEST; use const CURLOPT_HEADERFUNCTION; use const CURLOPT_FOLLOWLOCATION; use const CURLOPT_RESOLVE; use function curl_init; use function curl_setopt_array; /** * Utility class for transforming a Request object into a * cURL handler. * * @author Taniko Yamamoto <[email protected]> */ class RequestTransformer { public const CURL_SUPPORTED_ENCODINGS = [ "gzip", "identity", "deflate" ]; private function __construct() {} /** * Convert a CoffeeRequest Request object to a cURL handle. */ public static function convert(Request $request): RequestWrapper { $ch = curl_init($request->url); $wrapper = new RequestWrapper($request, $ch); curl_setopt_array($ch, self::convertOptions($wrapper)); return $wrapper; } /** * Convert the request options used by Request objects into a * cURL option array. * * @return mixed[] */ public static function convertOptions(RequestWrapper $wrapper): array { $request = $wrapper->instance; $target = [ // You almost never want this false, especially for this CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADERFUNCTION => self::getHeaderFunction($wrapper) ]; // Encoding: $target[CURLOPT_ENCODING] = isset($request->preferredEncoding) ? self::filterEncoding($request->preferredEncoding) : "" ; // Method: $target[CURLOPT_CUSTOMREQUEST] = $request->method; // Headers: $target[CURLOPT_HTTPHEADER] = self::convertHeaders($request->headers); // User agent: $target[CURLOPT_USERAGENT] = ($request->userAgent == "") ? $_SERVER["HTTP_USER_AGENT"] : $request->userAgent; // Post body: if ("POST" == $request->method && isset($request->body)) { $target[CURLOPT_POSTFIELDS] = $request->body; } // Redirect: if (isset($request->redirectPolicy)) switch ($request->redirectPolicy) { case RedirectPolicy::FOLLOW: $target[CURLOPT_FOLLOWLOCATION] = true; break; case RedirectPolicy::MANUAL: $target[CURLOPT_FOLLOWLOCATION] = false; break; } // Misc: $target[CURLOPT_RESOLVE] = CoffeeRequest::getResolve(); return $target; } /** * Filter the preferred encoding provided by the Request object * and ignore it if it's not supported by cURL. */ public static function filterEncoding(string $encoding): string { if (in_array($encoding, self::CURL_SUPPORTED_ENCODINGS)) { return $encoding; } return ""; } /** * Convert a CoffeeRequest headers associative array to a cURL- * compatible iterated array. * * @param string[] * @return string[] */ public static function convertHeaders(array $headers): array { $curlHeaders = []; foreach ($headers as $header => $value) { $curlHeaders[] = "{$header}: {$value}"; } return $curlHeaders; } /** * Returns a unique anonymous function bound to a Request's wrapper. * * CURLOPT_HEADERFUNCTION is called back for each header received during * response. These must be coalesced into the Response later. * * @see https://stackoverflow.com/a/41135574 */ public static function getHeaderFunction(RequestWrapper $w): callable { return function($ch, $header) use ($w) { $headers = &$w->responseHeaders; $len = strlen($header); $header = explode(":", $header, 2); // Ignore invalid headers if (count($header) < 2) { return $len; } $normalizedName = strtolower(trim($header[0])); if (!isset($headers[$normalizedName])) { $headers[$normalizedName] = trim($header[1]); } else if (!is_array($headers[$normalizedName])) { $headers[$normalizedName] = [$headers[$normalizedName]]; $headers[$normalizedName][] = trim($header[1]); } else { $headers[$normalizedName][] = trim($header[1]); } return $len; }; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Attributes; use Attribute; /** * Denotes a property or method as an override from a parent class. */ #[Attribute(Attribute::TARGET_METHOD|Attribute::TARGET_PROPERTY)] class Override {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Attributes; use Attribute; /** * Denotes a class member that is required on a trait. * * @author Taniko Yamamoto <[email protected]> */ #[Attribute(Attribute::TARGET_CLASS|Attribute::IS_REPEATABLE)] class RequireMember { /** * True if the member is a method. */ private bool $isMethod = false; /** * The name of the class member. */ private string $name; /** * A map of the argument types if specifying a method. * * @var string[] */ private array $arguments; public function __construct(string $memberName) { // Don't include argument types for methods. if (strstr($memberName, "(")) { $signature = explode("(", $memberName); $this->name = $signature[0]; $this->arguments = $this->extractArgsTypes($signature[1]); $this->isMethod = true; } else { $this->name = $memberName; $this->isMethod = false; } } /** * Extract the argument types into an ordered array. * * @return string[] */ private function extractArgsTypes(string $args): array { $args = explode(")", $args)[0]; return str_replace(" ", "", explode(",", $args)); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Enum; /** * States for Promise resolution status. * * Since this package targets PHP 7 and 8.0 as well, native * enums cannot be used. * * When the time comes to deprecate PHP 8.0 support, this class * may be seamlessly moved to an 8.1 native enum by replacing consts * with cases. As such, please use the enum constant exclusively, never the * corresponding integer value, as it will make this transition harder. * * @author Taniko Yamamoto <[email protected]> */ class PromiseStatus { public const PENDING = 0; public const RESOLVED = 1; public const REJECTED = 2; }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Enum; /** * Error policy for Requests. * * Since this package targets PHP 7 and 8.0 as well, native * enums cannot be used. * * When the time comes to deprecate PHP 8.0 support, this class * may be seamlessly moved to an 8.1 native enum by replacing consts * with cases. As such, please use the enum constant exclusively, never the * corresponding integer value, as it will make this transition harder. * * @author Taniko Yamamoto <[email protected]> */ class RequestErrorPolicy { public const THROW = 0; public const IGNORE = 1; }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Enum; /** * Redirect policy enum for CoffeeRequest. * * Since this package targets PHP 7 and 8.0 as well, native * enums cannot be used. * * When the time comes to deprecate PHP 8.0 support, this class * may be seamlessly moved to an 8.1 native enum by replacing consts * with cases. As such, please use the enum constant exclusively, never the * corresponding integer value, as it will make this transition harder. * * @author Taniko Yamamoto <[email protected]> */ class RedirectPolicy { public const FOLLOW = 0; public const MANUAL = 1; }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Exception; use YukisCoffee\CoffeeRequest\Attributes\Override; use Exception; /** * Thrown when any exception is uncaught in a Promise. * * @author Taniko Yamamoto <[email protected]> */ class UncaughtPromiseException extends BaseException { private Exception $original; private string $class; private function __construct(Exception $original, string $class) { $this->original = $original; $this->class = $class; } #[Override] public function __toString(): string { $class = $this->original::class; $message = $this->original->__toString(); return preg_replace("/$class:/", "$class (in promise):", $message, 1) ?? "(in promise) " . $message; } public static function from(Exception $e): UncaughtPromiseException { $className = $e::class; return new self($e, $className); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Exception; use YukisCoffee\CoffeeRequest\Promise; use YukisCoffee\CoffeeRequest\Debugging\PromiseStackTrace; /** * Thrown when a Promise is unhandled within a session. * * @author Taniko Yamamoto <[email protected]> */ class UnhandledPromiseException extends PromiseException { private PromiseStackTrace $originTrace; public function __construct(Promise $promise, PromiseStackTrace $originTrace) { parent::__construct($promise, ""); $this->originTrace = $originTrace; } public function __toString(): string { $promise = $this->relatedPromise; $originTrace = $this->originTrace; $promiseName = get_class($promise); $firstFile = self::formatErrorFile($promise->creationTrace->getTraceAsArray()[0]); $latestFile = self::formatErrorFile($originTrace->getTraceAsArray()[0]); if ($firstFile != $latestFile) { $source = "from $firstFile in $latestFile"; } else { $source = "in $latestFile"; } $errorMsg = "Unhandled Promise($promiseName) $source\n" . "Stack trace:\n" . $originTrace->getTraceAsString() . "\n\n" . "Full trace:\n" . $originTrace->getOriginalTraceAsString() ; do { ob_end_clean(); } while (ob_get_level() > 0); header("Content-Type: text/plain"); echo $errorMsg; return ""; } private static function formatErrorFile(array $traceItem): string { $fileName = $traceItem["file"]; $lineNumber = $traceItem["line"]; $formattedFile = "[unknown file]"; if (is_string($fileName)) { $formattedFile = $fileName; if (is_int($lineNumber)) { $formattedFile .= ":$lineNumber"; } } return $formattedFile; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Exception; /** * Used to implement an exception type that has a hard-coded message. * * Thus, no arguments are used to construct one. This is sometimes * useful where exception types tend not to differ. * * @author Taniko Yamamoto <[email protected]> */ abstract class BaseHardMessageException extends BaseException { protected const MESSAGE = ""; public function __construct() { parent::__construct(static::MESSAGE); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Exception; use Exception; /** * Triggered when a Promise::all() call is rejected. * * This is typically because a Promise that it awaits is rejected. As * such, this takes two arguments: a general message from Promise::all() * incidating the index of the failed Promise, as well as the reason for * that Promise's rejection. * * @author Taniko Yamamoto <[email protected]> */ final class PromiseAllException extends BaseException { private Exception $subexception; public function __construct(string $reason, Exception $subexception) { parent::__construct($reason); $this->subexception = $subexception; } public function getReason(): Exception { return $this->subexception; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Exception; /** * Thrown when a network request responds with a non-2xx code, indicating * that the server rejected it or failed. * * @author Taniko Yamamoto <[email protected]> */ class RequestFailedResponseCodeException extends BaseException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Exception; /** * A general exception class. * * @author Taniko Yamamoto <[email protected]> */ final class GeneralException extends BaseException {}
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Exception; /** * Thrown to notify a developer that no supported network handler * is present with their current PHP setup. * * @author Taniko Yamamoto <[email protected]> */ final class NoSupportedHandlerException extends BaseHardMessageException { protected const MESSAGE = ( "Could not proceed with request as there is no available " . "network handler installed. (Please recompile PHP with the cURL " . "extension and try again)" ); }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Exception; /** * Used by the Nameserver module when an error is encountered during * DNS lookup. * * @author Taniko Yamamoto <[email protected]> */ class NameserverDnsLookupException extends BaseException { public function __construct(string $uri, string $lookupServer) { parent::__construct( "Failed to get DNS records for $uri using server $lookupServer" ); } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }
<?php namespace YukisCoffee\CoffeeRequest\Exception; use YukisCoffee\CoffeeRequest\Promise; use YukisCoffee\CoffeeRequest\Debugging\PromiseStackTrace; use YukisCoffee\CoffeeRequest\Attributes\Override; use Exception; /** * Represents an Exception that occurs within or regarding Promises. * * @author Taniko Yamamoto <[email protected]> */ class PromiseException extends BaseException { protected Promise $relatedPromise; public function __construct( Promise $promise, string $message = "", int $code = 0, $previous = null ) { parent::__construct($message, $code, $previous); $this->relatedPromise = $promise; } public function getCustomTrace(): PromiseStackTrace { return $this->relatedPromise->latestTrace; } #[Override] public function __toString(): string { $class = get_called_class(); $file = $this->getCustomTrace()->getTraceAsArray()[0]["file"]; $line = $this->getCustomTrace()->getTraceAsArray()[0]["line"]; $result = "$class (in promise): $this->message in $file:$line\n"; $result .= "Stack trace:\n"; $result .= (string)$this->getCustomTrace(); $result .= "\n\nFull trace:\n"; $result .= $this->getCustomTrace()->getOriginalTraceAsString(); return $result; } }
{ "repo_name": "Rehike/Rehike", "stars": "81", "repo_language": "PHP", "file_name": "config.php", "mime_type": "text/x-php" }