repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Actions/RequestRelayAction.php
src/Modules/Relay/Actions/RequestRelayAction.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Actions; use Carbon\CarbonImmutable; use GuzzleHttp\Cookie\SetCookie; use Illuminate\Container\Container; use Illuminate\Cookie\CookieValuePrefix; use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Client\Response; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Http; use RuntimeException; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\AuthorizationHandlerFactory; use Sunchayn\Nimbus\Modules\Relay\DataTransferObjects\RelayedRequestResponseData; use Sunchayn\Nimbus\Modules\Relay\DataTransferObjects\RequestRelayData; use Sunchayn\Nimbus\Modules\Relay\Responses\DumpAndDieResponse; use Sunchayn\Nimbus\Modules\Relay\ValueObjects\PrintableResponseBody; use Sunchayn\Nimbus\Modules\Relay\ValueObjects\ResponseCookieValueObject; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; class RequestRelayAction { public const DEFAULT_CONTENT_TYPE = 'application/json'; public const MICROSECONDS_TO_MILLISECONDS = 1_000_000; public const NON_STANDARD_STATUS_CODES = [ 419 => 'Method Not Allowed', DumpAndDieResponse::DUMP_AND_DIE_STATUS_CODE => 'dd()', ]; public function __construct( private readonly Container $container, private readonly AuthorizationHandlerFactory $authorizationHandlerFactory, ) {} public function execute(RequestRelayData $requestRelayData): RelayedRequestResponseData { $pendingRequest = $this->prepareRequest($requestRelayData); $authorizationHandler = $this ->authorizationHandlerFactory ->create($requestRelayData->authorization); $pendingRequest = $authorizationHandler->authorize($pendingRequest); $start = hrtime(true); $response = $this->sendPendingRequest($pendingRequest, $requestRelayData); $durationInMs = $this->calculateDuration($start); return new RelayedRequestResponseData( statusCode: $response->getStatusCode(), statusText: $this->getStatusTextFromCode($response->getStatusCode()), body: PrintableResponseBody::fromResponse($response), headers: $response->getHeaders(), durationMs: $durationInMs, timestamp: CarbonImmutable::now()->getTimestamp(), cookies: $this->processCookies($response->getHeader('Set-Cookie')), ); } private function prepareRequest(RequestRelayData $requestRelayData): PendingRequest { $contentType = $requestRelayData->headers['content-type'] ?? self::DEFAULT_CONTENT_TYPE; $queryParameters = $requestRelayData->queryParameters; $requestBody = $requestRelayData->body; if (in_array($requestRelayData->method, ['get', 'head'])) { $queryParameters = array_merge( $queryParameters, $requestBody, ); $requestBody = []; } // SSL verification is disabled to support development environments with self-signed certificates. return Http::withoutVerifying() ->withHeaders($requestRelayData->headers) ->withQueryParameters($queryParameters) ->when( $requestBody !== [], fn (PendingRequest $pendingRequest) => $pendingRequest->withBody( json_encode($requestRelayData->body) ?: throw new RuntimeException('Cannot parse body.'), contentType: $contentType, ), ); } /** * Calculates request duration in milliseconds with precision formatting. * * Uses high-resolution time for accurate microsecond measurements, * formatted to 2 decimal places for readability. */ private function calculateDuration(int $startTime): float { return (float) number_format( (hrtime(true) - $startTime) / self::MICROSECONDS_TO_MILLISECONDS, 2, thousands_separator: '' ); } /** * Processes Set-Cookie headers into structured cookie objects. * * Cookies are URL-decoded and prefixed with Laravel's encryption key * to match the application's cookie handling behavior. * * @param string[] $setCookieHeaders * @return ResponseCookieValueObject[] */ private function processCookies(array $setCookieHeaders): array { return Arr::map( $setCookieHeaders, function (string $cookieString): ResponseCookieValueObject { $setCookie = SetCookie::fromString($cookieString); return new ResponseCookieValueObject( key: $setCookie->getName(), rawValue: urldecode($setCookie->getValue() ?? ''), prefix: CookieValuePrefix::create( $setCookie->getName(), $this->container->get('encrypter')->getKey() ), ); }, ); } /** * Maps HTTP status codes to human-readable status text. * * Includes Laravel-specific status codes like 419 (Method Not Allowed) * that aren't part of the standard HTTP specification. */ private function getStatusTextFromCode(int $statusCode): string { $statusCodeToTextMapping = SymfonyResponse::$statusTexts + self::NON_STANDARD_STATUS_CODES; return $statusCodeToTextMapping[$statusCode] ?? 'Non-standard Status Code.'; } private function sendPendingRequest(PendingRequest $pendingRequest, RequestRelayData $requestRelayData): Response { $response = $pendingRequest->send( method: $requestRelayData->method, url: $requestRelayData->endpoint, ); if (! $response->serverError()) { return $response; } if (! str_contains($response->body(), 'Sfdump = window.Sfdump')) { return $response; } return new DumpAndDieResponse($response->toPsrResponse()); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/ValueObjects/PrintableResponseBody.php
src/Modules/Relay/ValueObjects/PrintableResponseBody.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\ValueObjects; use Illuminate\Http\Client\Response; readonly class PrintableResponseBody { /** * @param string|array<array-key, mixed> $body */ public function __construct( public array|string $body, ) {} public static function fromResponse(Response $response): self { return new self( body: $response->json() ?? $response->body(), ); } public function toPrettyJSON(): string { if (is_array($this->body)) { return json_encode($this->body, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) ?: ''; } return $this->body; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/ValueObjects/ResponseCookieValueObject.php
src/Modules/Relay/ValueObjects/ResponseCookieValueObject.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\ValueObjects; use Illuminate\Support\Str; class ResponseCookieValueObject { protected ?string $decryptedValue; public function __construct( public string $key, protected string $rawValue, protected string $prefix, ) { $this->decryptedValue = $this->computeDecryptedValue(); } /** * @return array{ * key: string, * value: array{ * raw: string, * decrypted: string|null, * }, * } */ public function toArray(): array { return [ 'key' => $this->key, 'value' => [ 'raw' => $this->rawValue, 'decrypted' => $this->decryptedValue, ], ]; } private function computeDecryptedValue(): ?string { return rescue( fn () => Str::replaceStart($this->prefix, '', decrypt($this->rawValue, false)), report: false, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/DataTransferObjects/RequestRelayData.php
src/Modules/Relay/DataTransferObjects/RequestRelayData.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\DataTransferObjects; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Sunchayn\Nimbus\Http\Api\Relay\NimbusRelayRequest; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationCredentials; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationTypeEnum; use Symfony\Component\HttpFoundation\ParameterBag; readonly class RequestRelayData { /** * @param array<string, string> $headers * @param array<string, mixed> $body * @param array<string, string|null> $queryParameters */ public function __construct( public string $method, public string $endpoint, public AuthorizationCredentials $authorization, public array $headers, public array $body, public ParameterBag $cookies, public array $queryParameters = [], ) {} public static function fromRelayApiRequest(NimbusRelayRequest $nimbusRelayRequest): self { /** * @var array{ * headers?: array<array-key, array{key: string, value: string}>, * method: string, * endpoint: string, * authorization?: array{type: string, value?: string|array{username: string, password: string}|null}, * body: mixed, * } $data **/ $data = $nimbusRelayRequest->validated(); /** @var Collection<string, string> $headers */ $headers = collect($data['headers'] ?? []) ->pluck('value', 'key'); $headers->when( ! $headers->has('Accept'), fn () => $headers->put('Accept', 'application/json'), ); $headers->when( $nimbusRelayRequest->userAgent() !== null, fn () => $headers->put('User-Agent', (string) $nimbusRelayRequest->userAgent()), ); [ 'endpoint' => $endpoint, 'queryParameters' => $queryParameters, ] = self::extractAndRemoveQueryParametersFromEndpoint($data['endpoint']); return new self( method: strtolower($data['method']), endpoint: $endpoint, authorization: array_key_exists('authorization', $data) ? new AuthorizationCredentials( type: AuthorizationTypeEnum::from($data['authorization']['type']), value: $data['authorization']['value'] ?? null, ) : AuthorizationCredentials::none(), headers: $headers->mapWithKeys(fn (mixed $value, string $key): array => [strtolower($key) => $value])->all(), body: $nimbusRelayRequest->getBody(), cookies: $nimbusRelayRequest->cookies, queryParameters: $queryParameters, ); } /** * @return array{endpoint: string, queryParameters: array<string, string|null>} */ private static function extractAndRemoveQueryParametersFromEndpoint(string $endpoint): array { $urlParts = parse_url($endpoint); if (! $urlParts) { return [ 'endpoint' => $endpoint, 'queryParameters' => [], ]; } $cleanEndpoint = (array_key_exists('scheme', $urlParts) ? $urlParts['scheme'].'://' : '') .(array_key_exists('host', $urlParts) ? $urlParts['host'] : '') .(array_key_exists('port', $urlParts) ? ':'.$urlParts['port'] : '') .(array_key_exists('path', $urlParts) ? $urlParts['path'] : ''); $queryParameters = array_key_exists('query', $urlParts) ? Arr::mapWithKeys( explode('&', $urlParts['query']), static function (string $query): array { $parts = explode('=', $query); if (count($parts) !== 2) { return []; } return [$parts[0] => $parts[1]]; }, ) : []; return [ 'endpoint' => $cleanEndpoint, 'queryParameters' => $queryParameters, ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/DataTransferObjects/RelayedRequestResponseData.php
src/Modules/Relay/DataTransferObjects/RelayedRequestResponseData.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\DataTransferObjects; use Sunchayn\Nimbus\Modules\Relay\ValueObjects\PrintableResponseBody; use Sunchayn\Nimbus\Modules\Relay\ValueObjects\ResponseCookieValueObject; readonly class RelayedRequestResponseData { /** * @param string[][] $headers * @param ResponseCookieValueObject[] $cookies */ public function __construct( public int $statusCode, public string $statusText, public PrintableResponseBody $body, public array $headers, public float $durationMs, public int $timestamp, public array $cookies, ) {} }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Parsers/VarDumpParser/VarDumpParser.php
src/Modules/Relay/Parsers/VarDumpParser/VarDumpParser.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ObjectPropertyDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ParsedArrayResultDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ParsedClosureResultDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ParsedObjectResultDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ParsedValueDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ParseResultDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\Enums\DumpValueTypeEnum; class VarDumpParser { private const PATTERN_LARAVEL_COMMENT = '/<span[^>]*style=["\'][^"\']*color:\s*#A0A0A0[^"\']*["\'][^>]*>\s*\/\/\s*(.+?)<\/span>/s'; /** * Parse raw HTML output containing one or more Symfony dumps */ public function parse(string $html): ParseResultDto { $html = $this->cleanHtml($html); $dumpSections = $this->extractDumpSections($html); if ($dumpSections === []) { return ParseResultDto::empty(); } $dumps = []; foreach ($dumpSections as $dumpSection) { $cleanHtml = $this->removeCommentFromDump($dumpSection); $dumps[] = $this->parseValue(trim($cleanHtml)); } return new ParseResultDto( source: $this->extractComment($dumpSections[0]), dumps: $dumps, ); } /** * Clean HTML by removing unnecessary elements */ private function cleanHtml(string $html): string { // Remove style and script tags $html = (string) preg_replace('/<style\b[^>]*>.*?<\/style>/is', '', $html); $html = (string) preg_replace('/<script\b[^>]*>.*?<\/script>/is', '', $html); // Remove ellipsis elements for simpler parsing return (string) preg_replace('/<([a-z]+)\s+[^>]*class=(["\'])(?:[^"\'>]*\s)?sf-dump-ellipsis[^"\'>]*\2[^>]*>.*?<\/\1>/si', '', $html); } /** * Extract individual dump sections from HTML * * @return array<array-key, string> */ private function extractDumpSections(string $html): array { preg_match_all('/<pre\b[^>]*>\K.*?(?=<\/pre>)/s', $html, $matches); return $matches[0]; } /** * Extract Laravel file/line comment from dump output */ private function extractComment(string $html): ?string { if (preg_match(self::PATTERN_LARAVEL_COMMENT, $html, $match)) { return trim($match[1]); } return null; } /** * Remove Laravel comment from dump HTML */ private function removeCommentFromDump(string $html): string { return (string) preg_replace(self::PATTERN_LARAVEL_COMMENT, '', $html); } /** * Detect the root type of a dump value */ private function detectRootType(string $html): DumpValueTypeEnum { if ($html === '""') { return DumpValueTypeEnum::String; } if ($html === '[]') { return DumpValueTypeEnum::Array; } // Array with size notation: array:3 [ if (preg_match('/^<span\b[^>]*class="?sf-dump-note[^>]*>\s*array:\d+/s', $html)) { return DumpValueTypeEnum::Array; } // Closure (must check before object to avoid confusion with named objects) if (preg_match('/^<span class="?sf-dump-note[^>]*>Closure\([^)]*\)<\/span>/s', $html)) { return DumpValueTypeEnum::Closure; } // Named Objects (e.g. : ClassName {), or Closures. if (preg_match('/^<span class="?sf-dump-note[^>]*>[^<]*<\/span>\s*\{/s', $html, $matches)) { // If there are parenthesis in the matched portion (the beginning of the html) then it is a Closure. // e.g. <span class="sf-dump-note sf-dump-ellipsization" title="Illuminate\Foundation\Application::environment(...$environments)"></span> { // e.g. <span class=sf-dump-note>Illuminate\Foundation\Application::environment(...$environments)</span> { return preg_match('/^.+\([^)]*\)/s', $matches[0]) ? DumpValueTypeEnum::Closure : DumpValueTypeEnum::Object; } // Runtime object: {<a...> if (preg_match('/^\{<a class=sf-dump-ref/s', $html)) { return DumpValueTypeEnum::Object; } // String value if (preg_match('/^"<span\b[^>]*class=sf-dump-str\b/s', $html)) { return DumpValueTypeEnum::String; } // Uninitialized property (must be before const check). if (preg_match('/^<span [^>]* title="Uninitialized property">/s', $html)) { return DumpValueTypeEnum::Uninitialized; } // Boolean or null constants if (preg_match('/^<span\b[^>]*class=sf-dump-const\b/s', $html)) { return DumpValueTypeEnum::Constant; } // Numeric value if (preg_match('/^<span\b[^>]*class=sf-dump-num\b/s', $html)) { return DumpValueTypeEnum::Number; } return DumpValueTypeEnum::Unknown; } /** * Parse a value based on its detected type */ private function parseValue(string $html): ParsedValueDto { $dumpValueTypeEnum = $this->detectRootType($html); $value = match ($dumpValueTypeEnum) { DumpValueTypeEnum::Object => $this->parseObject($html), DumpValueTypeEnum::Array => $this->parseArray($html), DumpValueTypeEnum::String => $this->parseString($html), DumpValueTypeEnum::Constant => $this->parseConst($html), DumpValueTypeEnum::Number => $this->parseNumber($html), DumpValueTypeEnum::Closure => $this->parseClosure($html), DumpValueTypeEnum::Uninitialized => $this->parseUninitialized($html), DumpValueTypeEnum::Unknown => null, }; return new ParsedValueDto(type: $dumpValueTypeEnum, value: $value); } /** * Parse object structure and properties */ private function parseObject(string $html): ParsedObjectResultDto { $className = $this->extractObjectClassName($html); // Extract content between { and } if (! preg_match('/\{<a class=sf-dump-ref[^>]*>[^<]+<\/a><samp[^>]+>(.+)<\/samp>}\n?$/s', $html, $match)) { // Sometimes items are not listed when a certain depth is reached. // e.g. Symfony\Component\Routing\CompiledRoute {#369 …8} return new ParsedObjectResultDto(className: $className, properties: []); } $content = trim($match[1], "\n"); // Normalize indentation to simplify parsing $content = $this->normalizeIndentation($content); $properties = []; // Match properties with visibility markers: +/-/# "propertyName": value $pattern = '/[#\+\-]"?<span class=sf-dump-(public|protected|private)[^>]*>([^<]+)<\/span>"?:\s(.*?)(?=(?:\n[#\+\-](?:<|"<)|\Z))/s'; preg_match_all($pattern, $content, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $visibility = $match[1]; $propertyName = trim($match[2]); $propertyValueHtml = trim($match[3]); $properties[$propertyName] = new ObjectPropertyDto( visibility: $visibility, value: $this->parseValue($propertyValueHtml), ); } return new ParsedObjectResultDto(className: $className, properties: $properties); } /** * Parse array structure and items */ private function parseArray(string $html): ParsedArrayResultDto { if ($html === '[]') { return new ParsedArrayResultDto(items: [], numericallyIndexed: true); } // Extract content within <samp> tags if (! preg_match('/^<span\b[^>]*class=sf-dump-note[^>]*>\s*array:\d+\s*<\/span>\s*\[\s*<samp\b[^>]*>(.*?)<\/samp>]$/s', $html, $match)) { // Sometimes items are not listed when a certain depth is reached. // e.g. +methods: array:2 [ …2] return new ParsedArrayResultDto(items: [], numericallyIndexed: true); } $content = trim($match[1], "\n"); // Normalize indentation $content = $this->normalizeIndentation($content); $items = []; $isNumerical = true; // Match key => value pairs (works for both indexed and associative) $pattern = '/"?<span class=sf-dump-(key|index)[^>]*>([^<]+)<\/span>"?\s=>\s(.*?)(?=(?:\n"?<span class=sf-dump-(?:key|index))|\Z)/s'; preg_match_all($pattern, $content, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $keyType = $match[1]; // 'key' or 'index' $key = $match[2]; $valueHtml = trim($match[3]); // If any key is not an index, the array is not numerically indexed if ($keyType === 'key') { $isNumerical = false; } $items[$key] = $this->parseValue($valueHtml); } return new ParsedArrayResultDto(items: $items, numericallyIndexed: $isNumerical); } /** * Parse string primitive value */ private function parseString(string $html): string { if ($html === '""') { return ''; } if (preg_match('/<span class=sf-dump-str[^>]*>([^<]*)<\/span>/', $html, $match)) { return html_entity_decode($match[1], ENT_QUOTES | ENT_HTML5); } return ''; } /** * Parse constant value (true, false, null) */ private function parseConst(string $html): ?bool { if (preg_match('/<span class=sf-dump-const[^>]*>([^<]+)<\/span>/', $html, $match)) { return match (strtolower(trim($match[1]))) { 'true' => true, 'false' => false, default => null, }; } return null; } /** * Parse numeric value (int or float) */ private function parseNumber(string $html): int|float { if (preg_match('/<span class=sf-dump-num[^>]*>([^<]+)<\/span>/', $html, $match)) { $value = $match[1]; return str_contains($value, '.') ? (float) $value : (int) $value; } return 0; } /** * Parse closure information */ private function parseClosure(string $html): ParsedClosureResultDto { $signature = 'CLosure()'; $className = null; $thisReference = null; // Extract signature from between span tags. if (preg_match('/^<span[^>]*>([^<]+)/', $html, $match)) { $signature = trim($match[1]); } // Extract signature from the title elseif (preg_match('/^<span[^>]*title="([^"\n]+)/', $html, $match)) { $signature = trim($match[1]); } // Extract class context if (preg_match('/<span [^>]*class=sf-dump-meta\s*>class<\/span>:\s*"?<span [^>]*title="([^"\n]+)/', $html, $match)) { $className = trim($match[1]); } // Extract this reference if (preg_match('/<span [^>]*class=sf-dump-meta\s*>this<\/span>:\s*"?<span [^>]*title="([^"\n]+)/', $html, $match)) { $thisReference = trim($match[1]); } return new ParsedClosureResultDto( signature: $signature, className: $className, thisReference: $thisReference, ); } /** * Parse uninitialized property annotation */ private function parseUninitialized(string $html): string { if (preg_match('/^<span[^>]+>([^<]+)<\/span>$/', $html, $match)) { return $match[1]; } return 'undefined'; } /** * Extract class name from object dump */ private function extractObjectClassName(string $html): ?string { // Check for title attribute (ellipsized class names) if (preg_match('/^<span[^>]*title="([^"\n\s]+)/', $html, $match)) { return trim($match[1]); } // Check for class name in sf-dump-note span if (preg_match('/^<span class="?sf-dump-note[^>]*>([^<]+)<\/span>/s', $html, $match)) { return html_entity_decode(strip_tags(trim($match[1])), ENT_QUOTES | ENT_HTML5); } // Runtime object (no explicit class name) if (preg_match('/<a class=sf-dump-ref[^>]*>/', $html)) { return '<runtime object>'; } return null; } /** * Normalize indentation by removing common leading whitespace */ private function normalizeIndentation(string $content): string { // Find the indentation of the first line if (preg_match('/^(\s+)/s', $content, $match)) { $indent = $match[1]; // Remove this indentation from all lines return (string) preg_replace("/\n{$indent}/", "\n", ltrim($content)); } return ltrim($content); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Parsers/VarDumpParser/Enums/DumpValueTypeEnum.php
src/Modules/Relay/Parsers/VarDumpParser/Enums/DumpValueTypeEnum.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\Enums; enum DumpValueTypeEnum: string { case Object = 'object'; case Array = 'array'; case String = 'string'; case Constant = 'constant'; case Uninitialized = 'uninitialized'; case Number = 'number'; case Closure = 'closure'; case Unknown = 'unknown'; }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Parsers/VarDumpParser/DataTransferObjects/ParsedValueDto.php
src/Modules/Relay/Parsers/VarDumpParser/DataTransferObjects/ParsedValueDto.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects; use Illuminate\Contracts\Support\Arrayable; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\Enums\DumpValueTypeEnum; /** * @implements Arrayable<string, string|float|int|bool|null|array> */ readonly class ParsedValueDto implements Arrayable { public function __construct( public DumpValueTypeEnum $type, public ParsedArrayResultDto|ParsedObjectResultDto|ParsedClosureResultDto|string|float|int|bool|null $value, ) {} public function toArray(): array { return [ 'type' => $this->type->value, 'value' => $this->value instanceof Arrayable ? $this->value->toArray() : $this->value, ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Parsers/VarDumpParser/DataTransferObjects/ParsedArrayResultDto.php
src/Modules/Relay/Parsers/VarDumpParser/DataTransferObjects/ParsedArrayResultDto.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects; use Illuminate\Contracts\Support\Arrayable; /** * @implements Arrayable<string, int|array> */ readonly class ParsedArrayResultDto implements Arrayable { /** * @param array<string, mixed> $items */ public function __construct( public array $items, public bool $numericallyIndexed, ) {} public function toArray(): array { return [ 'items' => collect($this->items)->toArray(), 'length' => count($this->items), 'numericallyIndexed' => $this->numericallyIndexed, ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Parsers/VarDumpParser/DataTransferObjects/ParseResultDto.php
src/Modules/Relay/Parsers/VarDumpParser/DataTransferObjects/ParseResultDto.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects; use Illuminate\Contracts\Support\Arrayable; /** * @implements Arrayable<string, string|array> */ class ParseResultDto implements Arrayable { /** * @param ParsedValueDto[] $dumps */ public function __construct( public readonly ?string $source, public readonly array $dumps, ) {} public static function empty(): self { return new self( source: null, dumps: [], ); } public function toArray(): array { return [ 'source' => $this->source, 'dumps' => collect($this->dumps)->toArray(), ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Parsers/VarDumpParser/DataTransferObjects/ParsedObjectResultDto.php
src/Modules/Relay/Parsers/VarDumpParser/DataTransferObjects/ParsedObjectResultDto.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects; use Illuminate\Contracts\Support\Arrayable; /** * @implements Arrayable<string, string|int|null|array> */ readonly class ParsedObjectResultDto implements Arrayable { /** * @param ObjectPropertyDto[] $properties */ public function __construct( public ?string $className, public array $properties, ) {} public function toArray(): array { return [ 'class' => $this->className, 'properties' => collect($this->properties)->toArray(), 'propertiesCount' => count($this->properties), ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Parsers/VarDumpParser/DataTransferObjects/ObjectPropertyDto.php
src/Modules/Relay/Parsers/VarDumpParser/DataTransferObjects/ObjectPropertyDto.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects; use Illuminate\Contracts\Support\Arrayable; /** * @implements Arrayable<string, string|array> */ readonly class ObjectPropertyDto implements Arrayable { public function __construct( public string $visibility, public ParsedValueDto $value, ) {} public function toArray(): array { return [ 'visibility' => $this->visibility, 'value' => $this->value->toArray(), ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Parsers/VarDumpParser/DataTransferObjects/ParsedClosureResultDto.php
src/Modules/Relay/Parsers/VarDumpParser/DataTransferObjects/ParsedClosureResultDto.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects; use Illuminate\Contracts\Support\Arrayable; /** * @implements Arrayable<string, string|null> */ readonly class ParsedClosureResultDto implements Arrayable { public function __construct( public string $signature, public ?string $className, public ?string $thisReference, ) {} public function toArray(): array { return [ 'signature' => $this->signature, 'class' => $this->className, 'this' => $this->thisReference, ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Relay/Responses/DumpAndDieResponse.php
src/Modules/Relay/Responses/DumpAndDieResponse.php
<?php namespace Sunchayn\Nimbus\Modules\Relay\Responses; use Illuminate\Http\Client\Response; use Illuminate\Support\Str; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\VarDumpParser; class DumpAndDieResponse extends Response { public const DUMP_AND_DIE_STATUS_CODE = 999; public function getStatusCode(): int { return self::DUMP_AND_DIE_STATUS_CODE; } /** * @return array<string, string|array<array-key, mixed>> */ public function json($key = null, $default = null): array { [ 'source' => $source, 'dumps' => $dumps, ] = resolve(VarDumpParser::class)->parse($this->response->getBody())->toArray(); return [ 'id' => Str::uuid()->toString(), 'timestamp' => now()->format('Y-m-d H:i:s'), 'source' => $source, 'dumps' => $dumps, ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Exceptions/InvalidRouteDefinitionException.php
src/Modules/Routes/Exceptions/InvalidRouteDefinitionException.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Exceptions; class InvalidRouteDefinitionException extends RouteExtractionException { /** * @param string[] $routeMethods */ public static function forRoute( string $routeUri, array $routeMethods, string $controllerClass, string $controllerMethod, ): self { $properlyFormattedUsesStatement = filled($controllerClass) && filled($controllerMethod); $message = $properlyFormattedUsesStatement ? sprintf("Controller method '%s' not found in class '%s' for route '%s'.", $controllerMethod, $controllerClass, $routeUri) : sprintf("Malformed `uses` statement for route '%s'.", $routeUri); $suggestedSolution = $properlyFormattedUsesStatement ? sprintf("Check that the method '%s' exists in the '%s' class. This usually indicates an incorrect route definition in your routes file.", $controllerMethod, $controllerClass) : 'Make sure the `uses` statement is properly formatted `{controllerClass}@{controllerMethod}`. If it is an invokable controller then it must not have the `@` suffix.'; return new self( message: $message, routeUri: $routeUri, routeMethods: $routeMethods, controllerClass: $controllerClass, controllerMethod: $controllerMethod, suggestedSolution: $suggestedSolution, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Exceptions/RouteExtractionInternalException.php
src/Modules/Routes/Exceptions/RouteExtractionInternalException.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Exceptions; use Throwable; class RouteExtractionInternalException extends RouteExtractionException { /** * @param string[] $routeMethods */ public static function forRoute( Throwable $throwable, string $routeUri, array $routeMethods, ?string $controllerClass = null, ?string $controllerMethod = null, ): self { return new self( message: sprintf("Failed to extract route information for '%s' due to an unexpected error: %s", $routeUri, $throwable->getMessage()), routeUri: $routeUri, routeMethods: $routeMethods, controllerClass: $controllerClass, controllerMethod: $controllerMethod, suggestedSolution: 'Check the application logs for more details and ensure all dependencies are properly installed.' .'<br />In case of internal errors, please open an issue: <a class="hover:underline" href="https://github.com/sunchayn/nimbus/issues/new/choose">https://github.com/sunchayn/nimbus/issues/new/choose</a>', code: $throwable->getCode(), previous: $throwable, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Exceptions/RouteExtractionException.php
src/Modules/Routes/Exceptions/RouteExtractionException.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Exceptions; use RuntimeException; use Throwable; abstract class RouteExtractionException extends RuntimeException { private readonly string $controllerClass; private readonly string $controllerMethod; /** * @param string[] $routeMethods */ public function __construct( string $message, private readonly ?string $routeUri = null, private readonly ?array $routeMethods = null, ?string $controllerClass = null, ?string $controllerMethod = null, private readonly ?string $suggestedSolution = null, int $code = 0, ?Throwable $previous = null, ) { $this->controllerClass = filled($controllerClass) ? $controllerClass : '[unspecified]'; $this->controllerMethod = filled($controllerMethod) ? $controllerMethod : '[unspecified]'; parent::__construct($message, $code, $previous); } public function getSuggestedSolution(): ?string { return $this->suggestedSolution; } public function getIgnoreData(): ?string { if ($this->routeUri === null || $this->routeMethods === null) { return null; } return implode('|', [ $this->routeUri, json_encode($this->routeMethods), ]); } /** * @return array<string, array<string>|string|null> */ public function getRouteContext(): array { return [ 'uri' => $this->routeUri, 'methods' => $this->routeMethods, 'controllerClass' => $this->controllerClass, 'controllerMethod' => $this->controllerMethod, ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Actions/DisableThirdPartyUiAction.php
src/Modules/Routes/Actions/DisableThirdPartyUiAction.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Actions; /** * Disables third-party UI addons that interfere with Nimbus interface. */ class DisableThirdPartyUiAction { public function execute(): void { // The Debugbar will interfere with the UI, // The page is a third party so most likely no need to have the debug toolbar here. if (class_exists(\Barryvdh\Debugbar\Facades\Debugbar::class)) { \Barryvdh\Debugbar\Facades\Debugbar::disable(); } } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Actions/BuildGlobalHeadersAction.php
src/Modules/Routes/Actions/BuildGlobalHeadersAction.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Actions; use Illuminate\Config\Repository as ConfigRepository; use Illuminate\Support\Arr; use Sunchayn\Nimbus\Modules\Config\GlobalHeaderGeneratorTypeEnum; class BuildGlobalHeadersAction { public function __construct( private readonly ConfigRepository $configRepository, ) {} /** * @return array<array-key, scalar|null> */ public function execute(): array { /** @var array<array-key, mixed> $headers */ $headers = $this->configRepository->get('nimbus.headers'); return array_values( Arr::map( $headers, fn (mixed $value, string $header): array => [ 'header' => $header, 'type' => $value instanceof GlobalHeaderGeneratorTypeEnum ? 'generator' : 'raw', 'value' => match (true) { $value instanceof GlobalHeaderGeneratorTypeEnum => $value->value, is_scalar($value) => $value, default => null, }, ], ), ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Actions/IgnoreRouteErrorAction.php
src/Modules/Routes/Actions/IgnoreRouteErrorAction.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Actions; use Sunchayn\Nimbus\Modules\Routes\Services\IgnoredRoutesService; /** * Adda the specified route to the ignore list. * * @example * Input: "api/users|GET,POST" * Output: Redirects to clean URL after adding route to ignored list */ class IgnoreRouteErrorAction { public function __construct( private readonly IgnoredRoutesService $ignoredRoutesService, ) {} public function execute(string $ignoreData): void { // Parse the ignore data (format: "uri|methods") $parts = explode('|', $ignoreData); if (count($parts) !== 2) { return; } if (empty($parts[0])) { return; } $uri = $parts[0]; $methods = json_decode($parts[1], true) ?: []; $this->ignoredRoutesService->add($uri, $methods); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Actions/BuildCurrentUserAction.php
src/Modules/Routes/Actions/BuildCurrentUserAction.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Actions; use Illuminate\Contracts\Auth\Factory; class BuildCurrentUserAction { public function __construct( private readonly Factory $factory, ) {} /** * @return array{id: int}|null */ public function execute(): ?array { if ($this->factory->guard()->user() === null) { return null; } return ['id' => $this->factory->guard()->user()->getAuthIdentifier()]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Actions/ExtractRoutesAction.php
src/Modules/Routes/Actions/ExtractRoutesAction.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Actions; use Illuminate\Contracts\Config\Repository; use Illuminate\Routing\Route; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Psr\Log\LoggerInterface; use Sunchayn\Nimbus\Modules\Routes\Collections\ExtractedRoutesCollection; use Sunchayn\Nimbus\Modules\Routes\DataTransferObjects\ExtractedRoute; use Sunchayn\Nimbus\Modules\Routes\Exceptions\RouteExtractionException; use Sunchayn\Nimbus\Modules\Routes\Exceptions\RouteExtractionInternalException; use Sunchayn\Nimbus\Modules\Routes\Extractor\SchemaExtractor; use Sunchayn\Nimbus\Modules\Routes\Factories\ExtractableRouteFactory; use Sunchayn\Nimbus\Modules\Routes\Services\IgnoredRoutesService; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\Endpoint; use Throwable; /** * Orchestrates the extraction of validation schemas from Laravel routes. * * Filters routes by prefix, excludes ignored routes, and transforms each * route into a structured configuration with extracted validation schemas. */ class ExtractRoutesAction { public function __construct( protected SchemaExtractor $schemaExtractor, protected ExtractableRouteFactory $routeFactory, protected IgnoredRoutesService $ignoredRoutesService, protected Repository $config, protected LoggerInterface $logger, ) {} /** * Processes application routes and extracts schemas. * * @param array<int, \Illuminate\Routing\Route> $routes */ public function execute(array $routes): ExtractedRoutesCollection { $prefix = $this->config->get('nimbus.routes.prefix'); $configs = collect($routes) ->filter(function (Route $route) use ($prefix): bool { $uri = $route->uri(); return str_starts_with($uri, $prefix) || str_starts_with($uri, '/'.$prefix); }) ->when( $this->ignoredRoutesService->hasIgnoredRoutes(), fn (Collection $routes) => $routes->reject(fn (Route $route): bool => $this->ignoredRoutesService->isIgnored($route)) ) ->values() ->map(fn (Route $route): \Sunchayn\Nimbus\Modules\Routes\DataTransferObjects\ExtractedRoute => $this->transformRoute($route)); return ExtractedRoutesCollection::make($configs); } /** * Transforms a Laravel route into a RouteConfig with extracted schema. * * @throws RouteExtractionException */ protected function transformRoute(Route $route): ExtractedRoute { try { $extractableRoute = $this->routeFactory->fromLaravelRoute($route); $schema = $this->schemaExtractor->extract($extractableRoute); } catch (Throwable $throwable) { $this->logger->error( $throwable->getMessage(), context: [ 'trace' => $throwable->getTraceAsString(), ], ); throw RouteExtractionInternalException::forRoute( throwable: $throwable, routeUri: $route->uri(), routeMethods: $route->methods(), controllerClass: $extractableRoute->controllerClass ?? null, controllerMethod: $extractableRoute->controllerMethod ?? null, ); } $methods = Arr::where( $route->methods(), // We exclude the `HEAD` methods as they don't carry request bodies. fn (string $method): bool => $method !== 'HEAD', ); return new ExtractedRoute( uri: Endpoint::fromRaw( $route->uri(), routesPrefix: $this->config->get('nimbus.routes.prefix'), isVersioned: $this->config->get('nimbus.routes.versioned'), ), methods: $methods, schema: $schema, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Extractor/SchemaExtractor.php
src/Modules/Routes/Extractor/SchemaExtractor.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Extractor; use Illuminate\Container\Container; use Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies\ExtractorStrategyContract; use Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies\FormRequestExtractorStrategy; use Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies\InlineRequestValidatorExtractorStrategy; use Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies\SpatieDataObjectExtractorStrategy; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\ExtractableRoute; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; class SchemaExtractor { /** @var ExtractorStrategyContract[] */ protected array $strategies = []; public function __construct( Container $container, ) { $this->strategies = [ // Define in the extraction stragies in their execution order. // Only one strategy will run, and that will be the first matching strategy. $container->make(FormRequestExtractorStrategy::class), $container->make(SpatieDataObjectExtractorStrategy::class), $container->make(InlineRequestValidatorExtractorStrategy::class), // <- Must be the last one, so previous ones can match. ]; } public function extract(ExtractableRoute $extractableRoute): Schema { foreach ($this->strategies as $strategy) { if ($strategy->matches($extractableRoute)) { /** @var ExtractorStrategyContract $strategy */ return $strategy->extract($extractableRoute); } } return Schema::empty(); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Extractor/Strategies/SpatieDataObjectExtractorStrategy.php
src/Modules/Routes/Extractor/Strategies/SpatieDataObjectExtractorStrategy.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies; use Illuminate\Container\Container; use Illuminate\Support\Arr; use ReflectionNamedType; use ReflectionParameter; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\ExtractableRoute; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\RulesExtractionError; use Sunchayn\Nimbus\Modules\Schemas\Builders\SchemaBuilder; use Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; use Throwable; /** * Extracts validation rules from Spatie Data classes. */ class SpatieDataObjectExtractorStrategy implements ExtractorStrategyContract { public function __construct( private readonly SchemaBuilder $schemaBuilder, private readonly Container $container, ) {} public function matches(ExtractableRoute $extractableRoute): bool { // @codeCoverageIgnoreStart if (! class_exists(\Spatie\LaravelData\Data::class)) { return false; } // @codeCoverageIgnoreEnd foreach ($extractableRoute->parameters as $parameter) { if (! $parameter->hasType()) { continue; } $type = $parameter->getType(); if (! $type instanceof ReflectionNamedType) { continue; } $parameterType = $type->getName(); // If it is not a form request instance, we continue. if (! is_subclass_of($parameterType, \Spatie\LaravelData\Data::class)) { continue; } return true; } return false; // <- didn't find a form request. } public function extract(ExtractableRoute $extractableRoute): Schema { /** @var ?ReflectionParameter $dataParameter */ $dataParameter = Arr::first( $extractableRoute->parameters, function (ReflectionParameter $reflectionParameter): bool { $type = $reflectionParameter->getType(); if (! $type instanceof ReflectionNamedType) { return false; } return is_subclass_of($type->getName(), \Spatie\LaravelData\Data::class); }, ); if (! $dataParameter) { return Schema::empty(); } /** @var ReflectionNamedType $type */ $type = $dataParameter->getType(); /** @var class-string $spatieDataObjectClassName */ $spatieDataObjectClassName = $type->getName(); try { $rules = $this ->container ->make(\Spatie\LaravelData\Resolvers\DataValidationRulesResolver::class) ->execute( $spatieDataObjectClassName, [], \Spatie\LaravelData\Support\Validation\ValidationPath::create(), \Spatie\LaravelData\Support\Validation\DataRules::create() ); $ruleset = Ruleset::fromLaravelRules($rules); } catch (Throwable $throwable) { $throwable = new RulesExtractionError( throwable: $throwable, ); $ruleset = Ruleset::empty(); } return $this->schemaBuilder->buildSchemaFromRuleset($ruleset, rulesExtractionError: $throwable ?? null); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Extractor/Strategies/ExtractorStrategyContract.php
src/Modules/Routes/Extractor/Strategies/ExtractorStrategyContract.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\ExtractableRoute; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; interface ExtractorStrategyContract { public function matches(ExtractableRoute $extractableRoute): bool; public function extract(ExtractableRoute $extractableRoute): Schema; }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Extractor/Strategies/FormRequestExtractorStrategy.php
src/Modules/Routes/Extractor/Strategies/FormRequestExtractorStrategy.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies; use Illuminate\Http\Request; use Illuminate\Support\Arr; use PhpParser\Node; use PhpParser\NodeTraverser; use PhpParser\ParserFactory; use ReflectionClass; use ReflectionException; use ReflectionNamedType; use ReflectionParameter; use Sunchayn\Nimbus\Modules\Routes\Extractor\Ast\RulesMethodVisitor; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\ExtractableRoute; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\RulesExtractionError; use Sunchayn\Nimbus\Modules\Schemas\Builders\SchemaBuilder; use Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; use Throwable; /** * Extracts validation rules from Laravel Form Request classes. * * @example * Controller: public function store(StoreUserRequest $request) * FormRequest: rules() returns ['name' => 'required|string'] * Output: Schema with name field as required string */ class FormRequestExtractorStrategy implements ExtractorStrategyContract { public function __construct( private readonly SchemaBuilder $schemaBuilder, ) {} public function matches(ExtractableRoute $extractableRoute): bool { foreach ($extractableRoute->parameters as $parameter) { if (! $parameter->hasType()) { continue; } $type = $parameter->getType(); if (! $type instanceof ReflectionNamedType) { continue; } $parameterType = $type->getName(); // If Laravel Request is used, // we cannot figure out the schema from the request. if ($parameterType === Request::class) { return false; } // If it is not a form request instance, we continue. if (! is_subclass_of($parameterType, Request::class)) { continue; } return true; } return false; // <- didn't find a form request. } public function extract(ExtractableRoute $extractableRoute): Schema { $requestParameter = Arr::first( $extractableRoute->parameters, function (ReflectionParameter $reflectionParameter): bool { $type = $reflectionParameter->getType(); if (! $type instanceof ReflectionNamedType) { return false; } return is_subclass_of($type->getName(), Request::class); }, ); if (! $requestParameter) { return Schema::empty(); } $type = $requestParameter->getType(); if (! $type instanceof ReflectionNamedType) { return Schema::empty(); } /** @var class-string $requestClassName */ $requestClassName = $type->getName(); $instance = new $requestClassName; if (! method_exists($instance, 'rules')) { return Schema::empty(); } try { $rules = Ruleset::fromLaravelRules($instance->rules()); } catch (Throwable $throwable) { // We will give it one extra attempt to figure out the shape statically as much as possible. $rules = $this->attemptGettingRulesShape($requestClassName); $throwable = new RulesExtractionError( throwable: $throwable, ); } return $this->schemaBuilder->buildSchemaFromRuleset($rules, rulesExtractionError: $throwable ?? null); } /** * In some situations, the rules method might break due to dependency on request context, * or any other information that is not available when calling it statically. * * @param class-string $requestClassName */ private function attemptGettingRulesShape(string $requestClassName): Ruleset { if (! method_exists($requestClassName, 'rules')) { return Ruleset::empty(); } try { $fileName = (new ReflectionClass($requestClassName))->getFileName(); } catch (ReflectionException) { return Ruleset::empty(); } if (! $fileName || ! file_exists($fileName)) { return Ruleset::empty(); } $parser = (new ParserFactory)->createForNewestSupportedVersion(); $ast = $parser->parse(file_get_contents($fileName) ?: ''); if ($ast === null) { return Ruleset::empty(); } return $this->getRulesFromRequestAst($ast); } /** * @param Node[] $ast */ private function getRulesFromRequestAst(array $ast): Ruleset { $rulesMethodVisitor = new RulesMethodVisitor; $nodeTraverser = new NodeTraverser; $nodeTraverser->addVisitor($rulesMethodVisitor); $nodeTraverser->traverse($ast); return $rulesMethodVisitor->getRules(); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Extractor/Strategies/InlineRequestValidatorExtractorStrategy.php
src/Modules/Routes/Extractor/Strategies/InlineRequestValidatorExtractorStrategy.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies; use PhpParser\NodeTraverser; use Sunchayn\Nimbus\Modules\Routes\Extractor\Ast\ValidateCallVisitor; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\ExtractableRoute; use Sunchayn\Nimbus\Modules\Schemas\Builders\SchemaBuilder; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; class InlineRequestValidatorExtractorStrategy implements ExtractorStrategyContract { public function __construct( private readonly SchemaBuilder $schemaBuilder, ) {} public function matches(ExtractableRoute $extractableRoute): bool { // This strategy doesn't support anonymous routes for now. return $extractableRoute->methodName !== null; } public function extract(ExtractableRoute $extractableRoute): Schema { if (! $this->matches($extractableRoute)) { return Schema::empty(); } if ($extractableRoute->methodName === null) { return Schema::empty(); } $ast = ($extractableRoute->codeParser)(); if ($ast === null) { return Schema::empty(); } $validateCallVisitor = new ValidateCallVisitor($extractableRoute->methodName); $nodeTraverser = new NodeTraverser; $nodeTraverser->addVisitor($validateCallVisitor); $nodeTraverser->traverse($ast); return $this->schemaBuilder->buildSchemaFromRuleset($validateCallVisitor->getRules()); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Extractor/Ast/ValidateCallVisitor.php
src/Modules/Routes/Extractor/Ast/ValidateCallVisitor.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Extractor\Ast; use Illuminate\Http\Request; use Illuminate\Support\Arr; use PhpParser\Node; use PhpParser\Node\Expr\Assign; use PhpParser\Node\Expr\MethodCall; use PhpParser\Node\Expr\Variable; use PhpParser\Node\Identifier; use PhpParser\Node\Stmt\Expression; use PhpParser\NodeVisitor; use PhpParser\NodeVisitorAbstract; use Sunchayn\Nimbus\Modules\Routes\Extractor\Ast\Shared\QualifiesTypehint; use Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset; /** * Extracts validation rules from controller methods using AST analysis. * * Finds request validation calls (validate, validateWithBag) within controller * action methods and extracts their validation rule arguments. * * @example Controller: $request->validate(['name' => 'required|string']) * @example Output: ['name' => 'required|string'] */ class ValidateCallVisitor extends NodeVisitorAbstract { use QualifiesTypehint; private const SUPPORTED_VALIDATION_METHODS = ['validate', 'validateWithBag']; private string $targetControllerMethod; /** @var array<string, Node\Stmt\ClassMethod> */ private array $classMethodNodes = []; private ?Ruleset $rules = null; /** @var array<string, mixed> Variables defined within the method */ private array $context = []; public function __construct(string $routeActionMethod) { $this->targetControllerMethod = $routeActionMethod; } public function beforeTraverse(array $nodes): array { $this->gatherClassMethods($nodes); return $this->qualifyClassTypeHinting($nodes); } public function getRules(): Ruleset { return $this->rules ?? Ruleset::fromLaravelRules([]); } public function enterNode(Node $node): null|int|Node|array { if (! $this->isTargetControllerMethod($node)) { return null; } /** @var Node\Stmt\ClassMethod $node */ $this->extractValidationRules($node); return NodeVisitor::STOP_TRAVERSAL; } private function isTargetControllerMethod(Node $node): bool { return $node instanceof Node\Stmt\ClassMethod && $node->name->toString() === $this->targetControllerMethod; } private function extractValidationRules(Node\Stmt\ClassMethod $classMethod): void { // TODO [Enhancement] Support validation rules from wrapped method calls (e.g., $this->validateFormData(..)). if ($classMethod->stmts === null) { return; } foreach ($classMethod->stmts as $statement) { if (! ($statement instanceof Expression)) { continue; } if ($statement->expr instanceof Assign) { $this->storeVariableAssignment($statement->expr); } $expression = $this->extractExpressionFromNode($statement); if ($this->isEligibleMethodCall($expression, $classMethod)) { /** @var MethodCall $expression */ $this->processValidationCall($expression); } } } private function extractExpressionFromNode(Expression $expression): Node\Expr { return match (true) { $expression->expr instanceof Assign => $expression->expr->expr, default => $expression->expr, }; } private function isEligibleMethodCall( Node\Expr $expr, Node\Stmt\ClassMethod $classMethod ): bool { if (! ($expr instanceof MethodCall)) { return false; } if (! ($expr->name instanceof Identifier)) { return false; } if (! in_array($expr->name->toString(), self::SUPPORTED_VALIDATION_METHODS)) { return false; } return $this->isCalledOnRequestInstance($expr, $classMethod); } private function isCalledOnRequestInstance( MethodCall $methodCall, Node\Stmt\ClassMethod $classMethod ): bool { if (! ($methodCall->var instanceof Variable) || ! is_string($methodCall->var->name)) { return true; // <- Assume it's valid if we can't determine the variable. } $varName = $methodCall->var->name; $matchingParameter = Arr::first( $classMethod->params, fn (Node\Param $param): bool => $param->var instanceof Variable && $param->var->name === $varName, ); if ($matchingParameter === null) { return false; } $type = $matchingParameter->type->name ?? null; return $type === Request::class || is_subclass_of($type, Request::class); } private function processValidationCall(MethodCall $methodCall): void { $methodName = $methodCall->name instanceof Node\Identifier ? $methodCall->name->toString() : null; $argNode = $this->extractValidationRulesArgument($methodCall, $methodName); if (! $argNode instanceof \PhpParser\Node) { return; } if ($this->isNestedMethodCall($argNode)) { /** @var Identifier $argIdentifier */ $argIdentifier = $argNode->name; $this->processNestedMethodCall(methodName: $argIdentifier->name); return; } $this->rules = Ruleset::fromLaravelRules( ConvertNodeToConcreteValue::process($argNode, $this->context) ); } private function extractValidationRulesArgument(MethodCall $methodCall, ?string $methodName): ?Node { return match ($methodName) { 'validate' => $methodCall->args[0]->value ?? null, 'validateWithBag' => $methodCall->args[1]->value ?? null, default => null, }; } /** * @phpstan-assert-if-true MethodCall $argNode */ private function isNestedMethodCall(Node $argNode): bool { if (! ($argNode instanceof MethodCall)) { return false; } if (! ($argNode->name instanceof Identifier)) { return false; } return array_key_exists($argNode->name->name, $this->classMethodNodes); } private function processNestedMethodCall(string $methodName): void { $nestedMethod = $this->classMethodNodes[$methodName]; $this->extractRulesFromReturnStatement($nestedMethod); } private function extractRulesFromReturnStatement(Node\Stmt\ClassMethod $classMethod): void { /** @var Node\Stmt\Return_|null $returnStatement */ $returnStatement = Arr::first( $classMethod->stmts ?? [], fn ($stmt): bool => $stmt instanceof Node\Stmt\Return_, ); if ($returnStatement === null || ! $this->isArrayReturn($returnStatement)) { return; } // TODO [Enhancement] Account for nested method calls in return statements $this->addMethodVariablesToContext($classMethod); if (! ($returnStatement->expr instanceof Node)) { return; } $this->rules = Ruleset::fromLaravelRules( ConvertNodeToConcreteValue::process($returnStatement->expr, $this->context) ); } private function isArrayReturn(Node\Stmt\Return_ $return): bool { return $return->expr instanceof Node\Expr\Array_; } private function addMethodVariablesToContext(Node\Stmt\ClassMethod $classMethod): void { if ($classMethod->stmts === null) { return; } foreach ($classMethod->stmts as $statement) { if (! property_exists($statement, 'expr')) { continue; } if (! ($statement->expr instanceof Assign)) { continue; } $this->storeVariableAssignment($statement->expr); } } private function storeVariableAssignment(Assign $assign): void { if ($assign->expr instanceof MethodCall) { return; } if (! ($assign->var instanceof Variable) || ! is_string($assign->var->name)) { return; } $this->context[$assign->var->name] = ConvertNodeToConcreteValue::process( $assign->expr, $this->context ); } /** * Find all nodes that are a class method node. * * @param Node[] $nodes */ private function gatherClassMethods(array $nodes): void { /** @var Node\Stmt\Class_|null $classNode */ $classNode = Arr::first( $nodes, fn (Node $node): bool => $node instanceof Node\Stmt\Class_ ); if ($classNode === null) { return; } foreach ($classNode->stmts as $stmt) { if ($stmt instanceof Node\Stmt\ClassMethod) { $this->classMethodNodes[$stmt->name->name] = $stmt; } } } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Extractor/Ast/ConvertNodeToConcreteValue.php
src/Modules/Routes/Extractor/Ast/ConvertNodeToConcreteValue.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Extractor\Ast; use PhpParser\Node; use PhpParser\Node\Arg; use PhpParser\Node\Expr; use PhpParser\Node\Identifier; use PhpParser\Node\Name; use PhpParser\Node\VariadicPlaceholder; /** * Converts AST nodes into their concrete PHP values. * * @example Node\Scalar\LNumber(2) -> 2 * @example Node\Expr\Array_([2, 'example']) -> [2, 'example'] * @example Node\Expr\New_(SomeClass) -> new SomeClass() */ class ConvertNodeToConcreteValue { /** * @param array<string, mixed> $variablesContext */ public static function process(Node $node, array $variablesContext = []): mixed { return match (true) { $node instanceof Node\Scalar\String_ => $node->value, $node instanceof Node\Scalar\LNumber => $node->value, $node instanceof Node\Scalar\DNumber => $node->value, $node instanceof Node\Expr\Array_ => self::resolveArray($node, $variablesContext), $node instanceof Node\Expr\Variable => self::resolveVariable($node, $variablesContext), $node instanceof Node\Expr\StaticCall => self::resolveStaticCall($node, $variablesContext), $node instanceof Expr\New_ => self::resolveNewInstance($node, $variablesContext), $node instanceof Node\Expr\ConstFetch => self::resolveConstant($node), $node instanceof Node\Expr\BinaryOp\Concat => self::resolveConcatenation($node, $variablesContext), $node instanceof Node\Scalar\InterpolatedString => self::resolveInterpolatedString($node, $variablesContext), $node instanceof Node\InterpolatedStringPart => $node->value, $node instanceof Expr\ClassConstFetch && $node->class instanceof Name => $node->class->name, default => null, }; } /** * @param array<string, mixed> $variablesContext * @return array<array-key, mixed> */ private static function resolveArray(Node\Expr\Array_ $array, array $variablesContext): array { $result = []; foreach ($array->items as $item) { $value = self::process($item->value, $variablesContext); if ($item->key === null) { $result[] = $value; continue; } $key = self::process($item->key, $variablesContext); $result[$key] = $value; } return $result; } /** * @param array<string, mixed> $variablesContext */ private static function resolveVariable(Node\Expr\Variable $variable, array $variablesContext): mixed { $varName = $variable->name; if (! is_string($varName)) { return null; } return $variablesContext[$varName] ?? null; } /** * @param array<string, mixed> $variablesContext */ private static function resolveStaticCall(Node\Expr\StaticCall $staticCall, array $variablesContext): mixed { $arguments = array_filter( // <- TODO [Test] make sure to assert this filter if not already. array_map( function (Arg|VariadicPlaceholder $argNode) use ($variablesContext): mixed { if ($argNode instanceof VariadicPlaceholder) { return null; } return self::process($argNode->value, $variablesContext); }, $staticCall->args, ), ); // If we failed to resolve all arguments, return null to avoid incomplete values if (count($arguments) !== count($staticCall->args)) { return null; } if (! ($staticCall->name instanceof Identifier)) { return null; } if (! ($staticCall->class instanceof Name)) { return null; } return $staticCall->class->name::{$staticCall->name->name}(...$arguments); } /** * @param array<string, mixed> $variablesContext */ private static function resolveNewInstance(Expr\New_ $new, array $variablesContext): ?object { $arguments = array_filter( // <- TODO [Test] make sure to assert this filter if not already. array_map( function (Arg|VariadicPlaceholder $argNode) use ($variablesContext): mixed { if ($argNode instanceof VariadicPlaceholder) { return null; } return self::process($argNode->value, $variablesContext); }, $new->args, ), ); // If we failed to resolve all arguments, return null to avoid incomplete values if (count($arguments) !== count($new->args)) { return null; } if (! ($new->class instanceof Name)) { return null; } return new $new->class->name(...$arguments); } private static function resolveConstant(Node\Expr\ConstFetch $constFetch): mixed { return constant($constFetch->name->toString()); } /** * @param array<string, mixed> $variablesContext */ private static function resolveConcatenation(Node\Expr\BinaryOp\Concat $concat, array $variablesContext): string { return self::process($concat->left, $variablesContext).self::process($concat->right, $variablesContext); } /** * @param array<string, mixed> $variablesContext */ private static function resolveInterpolatedString(Node\Scalar\InterpolatedString $interpolatedString, array $variablesContext): string { return array_reduce( $interpolatedString->parts, fn ($carry, $current): string => $carry.self::process($current, $variablesContext), initial: '', ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Extractor/Ast/RulesMethodVisitor.php
src/Modules/Routes/Extractor/Ast/RulesMethodVisitor.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Extractor\Ast; use PhpParser\Node; use PhpParser\NodeVisitor; use PhpParser\NodeVisitorAbstract; use Sunchayn\Nimbus\Modules\Routes\Extractor\Ast\Shared\QualifiesTypehint; use Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset; /** * Extracts validation rules from FormRequest's `rules()` method. * * Walks through a class AST to find the `rules()` method and extracts * its return statement to determine the validation rules array. */ class RulesMethodVisitor extends NodeVisitorAbstract { use QualifiesTypehint; private ?Ruleset $rules = null; /** @var array<string, mixed> Variables defined within the rules() method */ private array $variablesContext = []; public function beforeTraverse(array $nodes): array { return $this->qualifyClassTypeHinting($nodes); } public function getRules(): Ruleset { return $this->rules ?? Ruleset::fromLaravelRules([]); } public function enterNode(Node $node): null|int|Node|array { if (! $this->isRulesMethod($node)) { return null; } /** @var Node\Stmt\ClassMethod $node */ $this->extractRulesFromMethod($node); return NodeVisitor::STOP_TRAVERSAL; } private function isRulesMethod(Node $node): bool { return $node instanceof Node\Stmt\ClassMethod && $node->name->toString() === 'rules'; } private function extractRulesFromMethod(Node\Stmt\ClassMethod $classMethod): void { if ($classMethod->stmts === null) { return; } foreach ($classMethod->stmts as $stmt) { if ($stmt instanceof Node\Stmt\Return_) { $this->processReturnStatement($stmt); continue; } if ($stmt instanceof Node\Stmt\Expression && $stmt->expr instanceof Node\Expr\Assign) { $this->addVariableValueToContext($stmt->expr); } } } private function processReturnStatement(Node\Stmt\Return_ $return): void { if (! $return->expr instanceof \PhpParser\Node\Expr) { return; } $rules = ConvertNodeToConcreteValue::process($return->expr, $this->variablesContext); if (is_array($rules)) { $this->rules = Ruleset::fromLaravelRules($rules); } } private function addVariableValueToContext(Node\Expr\Assign $assign): void { if (! ($assign->var instanceof Node\Expr\Variable)) { return; } if (! is_string($assign->var->name)) { return; } $this->variablesContext[$assign->var->name] = ConvertNodeToConcreteValue::process($assign->expr, $this->variablesContext); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Extractor/Ast/Shared/QualifiesTypehint.php
src/Modules/Routes/Extractor/Ast/Shared/QualifiesTypehint.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Extractor\Ast\Shared; use PhpParser\Node; use PhpParser\NodeTraverser; use PhpParser\NodeVisitor\NameResolver; /** * @codeCoverageIgnore covered in used classes. */ trait QualifiesTypehint { /** * Normalizes how classes are referenced in type hinting so that we can have more conclusive equality checks later on. * * @param Node[] $nodes * @return Node[] $nodes */ protected function qualifyClassTypeHinting(array $nodes): array { $nodeTraverser = new NodeTraverser; $nodeTraverser->addVisitor(new NameResolver); return $nodeTraverser->traverse($nodes); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Collections/ExtractedRoutesCollection.php
src/Modules/Routes/Collections/ExtractedRoutesCollection.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Collections; use Illuminate\Support\Collection; use Illuminate\Support\Str; use Sunchayn\Nimbus\Modules\Routes\DataTransferObjects\ExtractedRoute; /** * @phpstan-import-type SchemaShape from \Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema * * @phpstan-type RouteDefinitionShape array{ * uri: string, * shortUri: string, * methods: string[], * schema: SchemaShape, * extractionError: string, * } * * @extends Collection<array-key, ExtractedRoute> */ class ExtractedRoutesCollection extends Collection { /** * @return array<string, array<string, RouteDefinitionShape[]>> */ public function toFrontendArray(): array { /** @var Collection<string, self> $groupedByVersion */ $groupedByVersion = $this->groupBy(static fn (ExtractedRoute $extractedRoute): string => $extractedRoute->uri->version); return $groupedByVersion ->map( static function (self $group): Collection { /** @var Collection<string, self> $groupedByResource */ $groupedByResource = $group ->groupBy(static fn (ExtractedRoute $extractedRoute): string => $extractedRoute->uri->resource); return $groupedByResource ->map( static fn (self $group): Collection => $group->map( static fn (ExtractedRoute $extractedRoute): array => [ 'uri' => $extractedRoute->uri->value, 'shortUri' => Str::replaceStart('/', '', $extractedRoute->uri->getShortUri()), 'methods' => $extractedRoute->methods, 'schema' => $extractedRoute->schema->toJsonSchema(), 'extractionError' => $extractedRoute->schema->extractionError?->toHtml(), ], ), ); }, ) ->toArray(); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Services/IgnoredRoutesService.php
src/Modules/Routes/Services/IgnoredRoutesService.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Services; use Carbon\CarbonImmutable; use Illuminate\Contracts\Filesystem\FileNotFoundException; use Illuminate\Routing\Route; use Illuminate\Support\Facades\File; /** * Manages routes that should be excluded from schema extraction. * * Persists ignored routes to vendor directory to survive package updates, * allowing developers to maintain a blacklist of problematic routes. */ class IgnoredRoutesService { private const STORAGE_PATH = 'vendor/sunchayn/nimbus/storage/ignored_routes.json'; /** @var array<string, non-empty-array{methods: string[], reason: string, ignored_at: string}> */ private array $ignoredRoutes = []; private bool $isDirty = false; public function __construct() { $this->loadFromFile(); } public function __destruct() { if (! $this->isDirty) { return; } $this->writeToFile(); } /** * Adds a route to the ignored list with a reason for exclusion. * * Routes are ignored when extraction fails or when developers * explicitly want to exclude them from schema generation. * * @param non-empty-string $uri * @param array<int, string> $methods * @param non-empty-string $reason */ public function add(string $uri, array $methods, string $reason = 'Route extraction failed'): void { $routeData = [ 'methods' => $methods, 'reason' => $reason, 'ignored_at' => CarbonImmutable::now()->toISOString() ?? date('Y-m-d H:i:s'), ]; $this->ignoredRoutes[$uri] = $routeData; $this->isDirty = true; } /** * Removes specific HTTP methods from an ignored route. * * If all methods are removed, the entire route is removed from * the ignored list, allowing it to be processed again. * * @param non-empty-string $uri * @param array<int, string> $methods */ public function remove(string $uri, array $methods): void { if (! isset($this->ignoredRoutes[$uri])) { return; } $this->ignoredRoutes[$uri]['methods'] = array_diff($this->ignoredRoutes[$uri]['methods'], $methods); if (empty($this->ignoredRoutes[$uri]['methods'])) { unset($this->ignoredRoutes[$uri]); } $this->isDirty = true; } /** * Checks if a route should be ignored during schema extraction. * * A route is ignored if any of its HTTP methods are in the ignored list, * allowing partial ignoring of routes with multiple methods. */ public function isIgnored(Route $route): bool { $ignoredRoute = $this->ignoredRoutes[$route->uri()] ?? null; if ($ignoredRoute === null) { return false; } foreach ($route->methods() as $method) { if (in_array($method, $ignoredRoute['methods'])) { return true; } } return false; } /** * Checks if there are any ignored routes without loading full data. * * Performs a lightweight check to avoid unnecessary file operations * when no routes are ignored. */ public function hasIgnoredRoutes(): bool { if ($this->ignoredRoutes !== []) { return true; } try { $content = File::get(base_path(self::STORAGE_PATH)); } catch (FileNotFoundException) { return false; } if ($content === '[]') { return false; } json_decode($content); return json_last_error() === JSON_ERROR_NONE; } /** * Loads ignored routes from persistent storage. * * Gracefully handles missing or corrupted files by defaulting * to an empty ignored routes list. */ private function loadFromFile(): void { $filePath = base_path(self::STORAGE_PATH); if (! File::exists($filePath)) { $this->ignoredRoutes = []; return; } $content = File::get($filePath); $this->ignoredRoutes = json_decode($content, true) ?: []; } /** * Persists ignored routes to storage with automatic directory creation. * * Creates the storage directory if it doesn't exist and ensures * the file is always valid JSON, even if encoding fails. */ private function writeToFile(): void { $filePath = base_path(self::STORAGE_PATH); $directory = dirname($filePath); if (! File::exists($directory)) { File::makeDirectory($directory, 0755, true); } File::put( $filePath, json_encode($this->ignoredRoutes, JSON_PRETTY_PRINT) ?: '[]' ); $this->isDirty = false; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Services/Uri/UriContract.php
src/Modules/Routes/Services/Uri/UriContract.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Services\Uri; interface UriContract { public function getVersion(): string; public function getResource(): string; }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Services/Uri/VersionedUri.php
src/Modules/Routes/Services/Uri/VersionedUri.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Services\Uri; use Sunchayn\Nimbus\Modules\Routes\Services\Uri\Concerns\CleansUriPrefix; class VersionedUri implements UriContract { use CleansUriPrefix; /** * Clean parts are everything after the route prefix without empty strings. * * @var string[] */ private array $cleanParts; public function __construct( public string $value, public string $routesPrefix, ) { $this->cleanParts = $this->parseUriPartsAfterPrefixIfItExists(); } public function getVersion(): string { if ($this->cleanParts !== [] && $this->isVersionPart($this->cleanParts[0])) { return $this->cleanParts[0]; } return 'v1'; } public function getResource(): string { // If there's a version part, skip it to get the resource. if ($this->cleanParts !== [] && $this->isVersionPart($this->cleanParts[0])) { return $this->cleanParts[1] ?? ''; } // If there's no version part, the first part is the resource. return $this->cleanParts[0] ?? ''; } private function isVersionPart(string $part): bool { // Check if the part looks like a version (e.g., v1, v2, 1.0, etc.). return preg_match('/^v\d+$/', $part) || preg_match('/^\d+\.\d+$/', $part); } /** * @return string[] */ private function parseUriPartsAfterPrefixIfItExists(): array { if (! filled($this->routesPrefix)) { return array_values( array_filter(explode('/', $this->value), fn ($part): bool => $part !== ''), ); } return $this->parseUriPartsAfterPrefix( prefix: $this->routesPrefix, uri: $this->value, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Services/Uri/NonVersionedUri.php
src/Modules/Routes/Services/Uri/NonVersionedUri.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Services\Uri; use Sunchayn\Nimbus\Modules\Routes\Services\Uri\Concerns\CleansUriPrefix; class NonVersionedUri implements UriContract { use CleansUriPrefix; public function __construct( public string $value, public string $routesPrefix, ) {} public function getVersion(): string { return 'n/a'; } public function getResource(): string { return $this->parseUriPartsAfterPrefixIfItExists()[0] ?? ''; } /** * @return string[] */ private function parseUriPartsAfterPrefixIfItExists(): array { if (! filled($this->routesPrefix)) { return array_values( array_filter(explode('/', $this->value), fn ($part): bool => $part !== ''), ); } return $this->parseUriPartsAfterPrefix( prefix: $this->routesPrefix, uri: $this->value, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Services/Uri/Concerns/CleansUriPrefix.php
src/Modules/Routes/Services/Uri/Concerns/CleansUriPrefix.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Services\Uri\Concerns; trait CleansUriPrefix { /** * @return string[] */ protected function parseUriPartsAfterPrefix(string $prefix, string $uri): array { $parts = explode('/', $uri); $cleanParts = array_values(array_filter($parts, fn ($part): bool => $part !== '')); // Convert the prefix string (e.g. "app/api" or "api") into an array of parts: ["app", "api"] or ["api"]. $prefixParts = explode('/', trim($prefix, '/')); // Iterate through each prefix part and remove matching items from the start of $parts. foreach ($prefixParts as $index => $prefixPart) { // Stop checking once we hit a mismatch. if (! isset($cleanParts[$index]) || $cleanParts[$index] !== $prefixPart) { break; } unset($cleanParts[$index]); } return array_values($cleanParts); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/ValueObjects/ExtractableRoute.php
src/Modules/Routes/ValueObjects/ExtractableRoute.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\ValueObjects; use Closure; use PhpParser\Node; use ReflectionParameter; class ExtractableRoute { /** * @param ReflectionParameter[] $parameters * @param Closure() : (Node[]|null) $codeParser */ public function __construct( public readonly array $parameters, public readonly Closure $codeParser, public readonly ?string $methodName = null, public readonly ?string $controllerClass = null, public readonly ?string $controllerMethod = null, ) {} public static function empty(): self { return new self( parameters: [], codeParser: fn (): array => [], ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/ValueObjects/Endpoint.php
src/Modules/Routes/ValueObjects/Endpoint.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\ValueObjects; use RuntimeException; use Sunchayn\Nimbus\Modules\Routes\Services\Uri\NonVersionedUri; use Sunchayn\Nimbus\Modules\Routes\Services\Uri\VersionedUri; readonly class Endpoint { public function __construct( public string $version, public string $resource, public string $value, ) {} public static function fromRaw(string $uri, string $routesPrefix, bool $isVersioned): self { $uriObject = $isVersioned ? new VersionedUri($uri, routesPrefix: $routesPrefix) : new NonVersionedUri($uri, routesPrefix: $routesPrefix); return new self( version: $uriObject->getVersion(), resource: $uriObject->getResource(), value: $uri, ); } public function getShortUri(): string { if ($this->resource === '') { throw new RuntimeException('Invalid ValueObject. The resource cannot be empty.'); } $resourcePos = strpos($this->value, '/'.$this->resource); if ($resourcePos === false) { throw new RuntimeException('Invalid ValueObject. The `resource` MUST exist in the URI.'); } // To get the short URL, we remove everything before the resource. // This will include things like the versioning and the API prefix when provided. // @example /rest-api/v1/users/{user} -> /users/{user} // @example users/{user} -> users/{user} return substr($this->value, $resourcePos); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/ValueObjects/RulesExtractionError.php
src/Modules/Routes/ValueObjects/RulesExtractionError.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\ValueObjects; use Illuminate\Support\Str; use Throwable; class RulesExtractionError { public function __construct( private readonly Throwable $throwable, ) {} public function toHtml(): string { $errorMessage = filled($this->throwable->getMessage()) ? $this->throwable->getMessage() : '[no error message]'; $trace = Str::replace("\n", '<br >', $this->throwable->getTraceAsString()); return <<<ERROR_HTML <b>{$errorMessage}</b><br /> <small>{$this->throwable->getFile()}::{$this->throwable->getLine()}</small> <p class="text-xs">{$trace}</p> ERROR_HTML; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/Factories/ExtractableRouteFactory.php
src/Modules/Routes/Factories/ExtractableRouteFactory.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\Factories; use Closure; use Illuminate\Routing\Route; use PhpParser\Node; use PhpParser\Parser; use PhpParser\ParserFactory; use ReflectionClass; use ReflectionException; use ReflectionParameter; use Sunchayn\Nimbus\Modules\Routes\Exceptions\InvalidRouteDefinitionException; use Sunchayn\Nimbus\Modules\Routes\Exceptions\RouteExtractionException; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\ExtractableRoute; /** * Creates ExtractableRoute objects from Laravel Route instances. * * Handles the complexity of parsing `controller@method` syntax, validating * controller existence, and preparing code analysis tools for validation extraction. */ class ExtractableRouteFactory { private static ?ParserFactory $parserFactory = null; /** * Converts a Laravel route into an ExtractableRoute for validation analysis. * * @throws RouteExtractionException */ public function fromLaravelRoute(Route $route): ExtractableRoute { $uses = $route->getAction('uses'); // Currently only supports controller@method routes. Closure-based routes // would require different extraction strategies and are not yet supported if (! is_string($uses) || $this->isSerializedRoute($uses)) { return ExtractableRoute::empty(); } $parts = explode('@', $uses); $controllerClassName = $parts[0]; $controllerMethod = $parts[1] ?? ''; if ($controllerClassName === '' || $controllerClassName === '0' || ($controllerMethod === '' || $controllerMethod === '0')) { throw InvalidRouteDefinitionException::forRoute( routeUri: $route->uri(), routeMethods: $route->methods(), controllerClass: $controllerClassName, controllerMethod: $controllerMethod, ); } /** @var class-string $controllerClassName */ $methodInfo = $this->getMethodInfo($controllerClassName, $controllerMethod); if ($methodInfo === null) { throw InvalidRouteDefinitionException::forRoute( routeUri: $route->uri(), routeMethods: $route->methods(), controllerClass: $controllerClassName, controllerMethod: $controllerMethod, ); } return new ExtractableRoute( parameters: $methodInfo['parameters'], codeParser: $this->getCodeParserFor($methodInfo['fileName']), methodName: $controllerMethod, controllerClass: $controllerClassName, controllerMethod: $controllerMethod, ); } /** * Validates controller and method existence, returning metadata for extraction. * * Returns null if the controller class or method doesn't exist, allowing * the factory to handle missing controllers gracefully with proper exceptions. * * @param class-string $class * @param non-empty-string $method * @return null|array{ * parameters: array<int, ReflectionParameter>, * fileName: non-empty-string * } */ private function getMethodInfo(string $class, string $method): ?array { if (! class_exists($class)) { return null; } if (! method_exists($class, $method)) { return null; } $fileName = (new ReflectionClass($class))->getFileName(); if ($fileName === false) { return null; } $parameters = $this->getMethodParameters($class, $method); return [ 'parameters' => $parameters, 'fileName' => $fileName, ]; } private function isSerializedRoute(string $value): bool { return str_starts_with($value, 'a:') || str_starts_with($value, 'O:'); } /** * Extracts method parameters for validation analysis. * * Method parameters are needed to identify FormRequest classes that * contain validation rules for extraction. * * @param class-string $class * @param non-empty-string $method * @return array<int, ReflectionParameter> */ private function getMethodParameters(string $class, string $method): array { try { $reflectionClass = new ReflectionClass($class); $reflectionMethod = $reflectionClass->getMethod($method); } catch (ReflectionException) { return []; } return $reflectionMethod->getParameters(); } /** * Creates a parser closure for the controller file. * * Uses rescue() to prevent parsing errors from crashing the application * when controller files contain syntax errors or are unreadable. * * @param non-empty-string $fileName * @return Closure(): (Node[]|null) */ private function getCodeParserFor(string $fileName): Closure { return fn (): ?array => rescue( fn (): ?array => $this->getParser()->parse(file_get_contents($fileName) ?: ''), report: false, ); } /** * Provides a singleton PHP parser instance. * * ParserFactory is expensive to create, so we reuse a single instance * across all route extractions for better performance. */ private function getParser(): Parser { if (! self::$parserFactory instanceof \PhpParser\ParserFactory) { self::$parserFactory = new ParserFactory; } return self::$parserFactory->createForNewestSupportedVersion(); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/DataTransferObjects/ExtractedRoute.php
src/Modules/Routes/DataTransferObjects/ExtractedRoute.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\DataTransferObjects; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\Endpoint; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; /** * @codeCoverageIgnore a DTO with no behavior. */ class ExtractedRoute { /** * @param string[] $methods */ public function __construct( public readonly Endpoint $uri, public readonly array $methods, public readonly Schema $schema, ) {} }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Modules/Routes/DataTransferObjects/IgnoreRouteErrorData.php
src/Modules/Routes/DataTransferObjects/IgnoreRouteErrorData.php
<?php namespace Sunchayn\Nimbus\Modules\Routes\DataTransferObjects; /** * @codeCoverageIgnore a DTO with no behavior. */ readonly class IgnoreRouteErrorData { /** * @param string[] $methods */ public function __construct( public string $uri, public array $methods, ) {} }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/src/Commands/Intellisense/GenerateIntellisenseCommand.php
src/Commands/Intellisense/GenerateIntellisenseCommand.php
<?php namespace Sunchayn\Nimbus\Commands\Intellisense; use Carbon\CarbonImmutable; use Illuminate\Support\Str; use RuntimeException; use Sunchayn\Nimbus\IntellisenseProviders; use Sunchayn\Nimbus\IntellisenseProviders\Contracts\IntellisenseContract; use Symfony\Component\Console\Command\Command as SymfonyCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Throwable; /** * Generates TypeScript intellisense files for the BE centric features. */ class GenerateIntellisenseCommand extends SymfonyCommand { /** @var array<int, class-string<IntellisenseContract>> */ protected array $intellisenseProviders = [ IntellisenseProviders\AuthorizationTypeIntellisense::class, IntellisenseProviders\RandomValueGeneratorIntellisense::class, IntellisenseProviders\DumpValueTypeIntellisense::class, ]; const TARGET_BASE_PATH = '/resources/js/interfaces/generated/'; /** * Configures the command with its name, description, and options. */ protected function configure(): void { $this ->setName('generate-intellisense') ->setDescription('Generate TypeScript intellisense files from Laravel enums and configurations to resources/js/interfaces/generated/'); } /** * Executes the intellisense generation process. * * Processes each registered intellisense generator and creates * the corresponding TypeScript files in the target directory. */ protected function execute(InputInterface $input, OutputInterface $output): int { $this->printHeader($output); $output->writeln(' >> <info>Generating TypeScript Intellisense...</info>'); foreach ($this->intellisenseProviders as $intellisenseProvider) { /** @var IntellisenseContract $instance */ $instance = new $intellisenseProvider; $output->writeln(' > Generating '.$instance->getTargetFileName()); try { $content = $this->getFileHeader().$instance->generate(); $targetPath = $this->getTargetPath($instance->getTargetFileName()); $this->createDirectoryIfItDoesntExist(dirname($targetPath)); file_put_contents($targetPath, $content); $output->writeln('<info>✓ Generated.</info>'); } catch (Throwable $throwable) { $output->writeln(''); $output->writeln('<error>Failed to generate:</error>.'); $output->writeln($throwable->getMessage()); $output->writeln(''); return self::FAILURE; } } $output->writeln("\n<info>✓ All Intellisense generated successfully!</info>"); return self::SUCCESS; } /** * Constructs the target path for the generated file. * * Files are generated in the resources/js/interfaces/generated/ directory * to maintain organization and avoid conflicts with other generated files. */ private function getTargetPath(string $filename): string { return getcwd().self::TARGET_BASE_PATH.$filename; } /** * Ensures the target directory exists before writing files. */ private function createDirectoryIfItDoesntExist(string $directory): void { if (is_dir($directory)) { return; } mkdir($directory, 0755, true); } private function getFileHeader(): string { return Str::replace( '{{ date }}', CarbonImmutable::now()->toIso8601String(), file_get_contents(__DIR__.'/stubs/intellisense-header.stub') ?: throw new RuntimeException('Cannot load header stub.'), ); } /* * UI Helpers. */ private function printHeader(OutputInterface $output): void { $output->write(<<<HEAD _ _ _ _ ___ _ _ _ _ ____ | \ | (_)_ __ ___ | |__ _ _ ___ |_ _|_ __ | |_ ___| | (_) ___| ___ _ __ ___ ___ | \| | | '_ ` _ \| '_ \| | | / __| | || '_ \| __/ _ \ | | \___ \ / _ \ '_ \/ __|/ _ \ | |\ | | | | | | | |_) | |_| \__ \ | || | | | || __/ | | |___) | __/ | | \__ \ __/ |_| \_|_|_| |_| |_|_.__/ \__,_|___/ |___|_| |_|\__\___|_|_|_|____/ \___|_| |_|___/\___| HEAD); $output->writeln("\n"); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/TestCase.php
tests/TestCase.php
<?php namespace Sunchayn\Nimbus\Tests; use Illuminate\Support\Facades\Http; use Mockery; use Orchestra\Testbench\TestCase as BaseTestCase; use Sunchayn\Nimbus\NimbusServiceProvider; class TestCase extends BaseTestCase { protected function setUp(): void { parent::setUp(); config([ 'nimbus.prefix' => 'nimbus', 'nimbus.routes.prefix' => 'api', 'nimbus.routes.versioned' => false, 'nimbus.headers' => [ 'x-request-id' => 'uuid', 'x-session-id' => 'uuid', ], 'force', ]); Http::preventStrayRequests(); } protected function tearDown(): void { if ($container = Mockery::getContainer()) { $this->addToAssertionCount($container->mockery_getExpectationCount()); } Mockery::close(); parent::tearDown(); } protected function getPackageProviders($app): array { return [ NimbusServiceProvider::class, ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/Integration/NimbusIndexTest.php
tests/Integration/NimbusIndexTest.php
<?php namespace Sunchayn\Nimbus\Tests\Integration; use Generator; use Illuminate\Support\Facades\Vite; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use Sunchayn\Nimbus\Http\Web\Controllers\NimbusIndexController; use Sunchayn\Nimbus\Modules\Routes\Actions\BuildCurrentUserAction; use Sunchayn\Nimbus\Modules\Routes\Actions\BuildGlobalHeadersAction; use Sunchayn\Nimbus\Modules\Routes\Actions\DisableThirdPartyUiAction; use Sunchayn\Nimbus\Modules\Routes\Actions\ExtractRoutesAction; use Sunchayn\Nimbus\Modules\Routes\Collections\ExtractedRoutesCollection; use Sunchayn\Nimbus\Modules\Routes\Exceptions\RouteExtractionException; use Sunchayn\Nimbus\Modules\Routes\Services\IgnoredRoutesService; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(NimbusIndexController::class)] #[CoversClass(NimbusIndexController::class)] class NimbusIndexTest extends TestCase { protected function defineRoutes($router): void { $router ->post('/api/test', fn () => response()->json(['message' => 'success'])) ->name('api.test'); } protected function setUp(): void { parent::setUp(); // Mock Vite to prevent asset loading issues Vite::shouldReceive('useBuildDirectory')->with('/vendor/nimbus')->once(); Vite::shouldReceive('useHotFile')->with(base_path('/vendor/sunchayn/nimbus/resources/dist/hot'))->once(); Vite::shouldReceive('__invoke')->andReturn('<script src="/nimbus/app.js"></script>'); } #[DataProvider('indexRouteProvider')] public function test_it_loads_view_correctly(string $uri): void { // Arrange $disableThirdPartyUiActionSpy = $this->spy(DisableThirdPartyUiAction::class); $ignoreRoutesServiceSpy = $this->spy(IgnoredRoutesService::class); $buildGlobalHeadersActionMock = $this->mock(BuildGlobalHeadersAction::class); $buildCurrentUserActionMock = $this->mock(BuildCurrentUserAction::class); $extractRoutesActionMock = $this->mock(ExtractRoutesAction::class); // Anticipate $buildGlobalHeadersActionMock->shouldReceive('execute')->andReturn(['::global-headers::']); $buildCurrentUserActionMock->shouldReceive('execute')->andReturn(['::current-user::']); $extractedRoutesCollectionStub = new class extends ExtractedRoutesCollection { public function toFrontendArray(): array { return ['::extracted-routes::']; } }; $extractRoutesActionMock->shouldReceive('execute')->andReturn($extractedRoutesCollectionStub); // Act $response = $this->get(route('nimbus.index').$uri); // Assert $response->assertStatus(200); $response->assertViewIs('nimbus::app'); $response->assertViewHas('routes', ['::extracted-routes::']); $response->assertViewHas('headers', ['::global-headers::']); $response->assertViewHas('currentUser', ['::current-user::']); $disableThirdPartyUiActionSpy->shouldHaveReceived('execute')->once(); $ignoreRoutesServiceSpy->shouldNotHaveReceived('execute'); } public static function indexRouteProvider(): Generator { yield 'index route handles route extraction exception' => [ 'uri' => '/', ]; yield 'index route with catch all parameter' => [ 'uri' => '/some/deep/path', ]; } public function test_it_ignores_routes(): void { // Arrange $ignoreData = [ 'uri' => '/api/test', 'methods' => ['POST'], 'reason' => 'Test ignore', ]; $url = route('nimbus.index', ['ignore' => urlencode(json_encode($ignoreData))]); // Act $response = $this->get($url); // Assert $response ->assertStatus(302) ->assertRedirect('/nimbus'); } public function test_it_catches_extraction_errors(): void { // Arrange $disableThirdPartyUiActionSpy = $this->spy(DisableThirdPartyUiAction::class); $ignoreRoutesServiceSpy = $this->spy(IgnoredRoutesService::class); $buildGlobalHeadersActionSpy = $this->spy(BuildGlobalHeadersAction::class); $buildCurrentUserActionSpy = $this->spy(BuildCurrentUserAction::class); $extractionRoutesActionMock = $this->mock(ExtractRoutesAction::class); $exception = new class(message: fake()->words(asText: true), routeUri: fake()->url(), routeMethods: fake()->words(2), controllerClass: fake()->word(), controllerMethod: fake()->word(), suggestedSolution: fake()->words(asText: true)) extends RouteExtractionException {}; // Anticipate $extractionRoutesActionMock->shouldReceive('execute')->andThrow($exception); // Act $response = $this->get(route('nimbus.index')); // Assert $response->assertStatus(200); $response->assertViewIs('nimbus::app'); $response->assertViewHas( 'routeExtractorException', [ 'exception' => [ 'message' => $exception->getMessage(), 'previous' => $exception->getPrevious() ? [ 'message' => $exception->getPrevious()->getMessage(), 'file' => $exception->getPrevious()->getFile(), 'line' => $exception->getPrevious()->getLine(), ] : null, ], 'routeContext' => $exception->getRouteContext(), 'suggestedSolution' => $exception->getSuggestedSolution(), 'ignoreData' => $exception->getIgnoreData(), ], ); $disableThirdPartyUiActionSpy->shouldHaveReceived('execute')->once(); $ignoreRoutesServiceSpy->shouldNotHaveReceived('execute'); $buildGlobalHeadersActionSpy->shouldNotHaveReceived('execute'); $buildCurrentUserActionSpy->shouldNotHaveReceived('execute'); } public function test_it_integrates(): void { // Act $response = $this->get(route('nimbus.index')); // Assert $response->assertStatus(200); $response->assertViewIs('nimbus::app'); $response->assertViewHas(['routes', 'headers', 'currentUser']); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/Integration/NimbusRelayTest.php
tests/Integration/NimbusRelayTest.php
<?php namespace Sunchayn\Nimbus\Tests\Integration; use Generator; use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull; use Illuminate\Foundation\Http\Middleware\TrimStrings; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Route; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use Sunchayn\Nimbus\Http\Api\Relay\NimbusRelayController; use Sunchayn\Nimbus\Http\Api\Relay\NimbusRelayRequest; use Sunchayn\Nimbus\Http\Api\Relay\RelayResponseResource; use Sunchayn\Nimbus\Modules\Relay\Actions\RequestRelayAction; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationTypeEnum; use Sunchayn\Nimbus\Modules\Relay\DataTransferObjects\RelayedRequestResponseData; use Sunchayn\Nimbus\Modules\Relay\ValueObjects\PrintableResponseBody; use Sunchayn\Nimbus\Modules\Relay\ValueObjects\ResponseCookieValueObject; use Sunchayn\Nimbus\NimbusServiceProvider; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(NimbusRelayController::class)] #[CoversClass(NimbusRelayRequest::class)] #[CoversClass(RelayResponseResource::class)] #[CoversClass(NimbusServiceProvider::class)] class NimbusRelayTest extends TestCase { #[DataProvider('relayRequestProvider')] public function test_it_relays_requests(array $payload, RelayedRequestResponseData $relayResponseStub): void { // Arrange $requestRelayActionMock = $this->mock(RequestRelayAction::class); // We want to test that the logic is resilient with or without these middlewares. $this->withoutMiddleware(TrimStrings::class); $this->withoutMiddleware(ConvertEmptyStringsToNull::class); // Anticipate $requestRelayActionMock->shouldReceive('execute')->withAnyArgs()->andReturn($relayResponseStub); // Act $response = $this->post( route('nimbus.api.relay'), $payload, [ 'Content-Type' => 'multipart/form-data', 'Accept' => 'application/json', ] ); // Assert $response->assertStatus(200); $response->assertJson([ 'statusCode' => $relayResponseStub->statusCode, 'statusText' => $relayResponseStub->statusText, 'body' => $relayResponseStub->body->toPrettyJSON(), 'headers' => [ [ 'key' => 'header1', 'value' => 'value1', ], ], 'cookies' => collect($relayResponseStub->cookies)->map(fn ($cookie) => $cookie->toArray())->all(), 'duration' => $relayResponseStub->durationMs, 'timestamp' => $relayResponseStub->timestamp, ]); } public static function relayRequestProvider(): Generator { yield 'POST request without authorization' => [ 'payload' => [ 'method' => 'POST', 'endpoint' => '/test-endpoint', 'body' => ['test' => 'data'], 'headers' => [ ['key' => 'Content-Type', 'value' => 'application/json'], ], ], 'relayResponseStub' => new RelayedRequestResponseData( statusCode: 200, statusText: 'OK', body: new PrintableResponseBody('Hey!'), headers: [ 'header1' => ['value1'], ], durationMs: fake('en')->randomFloat(), timestamp: fake('en')->dateTime()->getTimestamp(), cookies: [ new ResponseCookieValueObject( key: 'cookie1', rawValue: '::value::', prefix: '::prefix::', ), ], ), ]; yield 'GET request with Bearer authorization' => [ 'payload' => [ 'method' => 'GET', 'endpoint' => '/protected-endpoint', 'authorization' => [ 'type' => AuthorizationTypeEnum::Bearer->value, 'value' => 'test-token-123', ], ], 'relayResponseStub' => new RelayedRequestResponseData( statusCode: 200, statusText: 'OK', body: new PrintableResponseBody('Authentoicated!'), headers: [ 'header1' => ['value1'], ], durationMs: fake('en')->randomFloat(), timestamp: fake('en')->dateTime()->getTimestamp(), cookies: [ new ResponseCookieValueObject( key: 'cookie1', rawValue: '::value::', prefix: '::prefix::', ), ], ), ]; yield 'GET request with invalid endpoint' => [ 'payload' => [ 'method' => 'GET', 'endpoint' => '/non-existent-endpoint', 'body' => ' ', ], 'relayResponseStub' => new RelayedRequestResponseData( statusCode: 404, statusText: 'Not Found', body: new PrintableResponseBody('Not Found!'), headers: [ 'header1' => ['value1'], ], durationMs: fake('en')->randomFloat(), timestamp: fake('en')->dateTime()->getTimestamp(), cookies: [], ), ]; } #[DataProvider('validationFailureProvider')] public function test_it_validates_requests(array $payload, array $expectedErrors): void { // Act $response = $this->postJson(route('nimbus.api.relay'), $payload); // Assert $response->assertStatus(422); $response->assertJsonValidationErrors($expectedErrors); } public static function validationFailureProvider(): Generator { yield 'missing method' => [ 'payload' => [ 'endpoint' => '/test-endpoint', ], 'expectedErrors' => ['method'], ]; yield 'missing endpoint' => [ 'payload' => [ 'method' => 'GET', ], 'expectedErrors' => ['endpoint'], ]; yield 'invalid authorization type' => [ 'payload' => [ 'method' => 'GET', 'endpoint' => '/test-endpoint', 'authorization' => [ 'type' => 'invalid-type', 'value' => 'test-value', ], ], 'expectedErrors' => ['authorization.type'], ]; } public function test_it_integrates(): void { // Arrange Route::get('/test-endpoint', fn () => response()->json(['message' => 'success'])) ->name('test.endpoint'); $payload = [ 'method' => 'GET', 'endpoint' => '/test-endpoint', 'body' => ['test' => 'data'], ]; Http::fake([ 'test-endpoint?test=data' => Http::response('Hey!', 200), ]); // Act $response = $this->postJson(route('nimbus.api.relay'), $payload); // Assert $response->assertStatus(200); $response->assertJsonStructure([ 'statusCode', 'statusText', 'body', 'headers', 'cookies', 'duration', 'timestamp', ]); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/E2E/install-current-nimbus-branch.php
tests/E2E/install-current-nimbus-branch.php
<?php declare(strict_types=1); $branchName = $argv[1] ?? null; if ($branchName === null || $branchName === '') { fwrite(STDERR, "Error: Branch name argument is required.\n"); exit(1); } $composerFilePath = __DIR__.'/.workdir/composer.json'; $packageName = 'sunchayn/nimbus'; $localPackagePath = '../../'; if (! file_exists($composerFilePath)) { fwrite(STDERR, "Error: composer.json not found.\n"); exit(1); } $composerJson = json_decode( file_get_contents($composerFilePath), true, flags: JSON_THROW_ON_ERROR ); /** * Ensure repositories key exists and is an array. */ $composerJson['repositories'] ??= []; if (! is_array($composerJson['repositories'])) { fwrite(STDERR, "Error: repositories must be an array.\n"); exit(1); } /** * Check whether the path repository already exists. */ $pathRepositoryAlreadyDefined = false; foreach ($composerJson['repositories'] as $repository) { if ( isset($repository['type'], $repository['url']) && $repository['type'] === 'path' && $repository['url'] === $localPackagePath ) { $pathRepositoryAlreadyDefined = true; break; } } /** * Append the repository only if it does not already exist. */ if (! $pathRepositoryAlreadyDefined) { $composerJson['repositories'][] = [ 'type' => 'path', 'url' => $localPackagePath, 'options' => [ 'symlink' => true, ], ]; } /** * Ensure require section exists. */ $composerJson['require'] ??= []; if (! array_key_exists($packageName, $composerJson['require'])) { fwrite( STDERR, "Error: Package '{$packageName}' is not present in require.\n" ); exit(1); } /** * Force the package version to the requested dev branch. */ $composerJson['require'][$packageName] = "dev-{$branchName}"; /** * Write back composer.json with stable formatting. */ file_put_contents( $composerFilePath, json_encode( $composerJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ).PHP_EOL ); echo "composer.json updated successfully.\n";
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Schemas/Builders/SchemaBuilderUnitTest.php
tests/App/Modules/Schemas/Builders/SchemaBuilderUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Schemas\Builders; namespace Sunchayn\Nimbus\Tests\App\Modules\Schemas\Builders; use Generator; use Illuminate\Support\Arr; use Illuminate\Validation\Rule; use Illuminate\Validation\Rules\Enum; use Illuminate\Validation\Rules\In; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use stdClass; use Sunchayn\Nimbus\Modules\Schemas\Builders\PropertyBuilder; use Sunchayn\Nimbus\Modules\Schemas\Builders\SchemaBuilder; use Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset; use Sunchayn\Nimbus\Modules\Schemas\RulesMapper\Processors\EnumRuleProcessor; use Sunchayn\Nimbus\Modules\Schemas\RulesMapper\Processors\InRuleProcessor; use Sunchayn\Nimbus\Modules\Schemas\RulesMapper\RuleToSchemaMapper; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\FieldPath; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty; use Sunchayn\Nimbus\Tests\App\Modules\Schemas\Builders\Stubs\StatusEnumStub; #[CoversClass(SchemaBuilder::class)] #[CoversClass(PropertyBuilder::class)] #[CoversClass(FieldPath::class)] #[CoversClass(RuleToSchemaMapper::class)] #[CoversClass(InRuleProcessor::class)] #[CoversClass(EnumRuleProcessor::class)] // TODO [Test] Move the mapper and process to their own tests. class SchemaBuilderUnitTest extends TestCase { private SchemaBuilder $schemaBuilder; protected function setUp(): void { parent::setUp(); $this->schemaBuilder = $this->createSchemaBuilder(); } #[DataProvider('schemaBuilderDataProvider')] public function test_builds_schema_with_correct_properties( array $rules, Schema $expectedSchema, ): void { // Act $actual = $this->schemaBuilder->buildSchemaFromRuleset(Ruleset::fromLaravelRules($rules)); // Assert $this->assertEquals( $expectedSchema, $actual, ); } public static function schemaBuilderDataProvider(): Generator { yield 'simple rules' => [ 'rules' => [ 'name' => 'required|string', 'email' => 'required|email', 'age' => 'required_with:email|integer|min:18|max:99', 'statuses' => ['required', new Enum(StatusEnumStub::class)], 'statuses_v2' => ['required', Rule::enum(StatusEnumStub::class)], 'role' => ['required', new In(1, 2, 3, 4)], 'role_v2' => ['required', Rule::in(1, 2, 3, 4)], 'role_2' => ['required', new In(new stdClass, 2, 3)], // <- Assert we rebase the array after filtering. ], 'expectedSchema' => new Schema( properties: [ new SchemaProperty(name: 'name', type: 'string', required: true, format: null, itemsSchema: null, propertiesSchema: null), new SchemaProperty(name: 'email', type: 'string', required: true, format: 'email', itemsSchema: null, propertiesSchema: null), new SchemaProperty(name: 'age', type: 'integer', required: false, format: null, itemsSchema: null, propertiesSchema: null, minimum: 18, maximum: 99), new SchemaProperty(name: 'statuses', type: 'string', required: true, format: null, enum: ['inactive', 'active'], itemsSchema: null, propertiesSchema: null), new SchemaProperty(name: 'statuses_v2', type: 'string', required: true, format: null, enum: ['inactive', 'active'], itemsSchema: null, propertiesSchema: null), new SchemaProperty(name: 'role', type: 'integer', required: true, format: null, enum: [1, 2, 3, 4], itemsSchema: null, propertiesSchema: null), new SchemaProperty(name: 'role_v2', type: 'integer', required: true, format: null, enum: [1, 2, 3, 4], itemsSchema: null, propertiesSchema: null), new SchemaProperty(name: 'role_2', type: 'integer', required: true, format: null, enum: [2, 3], itemsSchema: null, propertiesSchema: null), ], extractionError: null, ), ]; yield 'nested object rules' => [ 'rules' => [ 'user.name' => 'required|string', 'user.email' => 'required|email', ], 'expectedSchema' => new Schema( properties: [ new SchemaProperty( name: 'user', type: 'object', required: false, format: null, itemsSchema: null, propertiesSchema: new Schema( properties: [ new SchemaProperty(name: 'name', type: 'string', required: true, format: null, itemsSchema: null, propertiesSchema: null), new SchemaProperty(name: 'email', type: 'string', required: true, format: 'email', itemsSchema: null, propertiesSchema: null), ], extractionError: null, ), ), ], extractionError: null, ), ]; yield 'array of primitives' => [ 'rules' => [ 'tags' => 'array', 'tags.*' => 'string', ], 'expectedSchema' => new Schema( properties: [ new SchemaProperty( name: 'tags', type: 'array', required: false, format: null, itemsSchema: new SchemaProperty( name: 'tag', // <- Singular value of parent property `tags`. type: 'string', required: false, format: null, itemsSchema: null, propertiesSchema: null, ), propertiesSchema: null, ), ], extractionError: null, ), ]; yield 'array of objects rules' => [ 'rules' => [ 'persons' => 'array|required', 'persons.*.email' => 'string|email', 'persons.*.username' => 'string|max:20', ], 'expectedSchema' => new Schema( properties: [ new SchemaProperty( name: 'persons', type: 'array', required: true, format: null, itemsSchema: new SchemaProperty( name: 'item', type: 'object', required: false, format: null, itemsSchema: null, propertiesSchema: new Schema( properties: [ new SchemaProperty( name: 'email', type: 'string', required: false, format: 'email', itemsSchema: null, propertiesSchema: null, ), new SchemaProperty( name: 'username', type: 'string', required: false, format: null, itemsSchema: null, propertiesSchema: null, maximum: 20, ), ], extractionError: null, ) ), propertiesSchema: null, ), ], extractionError: null, ), ]; yield 'mixed data types' => [ 'rules' => [ 'id' => 'required|uuid', 'name' => 'required|string', 'age' => 'integer', 'is_active' => 'boolean', 'salary' => 'numeric', ], 'expectedSchema' => new Schema( properties: [ new SchemaProperty(name: 'id', type: 'string', required: true, format: 'uuid', itemsSchema: null, propertiesSchema: null), new SchemaProperty(name: 'name', type: 'string', required: true, format: null, itemsSchema: null, propertiesSchema: null), new SchemaProperty(name: 'age', type: 'integer', required: false, format: null, itemsSchema: null, propertiesSchema: null), new SchemaProperty(name: 'is_active', type: 'boolean', required: false, format: null, itemsSchema: null, propertiesSchema: null), new SchemaProperty(name: 'salary', type: 'number', required: false, format: null, itemsSchema: null, propertiesSchema: null), ], extractionError: null, ), ]; yield 'empty rules' => [ 'rules' => [], 'expectedSchema' => new Schema( properties: [], extractionError: null, ), ]; yield 'deep nesting (object)' => [ 'rules' => [ 'company.department.team.member.name' => 'required|string', ], 'expectedSchema' => new Schema( properties: [ new SchemaProperty( name: 'company', type: 'object', required: false, format: null, itemsSchema: null, propertiesSchema: new Schema( properties: [ new SchemaProperty( name: 'department', type: 'object', required: false, format: null, itemsSchema: null, propertiesSchema: new Schema( properties: [ new SchemaProperty( name: 'team', type: 'object', required: false, format: null, itemsSchema: null, propertiesSchema: new Schema( properties: [ new SchemaProperty( name: 'member', type: 'object', required: false, format: null, itemsSchema: null, propertiesSchema: new Schema( properties: [ new SchemaProperty(name: 'name', type: 'string', required: true, format: null, itemsSchema: null, propertiesSchema: null), ], extractionError: null, ), ), ], extractionError: null, ), ), ], extractionError: null, ), ), ], extractionError: null, ), ), ], extractionError: null, ), ]; yield 'deep nesting (array)' => [ 'rules' => [ 'company.teams.*.members.*.member.name' => 'string', 'company.teams.*.members' => 'required|array', ], 'expectedSchema' => new Schema( properties: [ new SchemaProperty( name: 'company', type: 'object', required: false, format: null, enum: null, itemsSchema: null, propertiesSchema: new Schema( properties: [ new SchemaProperty( name: 'teams', type: 'array', required: false, format: null, enum: null, itemsSchema: new SchemaProperty( name: 'item', type: 'object', required: false, format: null, enum: null, itemsSchema: null, propertiesSchema: new Schema( properties: [ new SchemaProperty( name: 'members', type: 'array', required: true, format: null, enum: null, itemsSchema: new SchemaProperty( name: 'item', type: 'object', required: false, format: null, enum: null, itemsSchema: null, propertiesSchema: new Schema( properties: [ new SchemaProperty( name: 'member', type: 'object', required: false, format: null, enum: null, itemsSchema: null, propertiesSchema: new Schema( properties: [ new SchemaProperty( name: 'name', type: 'string', required: false, format: null, enum: null, itemsSchema: null, propertiesSchema: null, ), ], extractionError: null, ), ), ], extractionError: null, ), ), propertiesSchema: null, ), ], extractionError: null, ), ), propertiesSchema: null, ), ], extractionError: null, ), ), ], extractionError: null, ), ]; } #[DataProvider('formatDetectionDataProvider')] public function test_detects_formats_correctly( array $rules, string $propertyName, ?string $expectedFormat ): void { // Act $schema = $this->schemaBuilder->buildSchemaFromRuleset(Ruleset::fromLaravelRules($rules)); // Assert $property = $this->findPropertyByName($schema, $propertyName); $this->assertNotNull($property, "Property '{$propertyName}' not found"); $this->assertEquals($expectedFormat, $property->format); } public static function formatDetectionDataProvider(): Generator { yield 'email format' => [ 'rules' => ['email' => 'required|email'], 'propertyName' => 'email', 'expectedFormat' => 'email', ]; yield 'UUID format' => [ 'rules' => ['id' => 'required|uuid'], 'propertyName' => 'id', 'expectedFormat' => 'uuid', ]; yield 'date-time format' => [ 'rules' => ['created_at' => 'required|date'], 'propertyName' => 'created_at', 'expectedFormat' => 'date-time', ]; yield 'no format' => [ 'rules' => ['name' => 'required|string'], 'propertyName' => 'name', 'expectedFormat' => null, ]; } #[DataProvider('enumValuesDataProvider')] public function test_extracts_enum_values_correctly( array $rules, string $propertyName, ?array $expectedEnum ): void { // Act $schema = $this->schemaBuilder->buildSchemaFromRuleset(Ruleset::fromLaravelRules($rules)); // Assert $property = $this->findPropertyByName($schema, $propertyName); $this->assertNotNull($property, "Property '{$propertyName}' not found"); $this->assertEquals($expectedEnum, $property->enum); } public static function enumValuesDataProvider(): Generator { yield 'enum values' => [ 'rules' => ['status' => 'required|in:active,inactive,pending'], 'propertyName' => 'status', 'expectedEnum' => ['active', 'inactive', 'pending'], ]; yield 'no enum' => [ 'rules' => ['name' => 'required|string'], 'propertyName' => 'name', 'expectedEnum' => null, ]; } /* * Helpers. */ private function findPropertyByName(Schema $schema, string $name): ?SchemaProperty { return Arr::first( $schema->properties, fn (SchemaProperty $property) => $property->name === $name, ); } /* * Generators. */ private function createSchemaBuilder(): SchemaBuilder { $ruleMapper = new RuleToSchemaMapper; $propertyBuilder = new PropertyBuilder($ruleMapper); return new SchemaBuilder( $propertyBuilder, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Schemas/Builders/Stubs/StatusEnumStub.php
tests/App/Modules/Schemas/Builders/Stubs/StatusEnumStub.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Schemas\Builders\Stubs; enum StatusEnumStub: string { case INACTIVE = 'inactive'; case ACTIVE = 'active'; }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Schemas/ValueObjects/PathSegmentUnitTest.php
tests/App/Modules/Schemas/ValueObjects/PathSegmentUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Schemas\ValueObjects; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\PathSegment; #[CoversClass(PathSegment::class)] class PathSegmentUnitTest extends TestCase { public function test_it_identifies_array_segments(): void { $segment = new PathSegment('*'); $this->assertTrue($segment->isArray()); } public function test_it_returns_false_for_non_array_segments(): void { $segment = new PathSegment('user'); $this->assertFalse($segment->isArray()); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Schemas/ValueObjects/RulesetUnitTest.php
tests/App/Modules/Schemas/ValueObjects/RulesetUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Schemas\ValueObjects; use Generator; use Illuminate\Validation\Rule; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset; #[CoversClass(Ruleset::class)] class RulesetUnitTest extends TestCase { #[DataProvider('rulesetCreationDataProvider')] public function test_creates_ruleset_from_various_formats(array $input, array $expected): void { // Act $ruleset = Ruleset::fromLaravelRules($input); // Assert $this->assertEquals($expected, $ruleset->all()); } public static function rulesetCreationDataProvider(): Generator { yield 'pipe-separated rules' => [ 'input' => ['example' => 'required|string|max:255'], 'expected' => ['example' => ['required', 'string', 'max:255']], ]; yield 'single rule' => [ 'input' => ['example' => 'required'], 'expected' => ['example' => ['required']], ]; yield 'empty string' => [ 'input' => ['example' => ''], 'expected' => ['example' => []], ]; yield 'array of rules' => [ 'input' => ['example' => ['required', 'string', 'max:255']], 'expected' => ['example' => ['required', 'string', 'max:255']], ]; yield 'empty array' => [ 'input' => [], 'expected' => [], ]; yield 'null input' => [ 'input' => ['example' => null], 'expected' => ['example' => []], ]; yield 'integer input' => [ 'input' => ['example' => 123], 'expected' => ['example' => []], ]; yield 'object input' => [ 'input' => ['example' => Rule::in(1, 2, 3)], 'expected' => ['example' => [Rule::in(1, 2, 3)]], ]; yield 'trailing pipe' => [ 'input' => ['example' => 'required|string|'], 'expected' => ['example' => ['required', 'string']], ]; yield 'leading pipe' => [ 'input' => ['example' => '|required|string'], 'expected' => ['example' => ['required', 'string']], ]; yield 'multiple consecutive pipes' => [ 'input' => ['example' => 'required||string'], 'expected' => ['example' => ['required', 'string']], ]; } #[DataProvider('emptyCheckDataProvider')] public function test_checks_if_ruleset_is_empty(array $rules, bool $expectedEmpty): void { // Arrange $ruleset = new Ruleset($rules); // Act $isEmpty = $ruleset->isEmpty(); // Assert $this->assertEquals($expectedEmpty, $isEmpty); } public static function emptyCheckDataProvider(): Generator { yield 'Empty ruleset' => [ 'rules' => [], 'expectedEmpty' => true, ]; yield 'Non-empty ruleset' => [ 'rules' => ['example' => ['required', 'string']], 'expectedEmpty' => false, ]; yield 'Single rule' => [ 'rules' => ['example' => ['required']], 'expectedEmpty' => false, ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Schemas/ValueObjects/SchemaUnitTest.php
tests/App/Modules/Schemas/ValueObjects/SchemaUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Schemas\ValueObjects; use Generator; use Mockery; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use RuntimeException; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\RulesExtractionError; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty; #[CoversClass(Schema::class)] class SchemaUnitTest extends TestCase { protected function tearDown(): void { Mockery::close(); parent::tearDown(); } public function test_builds_empty_schema(): void { // Act $schema = Schema::empty(); // Assert $this->assertEmpty($schema->properties); $this->assertNull($schema->extractionError); } #[DataProvider('isEmptyCheckDataProvider')] public function test_checks_if_empty(Schema $schema, bool $expected): void { // Act $isEmpty = $schema->isEmpty(); // Assert $this->assertEquals($expected, $isEmpty); } public static function isEmptyCheckDataProvider(): Generator { yield 'Empty schema' => [ 'schema' => new Schema(properties: []), 'expected' => true, ]; yield 'Empty with extraction error' => [ 'schema' => new Schema( properties: [], extractionError: new RulesExtractionError(new RuntimeException) ), 'expected' => true, ]; yield 'Non-empty schema' => [ 'schema' => new Schema(properties: [new SchemaProperty(name: 'field')]), 'expected' => false, ]; } #[DataProvider('toArrayDataProvider')] public function test_converts_to_array(array $properties, array $expected): void { // Arrange $schema = new Schema(properties: $properties); // Act $result = $schema->toArray(); // Assert $this->assertEquals($expected, $result); } public static function toArrayDataProvider(): Generator { yield 'empty schema' => [ 'properties' => [], 'expected' => [], ]; yield 'single property' => [ 'properties' => [ new class(name: 'name') extends SchemaProperty { public function toArray(): array { return ['type' => 'string']; } }, ], 'expected' => [ 'name' => ['type' => 'string'], ], ]; yield 'multiple properties' => [ 'properties' => [ new class(name: 'name') extends SchemaProperty { public function toArray(): array { return ['type' => 'string']; } }, new class(name: 'age') extends SchemaProperty { public function toArray(): array { return ['type' => 'integer']; } }, ], 'expected' => [ 'name' => ['type' => 'string'], 'age' => ['type' => 'integer'], ], ]; yield 'properties with formats' => [ 'properties' => [ new class(name: 'email') extends SchemaProperty { public function toArray(): array { return ['type' => 'string', 'format' => 'email']; } }, new class(name: 'uuid') extends SchemaProperty { public function toArray(): array { return ['type' => 'string', 'format' => 'uuid']; } }, ], 'expected' => [ 'email' => ['type' => 'string', 'format' => 'email'], 'uuid' => ['type' => 'string', 'format' => 'uuid'], ], ]; yield 'nested object properties' => [ 'properties' => [ new class(name: 'user') extends SchemaProperty { public function toArray(): array { return [ 'type' => 'object', 'properties' => [ 'name' => ['type' => 'string'], 'email' => ['type' => 'string', 'format' => 'email'], ], ]; } }, ], 'expected' => [ 'user' => [ 'type' => 'object', 'properties' => [ 'name' => ['type' => 'string'], 'email' => ['type' => 'string', 'format' => 'email'], ], ], ], ]; yield 'array properties' => [ 'properties' => [ new class(name: 'tags') extends SchemaProperty { public function toArray(): array { return [ 'type' => 'array', 'items' => ['type' => 'string'], ]; } }, ], 'expected' => [ 'tags' => [ 'type' => 'array', 'items' => ['type' => 'string'], ], ], ]; } #[DataProvider('toJsonSchemaDataProvider')] public function test_converts_to_json_schema(array $properties, array $expected): void { // Arrange $schema = new Schema(properties: $properties); // Act $result = $schema->toJsonSchema(); // Assert $this->assertEquals($expected, $result); } public static function toJsonSchemaDataProvider(): Generator { yield 'empty schema' => [ 'properties' => [], 'expected' => [ '$schema' => 'https://json-schema.org/draft/2020-12/schema', 'type' => 'object', 'properties' => [], 'required' => [], 'additionalProperties' => false, ], ]; yield 'single non-required property' => [ 'properties' => [ new class(name: 'name') extends SchemaProperty { public function toArray(): array { return ['type' => 'string']; } }, ], 'expected' => [ '$schema' => 'https://json-schema.org/draft/2020-12/schema', 'type' => 'object', 'properties' => [ 'name' => ['type' => 'string'], ], 'required' => [], 'additionalProperties' => false, ], ]; yield 'single required property' => [ 'properties' => [ new class(name: 'email', required: true) extends SchemaProperty { public function toArray(): array { return ['type' => 'string', 'format' => 'email']; } }, ], 'expected' => [ '$schema' => 'https://json-schema.org/draft/2020-12/schema', 'type' => 'object', 'properties' => [ 'email' => ['type' => 'string', 'format' => 'email'], ], 'required' => ['email'], 'additionalProperties' => false, ], ]; yield 'mixed required and optional properties' => [ 'properties' => [ new class(name: 'name', required: true) extends SchemaProperty { public function toArray(): array { return ['type' => 'string']; } }, new class(name: 'age') extends SchemaProperty { public function toArray(): array { return ['type' => 'integer']; } }, new class(name: 'email', required: true) extends SchemaProperty { public function toArray(): array { return ['type' => 'string', 'format' => 'email']; } }, ], 'expected' => [ '$schema' => 'https://json-schema.org/draft/2020-12/schema', 'type' => 'object', 'properties' => [ 'name' => ['type' => 'string'], 'age' => ['type' => 'integer'], 'email' => ['type' => 'string', 'format' => 'email'], ], 'required' => ['name', 'email'], 'additionalProperties' => false, ], ]; yield 'all required properties' => [ 'properties' => [ new class(name: 'id', required: true) extends SchemaProperty { public function toArray(): array { return ['type' => 'string', 'format' => 'uuid']; } }, new class(name: 'name', required: true) extends SchemaProperty { public function toArray(): array { return ['type' => 'string']; } }, new class(name: 'email', required: true) extends SchemaProperty { public function toArray(): array { return ['type' => 'string', 'format' => 'email']; } }, ], 'expected' => [ '$schema' => 'https://json-schema.org/draft/2020-12/schema', 'type' => 'object', 'properties' => [ 'id' => ['type' => 'string', 'format' => 'uuid'], 'name' => ['type' => 'string'], 'email' => ['type' => 'string', 'format' => 'email'], ], 'required' => ['id', 'name', 'email'], 'additionalProperties' => false, ], ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Schemas/ValueObjects/SchemaPropertyUnitTest.php
tests/App/Modules/Schemas/ValueObjects/SchemaPropertyUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Schemas\ValueObjects; use Closure; use Generator; use Mockery; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty; #[CoversClass(SchemaProperty::class)] class SchemaPropertyUnitTest extends TestCase { protected function tearDown(): void { Mockery::close(); parent::tearDown(); } #[DataProvider('toArrayDataProvider')] public function test_to_array(SchemaProperty|Closure $property, array $expected): void { // Arrange // Some properties have mock, so we need to evaluate the constructor here and not in the data provider. // This will prevent flakiness as the data providers are called first (in random order). // If all mocks are called, then the test will fail as it won't satisfy all expectations. $property = value($property); // Act $result = $property->toArray(); // Assert $this->assertEquals($expected, $result); } public static function toArrayDataProvider(): Generator { yield 'a minimal structure' => [ 'property' => new SchemaProperty( name: 'simpleProperty', type: 'string' ), 'expected' => [ 'type' => 'string', 'x-required' => false, 'x-name' => 'simpleProperty', ], ]; yield 'a formatted string' => [ 'property' => new SchemaProperty( name: 'emailProperty', type: 'string', format: 'email' ), 'expected' => [ 'type' => 'string', 'format' => 'email', 'x-required' => false, 'x-name' => 'emailProperty', ], ]; yield 'an enum' => [ 'property' => new SchemaProperty( name: 'statusProperty', type: 'string', enum: ['active', 'inactive', 'pending'] ), 'expected' => [ 'type' => 'string', 'enum' => ['active', 'inactive', 'pending'], 'x-required' => false, 'x-name' => 'statusProperty', ], ]; yield 'an array of primitives' => [ 'property' => fn () => new SchemaProperty( name: 'arrayProperty', type: 'array', itemsSchema: new SchemaProperty( name: 'item', type: 'integer', ), ), 'expected' => [ 'type' => 'array', 'items' => [ 'type' => 'integer', 'x-required' => false, 'x-name' => 'item', ], 'x-required' => false, 'x-name' => 'arrayProperty', ], ]; yield 'an array of objects' => [ 'property' => fn () => new SchemaProperty( name: 'arrayProperty', type: 'array', itemsSchema: new SchemaProperty( name: 'item', type: 'object', propertiesSchema: self::getSchemaMock( [ new SchemaProperty( name: 'productId', required: true, ), ], required: ['productId'], ), ) ), 'expected' => [ 'type' => 'array', 'items' => [ 'type' => 'object', 'properties' => [ 'productId' => [ 'type' => 'string', 'x-required' => true, 'x-name' => 'productId', ], ], 'required' => ['productId'], 'x-required' => false, 'x-name' => 'item', ], 'x-required' => false, 'x-name' => 'arrayProperty', ], ]; yield 'an object' => [ 'property' => fn () => new SchemaProperty( name: 'addressProperty', type: 'object', propertiesSchema: self::getSchemaMock( properties: [ new SchemaProperty( name: 'street', type: 'string', required: true, ), new SchemaProperty( name: 'city', type: 'string', ), ], required: [ 'street', ] ), ), 'expected' => [ 'type' => 'object', 'properties' => [ 'street' => [ 'type' => 'string', 'x-required' => true, 'x-name' => 'street', ], 'city' => [ 'type' => 'string', 'x-required' => false, 'x-name' => 'city', ], ], 'required' => ['street'], 'x-required' => false, 'x-name' => 'addressProperty', ], ]; yield 'an object without required fields' => [ 'property' => fn () => new SchemaProperty( name: 'addressProperty', type: 'object', required: true, propertiesSchema: self::getSchemaMock( properties: [ new SchemaProperty( name: 'street', type: 'string', ), new SchemaProperty( name: 'city', type: 'string', ), ], required: [] ), ), 'expected' => [ 'type' => 'object', 'properties' => [ 'street' => [ 'type' => 'string', 'x-required' => false, 'x-name' => 'street', ], 'city' => [ 'type' => 'string', 'x-required' => false, 'x-name' => 'city', ], ], 'required' => [], 'x-required' => true, 'x-name' => 'addressProperty', ], ]; yield 'a full structure' => [ 'property' => new SchemaProperty( name: 'fullProperty', type: 'string', required: true, format: 'date-time', enum: ['val1', 'val2'], ), 'expected' => [ 'type' => 'string', 'format' => 'date-time', 'enum' => ['val1', 'val2'], 'x-required' => true, 'x-name' => 'fullProperty', ], ]; yield 'an integer with format' => [ 'property' => new SchemaProperty( name: 'ageProperty', type: 'integer', format: 'int32', ), 'expected' => [ 'type' => 'integer', 'format' => 'int32', 'x-required' => false, 'x-name' => 'ageProperty', ], ]; yield 'a boolean' => [ 'property' => new SchemaProperty( name: 'isActiveProperty', type: 'boolean', ), 'expected' => [ 'type' => 'boolean', 'x-required' => false, 'x-name' => 'isActiveProperty', ], ]; } /* * Mocks. */ private static function getSchemaMock(array $properties, array $required): Schema { /** @var Schema&Mockery\MockInterface $schemaMock */ $schemaMock = Mockery::mock(Schema::class)->makePartial(); $schemaMock->__construct($properties); $schemaMock->shouldReceive('getRequiredProperties')->andReturn($required); return $schemaMock; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Authorization/AuthorizationCredentialsUnitTest.php
tests/App/Modules/Relay/Authorization/AuthorizationCredentialsUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization; use PHPUnit\Framework\Attributes\CoversClass; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationCredentials; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationTypeEnum; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(AuthorizationCredentials::class)] class AuthorizationCredentialsUnitTest extends TestCase { public function test_it_constructs_none_state(): void { $credentials = AuthorizationCredentials::none(); // Assert $this->assertEquals(AuthorizationTypeEnum::None, $credentials->type); $this->assertNull($credentials->value); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Authorization/Injectors/RememberMeCookieInjectorUnitTest.php
tests/App/Modules/Relay/Authorization/Injectors/RememberMeCookieInjectorUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Injectors; use Illuminate\Auth\SessionGuard; use Illuminate\Config\Repository as ConfigRepository; use Illuminate\Container\Container; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Encryption\Encrypter; use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Request; use Mockery; use PHPUnit\Framework\Attributes\CoversClass; use Sunchayn\Nimbus\Modules\Relay\Authorization\Injectors\RememberMeCookieInjector; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(RememberMeCookieInjector::class)] class RememberMeCookieInjectorUnitTest extends TestCase { private Container $containerMock; private ConfigRepository $configMock; private SessionGuard $authGuardMock; private UserProvider $userProviderMock; private Encrypter $encrypterMock; protected function setUp(): void { parent::setUp(); $this->containerMock = Mockery::mock(Container::class); $this->configMock = Mockery::mock(ConfigRepository::class); $this->authGuardMock = Mockery::mock(SessionGuard::class); $this->userProviderMock = Mockery::mock(UserProvider::class); $this->encrypterMock = Mockery::mock(Encrypter::class); } public function test_it_generates_and_attaches_remember_me_cookie_for_new_user(): void { // Arrange $authenticatable = $this->createAuthenticatable( id: 123, rememberToken: 'existing_token', passwordField: 'password' ); $relayRequest = Request::create('ping', server: ['HTTP_HOST' => 'example.com']); $relayRequest->setUserResolver(fn () => null); // <- no authenticated user in relay request $this->authGuardMock ->shouldReceive('getRecallerName') ->andReturn('remember_web'); $this->encrypterMock ->shouldReceive('getKey') ->andReturn('base64:test-key'); $this->encrypterMock ->shouldReceive('encrypt') ->withArgs(function (mixed $value, bool $serialize) { $this->assertStringEndsWith( '|123|existing_token|password', $value, ); $this->assertFalse($serialize); return true; }) ->once() ->andReturn('encrypted_recaller_token'); $pendingRequestMock = Mockery::mock(PendingRequest::class); $injector = $this->instantiateInjector($relayRequest); // Anticipate $pendingRequestMock ->shouldReceive('withCookies') ->once() ->withArgs(function (array $withCookiesArg, string $domain) { $this->assertEquals( ['remember_web' => 'encrypted_recaller_token'], $withCookiesArg, ); $this->assertEquals( 'example.com', $domain, ); return true; }) ->andReturnSelf(); // Act $result = $injector->attach($pendingRequestMock, $authenticatable); // Assert $this->assertSame($pendingRequestMock, $result); } public function test_it_generates_new_remember_token_when_user_has_none(): void { // Arrange $authenticatable = $this->createAuthenticatable( id: 456, rememberToken: null, // <- no existing token passwordField: 'password' ); $relayRequest = Request::create('ping', server: ['HTTP_HOST' => 'example.com']); $relayRequest->setUserResolver(fn () => null); $this->authGuardMock ->shouldReceive('getRecallerName') ->andReturn('remember_web'); $this->encrypterMock ->shouldReceive('getKey') ->andReturn('base64:test-key'); $this->encrypterMock ->shouldReceive('encrypt') ->andReturn('encrypted_recaller_token'); $pendingRequestMock = Mockery::mock(PendingRequest::class); $pendingRequestMock ->shouldReceive('withCookies') ->andReturnSelf(); $injector = $this->instantiateInjector($relayRequest); // Anticipate $this->userProviderMock->expects('updateRememberToken'); // Act $injector->attach($pendingRequestMock, $authenticatable); // Assert $this ->userProviderMock ->shouldHaveReceived('updateRememberToken') ->once() ->withArgs(function (Authenticatable $user, string $token) { $this->assertSame(456, $user->getAuthIdentifier()); $this->assertMatchesRegularExpression('/^[a-f0-9]{64}$/', $token); return true; }); } public function test_it_forwards_existing_remember_me_cookie_for_same_user(): void { // Arrange $currentUser = $this->createAuthenticatable( id: 789, rememberToken: 'current_token', passwordField: 'password' ); $targetUser = $this->createAuthenticatable( id: 789, // <- same ID as current user rememberToken: 'target_token', passwordField: 'password' ); $relayRequest = Request::create('ping', server: ['HTTP_HOST' => 'example.com']); $relayRequest->setUserResolver(fn () => $currentUser); $relayRequest->cookies->set('remember_web', $encrytpedCookieValue = sha1('::value::')); $this->authGuardMock ->shouldReceive('getRecallerName') ->andReturn('remember_web'); $this->encrypterMock ->shouldReceive('getKey') ->andReturn('base64:test-key'); $pendingRequestMock = Mockery::mock(PendingRequest::class); $injector = $this->instantiateInjector($relayRequest); // Anticipate $this->encrypterMock->shouldNotReceive('encrypt'); $pendingRequestMock ->expects('withCookies') ->andReturnSelf(); // Act $result = $injector->attach($pendingRequestMock, $targetUser); // Assert $this->assertSame($pendingRequestMock, $result); $pendingRequestMock ->shouldHaveReceived('withCookies') ->once() ->withArgs(function (array $cookies, string $domain) use ($encrytpedCookieValue) { $this->assertEquals( ['remember_web' => $encrytpedCookieValue], $cookies, ); $this->assertEquals('example.com', $domain); return true; }); } public function test_it_does_not_forward_cookie_when_users_differ(): void { // Arrange $currentUser = $this->createAuthenticatable( id: 100, rememberToken: 'current_token', passwordField: 'password' ); $targetUser = $this->createAuthenticatable( id: 200, // <- different ID rememberToken: 'target_token', passwordField: 'password2' ); $relayRequest = Request::create('ping', server: ['HTTP_HOST' => 'example.com']); $relayRequest->setUserResolver(fn () => $currentUser); $relayRequest->cookies->set('remember_web', 'existing_cookie_value'); $this->authGuardMock ->shouldReceive('getRecallerName') ->andReturn('remember_web'); $this->encrypterMock ->shouldReceive('getKey') ->andReturn('base64:test-key'); $pendingRequestMock = Mockery::mock(PendingRequest::class); $injector = $this->instantiateInjector($relayRequest); // Anticipate $this->encrypterMock ->shouldReceive('encrypt') ->once() ->withArgs(function (mixed $value, bool $serialize) { $this->assertStringEndsWith('|200|target_token|password2', $value); $this->assertFalse($serialize); return true; }) ->andReturn('encrypted_new_cookie'); $pendingRequestMock ->shouldReceive('withCookies') ->once() ->withArgs(function (array $cookies, string $domain) { $this->assertEquals( ['remember_web' => 'encrypted_new_cookie'], $cookies, ); $this->assertEquals('example.com', $domain); return true; }) ->andReturnSelf(); // Act $result = $injector->attach($pendingRequestMock, $targetUser); // Assert $this->assertSame($pendingRequestMock, $result); } public function test_it_does_not_forward_when_no_cookie_exists(): void { // Arrange $currentUser = $this->createAuthenticatable( id: 100, rememberToken: 'current_token', passwordField: 'password' ); $targetUser = $this->createAuthenticatable( id: 100, rememberToken: 'target_token', passwordField: 'password' ); $relayRequest = Request::create('ping', server: ['HTTP_HOST' => 'example.com']); $relayRequest->setUserResolver(fn () => $currentUser); // No cookie set $this->authGuardMock ->shouldReceive('getRecallerName') ->andReturn('remember_web'); $this->encrypterMock ->shouldReceive('getKey') ->andReturn('base64:test-key'); $pendingRequestMock = Mockery::mock(PendingRequest::class); $injector = $this->instantiateInjector($relayRequest); // Anticipate $this->encrypterMock ->shouldReceive('encrypt') ->once() ->withArgs(function (mixed $value, bool $serialize) { $this->assertStringEndsWith('|100|target_token|password', $value); $this->assertFalse($serialize); return true; }) ->andReturn('encrypted_new_cookie'); $pendingRequestMock ->shouldReceive('withCookies') ->once() ->andReturnSelf(); // Act $result = $injector->attach($pendingRequestMock, $targetUser); // Assert $this->assertSame($pendingRequestMock, $result); } /* * Helpers. */ private function instantiateInjector(Request $relayRequest): RememberMeCookieInjector { $this->configMock ->shouldReceive('get') ->with('nimbus.auth.guard') ->andReturn('web'); $authManagerMock = Mockery::mock(\Illuminate\Auth\AuthManager::class); $authManagerMock ->shouldReceive('guard') ->with('web') ->andReturn($this->authGuardMock); $this->authGuardMock ->shouldReceive('getProvider') ->andReturn($this->userProviderMock); $this->containerMock ->shouldReceive('get') ->with('encrypter') ->andReturn($this->encrypterMock); $this->containerMock ->shouldReceive('get') ->with('auth') ->andReturn($authManagerMock); return new RememberMeCookieInjector( relayRequest: $relayRequest, container: $this->containerMock, configRepository: $this->configMock, ); } private function createAuthenticatable( int $id, ?string $rememberToken, string $passwordField ): Authenticatable { $authenticatable = Mockery::mock(Authenticatable::class); $authenticatable ->shouldReceive('getAuthIdentifier') ->andReturn($id); $authenticatable ->shouldReceive('getRememberToken') ->andReturn($rememberToken); $authenticatable ->shouldReceive('getAuthPasswordName') ->andReturn($passwordField); return $authenticatable; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Authorization/Injectors/TymonJwtTokenInjectorUnitTest.php
tests/App/Modules/Relay/Authorization/Injectors/TymonJwtTokenInjectorUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Injectors; use Illuminate\Config\Repository as ConfigRepository; use Illuminate\Container\Container; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\Guard; use Illuminate\Http\Client\PendingRequest; use Mockery; use PHPUnit\Framework\Attributes\CoversClass; use Sunchayn\Nimbus\Modules\Config\Exceptions\MisconfiguredValueException; use Sunchayn\Nimbus\Modules\Relay\Authorization\Injectors\TymonJwtTokenInjector; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(TymonJwtTokenInjector::class)] class TymonJwtTokenInjectorUnitTest extends TestCase { private ConfigRepository $configMock; private Container $containerMock; protected function setUp(): void { parent::setUp(); $this->configMock = Mockery::mock(ConfigRepository::class); $this->containerMock = Mockery::mock(Container::class); } public function test_it_throws_exception_when_tymon_jwt_auth_not_installed(): void { // Arrange if (class_exists(\Tymon\JWTAuth\JWTGuard::class)) { $this->markTestSkipped('Tymon JWT Auth is installed, cannot test missing dependency scenario'); } // Anticipate $this->expectException(MisconfiguredValueException::class); $this->expectExceptionMessage('The config value for `nimbus.auth.special.injector` is an injector that requires the following dependency <tymon/jwt-auth>'); // Act new TymonJwtTokenInjector( configRepository: $this->configMock, container: $this->containerMock, ); } public function test_it_generates_jwt_token_and_attaches_to_request(): void { // Arrange $authenticatable = Mockery::mock(Authenticatable::class); $authenticatable ->shouldReceive('getAuthIdentifier') ->andReturn(123); $guardMock = Mockery::mock(Guard::class); $pendingRequestMock = Mockery::mock(PendingRequest::class); $injector = $this->instantiateInjector($guardMock); // Anticipate $guardMock ->shouldReceive('login') ->with($authenticatable) ->once() ->andReturn('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.test.token'); $pendingRequestMock ->shouldReceive('withToken') ->once() ->withArgs(function (string $token) { $this->assertEquals('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.test.token', $token); return true; }) ->andReturnSelf(); // Act $result = $injector->attach($pendingRequestMock, $authenticatable); // Assert $this->assertSame($pendingRequestMock, $result); } /* * Helpers. */ private function instantiateInjector( Guard $guardMock ): Mockery\MockInterface&TymonJwtTokenInjector { $mock = $this->mock(TymonJwtTokenInjector::class)->shouldAllowMockingProtectedMethods()->makePartial(); $mock->shouldReceive('getGuard')->andReturn($guardMock); return $mock; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Authorization/Handlers/ImpersonateUserAuthorizationHandlerFunctionalTest.php
tests/App/Modules/Relay/Authorization/Handlers/ImpersonateUserAuthorizationHandlerFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Request; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\CoversMethod; use PHPUnit\Framework\Attributes\TestWith; use Sunchayn\Nimbus\Modules\Relay\Authorization\Exceptions\InvalidAuthorizationValueException; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\ImpersonateUserAuthorizationHandler; use Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers\Shared\HandlesRecallerCookies; use Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers\Stubs\DummyAuthenticatable; use Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers\Stubs\DummySpecialAuthenticationInjector; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(ImpersonateUserAuthorizationHandler::class)] #[CoversMethod(InvalidAuthorizationValueException::class, 'becauseUserIsNotFound')] class ImpersonateUserAuthorizationHandlerFunctionalTest extends TestCase { use HandlesRecallerCookies; public function test_it_authorizes_requests(): void { // Arrange config([ 'nimbus.auth.guard' => $guardName = fake()->word(), 'nimbus.auth.special.injector' => DummySpecialAuthenticationInjector::class, ]); $dummyAuthenticatable = new DummyAuthenticatable(id: $userId = fake()->randomNumber()); $this->mockAuthManagerToUseDummyModel($userId, $dummyAuthenticatable, $guardName); $relayRequest = Request::create('ping'); $relayRequest->headers->set('HOST', $relayRequestHost = fake()->domainName()); $dummySpecialAuthenticationInjectorMock = $this->mock(DummySpecialAuthenticationInjector::class); $handler = resolve( ImpersonateUserAuthorizationHandler::class, [ 'userId' => $userId, 'relayRequest' => $relayRequest, ], ); $pendingRequest = resolve(PendingRequest::class); // Anticipate $dummySpecialAuthenticationInjectorMock ->shouldReceive('attach') ->withAnyArgs() ->andReturn($pendingRequest); // Act $responsePendingRequest = $handler->authorize($pendingRequest); // Assert $this->assertSame($pendingRequest, $responsePendingRequest); $dummySpecialAuthenticationInjectorMock ->shouldHaveReceived('attach') ->once() ->withArgs(function (PendingRequest $pendingRequestArg, Authenticatable $authenticatable) use ($pendingRequest, $dummyAuthenticatable) { $this->assertSame( $dummyAuthenticatable, $authenticatable, ); $this->assertSame($pendingRequestArg, $pendingRequest); return true; }); } #[TestWith([0], 'ID Equals to Zero')] #[TestWith([-1], 'Negative ID')] public function test_it_breaks_with_invalid_user_id(int $coefficient): void { // Arrange $invalidUserId = fake()->randomNumber() * $coefficient; // Anticipate $this->expectException(InvalidAuthorizationValueException::class); $this->expectExceptionMessage('User ID didn\'t resolve to a user to impersonate.'); $this->expectExceptionCode(InvalidAuthorizationValueException::USER_IS_NOT_FOUND); // Act resolve(ImpersonateUserAuthorizationHandler::class, ['userId' => $invalidUserId]); } public function test_it_breaks_when_user_is_not_found(): void { // Arrange $nonExistentUserId = fake()->randomNumber() + 1; $this->mockAuthManagerToUseDummyModel($nonExistentUserId, authenticatable: null, guardName: 'web'); $pendingRequest = resolve(PendingRequest::class); $handler = resolve(ImpersonateUserAuthorizationHandler::class, ['userId' => $nonExistentUserId]); // Anticipate $this->expectException(InvalidAuthorizationValueException::class); $this->expectExceptionMessage('User ID didn\'t resolve to a user to impersonate.'); $this->expectExceptionCode(InvalidAuthorizationValueException::USER_IS_NOT_FOUND); // Act $handler->authorize($pendingRequest); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Authorization/Handlers/NoAuthAuthorizationHandlerFunctionalTest.php
tests/App/Modules/Relay/Authorization/Handlers/NoAuthAuthorizationHandlerFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers; use Illuminate\Http\Client\PendingRequest; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\CoversClass; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\NoAuthorizationHandler; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(NoAuthorizationHandler::class)] class NoAuthAuthorizationHandlerFunctionalTest extends TestCase { public function test_it_does_nothing(): void { // Arrange /** * Creating a Mock in place of a Spy here so any method call breaks. We expect nothing to be called. * * @var PendingRequest&MockInterface $pendingRequestMock */ $pendingRequestMock = $this->mock(PendingRequest::class); $handler = resolve(NoAuthorizationHandler::class); // Act $pendingRequestResponse = $handler->authorize($pendingRequestMock); // Assert $this->assertSame($pendingRequestMock, $pendingRequestResponse); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Authorization/Handlers/AuthorizationHandlerFactoryUnitTest.php
tests/App/Modules/Relay/Authorization/Handlers/AuthorizationHandlerFactoryUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers; use Closure; use Generator; use Illuminate\Support\Arr; use InvalidArgumentException; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\CoversMethod; use PHPUnit\Framework\Attributes\DataProvider; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationCredentials; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationTypeEnum; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\AuthorizationHandlerFactory; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\BasicAuthAuthorizationHandler; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\BearerAuthorizationHandler; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\CurrentUserAuthorizationHandler; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\ImpersonateUserAuthorizationHandler; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\NoAuthorizationHandler; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(AuthorizationHandlerFactory::class)] #[CoversMethod(BasicAuthAuthorizationHandler::class, 'fromArray')] class AuthorizationHandlerFactoryUnitTest extends TestCase { #[DataProvider('createAuthorizationHandlerDataProvider')] public function test_it_creates_handler( AuthorizationCredentials $authorizationCredentials, string $expectedAuthorizationHandler, Closure $checkIsValid, ): void { // Arrange $factory = resolve(AuthorizationHandlerFactory::class); // Act $actualAuthorizationHandler = $factory->create($authorizationCredentials); // Assert $this->assertInstanceOf( $expectedAuthorizationHandler, $actualAuthorizationHandler, ); $this->assertTrue( $checkIsValid->call($this, $authorizationCredentials, $actualAuthorizationHandler), ); } public static function createAuthorizationHandlerDataProvider(): Generator { yield 'None handler' => [ 'authorizationCredentials' => AuthorizationCredentials::none(), 'expectedAuthorizationHandler' => NoAuthorizationHandler::class, 'checkIsValid' => fn (AuthorizationCredentials $credentials, NoAuthorizationHandler $handler): bool => true, ]; yield 'Bearer handler' => [ 'authorizationCredentials' => new AuthorizationCredentials(AuthorizationTypeEnum::Bearer, value: 'foobar'), 'expectedAuthorizationHandler' => BearerAuthorizationHandler::class, 'checkIsValid' => fn (AuthorizationCredentials $credentials, BearerAuthorizationHandler $handler): bool => $handler->token === 'foobar', ]; yield 'Basic handler' => [ 'authorizationCredentials' => new AuthorizationCredentials(AuthorizationTypeEnum::Basic, value: ['username' => 'foo', 'password' => 'bar']), 'expectedAuthorizationHandler' => BasicAuthAuthorizationHandler::class, 'checkIsValid' => fn (AuthorizationCredentials $credentials, BasicAuthAuthorizationHandler $handler): bool => $handler->username === 'foo' && $handler->password === 'bar', ]; yield 'Impersonate handler' => [ 'authorizationCredentials' => new AuthorizationCredentials(AuthorizationTypeEnum::Impersonate, value: 22), 'expectedAuthorizationHandler' => ImpersonateUserAuthorizationHandler::class, 'checkIsValid' => fn (AuthorizationCredentials $credentials, ImpersonateUserAuthorizationHandler $handler): bool => $handler->userId === 22, ]; yield 'Current User handler' => [ 'authorizationCredentials' => new AuthorizationCredentials(AuthorizationTypeEnum::CurrentUser, value: 22), 'expectedAuthorizationHandler' => CurrentUserAuthorizationHandler::class, 'checkIsValid' => fn (AuthorizationCredentials $credentials, CurrentUserAuthorizationHandler $handler): bool => true, ]; } #[DataProvider('authorizationHandlerValidationDataProvider')] public function test_it_validates_values_upon_creation( AuthorizationCredentials $authorizationCredentials, string $expectedError, ): void { // Arrange $factory = resolve(AuthorizationHandlerFactory::class); // Anticipate $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage($expectedError); // Act $factory->create($authorizationCredentials); } public static function authorizationHandlerValidationDataProvider(): Generator { yield 'Impersonate handler doesnt allow `nulls`' => [ 'authorizationCredentials' => new AuthorizationCredentials(AuthorizationTypeEnum::Impersonate, value: null), 'expectedError' => 'Impersonate user ID cannot be null.', ]; yield 'Impersonate handler doesnt allow strings`' => [ 'authorizationCredentials' => new AuthorizationCredentials(AuthorizationTypeEnum::Impersonate, value: 'abc'), 'expectedError' => 'Impersonate user ID must be an integer.', ]; yield 'Impersonate handler doesnt allow arrays`' => [ 'authorizationCredentials' => new AuthorizationCredentials(AuthorizationTypeEnum::Impersonate, value: ['username' => 'foo', 'password' => 'bar']), 'expectedError' => 'Impersonate user ID must be an integer.', ]; yield 'Bearer handler doesnt allow `nulls`' => [ 'authorizationCredentials' => new AuthorizationCredentials(AuthorizationTypeEnum::Bearer, value: null), 'expectedError' => 'Bearer token must be a string', ]; yield 'Bearer handler doesnt allow arrays' => [ 'authorizationCredentials' => new AuthorizationCredentials(AuthorizationTypeEnum::Bearer, value: ['username' => 'foo', 'password' => 'bar']), 'expectedError' => 'Bearer token must be a string', ]; yield 'Basic handler doesnt allow `nulls`' => [ 'authorizationCredentials' => new AuthorizationCredentials(AuthorizationTypeEnum::Basic, value: null), 'expectedError' => 'Basic auth credentials must be an array', ]; yield 'Basic handler doesnt allow strings' => [ 'authorizationCredentials' => new AuthorizationCredentials( AuthorizationTypeEnum::Basic, value: Arr::random(['abc', 22]) // <- 22 implicitly converted to "22" ), 'expectedError' => 'Basic auth credentials must be an array', ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Authorization/Handlers/CurrentUserAuthorizationHandlerFunctionalTest.php
tests/App/Modules/Relay/Authorization/Handlers/CurrentUserAuthorizationHandlerFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Request; use PHPUnit\Framework\Attributes\CoversClass; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\CurrentUserAuthorizationHandler; use Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers\Shared\HandlesRecallerCookies; use Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers\Stubs\DummyAuthenticatable; use Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers\Stubs\DummySpecialAuthenticationInjector; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(CurrentUserAuthorizationHandler::class)] class CurrentUserAuthorizationHandlerFunctionalTest extends TestCase { use HandlesRecallerCookies; public function test_it_uses_special_authentication_injector_to_authorize_request(): void { // Arrange config([ 'nimbus.auth.guard' => $guardName = fake()->word(), 'nimbus.auth.special.injector' => DummySpecialAuthenticationInjector::class, ]); $dummyAuthenticatable = new DummyAuthenticatable(id: $userId = fake()->randomNumber()); $this->mockAuthManagerToUseDummyModel($userId, $dummyAuthenticatable, $guardName); $relayRequest = Request::create('ping'); $relayRequest->setUserResolver(fn () => $dummyAuthenticatable); $dummySpecialAuthenticationInjectorMock = $this->mock(DummySpecialAuthenticationInjector::class); $handler = resolve(CurrentUserAuthorizationHandler::class, [ 'relayRequest' => $relayRequest, ]); $pendingRequest = resolve(PendingRequest::class); // Anticipate $dummySpecialAuthenticationInjectorMock ->shouldReceive('attach') ->withAnyArgs() ->andReturn($pendingRequest); // Act $responsePendingRequest = $handler->authorize($pendingRequest); // Assert $this->assertSame($pendingRequest, $responsePendingRequest); $dummySpecialAuthenticationInjectorMock ->shouldHaveReceived('attach') ->once() ->withArgs(function (PendingRequest $pendingRequestArg, Authenticatable $authenticatable) use ($pendingRequest, $dummyAuthenticatable) { $this->assertSame( $dummyAuthenticatable, $authenticatable, ); $this->assertSame($pendingRequestArg, $pendingRequest); return true; }); } public function test_it_returns_unmodified_request_when_no_cookies(): void { // Arrange $relayRequest = Request::create('ping'); $relayRequest->headers->set('HOST', fake()->domainName()); $handler = resolve( CurrentUserAuthorizationHandler::class, [ 'relayRequest' => $relayRequest, ], ); $pendingRequest = resolve(PendingRequest::class); // Act $pendingRequestResponse = $handler->authorize($pendingRequest); // Assert $cookies = $pendingRequestResponse->getOptions()['cookies'] ?? []; $this->assertEmpty($cookies); $this->assertSame($pendingRequest, $pendingRequestResponse); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Authorization/Handlers/BearerAuthorizationHandlerFunctionalTest.php
tests/App/Modules/Relay/Authorization/Handlers/BearerAuthorizationHandlerFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers; use Illuminate\Http\Client\PendingRequest; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\CoversMethod; use PHPUnit\Framework\Attributes\TestWith; use Sunchayn\Nimbus\Modules\Relay\Authorization\Exceptions\InvalidAuthorizationValueException; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\BearerAuthorizationHandler; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(BearerAuthorizationHandler::class)] #[CoversMethod(InvalidAuthorizationValueException::class, 'becauseBearerTokenValueIsNotString')] class BearerAuthorizationHandlerFunctionalTest extends TestCase { public function test_it_authorizes_requests(): void { // Arrange $pendingRequest = resolve(PendingRequest::class); $token = fake()->sha256(); $handler = new BearerAuthorizationHandler("$token "); // <- Adding a space to assert trimming. // Act $pendingRequestResponse = $handler->authorize($pendingRequest); // Assert $this->assertEquals( "Bearer $token", $pendingRequestResponse->getOptions()['headers']['Authorization'] ?? '--not-found--', ); $this->assertSame($pendingRequest, $pendingRequestResponse); } #[TestWith([''])] #[TestWith([' '])] public function test_it_breaks_with_invalid_token(string $invalidToken): void { // Anticipate $this->expectException(InvalidAuthorizationValueException::class); $this->expectExceptionMessage('Bearer token value is not a string.'); $this->expectExceptionCode(InvalidAuthorizationValueException::BEARER_TOKEN_IS_NOT_STRING); // Act resolve(BearerAuthorizationHandler::class, ['token' => $invalidToken]); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Authorization/Handlers/BasicAuthAuthorizationHandlerFunctionalTest.php
tests/App/Modules/Relay/Authorization/Handlers/BasicAuthAuthorizationHandlerFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers; use Illuminate\Http\Client\PendingRequest; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\CoversMethod; use PHPUnit\Framework\Attributes\TestWith; use Sunchayn\Nimbus\Modules\Relay\Authorization\Exceptions\InvalidAuthorizationValueException; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\BasicAuthAuthorizationHandler; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(BasicAuthAuthorizationHandler::class)] #[CoversMethod(InvalidAuthorizationValueException::class, 'becauseBasicAuthCredentialsAreInvalid')] class BasicAuthAuthorizationHandlerFunctionalTest extends TestCase { public function test_it_authorizes_requests(): void { // Arrange $pendingRequest = resolve(PendingRequest::class); $handler = new BasicAuthAuthorizationHandler( $username = fake()->userName(), $password = fake()->password(), ); // Act $pendingRequestResponse = $handler->authorize($pendingRequest); // Assert $this->assertEquals( [$username, $password], $pendingRequestResponse->getOptions()['auth'] ?? [], ); $this->assertSame($pendingRequest, $pendingRequestResponse); } #[TestWith(['username' => '', 'password' => ''])] #[TestWith(['username' => '', 'password' => ' '])] #[TestWith(['username' => ' ', 'password' => ' '])] public function test_it_breaks_with_invalid_credentials(string $username, string $password): void { // Anticipate $this->expectException(InvalidAuthorizationValueException::class); $this->expectExceptionMessage('Basic Auth credentials are invalid. Expects array{username: string, password: string}.'); $this->expectExceptionCode(InvalidAuthorizationValueException::BASIC_AUTH_SHAPE_IS_INVALID); // Act resolve(BasicAuthAuthorizationHandler::class, ['username' => $username, 'password' => $password]); } #[TestWith(['credentials' => ['username' => 'foobar']])] #[TestWith(['credentials' => ['password' => 'foobar']])] public function test_it_breaks_with_invalid_credentials_for_from_array(array $credentials): void { // Anticipate $this->expectException(InvalidAuthorizationValueException::class); $this->expectExceptionMessage('Basic Auth credentials are invalid. Expects array{username: string, password: string}.'); $this->expectExceptionCode(InvalidAuthorizationValueException::BASIC_AUTH_SHAPE_IS_INVALID); // Act BasicAuthAuthorizationHandler::fromArray($credentials); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Authorization/Handlers/Shared/HandlesRecallerCookies.php
tests/App/Modules/Relay/Authorization/Handlers/Shared/HandlesRecallerCookies.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers\Shared; use GuzzleHttp\Cookie\SetCookie; use Illuminate\Auth\AuthManager; use Illuminate\Contracts\Auth\Guard; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Cookie\CookieValuePrefix; use Mockery\MockInterface; use Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers\Stubs\DummyAuthenticatable; trait HandlesRecallerCookies { private const COOKIE_RECALLER_NAME = 'dummy_recaller'; /* * Mocks. */ private function mockAuthManagerToUseDummyModel(int $userId, ?DummyAuthenticatable $authenticatable, string $guardName): void { $userProvider = $this->mock(UserProvider::class, function (MockInterface $mock) use ($userId, $authenticatable) { $mock ->shouldReceive('retrieveById') ->with($userId) ->andReturn($authenticatable); }); $this->mockAuthManager($userProvider, $guardName); } private function mockAuthManager(MockInterface $userProvider, string $guard): void { $guardMock = $this->mock(Guard::class); $guardMock->shouldReceive('getProvider')->andReturn($userProvider); $guardMock->shouldReceive('getRecallerName')->andReturn(self::COOKIE_RECALLER_NAME); $authManagerMock = $this->mock(AuthManager::class); $authManagerMock->shouldReceive('guard')->with($guard)->andReturn($guardMock); app()->instance('auth', $authManagerMock); } /* * Asserts. */ private function assertCookieValue(SetCookie $cookie, string $expectedCookieValue): void { $encrypter = resolve('encrypter'); $expectedCookiePrefix = CookieValuePrefix::create(self::COOKIE_RECALLER_NAME, $encrypter->getKey()); $actualValueWithPrefix = $encrypter->decrypt($cookie->getValue(), unserialize: false); $this->assertStringStartsWith( $expectedCookiePrefix, $actualValueWithPrefix, 'The (decrypted) cookie value doesn\'t have the cookie prefix.', ); $actualValue = str_replace($expectedCookiePrefix, '', $actualValueWithPrefix); $this->assertEquals( $expectedCookieValue, $actualValue, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Authorization/Handlers/Stubs/DummyAuthenticatable.php
tests/App/Modules/Relay/Authorization/Handlers/Stubs/DummyAuthenticatable.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers\Stubs; use Illuminate\Contracts\Auth\Authenticatable; class DummyAuthenticatable implements Authenticatable { private readonly int $id; private string $rememberToken; public function __construct( ?int $id = null, ?string $rememberToken = null, ) { $this->id = $id ?? fake()->randomNumber(); $this->rememberToken = $rememberToken ?? fake()->sha256(); } public function getAuthIdentifierName() { return 'id'; } public function getAuthIdentifier() { return $this->id; } public function getAuthPasswordName() { return 'password'; } public function getAuthPassword() { return fake()->password(); } public function getRememberToken() { return $this->rememberToken; } public function setRememberToken($value) { $this->rememberToken = $value; } public function getRememberTokenName() { return 'remember_token'; } public function getRecallerCookieValue(): string { return $this->getAuthIdentifier().'|'.$this->getRememberToken().'|'.$this->getAuthPasswordName(); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Authorization/Handlers/Stubs/DummySpecialAuthenticationInjector.php
tests/App/Modules/Relay/Authorization/Handlers/Stubs/DummySpecialAuthenticationInjector.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers\Stubs; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Http\Client\PendingRequest; use Sunchayn\Nimbus\Modules\Relay\Authorization\Contracts\SpecialAuthenticationInjectorContract; class DummySpecialAuthenticationInjector implements SpecialAuthenticationInjectorContract { public function attach(PendingRequest $pendingRequest, Authenticatable $authenticatable): PendingRequest {} }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Actions/RequestRelayActionFunctionalTest.php
tests/App/Modules/Relay/Actions/RequestRelayActionFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Actions; use Carbon\CarbonImmutable; use Illuminate\Cookie\CookieValuePrefix; use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Client\Request; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Http; use Illuminate\Support\Str; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\TestWith; use Ramsey\Uuid\Uuid; use Sunchayn\Nimbus\Modules\Relay\Actions\RequestRelayAction; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationCredentials; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationTypeEnum; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\AuthorizationHandler; use Sunchayn\Nimbus\Modules\Relay\Authorization\Handlers\AuthorizationHandlerFactory; use Sunchayn\Nimbus\Modules\Relay\DataTransferObjects\RelayedRequestResponseData; use Sunchayn\Nimbus\Modules\Relay\DataTransferObjects\RequestRelayData; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ParseResultDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\VarDumpParser; use Sunchayn\Nimbus\Modules\Relay\Responses\DumpAndDieResponse; use Sunchayn\Nimbus\Modules\Relay\ValueObjects\ResponseCookieValueObject; use Sunchayn\Nimbus\Tests\TestCase; use Symfony\Component\HttpFoundation\ParameterBag; #[CoversClass(RequestRelayAction::class)] #[CoversClass(RequestRelayData::class)] #[CoversClass(RelayedRequestResponseData::class)] #[CoversClass(DumpAndDieResponse::class)] class RequestRelayActionFunctionalTest extends TestCase { private const ENDPOINT = 'https://localhost/api/test-endpoint'; #[TestWith([200, 'OK'])] #[TestWith([404, 'Not Found'])] #[TestWith([301, 'Moved Permanently'])] #[TestWith([500, 'Internal Server Error'])] #[TestWith([419, 'Method Not Allowed'])] public function test_it_relays_requests( int $stubStatusCode, string $expectedStatusText, ): void { // Arrange $requestData = new RequestRelayData( method: Arr::random([ 'POST', 'GET', 'PUT', ]), endpoint: self::ENDPOINT, authorization: $authorizationCredentials = $this->getRandomAuthorizationCredentials(), headers: [ 'Content-Type' => fake()->mimeType(), 'X-Custom-Header' => $customHeaderValue = uniqid(), ], body: ['test' => 'data'], cookies: new ParameterBag, ); CarbonImmutable::setTestNow(CarbonImmutable::now()); $stubBody = ['message' => 'success', 'data' => ['test' => 'data']]; $encryptedCookieOriginalValue = 'abc123xyzEncrypted'; $encryptedCookieValue = $this->getEncryptedCookieValue('sessionIdEncrypted', $encryptedCookieOriginalValue); $stubHeaders = [ 'Set-Cookie' => [ 'sessionId=abc123xyz; Path=/; HttpOnly; Secure; SameSite=Strict; Expires=Mon, 30 Sep 2025 23:59:59 GMT', "sessionIdEncrypted={$encryptedCookieValue}; Path=/; HttpOnly; Secure; SameSite=Strict; Expires=Mon, 30 Sep 2025 23:59:59 GMT", ], ]; // Anticipate Http::fake(function (Request $request) use ($stubStatusCode, $stubBody, $stubHeaders) { if ($request->url() !== self::ENDPOINT) { return null; } return Http::response( body: $stubBody + ['requestHeaders' => $request->headers()], status: $stubStatusCode, headers: $stubHeaders, ); }); $dummyAuthorizationHandler = $this->mock( AuthorizationHandler::class, fn (MockInterface $mock) => $mock->shouldReceive('authorize') ->with(Mockery::type(PendingRequest::class)) ->andReturnArg(index: 0), ); $this->mock( AuthorizationHandlerFactory::class, fn (MockInterface $mock) => $mock ->shouldReceive('create') ->with($authorizationCredentials) ->andReturn($dummyAuthorizationHandler), ); $requestRelayAction = resolve(RequestRelayAction::class); // Act $response = $requestRelayAction->execute($requestData); // Assert $this->assertEquals($stubStatusCode, $response->statusCode); $this->assertEquals($expectedStatusText, $response->statusText); $this->assertEquals( $stubBody, Arr::except( $response->body->body, 'requestHeaders', ), ); $this->assertEquals( $customHeaderValue, $response->body->body['requestHeaders']['X-Custom-Header'][0] ?? -1, ); $this->assertEquals( CarbonImmutable::now()->timestamp, $response->timestamp, ); $this->assertRelayResponseCookies( expectedCookies: [ [ 'name' => 'sessionId', 'raw' => 'abc123xyz', 'decrypted' => null, ], [ 'name' => 'sessionIdEncrypted', 'raw' => $encryptedCookieValue, 'decrypted' => $encryptedCookieOriginalValue, ], ], actualCookies: $response->cookies, ); $this->assertEquals( [ 'Content-Type' => ['application/json'], ...$stubHeaders, ], $response->headers, ); $this->assertEqualsWithDelta( 5, $response->durationMs, delta: 50, // <- Sweet spot for fluctuation. ); } #[TestWith(['get'])] #[TestWith(['head'])] public function test_it_merges_body_into_query_parameters_for_get_and_head_requests(string $method): void { // Arrange $bodyData = ['filter' => 'active', 'sort' => 'desc']; $queryParameters = ['page' => '1', 'limit' => '10']; $requestData = new RequestRelayData( method: $method, endpoint: self::ENDPOINT, authorization: AuthorizationCredentials::none(), headers: ['X-Custom-Header' => 'test'], body: $bodyData, cookies: new ParameterBag, queryParameters: $queryParameters, ); // Anticipate Http::fake(function (Request $request) use ($bodyData, $queryParameters) { // Assert that body data is merged into query parameters $expectedQueryParams = array_merge($queryParameters, $bodyData); foreach ($expectedQueryParams as $key => $value) { if (! str_contains($request->url(), "{$key}={$value}")) { return Http::response(['error' => 'Missing query parameter'], 400); } } // Assert that the request body is empty if (! empty($request->body())) { return Http::response(['error' => 'Body should be empty'], 400); } return Http::response([ 'success' => true, ]); }); $this->mockAuthorizationHandler(); $requestRelayAction = resolve(RequestRelayAction::class); // Act $response = $requestRelayAction->execute($requestData); // Assert $this->assertEquals(200, $response->statusCode); $this->assertEquals( [ 'success' => true, ], $response->body->body, ); } public function test_it_sends_json_body_by_default(): void { // Arrange $bodyData = ['user' => 'john', 'action' => 'login']; $requestData = new RequestRelayData( method: 'post', endpoint: self::ENDPOINT, authorization: AuthorizationCredentials::none(), headers: [], // <- Content-Type is missing => Json by default. body: $bodyData, cookies: new ParameterBag, ); // Anticipate Http::fake(function (Request $request) use ($bodyData) { $requestBody = json_decode($request->body(), true); return Http::response([ 'receivedBody' => $requestBody, 'bodyMatches' => $requestBody === $bodyData, ], 200); }); $this->mockAuthorizationHandler(); $requestRelayAction = resolve(RequestRelayAction::class); // Act $response = $requestRelayAction->execute($requestData); // Assert $this->assertTrue($response->body->body['bodyMatches'], 'POST body should be sent as JSON'); $this->assertEquals($bodyData, $response->body->body['receivedBody']); } public function test_it_url_decodes_cookie_values(): void { // Arrange $requestData = new RequestRelayData( method: 'get', endpoint: self::ENDPOINT, authorization: AuthorizationCredentials::none(), headers: [], body: [], cookies: new ParameterBag, ); $encodedValue = urlencode('test value with spaces'); $stubHeaders = [ 'Set-Cookie' => [ "testCookie={$encodedValue}; Path=/; HttpOnly", ], ]; // Anticipate Http::fake(fn () => Http::response(['success' => true], 200, $stubHeaders)); $this->mockAuthorizationHandler(); $requestRelayAction = resolve(RequestRelayAction::class); // Act $response = $requestRelayAction->execute($requestData); // Assert $this->assertCount(1, $response->cookies); $this->assertEquals('test value with spaces', $response->cookies[0]->toArray()['value']['raw']); } public function test_it_parses_dump_and_die_responses(): void { // Arrange $this->freezeTime(); $requestData = new RequestRelayData( method: 'GET', endpoint: self::ENDPOINT, authorization: AuthorizationCredentials::none(), headers: [ 'Content-Type' => 'application/json', 'X-Custom-Header' => $customHeaderValue = uniqid(), ], body: ['test' => 'data'], cookies: new ParameterBag, ); $uuid = fake()->uuid; $stubSource = fake()->filePath(); $stubDumps = [ 'type' => fake()->word(), 'value' => fake()->word(), ]; $parseResultDtoMock = Mockery::mock(ParseResultDto::class); $varDumpParserMock = $this->mock(VarDumpParser::class); $dumpHtml = '<script> Sfdump = window.Sfdump;</script><span>Hello World!</span>'; // Anticipate Str::createUuidsUsing(fn () => Uuid::fromString($uuid)); Http::fake(fn (Request $request) => Http::response( body: $dumpHtml, status: 500, headers: [], )); $parseResultDtoMock ->shouldReceive('toArray') ->andReturn([ 'source' => $stubSource, 'dumps' => $stubDumps, ]) ->once(); $varDumpParserMock->shouldReceive('parse')->with($dumpHtml)->andReturn($parseResultDtoMock)->once(); // Act $response = resolve(RequestRelayAction::class)->execute($requestData); // Assert $this->assertEquals(DumpAndDieResponse::DUMP_AND_DIE_STATUS_CODE, $response->statusCode); $this->assertEquals( [ 'id' => $uuid, 'timestamp' => now()->format('Y-m-d H:i:s'), 'source' => $stubSource, 'dumps' => $stubDumps, ], $response->body->body, ); } /* * Helpers. */ private function getRandomAuthorizationCredentials(): AuthorizationCredentials { return Arr::random([ AuthorizationCredentials::none(), new AuthorizationCredentials(AuthorizationTypeEnum::Basic, ['username' => 'user', 'password' => 'pass']), new AuthorizationCredentials(AuthorizationTypeEnum::Bearer, 'foobar'), new AuthorizationCredentials(AuthorizationTypeEnum::Impersonate, '14'), new AuthorizationCredentials(AuthorizationTypeEnum::CurrentUser, value: null), ]); } private function getEncryptedCookieValue(string $cookieName, string $rawValue): string { return app('encrypter') ->encrypt( value: CookieValuePrefix::create($cookieName, app('encrypter')->getKey()).$rawValue, serialize: false, ); } private function mockAuthorizationHandler(): void { $dummyAuthorizationHandler = $this->mock( AuthorizationHandler::class, fn (MockInterface $mock) => $mock->shouldReceive('authorize') ->andReturnArg(0), ); $this->mock( AuthorizationHandlerFactory::class, fn (MockInterface $mock) => $mock ->shouldReceive('create') ->andReturn($dummyAuthorizationHandler), ); } /* * Asserts. */ private function assertRelayResponseCookies(array $expectedCookies, array $actualCookies): void { $this->assertCount( count($expectedCookies), $actualCookies, ); $this->assertContainsOnlyInstancesOf( ResponseCookieValueObject::class, $actualCookies, ); foreach ($expectedCookies as $index => $expectedCookie) { $this->assertEquals( [ 'key' => $expectedCookie['name'], 'value' => [ 'raw' => $expectedCookie['raw'], 'decrypted' => $expectedCookie['decrypted'], ], ], $actualCookies[$index]->toArray(), ); } } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/ValueObjects/PrintableResponseBodyUnitTest.php
tests/App/Modules/Relay/ValueObjects/PrintableResponseBodyUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\ValueObjects; use Illuminate\Http\Client\Response; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Modules\Relay\ValueObjects\PrintableResponseBody; #[CoversClass(PrintableResponseBody::class)] class PrintableResponseBodyUnitTest extends TestCase { public function test_it_constructs_with_array_body(): void { // Arrange $body = ['foo' => 'bar', 'bar' => 'http://example.com/foo']; // Act $printable = new PrintableResponseBody($body); // Assert $this->assertSame($body, $printable->body); $this->assertSame(<<<'EXPECTED' { "foo": "bar", "bar": "http://example.com/foo" } EXPECTED, $printable->toPrettyJSON(), ); } public function test_it_constructs_with_string_body(): void { // Arrange $body = 'plain string'; // Act $printable = new PrintableResponseBody($body); // Assert $this->assertSame($body, $printable->body); $this->assertSame($body, $printable->toPrettyJSON()); } public function test_it_creates_from_response_with_json_body(): void { // Arrange $jsonData = ['hello' => 'world']; $response = $this->mockResponse(jsonMethodReturn: $jsonData); // Act $printable = PrintableResponseBody::fromResponse($response); // Assert $this->assertSame($jsonData, $printable->body); $this->assertSame(json_encode($jsonData, JSON_PRETTY_PRINT), $printable->toPrettyJSON()); } public function test_it_from_response_with_string_body(): void { // Arrange $stringData = 'raw string body'; // Act $response = $this->mockResponse(bodyMethodReturn: $stringData); // Assert $printable = PrintableResponseBody::fromResponse($response); $this->assertSame($stringData, $printable->body); $this->assertSame($stringData, $printable->toPrettyJSON()); } /* * Mocks. */ private function mockResponse(?array $jsonMethodReturn = null, ?string $bodyMethodReturn = null): Response { $mock = $this->getMockBuilder(Response::class) ->disableOriginalConstructor() ->getMock(); $mock->method('json')->willReturn($jsonMethodReturn); $mock->method('body')->willReturn($bodyMethodReturn ?? ''); return $mock; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/ValueObjects/ResponseCookieValueObjectFunctionalTest.php
tests/App/Modules/Relay/ValueObjects/ResponseCookieValueObjectFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\ValueObjects; use Mockery; use PHPUnit\Framework\Attributes\CoversClass; use Sunchayn\Nimbus\Modules\Relay\ValueObjects\ResponseCookieValueObject; #[CoversClass(ResponseCookieValueObject::class)] class ResponseCookieValueObjectFunctionalTest extends \Sunchayn\Nimbus\Tests\TestCase { public function test_it_computes_decrypted_value(): void { // Arrange $prefix = fake()->word(); $unencryptedValue = fake()->uuid(); $rawValue = encrypt($prefix.$unencryptedValue, serialize: false); // Act $actual = new ResponseCookieValueObject('foobar', rawValue: $rawValue, prefix: $prefix); // Assert $this->assertEquals( $unencryptedValue, invade($actual)->decryptedValue, ); } public function test_it_coverts_to_array(): void { // Arrange $prefix = fake()->word(); $unencryptedValue = fake()->uuid(); $rawValue = base64_encode($unencryptedValue); // <- Dummy value. // Mocked so that the __constructor is not called. We want to pretend it is already constructed. $invadedInstance = invade(Mockery::mock(ResponseCookieValueObject::class)->makePartial()); $invadedInstance->key = $key = fake()->word(); $invadedInstance->rawValue = $rawValue; $invadedInstance->decryptedValue = $unencryptedValue; $invadedInstance->prefix = $prefix; // Act $actual = $invadedInstance->toArray(); // Assert $this->assertEquals( [ 'key' => $key, 'value' => [ 'raw' => $rawValue, 'decrypted' => $unencryptedValue, ], ], $actual, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/DataTransferObjects/RequestRelayDataUnitTest.php
tests/App/Modules/Relay/DataTransferObjects/RequestRelayDataUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\DataTransferObjects; use Generator; use Mockery; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Http\Api\Relay\NimbusRelayRequest; use Sunchayn\Nimbus\Modules\Relay\Authorization\AuthorizationTypeEnum; use Sunchayn\Nimbus\Modules\Relay\DataTransferObjects\RequestRelayData; use Symfony\Component\HttpFoundation\InputBag; #[CoversClass(RequestRelayData::class)] class RequestRelayDataUnitTest extends TestCase { #[DataProvider('endpointsDataProvider')] public function test_it_creates_instance_from_api_request( string $endpoint, string $expectedEndpoint, array $expectedParameters, ): void { // Arrange $mockRequest = Mockery::mock(NimbusRelayRequest::class); $mockRequest->shouldReceive('userAgent')->andReturn('::dummy_user_agent::'); $mockRequest->shouldReceive('host')->andReturn('::dummy_host::'); $mockCookies = new InputBag; $mockRequest->cookies = $mockCookies; $stubAuthorizationType = AuthorizationTypeEnum::Bearer; // Anticipate $mockRequest ->shouldReceive('validated') ->andReturn( [ 'method' => $method = 'POST', 'endpoint' => $endpoint, 'authorization' => [ 'type' => $stubAuthorizationType->value, 'value' => $authorizationValue = 'foobar', ], 'headers' => [ ['key' => 'Content-Type', 'value' => 'application/json'], ['key' => 'X-Custom-Header', 'value' => '::value::'], ], 'body' => $body = ['test' => 'data'], ], ); $mockRequest->shouldReceive('getBody')->andReturn($body); // Act $result = RequestRelayData::fromRelayApiRequest($mockRequest); // Assert $this->assertEquals(strtolower($method), $result->method); $this->assertEquals($expectedEndpoint, $result->endpoint); $this->assertEquals($stubAuthorizationType, $result->authorization->type); $this->assertEquals($authorizationValue, $result->authorization->value); $this->assertEquals( [ 'accept' => 'application/json', 'content-type' => 'application/json', 'x-custom-header' => '::value::', 'user-agent' => '::dummy_user_agent::', ], $result->headers); $this->assertEquals($body, $result->body); $this->assertSame($mockCookies, $result->cookies); $this->assertEquals( $expectedParameters, $result->queryParameters, ); } public static function endpointsDataProvider(): Generator { yield 'simple path without params' => [ 'endpoint' => '/api/test', 'expectedEndpoint' => '/api/test', 'expectedParameters' => [], ]; yield 'simple path with single param' => [ 'endpoint' => '/api/test?parameter-1=value', 'expectedEndpoint' => '/api/test', 'expectedParameters' => ['parameter-1' => 'value'], ]; yield 'absolute URL without params' => [ 'endpoint' => 'https://127.0.0.1/api/test', 'expectedEndpoint' => 'https://127.0.0.1/api/test', 'expectedParameters' => [], ]; yield 'absolute URL with multiple params including broken' => [ 'endpoint' => 'https://127.0.0.1/api/test?key=1&key-2=&broken', 'expectedEndpoint' => 'https://127.0.0.1/api/test', 'expectedParameters' => ['key' => '1', 'key-2' => ''], ]; yield 'absolute URL with multiple valid params' => [ 'endpoint' => 'https://127.0.0.1/api/test?key=value&key-2=value-2', 'expectedEndpoint' => 'https://127.0.0.1/api/test', 'expectedParameters' => ['key' => 'value', 'key-2' => 'value-2'], ]; yield 'absolute URL with port and param' => [ 'endpoint' => 'https://127.0.0.1:8000/api/test?key=value', 'expectedEndpoint' => 'https://127.0.0.1:8000/api/test', 'expectedParameters' => ['key' => 'value'], ]; yield 'invalid URL with port and param' => [ 'endpoint' => 'http://:80?key=value', 'expectedEndpoint' => 'http://:80?key=value', // parse_url failed, return as is. 'expectedParameters' => [], ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Relay/Parsers/VarDumpParser/VarDumpParserUnitTest.php
tests/App/Modules/Relay/Parsers/VarDumpParser/VarDumpParserUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Relay\Parsers\VarDumpParser; use Generator; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ObjectPropertyDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ParsedArrayResultDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ParsedClosureResultDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ParsedObjectResultDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ParsedValueDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\DataTransferObjects\ParseResultDto; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\Enums\DumpValueTypeEnum; use Sunchayn\Nimbus\Modules\Relay\Parsers\VarDumpParser\VarDumpParser; #[CoversClass(VarDumpParser::class)] #[CoversClass(ParseResultDto::class)] #[CoversClass(ParsedValueDto::class)] #[CoversClass(ObjectPropertyDto::class)] #[CoversClass(ParsedArrayResultDto::class)] #[CoversClass(ParsedObjectResultDto::class)] #[CoversClass(ParsedClosureResultDto::class)] #[CoversClass(DumpValueTypeEnum::class)] class VarDumpParserUnitTest extends TestCase { private VarDumpParser $parser; protected function setUp(): void { parent::setUp(); $this->parser = new VarDumpParser; } #[DataProvider('primitiveTypesProvider')] public function test_it_parses_primitive_types( string $html, string $expectedType, mixed $expectedValue, ): void { // Act $result = $this->parser->parse($html); // Assert $dumps = $result->toArray()['dumps']; $this->assertJsonStructureMatches( [ 'type' => $expectedType, 'value' => $expectedValue, ], $dumps[0], ); } public static function primitiveTypesProvider(): Generator { // Strings yield 'simple string' => [ 'html' => '<pre class=sf-dump>"<span class=sf-dump-str title="3 characters">wow</span>"<span style="color: #A0A0A0;"> // test.php:10</span></pre>', 'expectedType' => DumpValueTypeEnum::String->value, 'expectedValue' => 'wow', ]; yield 'empty string' => [ 'html' => '<pre class=sf-dump>"<span class=sf-dump-str title="0 characters"></span>"</pre>', 'expectedType' => DumpValueTypeEnum::String->value, 'expectedValue' => '', ]; yield 'undefined string value' => [ 'html' => '<pre class=sf-dump>"<span class=sf-dump-str title="0 characters">"</pre>', 'expectedType' => DumpValueTypeEnum::String->value, 'expectedValue' => '', ]; yield 'string with special characters' => [ 'html' => '<pre class=sf-dump>"<span class=sf-dump-str title="5 characters">&lt;div&gt;</span>"</pre>', 'expectedType' => DumpValueTypeEnum::String->value, 'expectedValue' => '<div>', ]; yield 'string with ampersand' => [ 'html' => '<pre class=sf-dump>"<span class=sf-dump-str title="9 characters">Tom &amp; Jerry</span>"</pre>', 'expectedType' => DumpValueTypeEnum::String->value, 'expectedValue' => 'Tom & Jerry', ]; yield 'string with quotes' => [ 'html' => '<pre class=sf-dump>"<span class=sf-dump-str title="8 characters">He said &quot;hi&quot;</span>"</pre>', 'expectedType' => DumpValueTypeEnum::String->value, 'expectedValue' => 'He said "hi"', ]; yield 'string with angle brackets' => [ 'html' => '<pre class=sf-dump>"<span class=sf-dump-str title="11 characters">&lt;html&gt; tag</span>"</pre>', 'expectedType' => DumpValueTypeEnum::String->value, 'expectedValue' => '<html> tag', ]; // Numbers yield 'positive integer' => [ 'html' => '<pre class=sf-dump><span class=sf-dump-num>42</span><span style="color: #A0A0A0;"> // test.php:10</span></pre>', 'expectedType' => DumpValueTypeEnum::Number->value, 'expectedValue' => 42, ]; yield 'zero' => [ 'html' => '<pre class=sf-dump><span class=sf-dump-num>0</span></pre>', 'expectedType' => DumpValueTypeEnum::Number->value, 'expectedValue' => 0, ]; yield 'undefined number value' => [ 'html' => '<pre class=sf-dump><span class=sf-dump-num></span></pre>', 'expectedType' => DumpValueTypeEnum::Number->value, 'expectedValue' => 0, ]; yield 'negative integer' => [ 'html' => '<pre class=sf-dump><span class=sf-dump-num>-42</span></pre>', 'expectedType' => DumpValueTypeEnum::Number->value, 'expectedValue' => -42, ]; yield 'float value' => [ 'html' => '<pre class=sf-dump><span class=sf-dump-num>3.14</span><span style="color: #A0A0A0;"> // test.php:10</span></pre>', 'expectedType' => DumpValueTypeEnum::Number->value, 'expectedValue' => 3.14, ]; yield 'negative float' => [ 'html' => '<pre class=sf-dump><span class=sf-dump-num>-99.99</span></pre>', 'expectedType' => DumpValueTypeEnum::Number->value, 'expectedValue' => -99.99, ]; // Constants yield 'boolean true' => [ 'html' => '<pre class=sf-dump><span class=sf-dump-const>true</span><span style="color: #A0A0A0;"> // test.php:10</span></pre>', 'expectedType' => DumpValueTypeEnum::Constant->value, 'expectedValue' => true, ]; yield 'boolean false' => [ 'html' => '<pre class=sf-dump><span class=sf-dump-const>false</span><span style="color: #A0A0A0;"> // test.php:10</span></pre>', 'expectedType' => DumpValueTypeEnum::Constant->value, 'expectedValue' => false, ]; yield 'null value' => [ 'html' => '<pre class=sf-dump><span class=sf-dump-const>null</span><span style="color: #A0A0A0;"> // test.php:10</span></pre>', 'expectedType' => DumpValueTypeEnum::Constant->value, 'expectedValue' => null, ]; yield 'undefined const value' => [ 'html' => '<pre class=sf-dump><span class=sf-dump-const></span><span style="color: #A0A0A0;"> // test.php:10</span></pre>', 'expectedType' => DumpValueTypeEnum::Constant->value, 'expectedValue' => null, ]; } #[DataProvider('arrayStructuresProvider')] public function test_it_parses_array_structures( string $html, array $expectedStructure, ): void { // Act $result = $this->parser->parse($html); // Assert $dump = $result->toArray()['dumps'][0]; $this->assertEquals(DumpValueTypeEnum::Array->value, $dump['type']); $this->assertJsonStructureMatches( $expectedStructure, $dump['value'], ); } public static function arrayStructuresProvider(): Generator { yield 'empty array' => [ 'html' => <<<'HTML' <pre class=sf-dump id=sf-dump-265345762 data-indent-pad=" ">[]<span style="color: #A0A0A0;"> // app/Http/Controllers/Demo/DumpAndDieController.php:140</span> </pre></pre><script>Sfdump("sf-dump-265345762")</script> HTML, 'expectedStructure' => [ 'length' => 0, 'items' => [], 'numericallyIndexed' => true, ], ]; yield 'another empty array' => [ 'html' => <<<'HTML' <pre class=sf-dump id=sf-dump-265345762 data-indent-pad=" "><span class=sf-dump-note>array:2</span> [ &#8230;2]<span style="color: #A0A0A0;"> // app/Http/Controllers/Demo/DumpAndDieController.php:140</span> </pre> HTML, 'expectedStructure' => [ 'length' => 0, 'items' => [], 'numericallyIndexed' => true, ], ]; yield 'indexed array with strings' => [ 'html' => <<<'HTML' <pre class=sf-dump><span class=sf-dump-note>array:2</span> [<samp data-depth=1 class=sf-dump-expanded> <span class=sf-dump-index>0</span> => "<span class=sf-dump-str title="4 characters">Foo</span>" <span class=sf-dump-index>1</span> => "<span class=sf-dump-str title="5 characters">Bar</span>" </samp>]</pre> HTML, 'expectedStructure' => [ 'length' => 2, 'items' => [ 0 => ['type' => DumpValueTypeEnum::String->value, 'value' => 'Foo'], 1 => ['type' => DumpValueTypeEnum::String->value, 'value' => 'Bar'], ], 'numericallyIndexed' => true, ], ]; yield 'non-indexed array with strings numerical indices' => [ 'html' => <<<'HTML' <pre class=sf-dump><span class=sf-dump-note>array:2</span> [<samp data-depth=1 class=sf-dump-expanded> "<span class=sf-dump-key>0</span>" => "<span class=sf-dump-str title="3 characters">Foo</span>" "<span class=sf-dump-key>2</span>" => "<span class=sf-dump-str title="3 characters">Bar</span>" "<span class=sf-dump-key>4</span>" => "<span class=sf-dump-str title="3 characters">Baz</span>" </samp>]</pre> HTML, 'expectedStructure' => [ 'length' => 3, 'items' => [ 0 => ['type' => DumpValueTypeEnum::String->value, 'value' => 'Foo'], 2 => ['type' => DumpValueTypeEnum::String->value, 'value' => 'Bar'], 4 => ['type' => DumpValueTypeEnum::String->value, 'value' => 'Baz'], ], 'numericallyIndexed' => false, ], ]; yield 'associative array with strings' => [ 'html' => <<<'HTML' <pre class=sf-dump><span class=sf-dump-note>array:2</span> [<samp data-depth=1 class=sf-dump-expanded> "<span class=sf-dump-key>name</span>" => "<span class=sf-dump-str title="4 characters">John</span>" "<span class=sf-dump-key>role</span>" => "<span class=sf-dump-str title="5 characters">admin</span>" </samp>]</pre> HTML, 'expectedStructure' => [ 'length' => 2, 'items' => [ 'name' => ['type' => DumpValueTypeEnum::String->value, 'value' => 'John'], 'role' => ['type' => DumpValueTypeEnum::String->value, 'value' => 'admin'], ], 'numericallyIndexed' => false, ], ]; yield 'array with mixed types' => [ 'html' => <<<'HTML' <pre class=sf-dump><span class=sf-dump-note>array:3</span> [<samp data-depth=1 class=sf-dump-expanded> "<span class=sf-dump-key>name</span>" => "<span class=sf-dump-str title="4 characters">Jane</span>" "<span class=sf-dump-key>age</span>" => <span class=sf-dump-num>25</span> "<span class=sf-dump-key>active</span>" => <span class=sf-dump-const>true</span> </samp>]</pre> HTML, 'expectedStructure' => [ 'length' => 3, 'items' => [ 'name' => ['type' => DumpValueTypeEnum::String->value, 'value' => 'Jane'], 'age' => ['type' => DumpValueTypeEnum::Number->value, 'value' => 25], 'active' => ['type' => DumpValueTypeEnum::Constant->value, 'value' => true], ], 'numericallyIndexed' => false, ], ]; yield 'nested array' => [ 'html' => <<<'HTML' <pre class=sf-dump><span class=sf-dump-note>array:2</span> [<samp data-depth=1 class=sf-dump-expanded> "<span class=sf-dump-key>user</span>" => "<span class=sf-dump-str title="4 characters">John</span>" "<span class=sf-dump-key>meta</span>" => <span class=sf-dump-note>array:2</span> [<samp data-depth=2 class=sf-dump-compact> "<span class=sf-dump-key>role</span>" => "<span class=sf-dump-str title="5 characters">admin</span>" "<span class=sf-dump-key>level</span>" => <span class=sf-dump-num>5</span> </samp>] </samp>]</pre> HTML, 'expectedStructure' => [ 'length' => 2, 'items' => [ 'user' => ['type' => DumpValueTypeEnum::String->value, 'value' => 'John'], 'meta' => [ 'type' => DumpValueTypeEnum::Array->value, 'value' => [ 'length' => 2, 'items' => [ 'role' => ['type' => DumpValueTypeEnum::String->value, 'value' => 'admin'], 'level' => ['type' => DumpValueTypeEnum::Number->value, 'value' => 5], ], 'numericallyIndexed' => false, ], ], ], 'numericallyIndexed' => false, ], ]; } #[DataProvider('objectStructuresProvider')] public function test_it_parses_object_structures( string $html, ?string $expectedClass, array $expectedProperties, ): void { // Act $result = $this->parser->parse($html); // Assert $dumps = $result->toArray()['dumps']; $this->assertJsonStructureMatches( [ 'type' => DumpValueTypeEnum::Object->value, 'value' => [ 'class' => $expectedClass, 'properties' => $expectedProperties, 'propertiesCount' => count($expectedProperties), ], ], $dumps[0], ); } public static function objectStructuresProvider(): Generator { yield 'object with public properties (and improper indentation)' => [ 'html' => <<<'HTML' <pre class=sf-dump><span class=sf-dump-note>App\Models\User</span> {<a class=sf-dump-ref>#123</a><samp data-depth=1 class=sf-dump-expanded> +<span class=sf-dump-public title="Public property">id</span>: <span class=sf-dump-num>1</span> +<span class=sf-dump-public title="Public property">name</span>: "<span class=sf-dump-str title="4 characters">John</span>" </samp>}</pre> HTML, 'expectedClass' => 'App\Models\User', 'expectedProperties' => [ 'id' => [ 'visibility' => 'public', 'value' => ['type' => DumpValueTypeEnum::Number->value, 'value' => 1], ], 'name' => [ 'visibility' => 'public', 'value' => ['type' => DumpValueTypeEnum::String->value, 'value' => 'John'], ], ], ]; yield 'object with mixed visibility properties' => [ 'html' => <<<'HTML' <pre class=sf-dump><span class=sf-dump-note>App\Models\User</span> {<a class=sf-dump-ref>#456</a><samp data-depth=1 class=sf-dump-expanded> +<span class=sf-dump-public title="Public property">id</span>: <span class=sf-dump-num>1</span> #<span class=sf-dump-protected title="Protected property">password</span>: "<span class=sf-dump-str title="6 characters">secret</span>" -<span class=sf-dump-private title="Private property">token</span>: "<span class=sf-dump-str title="5 characters">12345</span>" </samp>}</pre> HTML, 'expectedClass' => 'App\Models\User', 'expectedProperties' => [ 'id' => [ 'visibility' => 'public', 'value' => ['type' => DumpValueTypeEnum::Number->value, 'value' => 1], ], 'password' => [ 'visibility' => 'protected', 'value' => ['type' => DumpValueTypeEnum::String->value, 'value' => 'secret'], ], 'token' => [ 'visibility' => 'private', 'value' => ['type' => DumpValueTypeEnum::String->value, 'value' => '12345'], ], ], ]; yield 'runtime object with nested structures' => [ 'html' => <<<'HTML'
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
true
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Actions/BuildGlobalHeadersActionFunctionalTest.php
tests/App/Modules/Routes/Actions/BuildGlobalHeadersActionFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Actions; use Illuminate\Config\Repository; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\CoversClass; use Sunchayn\Nimbus\Modules\Config\GlobalHeaderGeneratorTypeEnum; use Sunchayn\Nimbus\Modules\Routes\Actions\BuildGlobalHeadersAction; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(BuildGlobalHeadersAction::class)] class BuildGlobalHeadersActionFunctionalTest extends TestCase { public function test_it_builds_global_headers(): void { // Arrange $globalHeadersConfig = [ 'x-request-id' => GlobalHeaderGeneratorTypeEnum::Uuid, 'x-author-email' => GlobalHeaderGeneratorTypeEnum::Email, 'x-author-id' => GlobalHeaderGeneratorTypeEnum::String, 'X-Custom-Header' => '::value::', ]; $this->mock( Repository::class, function (MockInterface $mock) use ($globalHeadersConfig) { $mock ->shouldReceive('get') ->with('nimbus.headers') ->andReturn($globalHeadersConfig); }, ); $action = resolve(BuildGlobalHeadersAction::class); // Act $headers = $action->execute(); // Assert $this->assertEquals( [ [ 'header' => 'x-request-id', 'type' => 'generator', 'value' => 'UUID', ], [ 'header' => 'x-author-email', 'type' => 'generator', 'value' => 'Email', ], [ 'header' => 'x-author-id', 'type' => 'generator', 'value' => 'String', ], [ 'header' => 'X-Custom-Header', 'type' => 'raw', 'value' => '::value::', ], ], $headers ); } public function test_it_works_without_headers(): void { // Arrange $this->mock( Repository::class, function (MockInterface $mock) { $mock ->shouldReceive('get') ->with('nimbus.headers') ->andReturn([]); }, ); $action = resolve(BuildGlobalHeadersAction::class); // Act $headers = $action->execute(); // Assert $this->assertEmpty($headers); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Actions/DisableThirdPartyUiActionFunctionalTest.php
tests/App/Modules/Routes/Actions/DisableThirdPartyUiActionFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Actions; use PHPUnit\Framework\Attributes\CoversClass; use Sunchayn\Nimbus\Modules\Routes\Actions\DisableThirdPartyUiAction; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(DisableThirdPartyUiAction::class)] class DisableThirdPartyUiActionFunctionalTest extends TestCase { public function test_it_disables_debug_bar_w_hen_it_exists(): void { // TODO [Test] Figure out a way to test this. $this->addToAssertionCount(1); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Actions/IgnoreRouteErrorActionFunctionalTest.php
tests/App/Modules/Routes/Actions/IgnoreRouteErrorActionFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Actions; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\TestWith; use Sunchayn\Nimbus\Modules\Routes\Actions\IgnoreRouteErrorAction; use Sunchayn\Nimbus\Modules\Routes\Services\IgnoredRoutesService; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(IgnoreRouteErrorAction::class)] class IgnoreRouteErrorActionFunctionalTest extends TestCase { public function test_it_ignores_routes_when_applicable(): void { // Arrange $ignoredRoutesServiceSpy = $this->spy(IgnoredRoutesService::class); $ignoredRouteErrorAction = resolve(IgnoreRouteErrorAction::class); $uri = 'api/users'; $methods = ['GET', 'POST']; $ignoreData = $uri.'|'.json_encode($methods); // Act $ignoredRouteErrorAction->execute($ignoreData); // Assert $ignoredRoutesServiceSpy ->shouldHaveReceived( 'add', function (string $uriArg, array $methodsArg) use ($uri, $methods) { $this->assertEquals( $uri, $uriArg, ); $this->assertEquals( $methods, $methodsArg, ); return true; }, ); } public function test_it_gracefully_workaround_invalid_methods_structure(): void { // Arrange $ignoredRoutesServiceSpy = $this->spy(IgnoredRoutesService::class); $ignoredRouteErrorAction = resolve(IgnoreRouteErrorAction::class); $uri = 'api/users'; $methods = ['GET', 'POST']; $ignoreData = $uri.'|'.implode(',', $methods); // Act $ignoredRouteErrorAction->execute($ignoreData); // Assert $ignoredRoutesServiceSpy ->shouldHaveReceived( 'add', function (string $uriArg, array $methodsArg) use ($uri) { $this->assertEquals( $uri, $uriArg, ); $this->assertEquals( [], // <- Didn't use the methods and used empty array instead. $methodsArg, ); return true; }, ); } #[TestWith(['foobar'], 'Missing Parts')] #[TestWith(['foobar|["get","post"]|foobaz'], 'Extra Parts')] #[TestWith(['|["get","post"]'], 'Empty URI')] public function test_it_does_nothing_with_broken_input(string $ignoreData): void { // Arrange $ignoredRoutesServiceSpy = $this->spy(IgnoredRoutesService::class); $ignoredRouteErrorAction = resolve(IgnoreRouteErrorAction::class); // Act $ignoredRouteErrorAction->execute($ignoreData); // Assert $ignoredRoutesServiceSpy->shouldNotHaveReceived('add'); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Actions/BuildCurrentUserActionFunctionalTest.php
tests/App/Modules/Routes/Actions/BuildCurrentUserActionFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Actions; use PHPUnit\Framework\Attributes\CoversClass; use Sunchayn\Nimbus\Modules\Routes\Actions\BuildCurrentUserAction; use Sunchayn\Nimbus\Tests\App\Modules\Relay\Authorization\Handlers\Stubs\DummyAuthenticatable; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(BuildCurrentUserAction::class)] class BuildCurrentUserActionFunctionalTest extends TestCase { public function test_it_builds_current_user(): void { // Arrange $user = new DummyAuthenticatable($id = fake()->randomNumber()); auth()->setUser($user); $action = resolve(BuildCurrentUserAction::class); // Act $metadata = $action->execute(); // Assert $this->assertEquals( [ 'id' => $id, ], $metadata ); } public function test_it_builds_nothing_for_guests(): void { // Arrange $action = resolve(BuildCurrentUserAction::class); // Act $metadata = $action->execute(); // Assert $this->assertEmpty($metadata); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Collections/ExtractedRoutesCollectionUnitTest.php
tests/App/Modules/Routes/Collections/ExtractedRoutesCollectionUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Collections; use Error; use Generator; use Illuminate\Support\Arr; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Modules\Routes\Collections\ExtractedRoutesCollection; use Sunchayn\Nimbus\Modules\Routes\DataTransferObjects\ExtractedRoute; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\Endpoint; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\RulesExtractionError; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty; #[CoversClass(ExtractedRoutesCollection::class)] class ExtractedRoutesCollectionUnitTest extends TestCase { #[DataProvider('covertToFrontendArrayDataProvider')] public function test_it_converts_to_frontend_array( array $items, array $expected, ): void { // Arrange $collection = new ExtractedRoutesCollection($items); // Act $output = $collection->toFrontendArray(); // Assert $output = $this->replaceTraceWithPlaceholder($output); $this->assertEquals( $expected, $output, ); } public static function covertToFrontendArrayDataProvider(): Generator { yield 'Empty array' => [ 'items' => [], 'expected' => [], ]; yield 'Filled array' => [ 'items' => [ new ExtractedRoute( uri: new Endpoint( version: 'v1', resource: 'users', value: '/api/users', ), methods: ['GET'], schema: Schema::empty(), ), new ExtractedRoute( uri: new Endpoint( version: 'v1', resource: 'users', value: '/api/users', ), methods: ['POST'], schema: Schema::empty(), ), new ExtractedRoute( uri: new Endpoint( version: 'v1', resource: 'posts', value: '/api/posts', ), methods: ['POST'], schema: new Schema( properties: [ new SchemaProperty( name: 'type', ), ], ), ), ], 'expected' => [ 'v1' => [ 'users' => [ [ 'uri' => '/api/users', 'shortUri' => 'users', 'methods' => ['GET'], 'schema' => [ '$schema' => 'https://json-schema.org/draft/2020-12/schema', 'type' => 'object', 'properties' => [], 'required' => [], 'additionalProperties' => false, ], 'extractionError' => null, ], [ 'uri' => '/api/users', 'shortUri' => 'users', 'methods' => ['POST'], 'schema' => [ '$schema' => 'https://json-schema.org/draft/2020-12/schema', 'type' => 'object', 'properties' => [], 'required' => [], 'additionalProperties' => false, ], 'extractionError' => null, ], ], 'posts' => [ [ 'uri' => '/api/posts', 'shortUri' => 'posts', 'methods' => ['POST'], 'schema' => [ '$schema' => 'https://json-schema.org/draft/2020-12/schema', 'type' => 'object', 'properties' => [ 'type' => [ 'type' => 'string', 'x-name' => 'type', 'x-required' => false, ], ], 'required' => [], 'additionalProperties' => false, ], 'extractionError' => null, ], ], ], ], ]; yield 'Filled array with errors' => [ 'items' => [ new ExtractedRoute( uri: new Endpoint( version: 'v1', resource: 'users', value: '/api/users', ), methods: ['GET'], schema: Schema::empty(), ), new ExtractedRoute( uri: new Endpoint( version: 'v1', resource: 'users', value: '/api/users', ), methods: ['POST'], schema: new Schema( properties: [], extractionError: new RulesExtractionError( throwable: new Error, ) ), ), ], 'expected' => [ 'v1' => [ 'users' => [ [ 'uri' => '/api/users', 'shortUri' => 'users', 'methods' => ['GET'], 'schema' => [ '$schema' => 'https://json-schema.org/draft/2020-12/schema', 'type' => 'object', 'properties' => [], 'required' => [], 'additionalProperties' => false, ], 'extractionError' => null, ], [ 'uri' => '/api/users', 'shortUri' => 'users', 'methods' => ['POST'], 'schema' => [ '$schema' => 'https://json-schema.org/draft/2020-12/schema', 'type' => 'object', 'properties' => [], 'required' => [], 'additionalProperties' => false, ], 'extractionError' => '<b>[no error message]</b><br /> <small>'.__FILE__.'::163</small> <p class="text-xs">[trace]</p>', ], ], ], ], ]; } /* * Helpers. */ private function replaceTraceWithPlaceholder(array $output): array { return Arr::map( $output, fn (array $routesInVersion) => Arr::map( $routesInVersion, fn (array $resourceRoutes) => Arr::map( $resourceRoutes, function (array $route) { if ($route['extractionError'] === null) { return $route; } $route['extractionError'] = preg_replace('#(<p\b[^>]*>).*?(</p>)#si', '$1[trace]$2', $route['extractionError']); return $route; }, ) ) ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Collections/Stubs/DummyException.php
tests/App/Modules/Routes/Collections/Stubs/DummyException.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Collections\Stubs; use Error; class DummyException extends Error {}
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Services/IgnoredRoutesServiceFunctionalTest.php
tests/App/Modules/Routes/Services/IgnoredRoutesServiceFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Services; use Carbon\CarbonImmutable; use Generator; use Illuminate\Routing\Route; use Illuminate\Support\Facades\File; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use Sunchayn\Nimbus\Modules\Routes\Services\IgnoredRoutesService; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(IgnoredRoutesService::class)] class IgnoredRoutesServiceFunctionalTest extends TestCase { private const FILE_PATH = 'vendor/sunchayn/nimbus/storage/ignored_routes.json'; protected function setUp(): void { parent::setUp(); File::delete(base_path(self::FILE_PATH)); File::deleteDirectory(dirname(base_path(self::FILE_PATH))); } public function test_it_has_no_ignored_routes_initially(): void { // Arrange $service = resolve(IgnoredRoutesService::class); // Act $hasIgnoredRoutes = $service->hasIgnoredRoutes(); // Assert $this->assertFalse($hasIgnoredRoutes); } public function test_it_adds_route_to_ignored_list(): void { // Arrange $service = resolve(IgnoredRoutesService::class); $route = $this->createMockRoute(uri: '/api/users', methods: ['GET', 'POST']); // Act $service->add( uri: $route->uri(), methods: $route->methods(), reason: 'Test reason' ); // Assert $this->assertTrue($service->hasIgnoredRoutes()); $this->assertTrue($service->isIgnored($route)); } public function test_it_persists_ignored_routes_to_file_on_destruct(): void { // Arrange CarbonImmutable::setTestNow(CarbonImmutable::now()); $service = resolve(IgnoredRoutesService::class); $service->add(uri: '/api/users', methods: ['GET'], reason: 'Test reason'); $filePath = base_path(self::FILE_PATH); // Act $service->__destruct(); // Assert $this->assertTrue(File::exists($filePath)); $content = json_decode(File::get($filePath), true); $this->assertEquals( [ '/api/users' => [ 'methods' => ['GET'], 'reason' => 'Test reason', 'ignored_at' => CarbonImmutable::now()->toISOString(), ], ], $content, ); } public function test_it_overwrites_existing_ignored_route(): void { // Arrange $service = resolve(IgnoredRoutesService::class); $service->add(uri: '/api/users', methods: ['GET'], reason: 'First reason'); $service->add(uri: '/api/users', methods: ['POST'], reason: 'Second reason'); $filePath = base_path(self::FILE_PATH); // Act $service->__destruct(); // Assert $this->assertTrue(File::exists($filePath)); $content = json_decode(File::get($filePath), true); $this->assertEquals(['POST'], $content['/api/users']['methods']); $this->assertEquals('Second reason', $content['/api/users']['reason']); } public function test_it_does_not_write_to_file_if_not_dirty(): void { // Arrange $service = resolve(IgnoredRoutesService::class); $filePath = base_path(self::FILE_PATH); // Act $service->__destruct(); // Assert $this->assertFalse(File::exists($filePath)); } #[DataProvider('routeIgnoredProvider')] public function test_it_checks_if_route_is_ignored( array $ignoredMethods, array $routeMethods, bool $expectedIgnored ): void { // Arrange $service = resolve(IgnoredRoutesService::class); $route = $this->createMockRoute('/api/users', $routeMethods); $service->add(uri: $route->uri(), methods: $ignoredMethods, reason: 'Test'); // Act $isIgnored = $service->isIgnored($route); // Assert $this->assertEquals($expectedIgnored, $isIgnored); } public static function routeIgnoredProvider(): Generator { yield 'single method matches' => [ 'ignoredMethods' => ['GET'], 'routeMethods' => ['GET'], 'expectedIgnored' => true, ]; yield 'one of multiple methods matches' => [ 'ignoredMethods' => ['GET', 'POST'], 'routeMethods' => ['GET', 'PUT'], 'expectedIgnored' => true, ]; yield 'no methods match' => [ 'ignoredMethods' => ['GET'], 'routeMethods' => ['POST', 'PUT'], 'expectedIgnored' => false, ]; yield 'all methods match' => [ 'ignoredMethods' => ['GET', 'POST', 'PUT'], 'routeMethods' => ['GET', 'POST', 'PUT'], 'expectedIgnored' => true, ]; yield 'partial overlap' => [ 'ignoredMethods' => ['POST'], 'routeMethods' => ['GET', 'POST'], 'expectedIgnored' => true, ]; } #[DataProvider('routeRemovalProvider')] public function test_it_removes_ignored_routes( array $initialMethods, array $removeMethods, array $routeMethods, bool $expectedIgnored ): void { // Arrange $service = resolve(IgnoredRoutesService::class); $route = $this->createMockRoute('/api/users', $routeMethods); $service->add(uri: $route->uri(), methods: $initialMethods, reason: 'Test'); // Act $service->remove(uri: $route->uri(), methods: $removeMethods); // Assert $this->assertEquals($expectedIgnored, $service->isIgnored($route)); } public static function routeRemovalProvider(): Generator { yield 'remove some methods' => [ 'initialMethods' => ['GET', 'POST', 'PUT'], 'removeMethods' => ['GET', 'POST'], 'routeMethods' => ['PUT'], 'expectedIgnored' => true, ]; yield 'remove all methods' => [ 'initialMethods' => ['GET', 'POST'], 'removeMethods' => ['GET', 'POST'], 'routeMethods' => ['GET', 'POST'], 'expectedIgnored' => false, ]; yield 'remove non-existent route' => [ 'initialMethods' => ['GET'], 'removeMethods' => ['PATCH'], 'routeMethods' => ['GET'], 'expectedIgnored' => true, ]; } public function test_it_handles_corrupted_json_file_gracefully(): void { // Arrange $filePath = base_path(self::FILE_PATH); $directory = dirname($filePath); if (! File::exists($directory)) { File::makeDirectory($directory, 0755, true); } File::put($filePath, 'invalid json content'); // Act $service = resolve(IgnoredRoutesService::class); // Assert $this->assertFalse($service->hasIgnoredRoutes()); } public function test_it_skips_empty_array_content(): void { // Arrange $filePath = base_path(self::FILE_PATH); $directory = dirname($filePath); if (! File::exists($directory)) { File::makeDirectory($directory, 0755, true); } File::put($filePath, '[]'); $service = resolve(IgnoredRoutesService::class); // Act $hasIgnoredRoutes = $service->hasIgnoredRoutes(); // Assert $this->assertFalse($hasIgnoredRoutes); } /* * Mocks. */ private function createMockRoute(string $uri, array $methods): Route { $route = $this->createMock(Route::class); $route->method('uri')->willReturn($uri); $route->method('methods')->willReturn($methods); return $route; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Services/RouteExtractorServiceFunctionalTest.php
tests/App/Modules/Routes/Services/RouteExtractorServiceFunctionalTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Services; use Illuminate\Contracts\Config\Repository as ConfigRepository; use Illuminate\Routing\Route; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Route as RouteFacade; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\CoversClass; use RuntimeException; use Sunchayn\Nimbus\Modules\Routes\Actions\ExtractRoutesAction; use Sunchayn\Nimbus\Modules\Routes\DataTransferObjects\ExtractedRoute; use Sunchayn\Nimbus\Modules\Routes\Exceptions\RouteExtractionInternalException; use Sunchayn\Nimbus\Modules\Routes\Extractor\SchemaExtractor; use Sunchayn\Nimbus\Modules\Routes\Factories\ExtractableRouteFactory; use Sunchayn\Nimbus\Modules\Routes\Services\IgnoredRoutesService; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\ExtractableRoute; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(ExtractRoutesAction::class)] #[CoversClass(RouteExtractionInternalException::class)] class RouteExtractorServiceFunctionalTest extends TestCase { protected function defineRoutes($router): void { $router ->post('/api/users', fn () => response()->json(['users' => []])) ->name('api.users.store'); $router ->get('/api/users/{id}', fn () => response()->json(['user' => []])) ->name('api.users.show'); $router ->post('/api/posts', fn () => response()->json(['posts' => []])) ->name('api.posts.store'); $router ->post('/non-api/posts', fn () => response()->json(['posts' => []])) ->name('non-api.posts.store'); } public function test_it_processes_routes_properly(): void { // Anticipate $this->mock(ConfigRepository::class, function (MockInterface $mock) { $mock->shouldReceive('get')->with('nimbus.routes.prefix')->andReturn('api'); $mock->shouldReceive('get')->with('nimbus.routes.versioned')->andReturn(fake()->boolean()); }); $routeFactoryMock = $this->mock(ExtractableRouteFactory::class, function (MockInterface $mock) { $mock ->shouldReceive('fromLaravelRoute') ->withAnyArgs() ->andReturnUsing(fn (Route $route) => new ExtractableRoute( parameters: ['test_placeholder:name' => $route->getName()], codeParser: static fn () => '::fake::', )) ->times(3); }); $schemaExtractorMock = $this->mock(SchemaExtractor::class, function (MockInterface $mock) { $mock ->shouldReceive('extract') ->withAnyArgs() ->andReturnUsing( fn (ExtractableRoute $route) => new Schema([new SchemaProperty('foobar')]), ) ->times(3); }); // Arrange $routeExtractorService = resolve(ExtractRoutesAction::class); $routes = RouteFacade::getRoutes()->getRoutes(); // Act $result = $routeExtractorService->execute($routes); // Assert $this->assertEquals(3, $result->count()); $this->assertContainsOnlyInstancesOf( ExtractedRoute::class, $result, ); $result->each(function (ExtractedRoute $extractedRoute) use ($routeFactoryMock, $schemaExtractorMock, $routes) { $this->assertTrue( str_starts_with($extractedRoute->uri->value, 'api'), "Route should start with api prefix: {$extractedRoute->uri->value}.", ); $originalRoute = Arr::first( $routes, // We can do this simple check because we didn't set up routes that share the same URI. fn (Route $route) => $route->uri() === $extractedRoute->uri->value, ); $this->assertEquals( array_values( Arr::where( $originalRoute->methods(), fn (string $method) => ! in_array($method, ['HEAD']), ), ), $extractedRoute->methods, ); $this->assertEquals( [ 'foobar' => [ 'type' => 'string', 'x-name' => 'foobar', 'x-required' => false, ], ], $extractedRoute->schema->toArray(), ); $this->assertNotNull($originalRoute); $routeFactoryMock ->shouldHaveReceived( 'fromLaravelRoute', fn (Route $routeArg) => $routeArg->uri() === $originalRoute->uri && $routeArg->methods() === $originalRoute->methods, ); $schemaExtractorMock ->shouldHaveReceived( 'extract', fn (ExtractableRoute $extractableRouteArg) => $extractableRouteArg->parameters['test_placeholder:name'] === $originalRoute->getName() && ($extractableRouteArg->codeParser)() === '::fake::', ); }); } public function test_process_excludes_ignored_routes(): void { // Arrange $ignoredRoutesServiceMock = $this->mock(IgnoredRoutesService::class)->makePartial(); $routeExtractorService = resolve(ExtractRoutesAction::class); $routes = RouteFacade::getRoutes()->getRoutes(); // Anticipate $ignoredRoutesServiceMock->shouldReceive('hasIgnoredRoutes')->andReturnTrue(); $ignoredRoutesServiceMock ->shouldReceive('isIgnored') ->withArgs(fn (Route $route) => $route->uri() === 'api/users' && $route->methods() === ['POST']) ->andReturnTrue(); // Act $result = $routeExtractorService->execute($routes); // Assert $this->assertCount(2, $result); $ignoredRouteWithinResult = $result->first( fn (ExtractedRoute $extractedRoute) => $extractedRoute->uri->value === 'api/users' && in_array('POST', $extractedRoute->methods), ); $this->assertNull( $ignoredRouteWithinResult, 'Ignored route should not be in results', ); } public function test_process_handles_empty_routes_array(): void { // Arrange $routeExtractorService = resolve(ExtractRoutesAction::class); $routes = []; // Act $result = $routeExtractorService->execute($routes); // Assert $this->assertEquals(0, $result->count()); } public function test_process_uses_config_prefix(): void { // Arrange $config = $this->mock(ConfigRepository::class); RouteFacade::post('/custom/test', fn () => response()->json(['test' => true])) ->name('custom.test'); $routeExtractorService = resolve(ExtractRoutesAction::class); $routes = RouteFacade::getRoutes()->getRoutes(); // Anticipate $config->shouldReceive('get')->with('nimbus.routes.prefix')->andReturn('custom'); $config->shouldReceive('get')->with('nimbus.routes.versioned')->andReturnFalse(); // Act $result = $routeExtractorService->execute($routes); // Assert $customRouteWithinResult = $result->first( fn (ExtractedRoute $extractedRoute) => str_starts_with($extractedRoute->uri->value, 'custom'), ); $this->assertNotNull( $customRouteWithinResult, 'Should include routes with custom prefix', ); } public function test_it_handles_extraction_errors_gracefully(): void { // Anticipate $this->mock(ConfigRepository::class, function (MockInterface $mock) { $mock->shouldReceive('get')->with('nimbus.routes.prefix')->andReturn('api'); $mock->shouldReceive('get')->with('nimbus.routes.versioned')->andReturn(fake()->boolean()); }); $dummyFailingException = new RuntimeException(message: $dummyFailingExceptionMessage = fake()->sentence()); $this->mock(SchemaExtractor::class, function (MockInterface $mock) use ($dummyFailingException) { $mock ->shouldReceive('extract') ->withAnyArgs() ->andThrow($dummyFailingException); }); // Arrange $routeExtractorService = resolve(ExtractRoutesAction::class); $routes = RouteFacade::getRoutes()->getRoutes(); // Act try { $result = $routeExtractorService->execute($routes); } catch (RouteExtractionInternalException $exception) { } // Assert $this->assertNotNull($exception); $this->assertSame( $dummyFailingException, $exception->getPrevious(), ); $this->assertEquals( [ 'uri' => 'api/users', // <- First route from the list self::defineRoutes. 'methods' => ['POST'], 'controllerClass' => '[unspecified]', 'controllerMethod' => '[unspecified]', ], $exception->getRouteContext() ); $this->assertEquals( "Failed to extract route information for 'api/users' due to an unexpected error: {$dummyFailingExceptionMessage}", $exception->getMessage(), ); $this->assertEquals( 'Check the application logs for more details and ensure all dependencies are properly installed.' .'<br />In case of internal errors, please open an issue: <a class="hover:underline" href="https://github.com/sunchayn/nimbus/issues/new/choose">https://github.com/sunchayn/nimbus/issues/new/choose</a>', $exception->getSuggestedSolution() ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Services/Uri/VersionedUriUnitTest.php
tests/App/Modules/Routes/Services/Uri/VersionedUriUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Services\Uri; use Generator; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Modules\Routes\Services\Uri\VersionedUri; #[CoversClass(VersionedUri::class)] class VersionedUriUnitTest extends TestCase { #[DataProvider('versionExtractionProvider')] public function test_it_extracts_version_correctly( string $value, string $routesPrefix, string $expectedVersion ): void { $uri = new VersionedUri(value: $value, routesPrefix: $routesPrefix); $this->assertEquals($expectedVersion, $uri->getVersion()); } public static function versionExtractionProvider(): Generator { yield 'simple versioned uri with v prefix' => [ 'value' => '/v1/users', 'routesPrefix' => '', 'expectedVersion' => 'v1', ]; yield 'versioned uri with numeric version' => [ 'value' => '/v2/posts', 'routesPrefix' => '', 'expectedVersion' => 'v2', ]; yield 'versioned uri with semantic version' => [ 'value' => '/1.0/users', 'routesPrefix' => '', 'expectedVersion' => '1.0', ]; yield 'versioned uri with semantic version multiple digits' => [ 'value' => '/2.5/users', 'routesPrefix' => '', 'expectedVersion' => '2.5', ]; yield 'versioned uri with prefix' => [ 'value' => '/api/v1/users', 'routesPrefix' => 'api', 'expectedVersion' => 'v1', ]; yield 'versioned uri with prefix and semantic version' => [ 'value' => '/api/1.0/users', 'routesPrefix' => 'api', 'expectedVersion' => '1.0', ]; yield 'non-versioned uri returns default version' => [ 'value' => '/users', 'routesPrefix' => '', 'expectedVersion' => 'v1', ]; yield 'non-versioned uri with prefix returns default version' => [ 'value' => '/api/users', 'routesPrefix' => 'api', 'expectedVersion' => 'v1', ]; yield 'uri with invalid version format returns default version' => [ 'value' => '/version1/users', 'routesPrefix' => '', 'expectedVersion' => 'v1', ]; yield 'uri with v but no number returns default version' => [ 'value' => '/v/users', 'routesPrefix' => '', 'expectedVersion' => 'v1', ]; yield 'uri with v and letters returns default version' => [ 'value' => '/vabc/users', 'routesPrefix' => '', 'expectedVersion' => 'v1', ]; yield 'empty uri returns default version' => [ 'value' => '', 'routesPrefix' => '', 'expectedVersion' => 'v1', ]; yield 'only slashes returns default version' => [ 'value' => '///', 'routesPrefix' => '', 'expectedVersion' => 'v1', ]; yield 'only prefix returns default version' => [ 'value' => '/api', 'routesPrefix' => 'api', 'expectedVersion' => 'v1', ]; yield 'only version returns that version' => [ 'value' => '/v1', 'routesPrefix' => '', 'expectedVersion' => 'v1', ]; yield 'prefix and only version' => [ 'value' => '/api/v1', 'routesPrefix' => 'api', 'expectedVersion' => 'v1', ]; yield 'version without leading slash' => [ 'value' => 'v1/users', 'routesPrefix' => '', 'expectedVersion' => 'v1', ]; yield 'multiple consecutive slashes with version' => [ 'value' => '//v1//users', 'routesPrefix' => '', 'expectedVersion' => 'v1', ]; yield 'version with trailing slash' => [ 'value' => '/v1/', 'routesPrefix' => '', 'expectedVersion' => 'v1', ]; yield 'case sensitive prefix mismatch' => [ 'value' => '/API/v1/users', // <- API is treated as resource, not prefix 'routesPrefix' => 'api', 'expectedVersion' => 'v1', // <- Default value. ]; yield 'version-like string in middle is not detected' => [ 'value' => '/users/v2/posts', // <- only first part after prefix is checked 'routesPrefix' => '', 'expectedVersion' => 'v1', // <- Default value. ]; yield 'three digit semantic version returns empty' => [ 'value' => '/1.0.0/users', // <- regex only matches X.Y format 'routesPrefix' => '', 'expectedVersion' => 'v1', // <- Default value. ]; yield 'v with multiple digits' => [ 'value' => '/v123/users', 'routesPrefix' => '', 'expectedVersion' => 'v123', ]; yield 'semantic version with large numbers' => [ 'value' => '/99.99/users', 'routesPrefix' => '', 'expectedVersion' => '99.99', ]; } #[DataProvider('resourceExtractionProvider')] public function test_it_extracts_resource_correctly( string $value, string $routesPrefix, string $expectedResource ): void { $uri = new VersionedUri(value: $value, routesPrefix: $routesPrefix); $this->assertEquals($expectedResource, $uri->getResource()); } public static function resourceExtractionProvider(): Generator { yield 'versioned uri extracts resource after version' => [ 'value' => '/v1/users', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'versioned uri with semantic version extracts resource' => [ 'value' => '/1.0/users', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'versioned uri with prefix extracts resource' => [ 'value' => '/api/v1/users', 'routesPrefix' => 'api', 'expectedResource' => 'users', ]; yield 'versioned uri with composed prefix extracts resource' => [ 'value' => '/cms/api/v1/users', 'routesPrefix' => 'cms/api', 'expectedResource' => 'users', ]; yield 'versioned uri with multiple segments extracts first resource' => [ 'value' => '/v1/users/123/profile', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'non-versioned uri extracts resource' => [ 'value' => '/users', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'non-versioned uri with prefix extracts resource' => [ 'value' => '/api/users', 'routesPrefix' => 'api', 'expectedResource' => 'users', ]; yield 'non-versioned uri with multiple segments' => [ 'value' => '/users/123', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'empty uri returns empty resource' => [ 'value' => '', 'routesPrefix' => '', 'expectedResource' => '', ]; yield 'only slashes returns empty resource' => [ 'value' => '///', 'routesPrefix' => '', 'expectedResource' => '', ]; yield 'only prefix returns empty resource' => [ 'value' => '/api', 'routesPrefix' => 'api', 'expectedResource' => '', ]; yield 'only version returns empty resource' => [ 'value' => '/v1', 'routesPrefix' => '', 'expectedResource' => '', // <- no resource after version ]; yield 'prefix and only version returns empty resource' => [ 'value' => '/api/v1', 'routesPrefix' => 'api', 'expectedResource' => '', ]; yield 'version without leading slash' => [ 'value' => 'v1/users', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'multiple consecutive slashes with version' => [ 'value' => '//v1//users', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'resource without leading slash' => [ 'value' => 'users/123', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'versioned uri with trailing slash' => [ 'value' => '/v1/users/', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'single character resource with version' => [ 'value' => '/v1/a', 'routesPrefix' => '', 'expectedResource' => 'a', ]; yield 'numeric resource with version' => [ 'value' => '/v1/123', 'routesPrefix' => '', 'expectedResource' => '123', ]; yield 'resource with special characters and version' => [ 'value' => '/v1/user-profile', 'routesPrefix' => '', 'expectedResource' => 'user-profile', ]; yield 'case sensitive prefix mismatch' => [ 'value' => '/API/v1/users', 'routesPrefix' => 'api', 'expectedResource' => 'API', // <- API is treated as resource ]; yield 'prefix as part of resource name' => [ 'value' => '/api/v1/api-users', 'routesPrefix' => 'api', 'expectedResource' => 'api-users', ]; yield 'deeply nested versioned uri' => [ 'value' => '/api/v1/users/123/posts/456', 'routesPrefix' => 'api', 'expectedResource' => 'users', ]; yield 'whitespace in resource with version' => [ 'value' => '/v1/ users /123', 'routesPrefix' => '', 'expectedResource' => ' users ', ]; yield 'url encoded characters in resource' => [ 'value' => '/v1/user%20name', 'routesPrefix' => '', 'expectedResource' => 'user%20name', ]; yield 'invalid version format treats first part as resource' => [ 'value' => '/version1/users', 'routesPrefix' => '', 'expectedResource' => 'version1', // <- not a valid version format ]; yield 'three digit semantic version treats it as resource' => [ 'value' => '/1.0.0/users', 'routesPrefix' => '', 'expectedResource' => '1.0.0', // <- doesn't match version regex ]; } #[TestWith(['/v1/users', ''])] #[TestWith(['/api/v2/posts', 'api'])] #[TestWith(['/1.0/resources', ''])] public function test_it_can_call_get_version_multiple_times(string $value, string $routesPrefix): void { $uri = new VersionedUri(value: $value, routesPrefix: $routesPrefix); // This asserts against mutating the original value. $firstCall = $uri->getVersion(); $secondCall = $uri->getVersion(); $this->assertEquals($firstCall, $secondCall); $this->assertNotEmpty($firstCall); } #[TestWith(['/v1/users'])] #[TestWith(['/api/v2/posts'])] #[TestWith(['/users'])] public function test_it_can_call_get_resource_multiple_times(string $value): void { $uri = new VersionedUri(value: $value, routesPrefix: ''); // This asserts against mutating the original value. $firstCall = $uri->getResource(); $secondCall = $uri->getResource(); $this->assertEquals($firstCall, $secondCall); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Services/Uri/NonVersionedUriUnitTest.php
tests/App/Modules/Routes/Services/Uri/NonVersionedUriUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Services\Uri; use Generator; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Modules\Routes\Services\Uri\NonVersionedUri; #[CoversClass(NonVersionedUri::class)] class NonVersionedUriUnitTest extends TestCase { #[TestWith(['/users'])] #[TestWith(['/v1/users'])] public function test_it_always_returns_na_for_version(string $value): void { $uri = new NonVersionedUri(value: $value, routesPrefix: ''); $this->assertEquals('n/a', $uri->getVersion()); } #[DataProvider('resourceExtractionProvider')] public function test_it_extracts_resource_correctly( string $value, string $routesPrefix, string $expectedResource ): void { $uri = new NonVersionedUri($value, $routesPrefix); $this->assertEquals($expectedResource, $uri->getResource()); } public static function resourceExtractionProvider(): Generator { yield 'simple uri' => [ 'value' => '/users', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'uri with multiple segments' => [ 'value' => '/users/123/profile', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'uri with routesPrefix' => [ 'value' => '/api/users', 'routesPrefix' => 'api', 'expectedResource' => 'users', ]; yield 'uri with composed routesPrefix' => [ 'value' => '/web/api/users', 'routesPrefix' => 'web/api', 'expectedResource' => 'users', ]; yield 'uri with routesPrefix and multiple segments' => [ 'value' => '/api/users/123', 'routesPrefix' => 'api', 'expectedResource' => 'users', ]; yield 'routesPrefix not at start' => [ 'value' => '/users/api/123', 'routesPrefix' => 'api', 'expectedResource' => 'users', // <- /api/.. is considered part of the URI and disregarded the prefix. ]; yield 'empty uri' => [ 'value' => '', 'routesPrefix' => '', 'expectedResource' => '', ]; yield 'only slashes' => [ 'value' => '///', 'routesPrefix' => '', 'expectedResource' => '', ]; yield 'only routesPrefix' => [ 'value' => '/api', 'routesPrefix' => 'api', 'expectedResource' => '', ]; yield 'only routesPrefix with trailing slash' => [ 'value' => '/api/', 'routesPrefix' => 'api', 'expectedResource' => '', ]; yield 'empty routesPrefix' => [ 'value' => '/users', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'uri without leading slash' => [ 'value' => 'users/123', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'uri with trailing slash' => [ 'value' => '/users/', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'multiple consecutive slashes' => [ 'value' => '//users//123//', 'routesPrefix' => '', 'expectedResource' => 'users', ]; yield 'routesPrefix without leading slash in uri' => [ 'value' => 'api/users', 'routesPrefix' => 'api', 'expectedResource' => 'users', ]; yield 'single character resource' => [ 'value' => '/a', 'routesPrefix' => '', 'expectedResource' => 'a', ]; yield 'numeric resource' => [ 'value' => '/123', 'routesPrefix' => '', 'expectedResource' => '123', ]; yield 'resource with special characters' => [ 'value' => '/user-profile', 'routesPrefix' => '', 'expectedResource' => 'user-profile', ]; yield 'case sensitive routesPrefix mismatch' => [ 'value' => '/API/users', 'routesPrefix' => 'api', 'expectedResource' => 'API', ]; yield 'routesPrefix as part of resource name' => [ 'value' => '/api/api-users', 'routesPrefix' => 'api', 'expectedResource' => 'api-users', ]; yield 'deeply nested uri' => [ 'value' => '/api/v1/users/123/posts/456/comments', 'routesPrefix' => 'api', 'expectedResource' => 'v1', // <- remember: we are testing the `NonVersionedUri` ]; yield 'whitespace in uri' => [ 'value' => '/ users /123', 'routesPrefix' => '', 'expectedResource' => ' users ', ]; yield 'url encoded characters' => [ 'value' => '/user%20name', 'routesPrefix' => '', 'expectedResource' => 'user%20name', ]; } public function test_it_can_call_get_resource_multiple_times(): void { $uri = new NonVersionedUri('/users', ''); // This asserts against mutating the original value. $this->assertEquals('users', $uri->getResource()); $this->assertEquals('users', $uri->getResource()); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/ValueObjects/EndpointUnitTest.php
tests/App/Modules/Routes/ValueObjects/EndpointUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\ValueObjects; use Generator; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use RuntimeException; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\Endpoint; #[CoversClass(Endpoint::class)] class EndpointUnitTest extends TestCase { #[DataProvider('versionedEndpointProvider')] public function test_it_creates_versioned_endpoint_from_raw( string $uri, string $routesPrefix, string $expectedVersion, string $expectedResource, ): void { // Act $endpoint = Endpoint::fromRaw( uri: $uri, routesPrefix: $routesPrefix, isVersioned: true ); // Assert $this->assertEquals($expectedVersion, $endpoint->version); $this->assertEquals($expectedResource, $endpoint->resource); $this->assertEquals($uri, $endpoint->value); } public static function versionedEndpointProvider(): Generator { yield 'simple uri' => [ 'uri' => '/v1/users', 'routesPrefix' => '', 'expectedVersion' => 'v1', 'expectedResource' => 'users', ]; yield 'uri with semantic version' => [ 'uri' => '/1.0/posts', 'routesPrefix' => '', 'expectedVersion' => '1.0', 'expectedResource' => 'posts', ]; yield 'uri with prefix' => [ 'uri' => '/api/v1/users', 'routesPrefix' => 'api', 'expectedVersion' => 'v1', 'expectedResource' => 'users', ]; yield 'uri with prefix and semantic version' => [ 'uri' => '/rest-api/2.0/products', 'routesPrefix' => 'rest-api', 'expectedVersion' => '2.0', 'expectedResource' => 'products', ]; yield 'uri with multiple segments' => [ 'uri' => '/v1/users/{user}/posts', 'routesPrefix' => '', 'expectedVersion' => 'v1', 'expectedResource' => 'users', ]; yield 'uri with prefix and path parameters' => [ 'uri' => '/api/v2/users/{id}', 'routesPrefix' => 'api', 'expectedVersion' => 'v2', 'expectedResource' => 'users', ]; yield 'empty uri' => [ 'uri' => '', 'routesPrefix' => '', 'expectedVersion' => 'v1', // <- Default version. 'expectedResource' => '', ]; } #[DataProvider('nonVersionedEndpointProvider')] public function test_it_creates_non_versioned_endpoint_from_raw( string $uri, string $routesPrefix, string $expectedVersion, string $expectedResource, ): void { // Act $endpoint = Endpoint::fromRaw( uri: $uri, routesPrefix: $routesPrefix, isVersioned: false ); // Assert $this->assertEquals($expectedVersion, $endpoint->version); $this->assertEquals($expectedResource, $endpoint->resource); $this->assertEquals($uri, $endpoint->value); } public static function nonVersionedEndpointProvider(): Generator { yield 'simple uri' => [ 'uri' => '/users', 'routesPrefix' => '', 'expectedVersion' => 'n/a', 'expectedResource' => 'users', ]; yield 'uri with prefix' => [ 'uri' => '/api/users', 'routesPrefix' => 'api', 'expectedVersion' => 'n/a', 'expectedResource' => 'users', ]; yield 'uri with multiple segments' => [ 'uri' => '/users/{user}/posts', 'routesPrefix' => '', 'expectedVersion' => 'n/a', 'expectedResource' => 'users', ]; yield 'uri with prefix and path parameters' => [ 'uri' => '/api/posts/{id}', 'routesPrefix' => 'api', 'expectedVersion' => 'n/a', 'expectedResource' => 'posts', ]; yield 'empty uri' => [ 'uri' => '', 'routesPrefix' => '', 'expectedVersion' => 'n/a', 'expectedResource' => '', ]; } #[DataProvider('shortUriProvider')] public function test_it_returns_short_uri_correctly( string $version, string $resource, string $value, string $expectedShortUri, ): void { // Arrange $endpoint = new Endpoint( version: $version, resource: $resource, value: $value, ); // Act & Assert $this->assertEquals($expectedShortUri, $endpoint->getShortUri()); } public static function shortUriProvider(): Generator { yield 'versioned uri with prefix removes prefix and version' => [ 'version' => 'v1', 'resource' => 'users', 'value' => '/rest-api/v1/users/{user}', 'expectedShortUri' => '/users/{user}', ]; yield 'versioned uri without prefix removes only version' => [ 'version' => 'v1', 'resource' => 'users', 'value' => '/v1/users/{user}', 'expectedShortUri' => '/users/{user}', ]; yield 'uri with prefix removes only prefix' => [ 'version' => 'n/a', 'resource' => 'users', 'value' => '/api/users/{user}', 'expectedShortUri' => '/users/{user}', ]; yield 'uri without prefix returns as is' => [ 'version' => 'n/a', 'resource' => 'users', 'value' => '/users/{user}', 'expectedShortUri' => '/users/{user}', ]; yield 'simple resource without parameters' => [ 'version' => 'v1', 'resource' => 'users', 'value' => '/api/v1/users', 'expectedShortUri' => '/users', ]; yield 'deeply nested uri' => [ 'version' => 'v1', 'resource' => 'users', 'value' => '/api/v1/users/{user}/posts/{post}/comments', 'expectedShortUri' => '/users/{user}/posts/{post}/comments', ]; yield 'uri with semantic version' => [ 'version' => '1.0', 'resource' => 'products', 'value' => '/api/1.0/products/{id}', 'expectedShortUri' => '/products/{id}', ]; } #[DataProvider('invalidShortUriProvider')] public function test_it_throws_exception_for_invalid_short_uri( string $version, string $resource, string $value, string $expectedMessage, ): void { // Arrange $endpoint = new Endpoint( version: $version, resource: $resource, value: $value, ); // Anticipate $this->expectException(RuntimeException::class); $this->expectExceptionMessage($expectedMessage); // Act $endpoint->getShortUri(); } public static function invalidShortUriProvider(): Generator { yield 'empty resource' => [ 'version' => 'v1', 'resource' => '', 'value' => '/v1/users', 'expectedMessage' => 'Invalid ValueObject. The resource cannot be empty.', ]; yield 'resource not in uri' => [ 'version' => 'v1', 'resource' => 'posts', 'value' => '/v1/users/{user}', 'expectedMessage' => 'Invalid ValueObject. The `resource` MUST exist in the URI.', ]; yield 'resource with different casing' => [ 'version' => 'v1', 'resource' => 'Users', 'value' => '/v1/users', 'expectedMessage' => 'Invalid ValueObject. The `resource` MUST exist in the URI.', ]; yield 'resource without leading slash in uri' => [ 'version' => 'n/a', 'resource' => 'users', 'value' => 'users/{user}', 'expectedMessage' => 'Invalid ValueObject. The `resource` MUST exist in the URI.', ]; yield 'resource appears later in path' => [ 'version' => 'v1', 'resource' => 'comments', 'value' => '/v1/users/{user}/posts', 'expectedMessage' => 'Invalid ValueObject. The `resource` MUST exist in the URI.', ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/ValueObjects/ExtractableRouteUnitTest.php
tests/App/Modules/Routes/ValueObjects/ExtractableRouteUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\ValueObjects; use Mockery; use PHPUnit\Framework\Attributes\CoversClass; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\ExtractableRoute; use Sunchayn\Nimbus\Tests\TestCase; #[CoversClass(ExtractableRoute::class)] class ExtractableRouteUnitTest extends TestCase { protected function tearDown(): void { Mockery::close(); parent::tearDown(); } public function test_it_creates_empty_objects(): void { // Act $actual = ExtractableRoute::empty(); // Assert $this->assertEmpty($actual->parameters); $this->assertEmpty(($actual->codeParser)()); $this->assertNull($actual->methodName); $this->assertNull($actual->controllerClass); $this->assertNull($actual->controllerMethod); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Factories/ExtractableRouteFactoryUnitTest.php
tests/App/Modules/Routes/Factories/ExtractableRouteFactoryUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Factories; use Closure; use Generator; use Illuminate\Routing\Route; use Mockery; use PhpParser\Parser\Php8; use PhpParser\ParserFactory; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\PreserveGlobalState; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use PHPUnit\Framework\TestCase; use ReflectionParameter; use RuntimeException; use Sunchayn\Nimbus\Modules\Routes\Exceptions\InvalidRouteDefinitionException; use Sunchayn\Nimbus\Modules\Routes\Exceptions\RouteExtractionException; use Sunchayn\Nimbus\Modules\Routes\Factories\ExtractableRouteFactory; use Sunchayn\Nimbus\Tests\App\Modules\Routes\Factories\Stubs\ExtractableControllerStub; use Sunchayn\Nimbus\Tests\App\Modules\Routes\Factories\Stubs\RequestStub; #[CoversClass(ExtractableRouteFactory::class)] #[CoversClass(InvalidRouteDefinitionException::class)] class ExtractableRouteFactoryUnitTest extends TestCase { private ExtractableRouteFactory $factory; protected function setUp(): void { parent::setUp(); $this->factory = new ExtractableRouteFactory; } protected function tearDown(): void { Mockery::close(); parent::tearDown(); } public function test_it_creates_extractable_route_from_valid_controller_route(): void { // Arrange $route = new Route( ['GET'], '/users', ['uses' => ExtractableControllerStub::class.'@index'], ); // Act $extractableRoute = $this->factory->fromLaravelRoute($route); // Assert $this->assertEquals('index', $extractableRoute->methodName); $this->assertEquals( ExtractableControllerStub::class, $extractableRoute->controllerClass, ); $this->assertEquals('index', $extractableRoute->controllerMethod); $this->assertEquals([], $extractableRoute->parameters); $this->assertParsedCodeEquals( __DIR__.'/Stubs/ExtractableControllerStub.php', $extractableRoute->codeParser, ); } public function test_it_extracts_method_parameters_correctly(): void { // Arrange $route = new Route( ['POST'], '/users', action: ['uses' => ExtractableControllerStub::class.'@store'] // <- this method has parameters ); // Act $extractableRoute = $this->factory->fromLaravelRoute($route); // Assert $this->assertCount(1, $extractableRoute->parameters); $this->assertInstanceOf(ReflectionParameter::class, $extractableRoute->parameters[0]); $this->assertSame('request', $extractableRoute->parameters[0]->getName()); $this->assertSame(RequestStub::class, $extractableRoute->parameters[0]->getType()->getName()); } public function test_it_returns_empty_route_for_closure_based_routes(): void { // Arrange $route = new Route( ['POST'], '/closure', action: ['uses' => fn () => 'response'], ); // Act $extractableRoute = $this->factory->fromLaravelRoute($route); // Assert $this->assertEmpty($extractableRoute->parameters); $this->assertEmpty(($extractableRoute->codeParser)()); $this->assertNull($extractableRoute->methodName); $this->assertNull($extractableRoute->controllerClass); $this->assertNull($extractableRoute->controllerMethod); } #[DataProvider('invalidRoutesDataProvider')] public function test_it_breaks_correctly_for_invalid_routes( Route $route, string $expectedException, string $expectedExceptionMessage, string $expectedControllerClass, string $expectedControllerMethod, string $expectedSuggestedSolution, string $expectedIgnoreData, ): void { // Act try { $this->factory->fromLaravelRoute($route); } catch (RouteExtractionException $actualException) { } // Assert $this->assertInstanceOf($expectedException, $actualException); $this->assertEquals( $expectedExceptionMessage, $actualException->getMessage(), ); $this->assertEquals( $expectedSuggestedSolution, $actualException->getSuggestedSolution(), ); $this->assertEquals( $expectedIgnoreData, $actualException->getIgnoreData(), ); $this->assertEquals( [ 'uri' => $route->uri(), 'methods' => $route->methods(), 'controllerClass' => $expectedControllerClass, 'controllerMethod' => $expectedControllerMethod, ], $actualException->getRouteContext(), ); } public static function invalidRoutesDataProvider(): Generator { yield 'controller class is empty' => [ 'route' => new Route(methods: ['GET'], uri: '/invalid', action: ['uses' => '@method']), 'expectedException' => InvalidRouteDefinitionException::class, 'expectedExceptionMessage' => "Malformed `uses` statement for route 'invalid'.", 'expectedControllerClass' => '[unspecified]', 'expectedControllerMethod' => 'method', 'expectedSuggestedSolution' => 'Make sure the `uses` statement is properly formatted `{controllerClass}@{controllerMethod}`. If it is an invokable controller then it must not have the `@` suffix.', 'expectedIgnoreData' => 'invalid|["GET","HEAD"]', ]; yield 'controller method is empty' => [ 'route' => new Route(methods: ['GET'], uri: '/invalid-2', action: ['uses' => 'SomeController@']), 'expectedException' => InvalidRouteDefinitionException::class, 'expectedExceptionMessage' => "Malformed `uses` statement for route 'invalid-2'.", 'expectedControllerClass' => 'SomeController', 'expectedControllerMethod' => '[unspecified]', 'expectedSuggestedSolution' => 'Make sure the `uses` statement is properly formatted `{controllerClass}@{controllerMethod}`. If it is an invokable controller then it must not have the `@` suffix.', 'expectedIgnoreData' => 'invalid-2|["GET","HEAD"]', ]; yield 'controller class doesnt exist' => [ 'route' => new Route(methods: ['GET'], uri: '/invalid-3', action: ['uses' => 'App\Http\Controllers\NonExistentController@index']), 'expectedException' => InvalidRouteDefinitionException::class, 'expectedExceptionMessage' => "Controller method 'index' not found in class 'App\Http\Controllers\NonExistentController' for route 'invalid-3'.", 'expectedControllerClass' => 'App\Http\Controllers\NonExistentController', 'expectedControllerMethod' => 'index', 'expectedSuggestedSolution' => "Check that the method 'index' exists in the 'App\Http\Controllers\NonExistentController' class. This usually indicates an incorrect route definition in your routes file.", 'expectedIgnoreData' => 'invalid-3|["GET","HEAD"]', ]; yield 'controller method doesnt exist' => [ 'route' => new Route(methods: ['GET'], uri: '/invalid-4', action: ['uses' => ExtractableControllerStub::class.'@nonExistentMethod']), 'expectedException' => InvalidRouteDefinitionException::class, 'expectedExceptionMessage' => sprintf("Controller method 'nonExistentMethod' not found in class '%s' for route 'invalid-4'.", ExtractableControllerStub::class), 'expectedControllerClass' => ExtractableControllerStub::class, 'expectedControllerMethod' => 'nonExistentMethod', 'expectedSuggestedSolution' => sprintf("Check that the method 'nonExistentMethod' exists in the '%s' class. This usually indicates an incorrect route definition in your routes file.", ExtractableControllerStub::class), 'expectedIgnoreData' => 'invalid-4|["GET","HEAD"]', ]; } #[RunInSeparateProcess] // <- Having overload Mock here, let's not leak it. #[PreserveGlobalState(false)] public function test_it_handles_file_read_errors_gracefully(): void { // Arrange $route = new Route( ['GET'], '/users', action: ['uses' => ExtractableControllerStub::class.'@store'] ); $extractableRoute = $this->factory->fromLaravelRoute($route); $parserFactoryMock = Mockery::mock('overload:'.ParserFactory::class); $parserMock = Mockery::mock('overload:'.Php8::class); // Anticipate $parserMock->shouldReceive('parse')->andThrow(new RuntimeException('Cannot parse.')); $parserFactoryMock->shouldReceive('createForNewestSupportedVersion')->andReturn($parserMock); // Act $result = ($extractableRoute->codeParser)(); // Assert $this->assertNull($result); } /* * Asserts. */ private function assertParsedCodeEquals(string $expected, Closure $parser): void { $actualParsedCode = $parser(); $expectedParsedCode = file_get_contents($expected); $this->assertEquals( (new ParserFactory)->createForNewestSupportedVersion()->parse($expectedParsedCode), $actualParsedCode, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Factories/Stubs/RequestStub.php
tests/App/Modules/Routes/Factories/Stubs/RequestStub.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Factories\Stubs; use Illuminate\Http\Request; class RequestStub extends Request {}
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Factories/Stubs/ExtractableControllerStub.php
tests/App/Modules/Routes/Factories/Stubs/ExtractableControllerStub.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Factories\Stubs; class ExtractableControllerStub { public function index(): void {} public function store(RequestStub $request): void {} }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/SpatieDataObjectExtractorStrategyUnitTest.php
tests/App/Modules/Routes/Extractors/SpatieDataObjectExtractorStrategyUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors; use Generator; use Illuminate\Container\Container; use Mockery; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\PreserveGlobalState; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use PHPUnit\Framework\TestCase; use ReflectionClass; use ReflectionNamedType; use ReflectionParameter; use ReflectionUnionType; use Spatie\LaravelData\Data; use Spatie\LaravelData\Resolvers\DataValidationRulesResolver; use Spatie\LaravelData\Support\Validation\DataRules; use Spatie\LaravelData\Support\Validation\ValidationPath; use stdClass; use Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies\SpatieDataObjectExtractorStrategy; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\ExtractableRoute; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\RulesExtractionError; use Sunchayn\Nimbus\Modules\Schemas\Builders\SchemaBuilder; use Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty; use Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Stubs\SpatieDataObjectStub; #[CoversClass(SpatieDataObjectExtractorStrategy::class)] #[CoversClass(RulesExtractionError::class)] class SpatieDataObjectExtractorStrategyUnitTest extends TestCase { private SchemaBuilder $schemaBuilderMock; private Container&Mockery\MockInterface $containerMock; private SpatieDataObjectExtractorStrategy $strategy; protected function setUp(): void { parent::setUp(); $this->schemaBuilderMock = Mockery::mock(SchemaBuilder::class); $this->containerMock = Mockery::mock(Container::class); $this->strategy = new SpatieDataObjectExtractorStrategy($this->schemaBuilderMock, $this->containerMock); } protected function tearDown(): void { Mockery::close(); parent::tearDown(); } #[DataProvider('matchesProvider')] public function test_it_matches_correctly( array $parameterReflectionData, bool $expected ): void { // Arrange $parameters = array_map( fn (array $reflectionData) => $this->makeReflectionParameter($reflectionData), $parameterReflectionData ); $route = $this->makeExtractableRoute($parameters); // Act $actual = $this->strategy->matches($route); // Assert $this->assertEquals($expected, $actual); } public static function matchesProvider(): Generator { yield 'spatie data object parameter' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => SpatieDataObjectStub::class], // <- ReflectionParameter methods return values. ], 'expected' => true, ]; yield 'base abstract data class' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => Data::class], ], 'expected' => false, ]; yield 'parameter without type' => [ 'parameterReflectionData' => [ ['hasType' => false, 'getType' => null], ], 'expected' => false, ]; yield 'parameter with non-named type' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => null], ], 'expected' => false, ]; yield 'parameter not spatie data subclass' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => stdClass::class], ], 'expected' => false, ]; yield 'no parameters' => [ 'parameterReflectionData' => [], 'expected' => false, ]; yield 'multiple parameters with spatie data object' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => stdClass::class], ['hasType' => true, 'getType' => SpatieDataObjectStub::class], ], 'expected' => true, ]; yield 'multiple parameters without spatie data object' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => stdClass::class], ['hasType' => true, 'getType' => 'string'], ], 'expected' => false, ]; } public function test_it_extracts_schema_from_spatie_data_object(): void { // Arrange $parameter = $this->makeReflectionParameter([ 'getType' => $spatieDataObjectClass = SpatieDataObjectStub::class, 'hasType' => true, ]); $route = $this->makeExtractableRoute([$parameter]); $spatieDataValidationRulesResolverMock = Mockery::mock(DataValidationRulesResolver::class); $dummyRules = ['dummy' => '::dummy_value::']; $expectedRules = Ruleset::fromLaravelRules($dummyRules); // Anticipate $spatieDataValidationRulesResolverMock ->shouldReceive('execute') ->withAnyArgs() ->andReturn($dummyRules) ->once(); $this ->containerMock ->shouldReceive('make') ->with(DataValidationRulesResolver::class) ->andReturn($spatieDataValidationRulesResolverMock); $responseSchemaStub = new Schema(properties: [ new SchemaProperty( name: '::property::', ), ]); $this->schemaBuilderMock ->shouldReceive('buildSchemaFromRuleset') ->withAnyArgs() ->andReturn($responseSchemaStub) ->once(); // Act $schema = $this->strategy->extract($route); // Assert $this->assertSame($responseSchemaStub, $schema); $this ->schemaBuilderMock ->shouldHaveReceived('buildSchemaFromRuleset') ->withArgs(function (Ruleset $ruleset, ?RulesExtractionError $rulesExtractionError) use ($expectedRules) { $this->assertEquals( $expectedRules->all(), $ruleset->all(), ); $this->assertNull($rulesExtractionError); return true; }) ->once(); $spatieDataValidationRulesResolverMock ->shouldHaveReceived('execute') ->withArgs( function ( string $classArg, array $fullPayloadArg, ValidationPath $pathArg, DataRules $dataRulesArg ) use ($spatieDataObjectClass) { $this->assertEquals( $spatieDataObjectClass, $classArg, ); $this->assertEmpty($fullPayloadArg); $this->assertEquals( '', $pathArg->get(), ); $this->assertEmpty( $dataRulesArg->rules, ); return true; }) ->once(); } #[RunInSeparateProcess] // <- Having overload Mock here, let's not leak it. #[PreserveGlobalState(false)] public function test_it_handles_exception_when_calling_rules_method(): void { // Arrange $parameter = $this->makeReflectionParameter([ 'hasType' => true, 'getType' => SpatieDataObjectStub::class, ]); $route = $this->makeExtractableRoute([$parameter]); $responseSchemaStub = Schema::empty(); $expectedRuleset = Ruleset::make([]); $spatieDataValidationRulesResolverMock = Mockery::mock(DataValidationRulesResolver::class); // Anticipate $spatieDataValidationRulesResolverMock ->shouldReceive('execute') ->withAnyArgs() ->andThrow(new \RuntimeException('Broken spatie data')) ->once(); $this ->containerMock ->shouldReceive('make') ->with(DataValidationRulesResolver::class) ->andReturn($spatieDataValidationRulesResolverMock); $this ->schemaBuilderMock ->shouldReceive('buildSchemaFromRuleset') ->withAnyArgs() ->andReturn($responseSchemaStub); // Act $schema = $this->strategy->extract($route); // Assert $this->assertSame($responseSchemaStub, $schema); $this ->schemaBuilderMock ->shouldHaveReceived('buildSchemaFromRuleset') ->withArgs(function (Ruleset $ruleset, ?RulesExtractionError $rulesExtractionError) use ($expectedRuleset) { $this->assertEquals( $expectedRuleset->all(), $ruleset->all(), ); $this->assertNotNull($rulesExtractionError); $stubClassName = (new ReflectionClass(self::class))->getFileName(); $this->assertEquals( <<<HTML <b>Broken spatie data</b><br /> <small>{$stubClassName}::260</small> <p class="text-xs">[trace]</p> HTML, // TODO [Test] Test is not the right place to test this method. // TODO [Test] Figure a way to fully test this properly. Due to final methods we cannot assert the trace properly. preg_replace('#(<p\b[^>]*>).*?(</p>)#si', '$1[trace]$2', $rulesExtractionError->toHtml()), ); return true; }) ->once(); } #[DataProvider('emptySchemaEarlyReturnProvider')] public function test_it_returns_early_with_empty_schema(array $parameterReflectionData): void { // Arrange $parameters = array_map( fn ($config) => $this->makeReflectionParameter($config), $parameterReflectionData ); $route = $this->makeExtractableRoute($parameters); // Anticipate $this->schemaBuilderMock->shouldNotReceive('buildSchemaFromRuleset'); // Act $schema = $this->strategy->extract($route); // Assert $this->assertTrue($schema->isEmpty()); } public static function emptySchemaEarlyReturnProvider(): Generator { yield 'no spatie data object parameter' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => stdClass::class], ], ]; yield 'parameter type is not named type' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => null], ], ]; yield 'parameter type is not ReflectionNamedType' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => ReflectionUnionType::class], ], ]; yield 'no parameters' => [ 'parameterReflectionData' => [], ]; } /* * Generators. */ private function makeExtractableRoute(array $parameters): ExtractableRoute { return new ExtractableRoute( parameters: $parameters, codeParser: fn () => 'noop', ); } /** * @param array{hasType: bool, getType: string} $config */ private function makeReflectionParameter(array $config): ReflectionParameter { $reflectionParameter = $this->createMock(ReflectionParameter::class); $reflectionParameter->method('hasType')->willReturn($config['hasType']); if ($config['getType'] !== null) { $type = $this->createMock(ReflectionNamedType::class); $type->method('getName')->willReturn($config['getType']); $reflectionParameter->method('getType')->willReturn($type); return $reflectionParameter; } $reflectionParameter->method('getType')->willReturn(null); return $reflectionParameter; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/FormRequestExtractorStrategyUnitTest.php
tests/App/Modules/Routes/Extractors/FormRequestExtractorStrategyUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors; use Generator; use Illuminate\Http\Request; use Mockery; use PhpParser\NodeTraverser; use PhpParser\Parser\Php8; use PhpParser\ParserFactory; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\PreserveGlobalState; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use PHPUnit\Framework\TestCase; use ReflectionClass; use ReflectionNamedType; use ReflectionParameter; use Sunchayn\Nimbus\Modules\Routes\Extractor\Ast\RulesMethodVisitor; use Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies\FormRequestExtractorStrategy; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\ExtractableRoute; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\RulesExtractionError; use Sunchayn\Nimbus\Modules\Schemas\Builders\SchemaBuilder; use Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty; use Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Stubs\FormRequestStub; use Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Stubs\FormRequestWithDifferentRulesStub; use Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Stubs\FormRequestWithExceptionStub; use Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Stubs\FormRequestWithoutRulesStub; #[CoversClass(FormRequestExtractorStrategy::class)] #[CoversClass(RulesExtractionError::class)] class FormRequestExtractorStrategyUnitTest extends TestCase { private SchemaBuilder $schemaBuilderMock; private FormRequestExtractorStrategy $strategy; protected function setUp(): void { parent::setUp(); $this->schemaBuilderMock = Mockery::mock(SchemaBuilder::class); $this->strategy = new FormRequestExtractorStrategy($this->schemaBuilderMock); } protected function tearDown(): void { Mockery::close(); parent::tearDown(); } #[DataProvider('matchesProvider')] public function test_it_matches_correctly( array $parameterReflectionData, bool $expected ): void { // Arrange $parameters = array_map( fn (array $reflectionData) => $this->makeReflectionParameter($reflectionData), $parameterReflectionData ); $route = $this->makeExtractableRoute($parameters); // Act $actual = $this->strategy->matches($route); // Assert $this->assertEquals($expected, $actual); } public static function matchesProvider(): Generator { yield 'form request parameter' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => FormRequestStub::class], // <- ReflectionParameter methods return values. ], 'expected' => true, ]; yield 'base request parameter' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => Request::class], ], 'expected' => false, ]; yield 'parameter without type' => [ 'parameterReflectionData' => [ ['hasType' => false, 'getType' => null], ], 'expected' => false, ]; yield 'parameter with non-named type' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => null], ], 'expected' => false, ]; yield 'parameter not request subclass' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => \stdClass::class], ], 'expected' => false, ]; yield 'no parameters' => [ 'parameterReflectionData' => [], 'expected' => false, ]; yield 'multiple parameters with form request' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => \stdClass::class], ['hasType' => true, 'getType' => FormRequestStub::class], ], 'expected' => true, ]; yield 'multiple parameters without form request' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => \stdClass::class], ['hasType' => true, 'getType' => 'string'], ], 'expected' => false, ]; yield 'form request after base request' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => Request::class], ['hasType' => true, 'getType' => FormRequestStub::class], ], 'expected' => false, // <- stops at base Request ]; } #[DataProvider('extractProvider')] public function test_it_extracts_schema_from_form_request( string $formRequestClass, Ruleset $expectedRules ): void { // Arrange $parameter = $this->makeReflectionParameter([ 'getType' => $formRequestClass, 'hasType' => true, ]); $route = $this->makeExtractableRoute([$parameter]); // Anticipate $responseSchemaStub = new Schema(properties: [ new SchemaProperty( name: '::property::', ), ]); $this->schemaBuilderMock ->shouldReceive('buildSchemaFromRuleset') ->withAnyArgs() ->andReturn($responseSchemaStub) ->once(); // Act $schema = $this->strategy->extract($route); // Assert $this->assertSame($responseSchemaStub, $schema); $this ->schemaBuilderMock ->shouldHaveReceived('buildSchemaFromRuleset') ->withArgs(function (Ruleset $ruleset, ?RulesExtractionError $rulesExtractionError) use ($expectedRules) { $this->assertEquals( $expectedRules->all(), $ruleset->all(), ); $this->assertNull($rulesExtractionError); return true; }) ->once(); } public static function extractProvider(): Generator { yield 'form request with rules' => [ 'formRequestClass' => FormRequestStub::class, 'expectedRules' => Ruleset::make([ 'name' => ['required', 'string'], 'email' => ['required', 'email'], ]), ]; yield 'form request with different rules' => [ 'formRequestClass' => FormRequestWithDifferentRulesStub::class, 'expectedRules' => Ruleset::make([ 'title' => ['required'], 'content' => ['nullable', 'string'], ]), ]; } #[RunInSeparateProcess] // <- Having overload Mock here, let's not leak it. #[PreserveGlobalState(false)] public function test_it_handles_exception_when_calling_rules_method(): void { // Arrange $parameter = $this->makeReflectionParameter([ 'hasType' => true, 'getType' => FormRequestWithExceptionStub::class, ]); $route = $this->makeExtractableRoute([$parameter]); $visitorMock = Mockery::mock('overload:'.RulesMethodVisitor::class); $nodeTraverserMock = Mockery::mock('overload:'.NodeTraverser::class); $parserFactoryMock = Mockery::mock('overload:'.ParserFactory::class); $parserMock = Mockery::mock('overload:'.Php8::class); // Anticipate $parserMock->shouldReceive('parse')->andReturn([]); $parserFactoryMock->shouldReceive('createForNewestSupportedVersion')->andReturn($parserMock); $nodeTraverserMock ->shouldReceive('addVisitor') ->withAnyArgs() ->with(Mockery::type(RulesMethodVisitor::class)) ->ordered() ->once(); // TODO [Test] This is not a conclusive assert at the moment, it doesn't ensure the AST is extracted correctly. $nodeTraverserMock ->shouldReceive('traverse') ->with(Mockery::type('array')) ->ordered() ->once(); $responseSchemaStub = Schema::empty(); $expectedRuleset = Ruleset::make([ 'name' => ['required', 'string'], 'email' => ['required', 'email'], ]); $visitorMock ->shouldReceive('getRules') ->ordered() ->andReturn($expectedRuleset); $this ->schemaBuilderMock ->shouldReceive('buildSchemaFromRuleset') ->withAnyArgs() ->andReturn($responseSchemaStub); // Act $schema = $this->strategy->extract($route); // Assert $this->assertSame($responseSchemaStub, $schema); $this ->schemaBuilderMock ->shouldHaveReceived('buildSchemaFromRuleset') ->withArgs(function (Ruleset $ruleset, ?RulesExtractionError $rulesExtractionError) use ($expectedRuleset) { $this->assertEquals( $expectedRuleset->all(), $ruleset->all(), ); $this->assertNotNull($rulesExtractionError); $stubRequestClassName = (new ReflectionClass(FormRequestWithExceptionStub::class))->getFileName(); // Note the error will be coming from `FormRequestWithExceptionStub`. $this->assertEquals( <<<HTML <b>Cannot access request context</b><br /> <small>{$stubRequestClassName}::11</small> <p class="text-xs">[trace]</p> HTML, // TODO [Test] Test is not the right place to test this method. // TODO [Test] Figure a way to fully test this properly. Due to final methods we cannot assert the trace properly. preg_replace('#(<p\b[^>]*>).*?(</p>)#si', '$1[trace]$2', $rulesExtractionError->toHtml()), ); return true; }) ->once(); } public function test_it_extracts_from_first_form_request_with_multiple_parameters(): void { // Arrange $regularParam = $this->makeReflectionParameter([ 'hasType' => true, 'getType' => \stdClass::class, ]); $formRequestParam = $this->makeReflectionParameter([ 'hasType' => true, 'getType' => FormRequestStub::class, ]); $route = $this->makeExtractableRoute([$regularParam, $formRequestParam]); $expectedRuleset = Ruleset::make([ 'name' => ['required', 'string'], 'email' => ['required', 'email'], ]); // Anticipate $responseSchemaStub = new Schema(properties: [ new SchemaProperty( name: '::property::', ), ]); $this ->schemaBuilderMock ->shouldReceive('buildSchemaFromRuleset') ->withAnyArgs() ->andReturn($responseSchemaStub); // Act $schema = $this->strategy->extract($route); // Assert $this->assertSame($responseSchemaStub, $schema); $this ->schemaBuilderMock ->shouldHaveReceived('buildSchemaFromRuleset') ->withArgs(function (Ruleset $ruleset, ?RulesExtractionError $rulesExtractionError) use ($expectedRuleset) { $this->assertEquals( $expectedRuleset->all(), $ruleset->all(), ); $this->assertNull($rulesExtractionError); return true; }) ->once(); } #[DataProvider('emptySchemaEarlyReturnProvider')] public function test_it_returns_early_with_empty_schema(array $parameterReflectionData): void { // Arrange $parameters = array_map( fn ($config) => $this->makeReflectionParameter($config), $parameterReflectionData ); $route = $this->makeExtractableRoute($parameters); // Anticipate $this->schemaBuilderMock->shouldNotReceive('buildSchemaFromRuleset'); // Act $schema = $this->strategy->extract($route); // Assert $this->assertTrue($schema->isEmpty()); } public static function emptySchemaEarlyReturnProvider(): Generator { yield 'no form request parameter' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => \stdClass::class], ], ]; yield 'parameter type is not named type' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => null], ], ]; yield 'form request without rules method' => [ 'parameterReflectionData' => [ ['hasType' => true, 'getType' => FormRequestWithoutRulesStub::class], ], ]; yield 'no parameters' => [ 'parameterReflectionData' => [], ]; } /* * Generators. */ private function makeExtractableRoute(array $parameters): ExtractableRoute { return new ExtractableRoute( parameters: $parameters, codeParser: fn () => 'noop', ); } /** * @param array{hasType: bool, getType: string} $config */ private function makeReflectionParameter(array $config): ReflectionParameter { $reflectionParameter = $this->createMock(ReflectionParameter::class); $reflectionParameter->method('hasType')->willReturn($config['hasType']); if ($config['getType'] !== null) { $type = $this->createMock(ReflectionNamedType::class); $type->method('getName')->willReturn($config['getType']); $reflectionParameter->method('getType')->willReturn($type); return $reflectionParameter; } $reflectionParameter->method('getType')->willReturn(null); return $reflectionParameter; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/SchemaExtractorUnitTest.php
tests/App/Modules/Routes/Extractors/SchemaExtractorUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors; use Illuminate\Container\Container; use Illuminate\Support\Arr; use Mockery; use Mockery\MockInterface; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Modules\Routes\Extractor\SchemaExtractor; use Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies\ExtractorStrategyContract; use Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies\FormRequestExtractorStrategy; use Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies\InlineRequestValidatorExtractorStrategy; use Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies\SpatieDataObjectExtractorStrategy; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\ExtractableRoute; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; #[CoversClass(SchemaExtractor::class)] class SchemaExtractorUnitTest extends TestCase { protected function tearDown(): void { Mockery::close(); parent::tearDown(); } public function test_it_initialize_extractor_correctly(): void { // Arrange $formRequestExtractorStrategyMock = Mockery::mock(FormRequestExtractorStrategy::class); $spatieDataObjectExtractorStrategyMock = Mockery::mock(SpatieDataObjectExtractorStrategy::class); $inlineRequestValidatorExtractorStrategyMock = Mockery::mock(InlineRequestValidatorExtractorStrategy::class); $containerMock = Mockery::mock(Container::class); $this->swapMocksInDIContainer( $containerMock, implementations: [ FormRequestExtractorStrategy::class => $formRequestExtractorStrategyMock, SpatieDataObjectExtractorStrategy::class => $spatieDataObjectExtractorStrategyMock, InlineRequestValidatorExtractorStrategy::class => $inlineRequestValidatorExtractorStrategyMock, ], ); // Act $schemaExtractor = new SchemaExtractor($containerMock); // Assert $strategies = invade($schemaExtractor)->strategies; $this->assertCount(3, $strategies); $this->assertSame($formRequestExtractorStrategyMock, $strategies[0]); $this->assertSame($spatieDataObjectExtractorStrategyMock, $strategies[1]); $this->assertSame($inlineRequestValidatorExtractorStrategyMock, $strategies[2]); } public function test_it_extracts_using_the_matching_strategy(): void { // Arrange $containerMock = Mockery::mock( Container::class, function (MockInterface $mock) { // Ignore existent strategies. $mock->shouldReceive('make')->withAnyArgs()->andReturnNull(); }, ); [$matchingStrategyMock, $nonMatchingStrategyMock] = $this->makeMatchingStrategies(); // Make schema extractor with the stub strategies. $schemaExtractor = new SchemaExtractor($containerMock); invade($schemaExtractor)->strategies = Arr::shuffle([ $matchingStrategyMock, $nonMatchingStrategyMock, ]); $route = new ExtractableRoute( parameters: [], codeParser: fn () => 'noop', ); // Act $schemaExtractor->extract($route); // Assert $matchingStrategyMock ->shouldHaveReceived('extract') ->withArgs(function (ExtractableRoute $routeArg) use ($route) { $this->assertSame($route, $routeArg); return true; }) ->once(); $nonMatchingStrategyMock->shouldNotHaveReceived('extract'); } /* * Mocks. */ private function swapMocksInDIContainer(mixed $containerMock, array $implementations): void { foreach ($implementations as $abstract => $implementation) { $containerMock ->shouldReceive('make') ->with($abstract) ->once() ->andReturn($implementation); } } /* * Generators. */ private function makeMatchingStrategies(): array { $nonMatchingStrategy = new class implements ExtractorStrategyContract { public function matches(ExtractableRoute $route): bool { return false; } public function extract(ExtractableRoute $route): Schema { return Schema::empty(); } }; $matchingStrategy = new class implements ExtractorStrategyContract { public function matches(ExtractableRoute $route): bool { return true; } public function extract(ExtractableRoute $route): Schema { return Schema::empty(); } }; return [ Mockery::mock($matchingStrategy)->makePartial(), Mockery::mock($nonMatchingStrategy)->makePartial(), ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/InlineRequestValidatorExtractorStrategyUnitTest.php
tests/App/Modules/Routes/Extractors/InlineRequestValidatorExtractorStrategyUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors; use Generator; use Illuminate\Support\Arr; use Mockery; use PhpParser\NodeTraverser; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\PreserveGlobalState; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Modules\Routes\Extractor\Ast\ValidateCallVisitor; use Sunchayn\Nimbus\Modules\Routes\Extractor\Strategies\InlineRequestValidatorExtractorStrategy; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\ExtractableRoute; use Sunchayn\Nimbus\Modules\Routes\ValueObjects\RulesExtractionError; use Sunchayn\Nimbus\Modules\Schemas\Builders\SchemaBuilder; use Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\Schema; use Sunchayn\Nimbus\Modules\Schemas\ValueObjects\SchemaProperty; #[CoversClass(InlineRequestValidatorExtractorStrategy::class)] class InlineRequestValidatorExtractorStrategyUnitTest extends TestCase { private SchemaBuilder&Mockery\MockInterface $schemaBuilderMock; private InlineRequestValidatorExtractorStrategy $strategy; protected function setUp(): void { parent::setUp(); $this->schemaBuilderMock = Mockery::mock(SchemaBuilder::class); $this->strategy = new InlineRequestValidatorExtractorStrategy($this->schemaBuilderMock); } protected function tearDown(): void { Mockery::close(); parent::tearDown(); } #[DataProvider('matchesProvider')] public function test_it_matches_correctly( ?string $methodName, bool $expected ): void { // Arrange $route = $this->makeExtractableRoute( methodName: $methodName, codeParser: fn () => [] ); // Act $actual = $this->strategy->matches($route); // Assert $this->assertEquals($expected, $actual); } public static function matchesProvider(): Generator { yield 'route with method name' => [ 'methodName' => 'store', 'expected' => true, ]; yield 'route with different method name' => [ 'methodName' => 'update', 'expected' => true, ]; yield 'route without method name' => [ 'methodName' => null, 'expected' => false, ]; } #[RunInSeparateProcess] // <- Having overload Mock here, let's not leak it. #[PreserveGlobalState(false)] public function test_it_extracts_schema_from_inline_validation(): void { // Arrange $responseSchemaStub = new Schema(properties: [ new SchemaProperty(name: 'name'), new SchemaProperty(name: 'email'), ]); $ast = ['node' => 'value']; $methodName = Arr::random( [ 'store', 'get', 'edit', ], ); $route = $this->makeExtractableRoute( methodName: $methodName, codeParser: fn () => $ast ); $visitorMock = Mockery::mock('overload:'.ValidateCallVisitor::class); $nodeTraverserMock = Mockery::mock('overload:'.NodeTraverser::class); // Anticipate $visitorMock ->shouldReceive('__construct') ->once() ->withArgs(function ($methodArg) use ($methodName) { $this->assertEquals( $methodName, $methodArg, ); return true; }); $nodeTraverserMock->shouldReceive('addVisitor') ->with(Mockery::type(ValidateCallVisitor::class)) ->ordered() ->once(); $nodeTraverserMock->shouldReceive('traverse')->with($ast)->ordered()->once(); $expectedRuleset = Ruleset::fromLaravelRules([ 'name' => 'required|string', 'email' => 'required|email', ]); $visitorMock->shouldReceive('getRules')->ordered()->andReturn($expectedRuleset); $this->schemaBuilderMock ->shouldReceive('buildSchemaFromRuleset') ->withAnyArgs() ->andReturn($responseSchemaStub) ->once(); // Act $schema = $this->strategy->extract($route); // Assert $this->assertSame($responseSchemaStub, $schema); $this ->schemaBuilderMock ->shouldHaveReceived('buildSchemaFromRuleset') ->withArgs(function (Ruleset $ruleset, ?RulesExtractionError $rulesExtractionError = null) use ($expectedRuleset) { $this->assertEquals( $expectedRuleset->all(), $ruleset->all(), ); $this->assertNull($rulesExtractionError); return true; }) ->once(); } public function test_it_returns_empty_schema_when_route_does_not_match(): void { // Arrange $route = $this->makeExtractableRoute( methodName: null, codeParser: fn () => [] ); // Anticipate $this->schemaBuilderMock->shouldNotReceive('buildSchemaFromRuleset'); // Act $schema = $this->strategy->extract($route); // Assert $this->assertTrue($schema->isEmpty()); } public function test_it_builds_schema_with_empty_rules_when_no_validation_found(): void { // Arrange $route = $this->makeExtractableRoute( methodName: 'store', codeParser: fn () => [] // <- Empty AST, no `->validate()` (or other eligible methods) calls. ); $responseSchemaStub = Schema::empty(); // Anticipate $this->schemaBuilderMock ->shouldReceive('buildSchemaFromRuleset') ->withAnyArgs() ->andReturn($responseSchemaStub) ->once(); // Act $schema = $this->strategy->extract($route); // Assert $this->assertSame($responseSchemaStub, $schema); $this ->schemaBuilderMock ->shouldHaveReceived('buildSchemaFromRuleset') ->withArgs(function (Ruleset $ruleset, ?RulesExtractionError $rulesExtractionError = null) { $this->assertEquals( [], $ruleset->all(), ); $this->assertNull($rulesExtractionError); return true; }) ->once(); } /* * Generators. */ private function makeExtractableRoute(?string $methodName, callable $codeParser): ExtractableRoute { return new ExtractableRoute( parameters: [], // <- Not needed in this strategy. codeParser: $codeParser, methodName: $methodName, ); } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/Ast/ValidateCallVisitorUnitTest.php
tests/App/Modules/Routes/Extractors/Ast/ValidateCallVisitorUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Ast; use Generator; use Illuminate\Validation\Rule; use Illuminate\Validation\Rules\In; use PhpParser\NodeTraverser; use PhpParser\ParserFactory; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Modules\Routes\Extractor\Ast\ConvertNodeToConcreteValue; use Sunchayn\Nimbus\Modules\Routes\Extractor\Ast\ValidateCallVisitor; use Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset; use Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Stubs\StatusEnumStub; #[CoversClass(ValidateCallVisitor::class)] #[CoversClass(ConvertNodeToConcreteValue::class)] class ValidateCallVisitorUnitTest extends TestCase { #[DataProvider('scenariosDataProvider')] public function test_it_works( string $methodName, string $phpCode, array $expectedRules, ): void { // Arrange // Parse the stub into AST $parser = (new ParserFactory)->createForNewestSupportedVersion(); $ast = $parser->parse($phpCode); $visitor = new ValidateCallVisitor($methodName); $traverser = new NodeTraverser; $traverser->addVisitor($visitor); // Act $traverser->traverse($ast); // Assert $this->assertEquals(Ruleset::fromLaravelRules($expectedRules), $visitor->getRules()); } public static function scenariosDataProvider(): Generator { yield 'simple call' => [ 'methodName' => 'simple_call', 'phpCode' => file_get_contents(__DIR__.'/Stubs/controller.stub.php'), 'expectedRules' => [ 'foobar' => 'required|string', 'foobaz' => ['required', 'integer'], ], ]; yield 'simple call without variable assignment' => [ 'methodName' => 'simple_call_without_assignment', 'phpCode' => file_get_contents(__DIR__.'/Stubs/controller.stub.php'), 'expectedRules' => [ 'foobar' => 'required|string', 'foobaz' => ['required', 'integer'], ], ]; yield 'rules from sub method, concatenation, and interpolation' => [ 'methodName' => 'getting_rules_from_sub_method', 'phpCode' => file_get_contents(__DIR__.'/Stubs/controller.stub.php'), 'expectedRules' => [ 'foobar' => 'required_with:foobaz', 'foobarr' => 'present_with:foobar', 'fooobazz' => 'required|string|email|max:200', 'baz' => 'required|string|present|email', 'foobaz' => ['required', 'string', 'email'], ], ]; yield 'call from a variable' => [ 'methodName' => 'call_from_a_variable', 'phpCode' => file_get_contents(__DIR__.'/Stubs/controller.stub.php'), 'expectedRules' => [ 'foobar' => 'required|string', 'foobaz' => ['required', 'integer'], ], ]; yield 'call from nested variables' => [ 'methodName' => 'call_from_nested_variables', 'phpCode' => file_get_contents(__DIR__.'/Stubs/controller.stub.php'), 'expectedRules' => [ 'foobar' => 'required|string', 'foobaz' => ['required', 'string', 'email'], ], ]; yield 'call with rules instances' => [ 'methodName' => 'call_with_rules_instances', 'phpCode' => file_get_contents(__DIR__.'/Stubs/controller.stub.php'), 'expectedRules' => [ 'foobar' => [ 'required', Rule::in(1, 2, 3, 4), Rule::notIn(3, 4), null, // <- RequiredIf cannot be resolved with a closure. Rule::enum(StatusEnumStub::class), ], 'foobaz' => ['required', 'string', new In(1, 2)], ], ]; yield 'call with validateWithBag' => [ 'methodName' => 'call_validateWithBag', 'phpCode' => file_get_contents(__DIR__.'/Stubs/controller.stub.php'), 'expectedRules' => [ 'foobar' => [ 'required', 'in:1, 2, 3, 4', ], 'foobaz' => ['required', 'string', 'email'], ], ]; yield 'no validate call' => [ 'methodName' => 'no_validate_call', 'phpCode' => file_get_contents(__DIR__.'/Stubs/controller.stub.php'), 'expectedRules' => [], ]; yield 'calling validate on a non-request class' => [ 'methodName' => 'call_validate_on_different_class', 'phpCode' => file_get_contents(__DIR__.'/Stubs/controller.stub.php'), 'expectedRules' => [], ]; yield 'nested methods call' => [ 'methodName' => 'nested_methods_calls', 'phpCode' => file_get_contents(__DIR__.'/Stubs/controller.stub.php'), 'expectedRules' => [], // <- Currently this is not supported. ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/Ast/RulesMethodVisitorUnitTest.php
tests/App/Modules/Routes/Extractors/Ast/RulesMethodVisitorUnitTest.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Ast; use Generator; use PhpParser\NodeTraverser; use PhpParser\ParserFactory; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Sunchayn\Nimbus\Modules\Routes\Extractor\Ast\ConvertNodeToConcreteValue; use Sunchayn\Nimbus\Modules\Routes\Extractor\Ast\RulesMethodVisitor; use Sunchayn\Nimbus\Modules\Schemas\Collections\Ruleset; #[CoversClass(RulesMethodVisitor::class)] #[CoversClass(ConvertNodeToConcreteValue::class)] class RulesMethodVisitorUnitTest extends TestCase { #[DataProvider('scenariosDataProvider')] public function test_it_works( string $phpCode, array $expectedRules, ): void { // Arrange // Parse the stub into AST $parser = (new ParserFactory)->createForNewestSupportedVersion(); $ast = $parser->parse($phpCode); $visitor = new RulesMethodVisitor; $traverser = new NodeTraverser; $traverser->addVisitor($visitor); // Act $traverser->traverse($ast); // Assert $this->assertEquals(Ruleset::fromLaravelRules($expectedRules), $visitor->getRules()); } public static function scenariosDataProvider(): Generator { yield 'simple call' => [ 'phpCode' => file_get_contents(__DIR__.'/Stubs/FormRequestStub.php'), 'expectedRules' => [ 'name' => 'required|string', 'email' => 'required|email', ], ]; yield 'with variables call' => [ 'phpCode' => file_get_contents(__DIR__.'/Stubs/FormRequestWithVariablesStub.php'), 'expectedRules' => [ 'name' => 'required|string', 'email' => 'required|string|email', ], ]; yield 'with input conditional call' => [ 'phpCode' => file_get_contents(__DIR__.'/Stubs/FormRequestWithInputConditionalStub.php'), 'expectedRules' => [ 'name' => null, // <- Unable cannot figure it out given it is conditional. 'email' => 'required|string|email', ], ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/Ast/Stubs/FormRequestWithVariablesStub.php
tests/App/Modules/Routes/Extractors/Ast/Stubs/FormRequestWithVariablesStub.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Ast\Stubs; use Illuminate\Http\Request; class FormRequestWithVariablesStub extends Request { public function rules(): array { $rule = 'required|string'; return [ 'name' => $rule, 'email' => "{$rule}|email", ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/Ast/Stubs/FormRequestStub.php
tests/App/Modules/Routes/Extractors/Ast/Stubs/FormRequestStub.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Ast\Stubs; use Illuminate\Http\Request; class FormRequestStub extends Request { public function rules(): array { return [ 'name' => 'required|string', 'email' => 'required|email', ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/Ast/Stubs/controller.stub.php
tests/App/Modules/Routes/Extractors/Ast/Stubs/controller.stub.php
<?php use Illuminate\Container\Container; use Illuminate\Http\Request; use Illuminate\Validation\Rule; use Illuminate\Validation\Rules\In; use Illuminate\Validation\Rules\NotIn; use Illuminate\Validation\Rules\RequiredIf; use Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Ast\Stubs\FormRequestStub; use Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Stubs\StatusEnumStub; class TestController { public function simple_call(Request $request): void { $validated = $request->validate([ 'foobar' => 'required|string', 'foobaz' => ['required', 'integer'], ]); } public function simple_call_without_assignment(FormRequestStub $request) { $request->validate([ 'foobar' => 'required|string', 'foobaz' => ['required', 'integer'], ]); } public function getting_rules_from_sub_method(Request $request): void { $validated = $request->validate($this->craftRules()); } public function call_from_a_variable(Request $request) { $rules = [ 'foobar' => 'required|string', 'foobaz' => ['required', 'integer'], ]; $validated = $request->validate($rules); } public function call_from_nested_variables(Request $request) { $rule = ['required', 'string', 'email']; $rules = [ 'foobar' => 'required|string', 'foobaz' => $rule, ]; $validated = $request->validate($rules); } public function call_with_rules_instances(Request $request) { $rules = [ 'foobar' => [ 'required', Rule::in(1, 2, 3, 4), new NotIn(3, 4), new RequiredIf(fn () => '::value::'), Rule::enum(StatusEnumStub::class), ], 'foobaz' => ['required', 'string', new In(1, 2)], ]; $validated = $request->validate($rules); } public function call_validateWithBag(Request $request) { $rules = [ 'foobar' => [ 'required', 'in:1, 2, 3, 4', ], 'foobaz' => ['required', 'string', 'email'], ]; $validated = $request->validateWithBag('foobaz', $rules); } public function no_validate_call(Request $request) { return response()->json('Hi'); } public function call_validate_on_different_class(Container $container) { $container->validate([ 'foobar' => [ 'required', 'in:1, 2, 3, 4', ], 'foobaz' => ['required', 'string', 'email'], ]); } public function nested_methods_calls(Request $request) { $this->validateFormData($request); return response()->json('Hi'); } private function validateFormData(Request $request) { return $request->validate([ 'foobaz' => ['required', 'string', 'email'], ]); } private function craftRules(): array { $rule = ['required', 'string', 'email']; $interpolation = 'required|string'; $interpolation2 = '|max:200'; $fieldname = 'foobaz'; return [ 'foobar' => 'required_with:'.$fieldname, 'foobarr' => 'present_with'.':'.'foobar', 'fooobazz' => "{$interpolation}|email{$interpolation2}", 'baz' => "{$interpolation}|present".'|'.'email', 'foobaz' => $rule, ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/Ast/Stubs/FormRequestWithInputConditionalStub.php
tests/App/Modules/Routes/Extractors/Ast/Stubs/FormRequestWithInputConditionalStub.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Ast\Stubs; use Illuminate\Http\Request; class FormRequestWithInputConditionalStub extends Request { public function rules(): array { $rule = 'required|string'; $shouldAllowSomething = $this->boolean('something'); return [ 'name' => $shouldAllowSomething ? 'required|string' : 'present|string', 'email' => "{$rule}|email", ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/Stubs/FormRequestWithDifferentRulesStub.php
tests/App/Modules/Routes/Extractors/Stubs/FormRequestWithDifferentRulesStub.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Stubs; use Illuminate\Http\Request; class FormRequestWithDifferentRulesStub extends Request { public function rules(): array { return [ 'title' => 'required', 'content' => 'nullable|string', ]; } }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/Stubs/StatusEnumStub.php
tests/App/Modules/Routes/Extractors/Stubs/StatusEnumStub.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Stubs; enum StatusEnumStub: string { case INACTIVE = 'inactive'; case ACTIVE = 'active'; }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/Stubs/FormRequestWithoutRulesStub.php
tests/App/Modules/Routes/Extractors/Stubs/FormRequestWithoutRulesStub.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Stubs; use Illuminate\Http\Request; class FormRequestWithoutRulesStub extends Request { // No rules method }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false
sunchayn/nimbus
https://github.com/sunchayn/nimbus/blob/8bdd510f179b0c86175557d41fbda2797a41a507/tests/App/Modules/Routes/Extractors/Stubs/SpatieDataObjectStub.php
tests/App/Modules/Routes/Extractors/Stubs/SpatieDataObjectStub.php
<?php namespace Sunchayn\Nimbus\Tests\App\Modules\Routes\Extractors\Stubs; use Spatie\LaravelData\Attributes\Validation\Max; use Spatie\LaravelData\Data; class SpatieDataObjectStub extends Data { public function __construct( public string $title, #[Max(20)] public ?string $artist, ) {} }
php
MIT
8bdd510f179b0c86175557d41fbda2797a41a507
2026-01-05T05:17:17.516160Z
false