diff --git a/specs/001-aggregate-renderer/plan.md b/specs/001-aggregate-renderer/plan.md index a171934..104bc1a 100644 --- a/specs/001-aggregate-renderer/plan.md +++ b/specs/001-aggregate-renderer/plan.md @@ -133,12 +133,13 @@ src/ ├── Console/ │ └── BuildCommand.php # site:build, human summary or --json ├── Discovery/ -│ ├── DiscoveryFailed.php # Discovery failure with a reason code │ ├── GitHubProjectSource.php # Org repositories and doc-target property │ ├── Project.php # Readonly discovered project │ ├── ProjectSourceInterface.php # all(): list │ ├── SitePath.php # Derives a site path from a repository name │ └── Token.php # Reads the token from its environment variable at use +├── Exception/ +│ └── DiscoveryException.php # Discovery failure with a reason code ├── Output/ │ ├── CnameFile.php # Writes and verifies the site address file │ └── OutputTree.php # Resets, writes and reads output paths diff --git a/src/Build/Container/SiteBuildFactoryFactory.php b/src/Build/Container/SiteBuildFactoryFactory.php index fb940c2..83b9d3f 100644 --- a/src/Build/Container/SiteBuildFactoryFactory.php +++ b/src/Build/Container/SiteBuildFactoryFactory.php @@ -15,7 +15,7 @@ namespace CommonDoc\Aggregate\Build\Container; use CommonDoc\Aggregate\Build\SiteBuildFactory; -use CommonDoc\Aggregate\Discovery\ProjectSourceInterface; +use CommonDoc\Aggregate\Discovery\ProjectSourceFactoryInterface; use CommonDoc\Aggregate\Render\SiteRendererFactoryInterface; use CommonDoc\Aggregate\Source\SourceFactoryInterface; use CommonDoc\Aggregate\Version\StrategyFactory; @@ -49,7 +49,7 @@ public function __invoke( ?array $options = null, ): SiteBuildFactory { return new SiteBuildFactory( - discovery : $container->get(ProjectSourceInterface::class), + projects : $container->get(ProjectSourceFactoryInterface::class), sources : $container->get(SourceFactoryInterface::class), strategies: $container->get(StrategyFactory::class), renderers : $container->get(SiteRendererFactoryInterface::class), diff --git a/src/Build/SiteBuild.php b/src/Build/SiteBuild.php index 623b5fe..fd2d1ee 100644 --- a/src/Build/SiteBuild.php +++ b/src/Build/SiteBuild.php @@ -7,6 +7,7 @@ use CommonDoc\Aggregate\Config\SiteConfig; use CommonDoc\Aggregate\Discovery\Project; use CommonDoc\Aggregate\Discovery\ProjectSourceInterface; +use CommonDoc\Aggregate\Exception\DiscoveryException; use CommonDoc\Aggregate\Exception\MissingCnameException; use CommonDoc\Aggregate\Output\CnameFile; use CommonDoc\Aggregate\Output\OutputTree; @@ -49,6 +50,7 @@ public function __construct( * @throws MissingCnameException When the site address file does not hold the configured hostname * @throws RuntimeException When the output tree or the report cannot be written * @throws TemplateExceptionInterface When a page cannot be rendered + * @throws DiscoveryException When no project could be discovered at all */ public function build(SiteConfig $config): BuildReport { diff --git a/src/Build/SiteBuildFactory.php b/src/Build/SiteBuildFactory.php index b7d78ec..224e858 100644 --- a/src/Build/SiteBuildFactory.php +++ b/src/Build/SiteBuildFactory.php @@ -15,7 +15,7 @@ namespace CommonDoc\Aggregate\Build; use CommonDoc\Aggregate\Config\SiteConfig; -use CommonDoc\Aggregate\Discovery\ProjectSourceInterface; +use CommonDoc\Aggregate\Discovery\ProjectSourceFactoryInterface; use CommonDoc\Aggregate\Render\SiteRendererFactoryInterface; use CommonDoc\Aggregate\Source\SourceFactoryInterface; use CommonDoc\Aggregate\Version\StrategyFactory; @@ -30,12 +30,13 @@ * The source is built once here and handed to both the renderer and the project build, so a project * is listed and then read against one checkout cache. Everything the build needs that does not come * from the configuration is injected, so this is the only class that knows the order in which the - * pieces fit together. + * pieces fit together. Discovery is the one seam that is itself a factory, because the organization + * it lists belongs to the configuration and therefore cannot be known when the container is built. */ final readonly class SiteBuildFactory implements SiteBuildFactoryInterface { public function __construct( - private ProjectSourceInterface $discovery, + private ProjectSourceFactoryInterface $projects, private SourceFactoryInterface $sources, private StrategyFactory $strategies, private SiteRendererFactoryInterface $renderers, @@ -56,7 +57,7 @@ public function create(SiteConfig $config): SiteBuild ); return new SiteBuild( - discovery : $this->discovery, + discovery : $this->projects->create(config: $config), renderer : $renderer, projectBuild: new ProjectBuild( source : $source, diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index a6f5813..46598de 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -20,7 +20,9 @@ use CommonDoc\Aggregate\Config\SiteConfigReader; use CommonDoc\Aggregate\Console\BuildCommand; use CommonDoc\Aggregate\Console\Container\BuildCommandFactory; -use CommonDoc\Aggregate\Discovery\ProjectSourceInterface; +use CommonDoc\Aggregate\Discovery\Container\GitHubProjectSourceFactoryFactory; +use CommonDoc\Aggregate\Discovery\GitHubProjectSourceFactory; +use CommonDoc\Aggregate\Discovery\ProjectSourceFactoryInterface; use CommonDoc\Aggregate\Render\SiteRendererFactory; use CommonDoc\Aggregate\Render\SiteRendererFactoryInterface; use CommonDoc\Aggregate\Render\ViewFactory; @@ -39,9 +41,11 @@ * * Everything registered here is either configuration-free or a factory that needs the configuration * to build its product, because the output tree, the git source and the renderer all depend on - * values that only exist once `site.json` has been read. Discovery is deliberately absent: this - * package does not yet ship a project source, so a consumer must register one against - * {@see ProjectSourceInterface} before the command can be built. + * values that only exist once `site.json` has been read. Discovery follows the same rule: the + * organization it lists and the variable holding the token live in the configuration, so the + * container supplies the HTTP seams and {@see ProjectSourceFactoryInterface} turns them into a + * source per build. The PSR-18 client is the one service this package cannot register for a + * consumer, so a site that never builds still resolves everything else. * * @internal */ @@ -61,19 +65,21 @@ public function getDependencies(): array { return [ 'aliases' => [ - ReportFileFactoryInterface::class => ReportFileFactory::class, - SiteBuildFactoryInterface::class => SiteBuildFactory::class, - SiteRendererFactoryInterface::class => SiteRendererFactory::class, - SourceFactoryInterface::class => SourceFactory::class, + ProjectSourceFactoryInterface::class => GitHubProjectSourceFactory::class, + ReportFileFactoryInterface::class => ReportFileFactory::class, + SiteBuildFactoryInterface::class => SiteBuildFactory::class, + SiteRendererFactoryInterface::class => SiteRendererFactory::class, + SourceFactoryInterface::class => SourceFactory::class, ], 'factories' => [ - BuildCommand::class => BuildCommandFactory::class, - ReportFileFactory::class => InvokableFactory::class, - SiteBuildFactory::class => SiteBuildFactoryFactory::class, - SiteConfigReader::class => InvokableFactory::class, - SiteRendererFactory::class => InvokableFactory::class, - SourceFactory::class => InvokableFactory::class, - StrategyFactory::class => InvokableFactory::class, + BuildCommand::class => BuildCommandFactory::class, + GitHubProjectSourceFactory::class => GitHubProjectSourceFactoryFactory::class, + ReportFileFactory::class => InvokableFactory::class, + SiteBuildFactory::class => SiteBuildFactoryFactory::class, + SiteConfigReader::class => InvokableFactory::class, + SiteRendererFactory::class => InvokableFactory::class, + SourceFactory::class => InvokableFactory::class, + StrategyFactory::class => InvokableFactory::class, ], ]; } diff --git a/src/Console/BuildCommand.php b/src/Console/BuildCommand.php index 16bbc36..54e2968 100644 --- a/src/Console/BuildCommand.php +++ b/src/Console/BuildCommand.php @@ -17,6 +17,7 @@ use CommonDoc\Aggregate\Build\BuildReport; use CommonDoc\Aggregate\Build\SiteBuildFactoryInterface; use CommonDoc\Aggregate\Config\SiteConfigReader; +use CommonDoc\Aggregate\Exception\DiscoveryException; use CommonDoc\Aggregate\Exception\InvalidSiteConfigException; use CommonDoc\Aggregate\Exception\MissingCnameException; use CommonDoc\Aggregate\Report\ReportFile; @@ -42,7 +43,9 @@ * * Configuration is read before anything is built, so an unusable `site.json` exits 2 with a diagnostic * and no report is written: a report describes a build, and a build that never started has nothing to - * describe. Every other outcome is the report's own exit code, which is why the command never decides + * describe. Discovery is the second thing that can block a run before rendering, for the same reason + * and with the same exit code: no token and no boundary mean no project was read, so there is nothing + * to report. Every other outcome is the report's own exit code, which is why the command never decides * an exit code of its own. */ #[AsCommand(name: self::NAME, description: 'Render the aggregate documentation site.')] @@ -112,7 +115,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int return self::EXIT_BLOCKED; } - $report = $this->builds->create(config: $config)->build(config: $config); + try { + $report = $this->builds->create(config: $config)->build(config: $config); + } catch (DiscoveryException $failed) { + $this->errorsOf($output)->writeln(sprintf('%s', $failed->getMessage())); + + return self::EXIT_BLOCKED; + } if (true === $input->getOption('json')) { $this->writeJson($output, $this->reports->create(config: $config), $report); diff --git a/src/Discovery/Container/GitHubProjectSourceFactoryFactory.php b/src/Discovery/Container/GitHubProjectSourceFactoryFactory.php new file mode 100644 index 0000000..a35984a --- /dev/null +++ b/src/Discovery/Container/GitHubProjectSourceFactoryFactory.php @@ -0,0 +1,53 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\Aggregate\Discovery\Container; + +use CommonDoc\Aggregate\Discovery\GitHubProjectSourceFactory; +use Laminas\ServiceManager\Factory\FactoryInterface; +use Override; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\ContainerInterface; +use Psr\Container\NotFoundExceptionInterface; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; + +/** + * Builds the GitHub project source factory from the HTTP seams a consumer registered. + * + * The client is the one seam this package cannot supply: a PSR-18 implementation is a consumer + * choice, so a missing registration is reported as a missing service when the command is built + * rather than as a fatal error later. The request factory has an invokable default from + * laminas-diactoros, a dependency this package already carries. + */ +final readonly class GitHubProjectSourceFactoryFactory implements FactoryInterface +{ + /** + * @param ?array $options + * + * @throws ContainerExceptionInterface When a service cannot be created + * @throws NotFoundExceptionInterface When a service is not registered + */ + #[Override] + public function __invoke( + ContainerInterface $container, + string $requestedName, + ?array $options = null, + ): GitHubProjectSourceFactory { + return new GitHubProjectSourceFactory( + client : $container->get(ClientInterface::class), + requests: $container->get(RequestFactoryInterface::class), + ); + } +} diff --git a/src/Discovery/DocTarget.php b/src/Discovery/DocTarget.php new file mode 100644 index 0000000..591da9b --- /dev/null +++ b/src/Discovery/DocTarget.php @@ -0,0 +1,53 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\Aggregate\Discovery; + +use function array_find; +use function is_string; +use function trim; + +/** + * The `doc-target` repository custom property, which is the whole onboarding surface: a repository + * carrying a non-empty value is onboarded and a repository carrying anything else is not. + * + * @internal + */ +final class DocTarget +{ + public const string PROPERTY = 'doc-target'; + + private function __construct() {} + + /** + * @param list> $properties the property list a repository answers with + */ + public static function from(array $properties): ?string + { + $property = array_find( + $properties, + /** @param array $entry */ + static fn(array $entry): bool => self::PROPERTY === ($entry['property_name'] ?? null), + ); + + if (null === $property) { + return null; + } + + /** @var mixed $value */ + $value = $property['value'] ?? null; + + return is_string($value) && '' !== trim($value) ? trim($value) : null; + } +} diff --git a/src/Discovery/GitHubApi.php b/src/Discovery/GitHubApi.php new file mode 100644 index 0000000..fc65603 --- /dev/null +++ b/src/Discovery/GitHubApi.php @@ -0,0 +1,159 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\Aggregate\Discovery; + +use CommonDoc\Aggregate\Exception\DiscoveryException; +use InvalidArgumentException; +use JsonException; +use Psr\Http\Client\ClientExceptionInterface; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; +use SensitiveParameter; + +use function array_filter; +use function array_values; +use function is_array; +use function json_decode; +use function sprintf; + +use const JSON_THROW_ON_ERROR; + +/** + * The GitHub boundary, kept to the two things that touch it: sending a request and reading an answer. + * + * Every request is built from the injected PSR-17 factory and sent through the injected PSR-18 client, + * which is what lets the contract test assert request shapes against recorded responses without a + * vendor SDK. What an answer means is decided by the caller; this type only refuses it. + * + * @internal + */ +final readonly class GitHubApi +{ + private const string ACCEPT = 'application/vnd.github+json'; + + private const string USER_AGENT = 'common-doc/aggregate-renderer'; + + private const string AUTHORIZATION = 'Bearer '; + + private const int UNAUTHORIZED = 401; + + private const int NOT_FOUND = 404; + + private const int OK = 200; + + public function __construct( + private ClientInterface $client, + private RequestFactoryInterface $requests, + #[SensitiveParameter] + private Token $token, + ) {} + + /** + * @return list> + * + * @throws DiscoveryException When the body is not a JSON array of objects + */ + private static function objects(string $body, string $address): array + { + try { + /** @var mixed $decoded */ + $decoded = json_decode($body, associative: true, flags: JSON_THROW_ON_ERROR); + } catch (JsonException $malformed) { + throw DiscoveryException::unavailable($address, 'its answer is not JSON.', $malformed); + } + + if (! is_array($decoded)) { + throw DiscoveryException::unavailable($address, 'its answer is not a JSON array.'); + } + + if ([] !== array_filter($decoded, static fn(mixed $entry): bool => ! is_array($entry))) { + throw DiscoveryException::unavailable($address, 'its answer is not a JSON array of objects.'); + } + + /** @var list> */ + return array_values($decoded); + } + + /** + * Reads an address whose absence is meaningful, so a 404 is an answer rather than a failure. + * + * @return list>|null Null when the address is absent + * + * @throws DiscoveryException When the answer is an error status or is not a JSON array of objects + */ + public function find(string $address): ?array + { + return $this->answer($address); + } + + /** + * @return list> + * + * @throws DiscoveryException When the answer is an error status or is not a JSON array of objects + */ + public function get(string $address): array + { + $objects = $this->answer($address); + + if (null === $objects) { + throw DiscoveryException::unavailable($address, 'it answered with status 404.'); + } + + return $objects; + } + + /** + * @return list>|null Null when the address is absent + * + * @throws DiscoveryException When the answer is an error status or is not a JSON array of objects + */ + private function answer(string $address): ?array + { + try { + $request = $this->requests + ->createRequest('GET', $address) + ->withHeader('Accept', self::ACCEPT) + ->withHeader('Authorization', self::AUTHORIZATION . $this->token->reveal()) + ->withHeader('User-Agent', self::USER_AGENT); + } catch (InvalidArgumentException $unbuildable) { + throw DiscoveryException::unavailable($address, 'the request could not be built.', $unbuildable); + } + + try { + $response = $this->client->sendRequest($request); + } catch (ClientExceptionInterface $failure) { + throw DiscoveryException::unavailable($address, 'the request failed in transport.', $failure); + } + + $status = $response->getStatusCode(); + + if (self::UNAUTHORIZED === $status) { + throw DiscoveryException::rejectedToken($address); + } + + if (self::NOT_FOUND === $status) { + return null; + } + + if (self::OK !== $status) { + throw DiscoveryException::unavailable( + $address, + sprintf('it answered with status %d.', $status), + ); + } + + return self::objects((string) $response->getBody(), $address); + } +} diff --git a/src/Discovery/GitHubProjectSource.php b/src/Discovery/GitHubProjectSource.php new file mode 100644 index 0000000..5d7ea3f --- /dev/null +++ b/src/Discovery/GitHubProjectSource.php @@ -0,0 +1,203 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\Aggregate\Discovery; + +use CommonDoc\Aggregate\Exception\DiscoveryException; +use InvalidArgumentException; +use Override; + +use function array_merge; +use function count; +use function is_array; +use function is_string; +use function rawurlencode; +use function sprintf; + +/** + * Discovers the onboarded repositories of one GitHub organization. + * + * Two endpoints, and no vendor SDK: the organization's repositories, then each repository's custom + * property values. A repository is onboarded when its `doc-target` property carries a directory, so + * the property is the whole onboarding cost and a repository without it is simply not listed. + * + * A failure here is not a project defect: nothing was read, so nothing can be reported per project. + * Every failure names a reason code and stops the run before rendering. + */ +final readonly class GitHubProjectSource implements ProjectSourceInterface +{ + public const string DEFAULT_ENDPOINT = 'https://api.github.com'; + + private const int PER_PAGE = 100; + + /** + * @param non-empty-string $organization + * @param non-empty-string $endpoint + */ + public function __construct( + private GitHubApi $api, + private string $organization, + private string $endpoint = self::DEFAULT_ENDPOINT, + ) {} + + /** + * @return list + * + * @throws DiscoveryException When no token is configured or the boundary refuses the run + * @throws InvalidArgumentException When a repository name does not derive a site path + */ + #[Override] + public function all(): array + { + $projects = []; + + foreach ($this->repositories() as $repository) { + $project = $this->project($repository); + + if (null !== $project) { + $projects[] = $project; + } + } + + return $projects; + } + + /** + * A repository nobody onboarded answers the properties endpoint with a 404, which is an answer + * rather than a failure, so it is read as "no property" and the repository is not listed. + * + * @param array $repository + * + * @throws DiscoveryException When the boundary is unreachable or refuses the token + */ + private function docTarget(array $repository): ?string + { + $properties = $this->api->find( + sprintf( + '%s/repos/%s/%s/properties/values', + $this->endpoint, + rawurlencode($this->owner($repository)), + rawurlencode($this->requiredString($repository, 'name')), + ), + ); + + if (null === $properties) { + return null; + } + + return DocTarget::from($properties); + } + + /** + * @param array $repository + * + * @throws DiscoveryException When the repository carries no owner + */ + private function owner(array $repository): string + { + /** @var mixed $owner */ + $owner = $repository['owner'] ?? null; + + if (! is_array($owner)) { + throw DiscoveryException::unavailable( + $this->endpoint, + 'a repository in the listing carries no owner.', + ); + } + + /** @var array $owner */ + return $this->requiredString($owner, 'login'); + } + + /** + * @return list> + * + * @throws DiscoveryException When the page is unreachable or refuses the token + */ + private function page(int $page): array + { + return $this->api->get( + sprintf( + '%s/orgs/%s/repos?per_page=%d&page=%d', + $this->endpoint, + rawurlencode($this->organization), + self::PER_PAGE, + $page, + ), + ); + } + + /** + * @param array $repository + * + * @throws DiscoveryException When the listing entry names no repository + * @throws InvalidArgumentException When the repository name does not derive a site path + */ + private function project(array $repository): ?Project + { + $directory = $this->docTarget($repository); + + if (null === $directory) { + return null; + } + + $name = $this->requiredString($repository, 'name'); + + return new Project( + name : $name, + owner : $this->owner($repository), + sitePath : SitePath::derive($name)->value, + docDirectory: $directory, + ); + } + + /** + * @return list> + * + * @throws DiscoveryException When a page of the listing cannot be read + */ + private function repositories(): array + { + $pages = []; + $page = 1; + + do { + $batch = $this->page($page); + $pages[] = $batch; + $page++; + } while (count($batch) === self::PER_PAGE); + + return array_merge(...$pages); + } + + /** + * @param array $object + * + * @throws DiscoveryException When the key is absent or is not a string + */ + private function requiredString(array $object, string $key): string + { + /** @var mixed $value */ + $value = $object[$key] ?? null; + + if (! is_string($value) || '' === $value) { + throw DiscoveryException::unavailable( + $this->endpoint, + sprintf('a repository in the listing carries no "%s".', $key), + ); + } + + return $value; + } +} diff --git a/src/Discovery/GitHubProjectSourceFactory.php b/src/Discovery/GitHubProjectSourceFactory.php new file mode 100644 index 0000000..3978b26 --- /dev/null +++ b/src/Discovery/GitHubProjectSourceFactory.php @@ -0,0 +1,50 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\Aggregate\Discovery; + +use CommonDoc\Aggregate\Config\SiteConfig; +use Override; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; + +/** + * Builds the GitHub project source one site configuration describes. + * + * The HTTP seams arrive from the container, because a consumer may need to swap the client for one + * with its own transport, proxy or retry policy. The organization and the token variable come from + * the configuration, because they belong to the site rather than to the process. Only the request + * factory is needed: discovery reads two endpoints and writes nothing, so there is no request body to + * build. + */ +final readonly class GitHubProjectSourceFactory implements ProjectSourceFactoryInterface +{ + public function __construct( + private ClientInterface $client, + private RequestFactoryInterface $requests, + ) {} + + #[Override] + public function create(SiteConfig $config): ProjectSourceInterface + { + return new GitHubProjectSource( + api : new GitHubApi( + client : $this->client, + requests: $this->requests, + token : new Token($config->tokenEnvVar), + ), + organization: $config->organization, + ); + } +} diff --git a/src/Discovery/ProjectSourceFactoryInterface.php b/src/Discovery/ProjectSourceFactoryInterface.php new file mode 100644 index 0000000..f852aad --- /dev/null +++ b/src/Discovery/ProjectSourceFactoryInterface.php @@ -0,0 +1,33 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\Aggregate\Discovery; + +use CommonDoc\Aggregate\Config\SiteConfig; + +/** + * The project source as the build obtains it. + * + * Which organization is listed and which environment variable holds the token are configuration + * values, so they only exist once `site.json` has been read. The build therefore holds this factory + * and asks for a source while building, rather than being handed one before the configuration is + * known. One build asks once: the source reads the listing per call, and nothing about it outlives + * the run. + * + * @internal + */ +interface ProjectSourceFactoryInterface +{ + public function create(SiteConfig $config): ProjectSourceInterface; +} diff --git a/src/Discovery/SitePath.php b/src/Discovery/SitePath.php new file mode 100644 index 0000000..3cc4771 --- /dev/null +++ b/src/Discovery/SitePath.php @@ -0,0 +1,71 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\Aggregate\Discovery; + +use InvalidArgumentException; + +use function preg_replace; +use function sprintf; +use function strtolower; +use function trim; + +/** + * The addressable name a repository contributes to the site. + * + * Derived from the repository name, and never configured: onboarding a project costs exactly one + * custom property, so the site path has to be something the repository already carries. Lowercasing + * and collapsing every run outside `[a-z0-9]` into a single hyphen yields a name that needs no + * encoding in a path or a URL, and that two repositories differing only in punctuation cannot share + * by accident, because they derive the same path deliberately. + */ +final readonly class SitePath +{ + private const string SEPARATORS = '/[^a-z0-9]+/'; + + /** @var non-empty-string */ + public string $value; + + /** + * @param non-empty-string $value + */ + private function __construct(string $value) + { + $this->value = $value; + } + + /** + * @throws InvalidArgumentException When the repository name derives no path at all + */ + public static function derive(string $repositoryName): self + { + $collapsed = preg_replace( + pattern : self::SEPARATORS, + replacement: '-', + subject : strtolower($repositoryName), + ); + $path = trim( + string : $collapsed ?? '', + characters: '-', + ); + + if ('' === $path) { + throw new InvalidArgumentException( + sprintf('The repository name "%s" does not derive a site path.', $repositoryName), + ); + } + + return new self($path); + } +} diff --git a/src/Discovery/Token.php b/src/Discovery/Token.php new file mode 100644 index 0000000..6f7ae1c --- /dev/null +++ b/src/Discovery/Token.php @@ -0,0 +1,55 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\Aggregate\Discovery; + +use CommonDoc\Aggregate\Exception\DiscoveryException; + +use function getenv; +use function trim; + +/** + * The organization credential, named here and read from the environment when it is needed. + * + * Nothing holds the token itself: this value carries the name of the variable, so a token cannot + * reach a configuration hash, a template, a diagnostic or the report by being passed around. Reading + * the environment on every call rather than caching the value also means a rotated token takes effect + * on the next request without restarting anything. + */ +final readonly class Token +{ + /** + * @param non-empty-string $envVar + */ + public function __construct( + private string $envVar, + ) {} + + /** + * @return non-empty-string + * + * @throws DiscoveryException When the variable is unset or carries nothing + */ + public function reveal(): string + { + $value = getenv($this->envVar); + $token = false === $value ? '' : trim($value); + + if ('' === $token) { + throw DiscoveryException::missingToken($this->envVar); + } + + return $token; + } +} diff --git a/src/Exception/DiscoveryException.php b/src/Exception/DiscoveryException.php new file mode 100644 index 0000000..55a840d --- /dev/null +++ b/src/Exception/DiscoveryException.php @@ -0,0 +1,70 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDoc\Aggregate\Exception; + +use CommonDoc\Aggregate\Build\ReasonCode; +use RuntimeException; +use Throwable; + +use function sprintf; + +/** + * Discovery could not produce a project list at all. + * + * This is the "blocked before rendering" family: no project was read, so there is nothing a report + * could describe and the run stops with a diagnostic instead. The reason code travels with the + * exception so the exit code and the message cannot disagree about why. + * + * Nothing in a message or a previous exception carries the token itself. The environment variable + * name is printable; the value never is. + */ +final class DiscoveryException extends RuntimeException +{ + private function __construct( + public readonly ReasonCode $reasonCode, + string $reason, + ?Throwable $previous = null, + ) { + parent::__construct($reason, previous: $previous); + } + + public static function missingToken(string $envVar): self + { + return new self( + ReasonCode::MissingToken, + sprintf( + 'The environment variable "%s" is unset or empty, so no organization token is available.', + $envVar, + ), + ); + } + + public static function rejectedToken(string $boundary): self + { + return new self( + ReasonCode::RejectedToken, + sprintf('The credential was rejected by "%s".', $boundary), + ); + } + + public static function unavailable(string $boundary, string $detail, ?Throwable $previous = null): self + { + return new self( + ReasonCode::DiscoveryUnavailable, + sprintf('The boundary "%s" is unavailable: %s', $boundary, $detail), + $previous, + ); + } +} diff --git a/test/integration/Discovery/GitHubProjectSourceTest.php b/test/integration/Discovery/GitHubProjectSourceTest.php new file mode 100644 index 0000000..cbdf80a --- /dev/null +++ b/test/integration/Discovery/GitHubProjectSourceTest.php @@ -0,0 +1,434 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTestIntegration\Aggregate\Discovery; + +use CommonDoc\Aggregate\Build\ReasonCode; +use CommonDoc\Aggregate\Discovery\GitHubApi; +use CommonDoc\Aggregate\Discovery\GitHubProjectSource; +use CommonDoc\Aggregate\Discovery\Project; +use CommonDoc\Aggregate\Discovery\Token; +use CommonDoc\Aggregate\Exception\DiscoveryException; +use JsonException; +use Laminas\Diactoros\RequestFactory; +use Laminas\Diactoros\Response; +use Laminas\Diactoros\StreamFactory; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use Psr\Http\Client\ClientExceptionInterface; +use Psr\Http\Message\ResponseInterface; + +use function implode; +use function json_encode; +use function putenv; +use function sprintf; + +use const JSON_THROW_ON_ERROR; + +/** + * The contract test for the GitHub boundary. + * + * Every case here is a recorded answer, so what is asserted is the request the source builds and the + * project list it derives from the answer, not the shape of a live endpoint. The four answers that + * decide onboarding are covered deliberately: a repository with the property, one with an empty + * value, one with no property at all, and a refused credential. + */ +#[CoversClass(GitHubApi::class)] +#[CoversMethod(GitHubApi::class, '__construct')] +#[CoversMethod(GitHubApi::class, 'find')] +#[CoversMethod(GitHubApi::class, 'get')] +#[CoversClass(GitHubProjectSource::class)] +#[CoversMethod(GitHubProjectSource::class, '__construct')] +#[CoversMethod(GitHubProjectSource::class, 'all')] +final class GitHubProjectSourceTest extends TestCase +{ + private const string TOKEN_VARIABLE = 'AGGREGATE_RENDERER_CONTRACT_TOKEN'; + + private const string BEARER = 'contract-bearer-7'; + + private const string ORGANIZATION = 'common-doc'; + + private const string LISTING = 'https://api.github.com/orgs/common-doc/repos?per_page=100&page=1'; + + private const string SECOND_PAGE = 'https://api.github.com/orgs/common-doc/repos?per_page=100&page=2'; + + /** + * @throws JsonException + */ + #[Test] + public function asksTheTwoEndpointsWithTheAgreedShape(): void + { + $client = new RecordedClient( + $this->response($this->listing($this->repository('commondoc'))), + $this->response($this->properties($this->property('docs'))), + ); + + $this->source($client)->all(); + + static::assertCount(2, $client->sent); + + static::assertSame('GET', $client->sent[0]->getMethod()); + static::assertSame(self::LISTING, (string) $client->sent[0]->getUri()); + static::assertSame( + 'https://api.github.com/repos/common-doc/commondoc/properties/values', + (string) $client->sent[1]->getUri(), + ); + static::assertSame('Bearer ' . self::BEARER, $client->sent[0]->getHeaderLine('Authorization')); + static::assertSame('Bearer ' . self::BEARER, $client->sent[1]->getHeaderLine('Authorization')); + static::assertSame('application/vnd.github+json', $client->sent[0]->getHeaderLine('Accept')); + static::assertSame('common-doc/aggregate-renderer', $client->sent[0]->getHeaderLine('User-Agent')); + } + + /** + * @throws JsonException + */ + #[Test] + public function pagesThroughTheListingUntilAPageIsNotFull(): void + { + $fullPage = []; + $recorded = []; + + for ($index = 1; $index <= 100; $index++) { + $fullPage[] = $this->repository(sprintf('empty-target-%03d', $index)); + } + + $recorded[] = $this->response($this->listing(...$fullPage)); + $recorded[] = $this->response($this->listing($this->repository('commondoc'))); + + for ($index = 1; $index <= 100; $index++) { + $recorded[] = $this->response($this->properties($this->property(''))); + } + + $recorded[] = $this->response($this->properties($this->property('docs'))); + + $client = new RecordedClient(...$recorded); + + $projects = $this->source($client)->all(); + + static::assertCount(1, $projects); + static::assertSame('commondoc', $projects[0]->name); + static::assertCount(103, $client->sent); + static::assertSame(self::SECOND_PAGE, (string) $client->sent[1]->getUri()); + } + + /** + * @throws JsonException + */ + #[Test] + public function refusesAnAnswerThatIsNotAnArray(): void + { + $client = new RecordedClient($this->response('{"message":"Bad credentials"}')); + + try { + $this->source($client)->all(); + + static::fail('A body that is not a JSON array must block the run.'); + } catch (DiscoveryException $failed) { + static::assertStringContainsString('not a JSON array', $failed->getMessage()); + } + } + + /** + * @throws JsonException + */ + #[Test] + public function refusesAnAnswerThatIsNotJson(): void + { + $client = new RecordedClient($this->response('maintenance')); + + try { + $this->source($client)->all(); + + static::fail('A body that is not JSON must block the run.'); + } catch (DiscoveryException $failed) { + static::assertSame(ReasonCode::DiscoveryUnavailable, $failed->reasonCode); + static::assertStringContainsString('its answer is not JSON', $failed->getMessage()); + static::assertInstanceOf(JsonException::class, $failed->getPrevious()); + } + } + + /** + * @throws JsonException + */ + #[Test] + public function refusesAnAnswerWhoseEntriesAreNotObjects(): void + { + $client = new RecordedClient($this->response('[1,2,3]')); + + try { + $this->source($client)->all(); + + static::fail('An entry that is not an object must block the run.'); + } catch (DiscoveryException $failed) { + static::assertStringContainsString('not a JSON array of objects', $failed->getMessage()); + } + } + + /** + * @throws JsonException + */ + #[Test] + public function refusesAnUnreachableBoundary(): void + { + $client = new RecordedClient($this->response('{"message":"Server Error"}', 500)); + + try { + $this->source($client)->all(); + + static::fail('An error status must block the run.'); + } catch (DiscoveryException $failed) { + static::assertSame(ReasonCode::DiscoveryUnavailable, $failed->reasonCode); + static::assertStringContainsString('status 500', $failed->getMessage()); + } + } + + /** + * @throws JsonException + */ + #[Test] + public function refusesARejectedCredential(): void + { + $client = new RecordedClient( + $this->response('{"message":"Bad credentials"}', 401), + ); + + try { + $this->source($client)->all(); + + static::fail('A refused credential must block the run.'); + } catch (DiscoveryException $failed) { + static::assertSame(ReasonCode::RejectedToken, $failed->reasonCode); + static::assertStringNotContainsString(self::BEARER, $failed->getMessage()); + static::assertCount(1, $client->sent); + } + } + + /** + * @throws JsonException + */ + #[Test] + public function refusesARepositoryThatCarriesNoName(): void + { + $client = new RecordedClient( + $this->response($this->listing('{"owner":{"login":"common-doc"}}')), + ); + + try { + $this->source($client)->all(); + + static::fail('A repository without a name must block the run.'); + } catch (DiscoveryException $failed) { + static::assertStringContainsString('carries no "name"', $failed->getMessage()); + } + } + + /** + * @throws JsonException + */ + #[Test] + public function refusesARepositoryThatCarriesNoOwner(): void + { + $client = new RecordedClient( + $this->response($this->listing('{"name":"commondoc"}')), + ); + + try { + $this->source($client)->all(); + + static::fail('A repository without an owner must block the run.'); + } catch (DiscoveryException $failed) { + static::assertStringContainsString('carries no owner', $failed->getMessage()); + } + } + + #[Test] + public function refusesATransportThatFails(): void + { + $cause = $this->createStub(ClientExceptionInterface::class); + + $client = new RecordedClient($cause); + + try { + $this->source($client)->all(); + + static::fail('A transport failure must block the run.'); + } catch (DiscoveryException $failed) { + static::assertSame(ReasonCode::DiscoveryUnavailable, $failed->reasonCode); + static::assertSame($cause, $failed->getPrevious()); + static::assertStringContainsString('failed in transport', $failed->getMessage()); + } + } + + #[Test] + public function refusesToAskAnythingWhenNoTokenIsConfigured(): void + { + $client = new RecordedClient(); + $source = $this->source($client); + + putenv(self::TOKEN_VARIABLE); + + try { + $source->all(); + + static::fail('A missing token must block the run before any request.'); + } catch (DiscoveryException $failed) { + static::assertSame(ReasonCode::MissingToken, $failed->reasonCode); + static::assertCount(0, $client->sent); + } + } + + /** + * @throws JsonException + */ + #[Test] + public function reportsTheProjectOfARepositoryThatCarriesTheProperty(): void + { + $client = new RecordedClient( + $this->response($this->listing($this->repository('commondoc'))), + $this->response($this->properties($this->property('docs'))), + ); + + $projects = $this->source($client)->all(); + + static::assertCount(1, $projects); + static::assertInstanceOf(Project::class, $projects[0]); + static::assertSame('commondoc', $projects[0]->name); + static::assertSame(self::ORGANIZATION, $projects[0]->owner); + static::assertSame('commondoc', $projects[0]->sitePath); + static::assertSame('docs', $projects[0]->docDirectory); + } + + /** + * @throws JsonException + */ + #[Test] + public function skipsARepositoryThatCarriesNoDocTargetProperty(): void + { + $client = new RecordedClient( + $this->response($this->listing($this->repository('no-target'))), + $this->response($this->properties($this->property('docs', 'unrelated'))), + ); + + static::assertSame([], $this->source($client)->all()); + } + + /** + * @throws JsonException + */ + #[Test] + public function skipsARepositoryWhosePropertiesCannotBeRead(): void + { + $client = new RecordedClient( + $this->response($this->listing($this->repository('no-properties'))), + $this->response('{"message":"Not Found"}', 404), + ); + + static::assertSame([], $this->source($client)->all()); + } + + /** + * @throws JsonException + */ + #[Test] + public function skipsARepositoryWhosePropertyValueIsEmpty(): void + { + $client = new RecordedClient( + $this->response($this->listing( + $this->repository('empty-target'), + $this->repository('commondoc'), + )), + $this->response($this->properties($this->property(''))), + $this->response($this->properties($this->property('docs'))), + ); + + $projects = $this->source($client)->all(); + + static::assertCount(1, $projects); + static::assertSame('commondoc', $projects[0]->name); + } + + /** + * @throws JsonException + */ + #[Test] + public function trimsThePropertyValue(): void + { + $client = new RecordedClient( + $this->response($this->listing($this->repository('commondoc'))), + $this->response($this->properties($this->property(' docs/site '))), + ); + + static::assertSame('docs/site', $this->source($client)->all()[0]->docDirectory); + } + + protected function tearDown(): void + { + putenv(self::TOKEN_VARIABLE); + + parent::tearDown(); + } + + private function listing(string ...$repositories): string + { + return sprintf('[%s]', implode(',', $repositories)); + } + + private function properties(string $property): string + { + return sprintf('[%s]', $property); + } + + /** + * @throws JsonException + */ + private function property(string $value, string $name = 'doc-target'): string + { + return (string) json_encode( + ['property_name' => $name, 'value' => $value], + JSON_THROW_ON_ERROR, + ); + } + + /** + * @throws JsonException + */ + private function repository(string $name, string $owner = self::ORGANIZATION): string + { + return (string) json_encode( + ['name' => $name, 'owner' => ['login' => $owner]], + JSON_THROW_ON_ERROR, + ); + } + + private function response(string $body, int $status = 200): ResponseInterface + { + return new Response(new StreamFactory()->createStream($body), $status); + } + + private function source(RecordedClient $client): GitHubProjectSource + { + putenv(self::TOKEN_VARIABLE . '=' . self::BEARER); + + return new GitHubProjectSource( + api : new GitHubApi( + client : $client, + requests: new RequestFactory(), + token : new Token(self::TOKEN_VARIABLE), + ), + organization: self::ORGANIZATION, + ); + } +} diff --git a/test/integration/Discovery/RecordedClient.php b/test/integration/Discovery/RecordedClient.php new file mode 100644 index 0000000..e457869 --- /dev/null +++ b/test/integration/Discovery/RecordedClient.php @@ -0,0 +1,61 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTestIntegration\Aggregate\Discovery; + +use Psr\Http\Client\ClientExceptionInterface; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; +use RuntimeException; + +use function array_shift; + +/** + * A PSR-18 client that replays recorded responses in the order they are asked for. + * + * Discovery is the only boundary the package talks to over HTTP, and the point of the recorded client + * is that a contract test asserts the request the source makes, not the parsing of a response the + * source was handed directly. Every request is kept, so a test can assert both addresses and headers. + */ +final class RecordedClient implements ClientInterface +{ + /** @var list */ + public array $sent = []; + + /** @var list */ + private array $recorded; + + public function __construct(ClientExceptionInterface|ResponseInterface ...$recorded) + { + $this->recorded = [...$recorded]; + } + + /** + * @throws ClientExceptionInterface When the recording holds a transport failure for this call + * @throws RuntimeException When the recording runs out of answers + */ + public function sendRequest(RequestInterface $request): ResponseInterface + { + $this->sent[] = $request; + + $next = array_shift($this->recorded); + + if ($next instanceof ClientExceptionInterface) { + throw $next; + } + + return $next ?? throw new RuntimeException('The recording holds no response for this request.'); + } +} diff --git a/test/unit/Build/Container/SiteBuildFactoryFactoryTest.php b/test/unit/Build/Container/SiteBuildFactoryFactoryTest.php index 6afaebe..0f8cda4 100644 --- a/test/unit/Build/Container/SiteBuildFactoryFactoryTest.php +++ b/test/unit/Build/Container/SiteBuildFactoryFactoryTest.php @@ -16,7 +16,7 @@ use CommonDoc\Aggregate\Build\Container\SiteBuildFactoryFactory; use CommonDoc\Aggregate\Build\SiteBuildFactory; -use CommonDoc\Aggregate\Discovery\ProjectSourceInterface; +use CommonDoc\Aggregate\Discovery\ProjectSourceFactoryInterface; use CommonDoc\Aggregate\Render\SiteRendererFactory; use CommonDoc\Aggregate\Render\SiteRendererFactoryInterface; use CommonDoc\Aggregate\Source\SourceFactory; @@ -60,8 +60,8 @@ private function container(): ServiceManager $container = new ServiceManager(); $container->setService( - ProjectSourceInterface::class, - $this->createStub(ProjectSourceInterface::class), + ProjectSourceFactoryInterface::class, + $this->createStub(ProjectSourceFactoryInterface::class), ); $container->setService(SourceFactoryInterface::class, new SourceFactory()); $container->setService(StrategyFactory::class, new StrategyFactory()); diff --git a/test/unit/Build/SiteBuildFactoryTest.php b/test/unit/Build/SiteBuildFactoryTest.php index 5393d2d..8232b5f 100644 --- a/test/unit/Build/SiteBuildFactoryTest.php +++ b/test/unit/Build/SiteBuildFactoryTest.php @@ -17,6 +17,7 @@ use CommonDoc\Aggregate\Build\SiteBuild; use CommonDoc\Aggregate\Build\SiteBuildFactory; use CommonDoc\Aggregate\Build\SiteBuildFactoryInterface; +use CommonDoc\Aggregate\Discovery\ProjectSourceFactoryInterface; use CommonDoc\Aggregate\Discovery\ProjectSourceInterface; use CommonDoc\Aggregate\Render\SiteRendererFactoryInterface; use CommonDoc\Aggregate\Render\SiteRendererInterface; @@ -74,8 +75,11 @@ private function factory( ?SourceFactoryInterface $sources = null, ?SiteRendererFactoryInterface $renderers = null, ): SiteBuildFactory { + $projects = $this->createStub(ProjectSourceFactoryInterface::class); + $projects->method('create')->willReturn($this->createStub(ProjectSourceInterface::class)); + return new SiteBuildFactory( - discovery : $this->createStub(ProjectSourceInterface::class), + projects : $projects, sources : $sources ?? $this->createStub(SourceFactoryInterface::class), strategies: new StrategyFactory(), renderers : $renderers ?? $this->createStub(SiteRendererFactoryInterface::class), diff --git a/test/unit/BuildCommandTest.php b/test/unit/BuildCommandTest.php index 9f075a1..043e46e 100644 --- a/test/unit/BuildCommandTest.php +++ b/test/unit/BuildCommandTest.php @@ -15,7 +15,9 @@ use CommonDoc\Aggregate\Config\SiteConfigReader; use CommonDoc\Aggregate\Console\BuildCommand; use CommonDoc\Aggregate\Discovery\Project; +use CommonDoc\Aggregate\Discovery\ProjectSourceFactoryInterface; use CommonDoc\Aggregate\Discovery\ProjectSourceInterface; +use CommonDoc\Aggregate\Exception\DiscoveryException; use CommonDoc\Aggregate\Exception\MissingDocDirectoryException; use CommonDoc\Aggregate\Exception\SourceUnavailableException; use CommonDoc\Aggregate\Render\SiteRendererFactoryInterface; @@ -83,6 +85,29 @@ public function countsEveryProjectOfEveryStatusInTheSummary(): void ); } + #[Test] + public function exitsTwoWithADiagnosticAndNoReportWhenNoProjectCanBeDiscovered(): void + { + $projects = $this->createStub(ProjectSourceInterface::class); + $projects + ->method('all') + ->willThrowException( + DiscoveryException::missingToken('COMMONDOC_TOKEN'), + ); + + $discovery = $this->createStub(ProjectSourceFactoryInterface::class); + $discovery->method('create')->willReturn($projects); + + $tester = new CommandTester($this->command(source: $discovery)); + + $statusCode = $tester->execute(['--site' => $this->siteFile()], self::SEPARATE_STREAMS); + + static::assertSame(2, $statusCode); + static::assertStringContainsString('COMMONDOC_TOKEN', $tester->getErrorOutput()); + static::assertSame('', $tester->getDisplay()); + static::assertFalse(is_file($this->reportPath())); + } + #[Test] public function exitsTwoWithADiagnosticAndNoReportWhenTheConfigurationIsMissing(): void { @@ -176,17 +201,15 @@ private function command( array $candidates = [], array $unavailable = [], array $missing = [], + ?ProjectSourceFactoryInterface $source = null, ): BuildCommand { - $discovery = $this->createStub(ProjectSourceInterface::class); - $discovery->method('all')->willReturn(array_map(self::project(...), $projects)); - $renderers = $this->createStub(SiteRendererFactoryInterface::class); $renderers->method('create')->willReturn(new SiteRenderer()); return new BuildCommand( new SiteConfigReader(), new SiteBuildFactory( - discovery : $discovery, + projects : $source ?? $this->projects($projects), sources : $this->sources($candidates, $unavailable, $missing), strategies: new StrategyFactory(), renderers : $renderers, @@ -195,6 +218,20 @@ private function command( ); } + /** + * @param list $projects + */ + private function projects(array $projects): ProjectSourceFactoryInterface + { + $projectsSource = $this->createStub(ProjectSourceInterface::class); + $projectsSource->method('all')->willReturn(array_map(self::project(...), $projects)); + + $discovery = $this->createStub(ProjectSourceFactoryInterface::class); + $discovery->method('create')->willReturn($projectsSource); + + return $discovery; + } + private function reportPath(): string { return "{$this->directory->path}/build/report.json"; diff --git a/test/unit/ConfigProviderTest.php b/test/unit/ConfigProviderTest.php index 401c316..8774e76 100644 --- a/test/unit/ConfigProviderTest.php +++ b/test/unit/ConfigProviderTest.php @@ -21,7 +21,9 @@ use CommonDoc\Aggregate\ConfigProvider; use CommonDoc\Aggregate\Console\BuildCommand; use CommonDoc\Aggregate\Console\Container\BuildCommandFactory; -use CommonDoc\Aggregate\Discovery\ProjectSourceInterface; +use CommonDoc\Aggregate\Discovery\Container\GitHubProjectSourceFactoryFactory; +use CommonDoc\Aggregate\Discovery\GitHubProjectSourceFactory; +use CommonDoc\Aggregate\Discovery\ProjectSourceFactoryInterface; use CommonDoc\Aggregate\Render\SiteRendererFactory; use CommonDoc\Aggregate\Render\SiteRendererFactoryInterface; use CommonDoc\Aggregate\Render\ViewFactory; @@ -30,12 +32,15 @@ use CommonDoc\Aggregate\Source\SourceFactory; use CommonDoc\Aggregate\Source\SourceFactoryInterface; use CommonDoc\Aggregate\Version\StrategyFactory; +use Laminas\Diactoros\RequestFactory; use Laminas\ServiceManager\Factory\InvokableFactory; use Laminas\ServiceManager\ServiceManager; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\CoversMethod; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; use function dirname; @@ -46,13 +51,11 @@ final class ConfigProviderTest extends TestCase { #[Test] - public function buildsTheCommandThroughARealContainerOnceAProjectSourceIsRegistered(): void + public function buildsTheCommandThroughARealContainerOnceTheHttpSeamsAreRegistered(): void { $container = new ServiceManager(new ConfigProvider()->getDependencies()); - $container->setService( - ProjectSourceInterface::class, - $this->createStub(ProjectSourceInterface::class), - ); + $container->setService(ClientInterface::class, $this->createStub(ClientInterface::class)); + $container->setService(RequestFactoryInterface::class, new RequestFactory()); static::assertInstanceOf(BuildCommand::class, $container->get(BuildCommand::class)); } @@ -102,19 +105,21 @@ public function returnsTheDependencyFactoryMap(): void static::assertSame( [ 'aliases' => [ - ReportFileFactoryInterface::class => ReportFileFactory::class, - SiteBuildFactoryInterface::class => SiteBuildFactory::class, - SiteRendererFactoryInterface::class => SiteRendererFactory::class, - SourceFactoryInterface::class => SourceFactory::class, + ProjectSourceFactoryInterface::class => GitHubProjectSourceFactory::class, + ReportFileFactoryInterface::class => ReportFileFactory::class, + SiteBuildFactoryInterface::class => SiteBuildFactory::class, + SiteRendererFactoryInterface::class => SiteRendererFactory::class, + SourceFactoryInterface::class => SourceFactory::class, ], 'factories' => [ - BuildCommand::class => BuildCommandFactory::class, - ReportFileFactory::class => InvokableFactory::class, - SiteBuildFactory::class => SiteBuildFactoryFactory::class, - SiteConfigReader::class => InvokableFactory::class, - SiteRendererFactory::class => InvokableFactory::class, - SourceFactory::class => InvokableFactory::class, - StrategyFactory::class => InvokableFactory::class, + BuildCommand::class => BuildCommandFactory::class, + GitHubProjectSourceFactory::class => GitHubProjectSourceFactoryFactory::class, + ReportFileFactory::class => InvokableFactory::class, + SiteBuildFactory::class => SiteBuildFactoryFactory::class, + SiteConfigReader::class => InvokableFactory::class, + SiteRendererFactory::class => InvokableFactory::class, + SourceFactory::class => InvokableFactory::class, + StrategyFactory::class => InvokableFactory::class, ], ], new ConfigProvider()->getDependencies(), diff --git a/test/unit/Discovery/Container/GitHubProjectSourceFactoryFactoryTest.php b/test/unit/Discovery/Container/GitHubProjectSourceFactoryFactoryTest.php new file mode 100644 index 0000000..c45e3ae --- /dev/null +++ b/test/unit/Discovery/Container/GitHubProjectSourceFactoryFactoryTest.php @@ -0,0 +1,59 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest\Aggregate\Discovery\Container; + +use CommonDoc\Aggregate\Discovery\Container\GitHubProjectSourceFactoryFactory; +use CommonDoc\Aggregate\Discovery\GitHubProjectSourceFactory; +use Laminas\Diactoros\RequestFactory; +use Laminas\ServiceManager\ServiceManager; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use Psr\Container\ContainerExceptionInterface; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; + +#[CoversClass(GitHubProjectSourceFactoryFactory::class)] +#[CoversMethod(GitHubProjectSourceFactoryFactory::class, '__invoke')] +final class GitHubProjectSourceFactoryFactoryTest extends TestCase +{ + #[Test] + public function buildsTheFactoryFromTheRegisteredHttpSeams(): void + { + static::assertInstanceOf( + GitHubProjectSourceFactory::class, + new GitHubProjectSourceFactoryFactory()($this->container(), GitHubProjectSourceFactory::class), + ); + } + + #[Test] + public function reportsAMissingHttpClientAsAContainerException(): void + { + $this->expectException(ContainerExceptionInterface::class); + + new GitHubProjectSourceFactoryFactory()(new ServiceManager(), GitHubProjectSourceFactory::class); + } + + private function container(): ServiceManager + { + $container = new ServiceManager(); + + $container->setService(ClientInterface::class, $this->createStub(ClientInterface::class)); + $container->setService(RequestFactoryInterface::class, new RequestFactory()); + + return $container; + } +} diff --git a/test/unit/Discovery/DocTargetTest.php b/test/unit/Discovery/DocTargetTest.php new file mode 100644 index 0000000..a296bc6 --- /dev/null +++ b/test/unit/Discovery/DocTargetTest.php @@ -0,0 +1,98 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest\Aggregate\Discovery; + +use CommonDoc\Aggregate\Discovery\DocTarget; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +#[CoversClass(DocTarget::class)] +#[CoversMethod(DocTarget::class, 'from')] +final class DocTargetTest extends TestCase +{ + #[Test] + public function readsTheFirstMatchingPropertyOnly(): void + { + static::assertSame( + 'first', + DocTarget::from([ + ['property_name' => 'doc-target', 'value' => 'first'], + ['property_name' => 'doc-target', 'value' => 'second'], + ]), + ); + } + + #[Test] + public function readsTheValueOfTheDocumentTargetProperty(): void + { + static::assertSame( + 'docs', + DocTarget::from([ + ['property_name' => 'unrelated', 'value' => 'ignored'], + ['property_name' => 'doc-target', 'value' => 'docs'], + ]), + ); + } + + #[Test] + public function reportsNoTargetForAnEmptyPropertyList(): void + { + static::assertNull(DocTarget::from([])); + } + + #[Test] + public function reportsNoTargetWhenThePropertyCarriesNoNameKey(): void + { + static::assertNull(DocTarget::from([['value' => 'docs']])); + } + + #[Test] + public function reportsNoTargetWhenThePropertyCarriesNoValueKey(): void + { + static::assertNull(DocTarget::from([['property_name' => 'doc-target']])); + } + + #[Test] + public function reportsNoTargetWhenThePropertyHoldsAnEmptyValue(): void + { + static::assertNull(DocTarget::from([['property_name' => 'doc-target', 'value' => '']])); + } + + #[Test] + public function reportsNoTargetWhenThePropertyHoldsNoString(): void + { + static::assertNull(DocTarget::from([['property_name' => 'doc-target', 'value' => ['docs']]])); + } + + #[Test] + public function reportsNoTargetWhenThePropertyHoldsOnlyWhitespace(): void + { + static::assertNull(DocTarget::from([['property_name' => 'doc-target', 'value' => ' ']])); + } + + #[Test] + public function reportsNoTargetWhenThePropertyIsAbsent(): void + { + static::assertNull(DocTarget::from([['property_name' => 'unrelated', 'value' => 'docs']])); + } + + #[Test] + public function trimsTheValueItReads(): void + { + static::assertSame('docs', DocTarget::from([['property_name' => 'doc-target', 'value' => ' docs ']])); + } +} diff --git a/test/unit/Discovery/GitHubProjectSourceFactoryTest.php b/test/unit/Discovery/GitHubProjectSourceFactoryTest.php new file mode 100644 index 0000000..7698199 --- /dev/null +++ b/test/unit/Discovery/GitHubProjectSourceFactoryTest.php @@ -0,0 +1,88 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest\Aggregate\Discovery; + +use CommonDoc\Aggregate\Discovery\GitHubProjectSourceFactory; +use CommonDoc\Aggregate\Exception\DiscoveryException; +use CommonDocTest\Aggregate\Support\Config; +use Laminas\Diactoros\RequestFactory; +use Laminas\Diactoros\Response; +use Laminas\Diactoros\StreamFactory; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestInterface; + +use function putenv; +use function str_contains; + +#[CoversClass(GitHubProjectSourceFactory::class)] +#[CoversMethod(GitHubProjectSourceFactory::class, '__construct')] +#[CoversMethod(GitHubProjectSourceFactory::class, 'create')] +final class GitHubProjectSourceFactoryTest extends TestCase +{ + private const string TOKEN_VARIABLE = 'COMMONDOC_TOKEN'; + + #[Test] + public function listsTheOrganizationOfTheConfiguration(): void + { + putenv(self::TOKEN_VARIABLE . '=a-token'); + + $client = $this->createMock(ClientInterface::class); + $client + ->expects($this->once()) + ->method('sendRequest') + ->with(static::callback(static fn(RequestInterface $request): bool => str_contains( + (string) $request->getUri(), + '/orgs/common-doc/repos', + ))) + ->willReturn(new Response( + new StreamFactory()->createStream('[]'), + 200, + ['Content-Type' => 'application/json'], + )); + + $source = $this->factory($client)->create(Config::site()); + + static::assertSame([], $source->all()); + } + + #[Test] + public function readsTheTokenVariableOfTheConfigurationRatherThanAConstantOne(): void + { + putenv(self::TOKEN_VARIABLE); + + $source = $this->factory($this->createStub(ClientInterface::class)) + ->create(Config::site()); + + try { + $source->all(); + + static::fail('A source without a token must not reach the boundary.'); + } catch (DiscoveryException $failed) { + static::assertStringContainsString(self::TOKEN_VARIABLE, $failed->getMessage()); + } + } + + private function factory(ClientInterface $client): GitHubProjectSourceFactory + { + return new GitHubProjectSourceFactory( + client : $client, + requests: new RequestFactory(), + ); + } +} diff --git a/test/unit/Discovery/SitePathTest.php b/test/unit/Discovery/SitePathTest.php new file mode 100644 index 0000000..81218c7 --- /dev/null +++ b/test/unit/Discovery/SitePathTest.php @@ -0,0 +1,84 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest\Aggregate\Discovery; + +use CommonDoc\Aggregate\Discovery\SitePath; +use InvalidArgumentException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +#[CoversClass(SitePath::class)] +#[CoversMethod(SitePath::class, 'derive')] +final class SitePathTest extends TestCase +{ + #[Test] + public function collapsesConsecutiveSeparatorsIntoOne(): void + { + static::assertSame('a-b', SitePath::derive('a___b')->value); + static::assertSame('a-b', SitePath::derive('a .-_ b')->value); + } + + #[Test] + public function collapsesSpacesIntoOneSeparator(): void + { + static::assertSame('my-docs', SitePath::derive('my docs')->value); + } + + #[Test] + public function derivesOnePathForTwoNamesThatDifferOnlyInPunctuation(): void + { + static::assertSame('foo-bar', SitePath::derive('Foo_Bar')->value); + static::assertSame('foo-bar', SitePath::derive('foo.bar')->value); + static::assertSame(SitePath::derive('Foo_Bar')->value, SitePath::derive('foo-bar')->value); + } + + #[Test] + public function keepsDigitsOfAVersionedName(): void + { + static::assertSame('site-2-tools', SitePath::derive('Site 2 Tools')->value); + } + + #[Test] + public function lowercasesANameThatCarriesUppercase(): void + { + static::assertSame('commondoc', SitePath::derive('CommonDoc')->value); + } + + #[Test] + public function refusesANameThatDerivesNothing(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The repository name "___" does not derive a site path.'); + + SitePath::derive('___'); + } + + #[Test] + public function refusesAnEmptyName(): void + { + $this->expectException(InvalidArgumentException::class); + + SitePath::derive(''); + } + + #[Test] + public function trimsLeadingAndTrailingSeparators(): void + { + static::assertSame('docs', SitePath::derive('--docs--')->value); + static::assertSame('docs', SitePath::derive('_docs_')->value); + } +} diff --git a/test/unit/Discovery/TokenTest.php b/test/unit/Discovery/TokenTest.php new file mode 100644 index 0000000..e1ba270 --- /dev/null +++ b/test/unit/Discovery/TokenTest.php @@ -0,0 +1,124 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest\Aggregate\Discovery; + +use CommonDoc\Aggregate\Build\ReasonCode; +use CommonDoc\Aggregate\Discovery\Token; +use CommonDoc\Aggregate\Exception\DiscoveryException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; + +use function getenv; +use function putenv; + +#[CoversClass(Token::class)] +#[CoversMethod(Token::class, '__construct')] +#[CoversMethod(Token::class, 'reveal')] +final class TokenTest extends TestCase +{ + private const string VARIABLE = 'AGGREGATE_RENDERER_TEST_TOKEN'; + + private const string OTHER = 'AGGREGATE_RENDERER_TEST_TOKEN_OTHER'; + + #[Test] + public function readsOnlyTheVariableItWasGiven(): void + { + putenv(self::OTHER . '=ghp_other'); + putenv(self::VARIABLE . '=ghp_ours'); + + static::assertSame('ghp_ours', new Token(self::VARIABLE)->reveal()); + static::assertSame('ghp_other', getenv(self::OTHER)); + } + + #[Test] + public function readsTheVariableOnEveryCallRatherThanCachingIt(): void + { + $token = new Token(self::VARIABLE); + + putenv(self::VARIABLE . '=first'); + static::assertSame('first', $token->reveal()); + + putenv(self::VARIABLE . '=second'); + static::assertSame('second', $token->reveal()); + } + + #[Test] + public function refusesAnUnsetVariable(): void + { + $token = new Token(self::VARIABLE); + + $this->expectException(DiscoveryException::class); + $this->expectExceptionMessage( + 'The environment variable "' + . self::VARIABLE + . '" is unset or empty, so no organization token is available.', + ); + + $token->reveal(); + } + + #[Test] + public function refusesAVariableThatHoldsNothing(): void + { + putenv(self::VARIABLE . '='); + + $token = new Token(self::VARIABLE); + + $this->expectException(DiscoveryException::class); + $this->expectExceptionCode(0); + + $token->reveal(); + } + + #[Test] + public function refusesAVariableThatHoldsOnlyWhitespace(): void + { + putenv(self::VARIABLE . '= '); + + try { + new Token(self::VARIABLE)->reveal(); + + static::fail('A whitespace-only variable must not produce a token.'); + } catch (DiscoveryException $failed) { + static::assertSame(ReasonCode::MissingToken, $failed->reasonCode); + } + } + + #[Test] + public function revealsTheValueTheConfiguredVariableHolds(): void + { + putenv(self::VARIABLE . '=ghp_example'); + + static::assertSame('ghp_example', new Token(self::VARIABLE)->reveal()); + } + + #[Test] + public function trimsTheSurroundingWhitespaceOfTheValue(): void + { + putenv(self::VARIABLE . '= ghp_example '); + + static::assertSame('ghp_example', new Token(self::VARIABLE)->reveal()); + } + + protected function tearDown(): void + { + putenv(self::VARIABLE); + putenv(self::OTHER); + + parent::tearDown(); + } +} diff --git a/test/unit/Exception/DiscoveryExceptionTest.php b/test/unit/Exception/DiscoveryExceptionTest.php new file mode 100644 index 0000000..715df11 --- /dev/null +++ b/test/unit/Exception/DiscoveryExceptionTest.php @@ -0,0 +1,76 @@ + + * and contributors. + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace CommonDocTest\Aggregate\Exception; + +use CommonDoc\Aggregate\Build\ReasonCode; +use CommonDoc\Aggregate\Exception\DiscoveryException; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversMethod; +use PHPUnit\Framework\Attributes\Test; +use PHPUnit\Framework\TestCase; +use RuntimeException; + +#[CoversClass(DiscoveryException::class)] +#[CoversMethod(DiscoveryException::class, 'missingToken')] +#[CoversMethod(DiscoveryException::class, 'rejectedToken')] +#[CoversMethod(DiscoveryException::class, 'unavailable')] +final class DiscoveryExceptionTest extends TestCase +{ + #[Test] + public function namesTheMissingVariableWithoutNamingAValue(): void + { + $failed = DiscoveryException::missingToken('COMMONDOC_TOKEN'); + + static::assertSame(ReasonCode::MissingToken, $failed->reasonCode); + static::assertSame( + 'The environment variable "COMMONDOC_TOKEN" is unset or empty, so no organization token is available.', + $failed->getMessage(), + ); + } + + #[Test] + public function recordsAnUnreachableBoundaryWithItsCause(): void + { + $cause = new RuntimeException('the transport refused the connection'); + $failed = DiscoveryException::unavailable('https://api.github.com', 'it answered with status 500.', $cause); + + static::assertSame(ReasonCode::DiscoveryUnavailable, $failed->reasonCode); + static::assertSame( + 'The boundary "https://api.github.com" is unavailable: it answered with status 500.', + $failed->getMessage(), + ); + static::assertSame($cause, $failed->getPrevious()); + } + + #[Test] + public function recordsAnUnreachableBoundaryWithoutACause(): void + { + $failed = DiscoveryException::unavailable('https://api.github.com', 'its answer is not JSON.'); + + static::assertNull($failed->getPrevious()); + } + + #[Test] + public function recordsARejectedCredential(): void + { + $failed = DiscoveryException::rejectedToken('https://api.github.com/orgs/common-doc/repos'); + + static::assertSame(ReasonCode::RejectedToken, $failed->reasonCode); + static::assertSame( + 'The credential was rejected by "https://api.github.com/orgs/common-doc/repos".', + $failed->getMessage(), + ); + } +}