diff --git a/docs/architecture-concepts/the-hydekernel.md b/docs/architecture-concepts/the-hydekernel.md index 2f4e0d9b43f..1dcfa615456 100644 --- a/docs/architecture-concepts/the-hydekernel.md +++ b/docs/architecture-concepts/the-hydekernel.md @@ -41,7 +41,7 @@ app(HydeKernel::class)->version(); hyde()->version(); ``` -The Kernel instance is constructed in `bootstrap.php`, and is available globally as `$hyde`. +The Kernel instance is constructed and bound in the `app/bootstrap.php` file. ## The Kernel Lifecycle diff --git a/monorepo/CodeIntelligence/CodeIntelligence.php b/monorepo/CodeIntelligence/CodeIntelligence.php index ffbff91f091..397ed662ac7 100644 --- a/monorepo/CodeIntelligence/CodeIntelligence.php +++ b/monorepo/CodeIntelligence/CodeIntelligence.php @@ -14,6 +14,8 @@ use Hyde\Foundation\HydeKernel; use Hyde\Markdown\Models\MarkdownDocument; +use function Hyde\normalize_slashes; + if (php_sapi_name() !== 'cli') { // Run the file and proxy the dashboard page for a live browser preview exec('php '.realpath(__FILE__).' 2>&1', $output, $returnCode); @@ -70,7 +72,7 @@ )); $this->line(); - $this->line('Dashboard page generated at '.OUTPUT_PATH.'/dashboard.html'); + $this->line(sprintf('Dashboard page generated at file:///%s', normalize_slashes(realpath(OUTPUT_PATH.'/dashboard.html')))); $this->line(); $this->info(sprintf('Time taken: %s. Memory used: %s', diff --git a/packages/framework/src/Console/Commands/BuildSiteCommand.php b/packages/framework/src/Console/Commands/BuildSiteCommand.php index cfa73df8a74..84ecf1fda17 100644 --- a/packages/framework/src/Console/Commands/BuildSiteCommand.php +++ b/packages/framework/src/Console/Commands/BuildSiteCommand.php @@ -10,11 +10,11 @@ use Hyde\Console\Concerns\Command; use Hyde\Framework\Services\BuildService; use Hyde\Framework\Services\BuildTaskService; +use Illuminate\Support\Facades\Process; use function memory_get_peak_usage; use function number_format; use function array_search; -use function shell_exec; use function microtime; use function sprintf; use function app; @@ -137,13 +137,9 @@ protected function runNodeCommand(string $command, string $message, ?string $act { $this->info($message.' This may take a second.'); - $output = shell_exec(sprintf( - '%s%s', - (string) app()->environment() === 'testing' ? 'echo ' : '', - $command - )); + $output = Process::command($command)->run(); - $this->line($output ?? sprintf( + $this->line($output->output() ?? sprintf( 'Could not %s! Is NPM installed?', $actionMessage ?? 'run script' )); diff --git a/packages/framework/src/Console/Commands/PublishHomepageCommand.php b/packages/framework/src/Console/Commands/PublishHomepageCommand.php index 50b7ddb9df6..61f49beb9c4 100644 --- a/packages/framework/src/Console/Commands/PublishHomepageCommand.php +++ b/packages/framework/src/Console/Commands/PublishHomepageCommand.php @@ -64,8 +64,8 @@ public function handle(): int Artisan::call('vendor:publish', [ '--tag' => $this->options[$selected]['group'] ?? $selected, - '--force' => true, // Todo add force state dynamically depending on existing file state - ], ! $tagExists ? $this->output : null); + '--force' => true, + ], $tagExists ? null : $this->output); // If the tag doesn't exist, we pass the output to use the called command's error output. if ($tagExists) { $this->infoComment("Published page [$selected]"); diff --git a/packages/framework/src/Facades/Features.php b/packages/framework/src/Facades/Features.php index d1a07cd6c28..1ee34439515 100644 --- a/packages/framework/src/Facades/Features.php +++ b/packages/framework/src/Facades/Features.php @@ -92,7 +92,112 @@ public static function hasDarkmode(): bool */ public static function hasSitemap(): bool { - return Hyde::hasSiteUrl() + return static::enabled(Feature::Torchlight) + && (Config::getNullableString('torchlight.token') !== null) + && (app('env') !== 'testing'); + } + + // ================================================= + // Configure features to be used in the config file. + // ================================================= + + /** + * @codeCoverageIgnore Deprecated method. + * + * @deprecated This method will be removed in v2.0. Please use `Feature::HtmlPages` instead. + */ + #[Deprecated(reason: 'Replaced by the \Hyde\Enums\Feature::HtmlPages Enum case', replacement: 'Feature::HtmlPages', since: '1.6.0')] + public static function htmlPages(): Feature + { + return Feature::HtmlPages; + } + + /** + * @codeCoverageIgnore Deprecated method. + * + * @deprecated This method will be removed in v2.0. Please use `Feature::BladePages` instead. + */ + #[Deprecated(reason: 'Replaced by the \Hyde\Enums\Feature::BladePages Enum case', replacement: 'Feature::BladePages', since: '1.6.0')] + public static function bladePages(): Feature + { + return Feature::BladePages; + } + + /** + * @codeCoverageIgnore Deprecated method. + * + * @deprecated This method will be removed in v2.0. Please use `Feature::MarkdownPages` instead. + */ + #[Deprecated(reason: 'Replaced by the \Hyde\Enums\Feature::MarkdownPages Enum case', replacement: 'Feature::MarkdownPages', since: '1.6.0')] + public static function markdownPages(): Feature + { + return Feature::MarkdownPages; + } + + /** + * @codeCoverageIgnore Deprecated method. + * + * @deprecated This method will be removed in v2.0. Please use `Feature::MarkdownPosts` instead. + */ + #[Deprecated(reason: 'Replaced by the \Hyde\Enums\Feature::MarkdownPosts Enum case', replacement: 'Feature::MarkdownPosts', since: '1.6.0')] + public static function markdownPosts(): Feature + { + return Feature::MarkdownPosts; + } + + /** + * @codeCoverageIgnore Deprecated method. + * + * @deprecated This method will be removed in v2.0. Please use `Feature::DocumentationPages` instead. + */ + #[Deprecated(reason: 'Replaced by the \Hyde\Enums\Feature::DocumentationPages Enum case', replacement: 'Feature::DocumentationPages', since: '1.6.0')] + public static function documentationPages(): Feature + { + return Feature::DocumentationPages; + } + + /** + * @codeCoverageIgnore Deprecated method. + * + * @deprecated This method will be removed in v2.0. Please use `Feature::DocumentationSearch` instead. + */ + #[Deprecated(reason: 'Replaced by the \Hyde\Enums\Feature::DocumentationSearch Enum case', replacement: 'Feature::DocumentationSearch', since: '1.6.0')] + public static function documentationSearch(): Feature + { + return Feature::DocumentationSearch; + } + + /** + * @codeCoverageIgnore Deprecated method. + * + * @deprecated This method will be removed in v2.0. Please use `Feature::Darkmode` instead. + */ + #[Deprecated(reason: 'Replaced by the \Hyde\Enums\Feature::Darkmode Enum case', replacement: 'Feature::Darkmode', since: '1.6.0')] + public static function darkmode(): Feature + { + return Feature::Darkmode; + } + + /** + * @codeCoverageIgnore Deprecated method. + * + * @deprecated This method will be removed in v2.0. Please use `Feature::Torchlight` instead. + */ + #[Deprecated(reason: 'Replaced by the \Hyde\Enums\Feature::Torchlight Enum case', replacement: 'Feature::Torchlight', since: '1.6.0')] + public static function torchlight(): Feature + { + return Feature::Torchlight; + } + + // ==================================================== + // Dynamic features that in addition to being enabled + // in the config file, require preconditions to be met. + // ==================================================== + + /** Can a sitemap be generated? */ + public static function sitemap(): bool + { + return static::resolveMockedInstance('sitemap') ?? Hyde::hasSiteUrl() && Config::getBool('hyde.generate_sitemap', true) && extension_loaded('simplexml'); } diff --git a/packages/framework/src/Foundation/HydeKernel.php b/packages/framework/src/Foundation/HydeKernel.php index 0283a4fbc37..f4284f909be 100644 --- a/packages/framework/src/Foundation/HydeKernel.php +++ b/packages/framework/src/Foundation/HydeKernel.php @@ -31,10 +31,9 @@ * The HydeKernel It is stored as a singleton in this class, and is bound into the * Laravel Application Service Container, and can be accessed in a few ways. * - * Commonly, you'll use the Hyde facade, but you can also use Dependency Injection + * Commonly, you'll use the Hyde facade to access it, but you can also use Dependency Injection * by type-hinting the HydeKernel::class, or use the hyde() function to get the Kernel. - * - * The Kernel instance is constructed in bootstrap.php, and is available globally as $hyde. + * The Kernel instance is constructed and bound in the app/bootstrap.php script. */ class HydeKernel implements SerializableContract { diff --git a/packages/framework/src/Foundation/Internal/LoadConfiguration.php b/packages/framework/src/Foundation/Internal/LoadConfiguration.php index db1b31e4090..591430ecd2f 100644 --- a/packages/framework/src/Foundation/Internal/LoadConfiguration.php +++ b/packages/framework/src/Foundation/Internal/LoadConfiguration.php @@ -19,7 +19,7 @@ class LoadConfiguration extends BaseLoadConfiguration /** Get all the configuration files for the application. */ protected function getConfigurationFiles(Application $app): array { - return (array) tap(parent::getConfigurationFiles($app), function (array &$files) use ($app): void { + return (array) tap(parent::getConfigurationFiles($app), /** @param array $files */ function (array &$files) use ($app): void { // Inject our custom config file which is stored in `app/config.php`. $files['app'] ??= $app->basePath().DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'config.php'; }); diff --git a/packages/framework/src/Foundation/Internal/LoadYamlConfiguration.php b/packages/framework/src/Foundation/Internal/LoadYamlConfiguration.php index 833f47fb595..faf25ce3713 100644 --- a/packages/framework/src/Foundation/Internal/LoadYamlConfiguration.php +++ b/packages/framework/src/Foundation/Internal/LoadYamlConfiguration.php @@ -46,7 +46,7 @@ protected function hasYamlConfigFile(): bool || file_exists(Hyde::path('hyde.yaml')); } - /** @return array */ + /** @return array */ protected function getYaml(): array { return Arr::undot((array) Yaml::parse(file_get_contents($this->getFile()))); diff --git a/packages/framework/src/Foundation/Kernel/Filesystem.php b/packages/framework/src/Foundation/Kernel/Filesystem.php index 883663d3f31..97fa11bec30 100644 --- a/packages/framework/src/Foundation/Kernel/Filesystem.php +++ b/packages/framework/src/Foundation/Kernel/Filesystem.php @@ -16,7 +16,6 @@ use function array_map; use function is_string; use function is_array; -use function collect; use function str_starts_with; use function unslash; use function unlink; @@ -198,8 +197,9 @@ public function unlinkIfExists(string $path): bool /** @return \Illuminate\Support\Collection */ public function smartGlob(string $pattern, int $flags = 0): Collection { - return collect(\Hyde\Facades\Filesystem::glob($pattern, $flags)) - ->map(fn (string $path): string => $this->pathToRelative($path)) - ->values(); + /** @var \Illuminate\Support\Collection $files */ + $files = collect(\Hyde\Facades\Filesystem::glob($pattern, $flags)); + + return $files->map(fn (string $path): string => $this->pathToRelative($path)); } } diff --git a/packages/framework/src/Foundation/Kernel/PageCollection.php b/packages/framework/src/Foundation/Kernel/PageCollection.php index 865b723383a..4739a17743b 100644 --- a/packages/framework/src/Foundation/Kernel/PageCollection.php +++ b/packages/framework/src/Foundation/Kernel/PageCollection.php @@ -49,7 +49,7 @@ protected function runExtensionHandlers(): void } /** @param class-string<\Hyde\Pages\Concerns\HydePage> $pageClass */ - protected static function parsePage(string $pageClass, string $path) + protected static function parsePage(string $pageClass, string $path): HydePage { return $pageClass::parse($pageClass::pathToIdentifier($path)); } diff --git a/packages/framework/src/Framework/Actions/BladeMatterParser.php b/packages/framework/src/Framework/Actions/BladeMatterParser.php index 1f6c03f2530..2f2dcc6eb9c 100644 --- a/packages/framework/src/Framework/Actions/BladeMatterParser.php +++ b/packages/framework/src/Framework/Actions/BladeMatterParser.php @@ -136,7 +136,11 @@ protected static function getValueWithType(string $value): mixed // This will cast integers, floats, and booleans to their respective types // Still working on a way to handle multidimensional arrays and objects - return json_decode($value) ?? $value; + + /** @var scalar|null $decoded */ + $decoded = json_decode($value); + + return $decoded ?? $value; } /** @return array */ @@ -153,7 +157,7 @@ protected static function parseArrayString(string $string): array } // Check if string is multidimensional (not yet supported) - if (substr_count($string, '[') > 1 || substr_count($string, ']') > 1) { + if ((substr_count($string, '[') > 1) || (substr_count($string, ']') > 1)) { throw new RuntimeException('Failed parsing BladeMatter array. Multidimensional arrays are not supported yet.'); } @@ -171,6 +175,7 @@ protected static function parseArrayString(string $string): array // Add key/value pair to array $key = (string) static::getValueWithType(trim(trim($pair[0]), "'")); $value = static::getValueWithType(trim(trim($pair[1]), "'")); + $array[$key] = $value; } diff --git a/packages/framework/src/Framework/Actions/ConvertsMarkdownToPlainText.php b/packages/framework/src/Framework/Actions/ConvertsMarkdownToPlainText.php index d0a99ba1f0f..8b9b2229cdb 100644 --- a/packages/framework/src/Framework/Actions/ConvertsMarkdownToPlainText.php +++ b/packages/framework/src/Framework/Actions/ConvertsMarkdownToPlainText.php @@ -4,7 +4,9 @@ namespace Hyde\Framework\Actions; +use function trim; use function rtrim; +use function is_numeric; use function str_ends_with; use function str_starts_with; use function substr; diff --git a/packages/framework/src/Framework/Actions/PostBuildTasks/GenerateBuildManifest.php b/packages/framework/src/Framework/Actions/PostBuildTasks/GenerateBuildManifest.php index df549f48d34..d5868157740 100644 --- a/packages/framework/src/Framework/Actions/PostBuildTasks/GenerateBuildManifest.php +++ b/packages/framework/src/Framework/Actions/PostBuildTasks/GenerateBuildManifest.php @@ -77,7 +77,7 @@ protected function jsonEncodeOutput(Collection $pages): string ], JSON_PRETTY_PRINT); } - public function setOutput(OutputStyle $output) + public function setOutput(OutputStyle $output): void { // Disable output } diff --git a/packages/framework/src/Framework/Actions/PostBuildTasks/GenerateSitemap.php b/packages/framework/src/Framework/Actions/PostBuildTasks/GenerateSitemap.php index 3f6b5dcda1f..e2e15c55809 100644 --- a/packages/framework/src/Framework/Actions/PostBuildTasks/GenerateSitemap.php +++ b/packages/framework/src/Framework/Actions/PostBuildTasks/GenerateSitemap.php @@ -9,6 +9,7 @@ use Hyde\Framework\Concerns\InteractsWithDirectories; use Hyde\Framework\Features\XmlGenerators\SitemapGenerator; +use function blank; use function file_put_contents; class GenerateSitemap extends PostBuildTask diff --git a/packages/framework/src/Framework/Actions/PreBuildTasks/CleanSiteDirectory.php b/packages/framework/src/Framework/Actions/PreBuildTasks/CleanSiteDirectory.php index f00e37ce798..849f077b7cb 100644 --- a/packages/framework/src/Framework/Actions/PreBuildTasks/CleanSiteDirectory.php +++ b/packages/framework/src/Framework/Actions/PreBuildTasks/CleanSiteDirectory.php @@ -6,10 +6,9 @@ use Hyde\Hyde; use Hyde\Facades\Config; +use Hyde\Facades\Filesystem; use Hyde\Framework\Features\BuildTasks\PreBuildTask; -use Illuminate\Support\Facades\File; -use function array_map; use function basename; use function glob; use function in_array; @@ -22,8 +21,8 @@ class CleanSiteDirectory extends PreBuildTask public function handle(): void { if ($this->isItSafeToCleanOutputDirectory()) { - array_map('unlink', glob(Hyde::sitePath('*.{html,json}'), GLOB_BRACE)); - File::cleanDirectory(Hyde::siteMediaPath()); + Filesystem::unlink(glob(Hyde::sitePath('*.{html,json}'), GLOB_BRACE)); + Filesystem::cleanDirectory(Hyde::siteMediaPath()); } } diff --git a/packages/framework/src/Framework/Concerns/Internal/ForwardsIlluminateFilesystem.php b/packages/framework/src/Framework/Concerns/Internal/ForwardsIlluminateFilesystem.php index 1b9897700c7..0a405873597 100644 --- a/packages/framework/src/Framework/Concerns/Internal/ForwardsIlluminateFilesystem.php +++ b/packages/framework/src/Framework/Concerns/Internal/ForwardsIlluminateFilesystem.php @@ -59,7 +59,7 @@ * @method static bool isWritable(string $path) * @method static bool hasSameHash(string $firstFile, string $secondFile) * @method static bool isFile(string $file) - * @method static array glob(string $pattern, int $flags = 0) + * @method static array glob(string $pattern, int $flags = 0) * @method static SplFileInfo[] files(string $directory, bool $hidden = false) * @method static SplFileInfo[] allFiles(string $directory, bool $hidden = false) * @method static array directories(string $directory) @@ -89,10 +89,7 @@ protected static function getParameterNames(string $name): array protected static function qualifyArguments(array $parameterNames, array $arguments): Collection { return collect($arguments)->mapWithKeys(function (string|array|int|bool $argumentValue, int|string $key) use ($parameterNames): string|array|int|bool { - $argumentsToQualify = [ - 'path', 'paths', 'file', 'target', 'directory', 'destination', 'firstFile', 'secondFile', - 'pattern', 'link', 'from', 'to', - ]; + $argumentsToQualify = ['path', 'paths', 'file', 'target', 'directory', 'destination', 'firstFile', 'secondFile', 'pattern', 'link', 'from', 'to']; if (is_int($key)) { // If the argument is not named, we'll retrieve it from the reflection data. diff --git a/packages/framework/src/Framework/Factories/BlogPostDataFactory.php b/packages/framework/src/Framework/Factories/BlogPostDataFactory.php index 667800b0718..161477a98d9 100644 --- a/packages/framework/src/Framework/Factories/BlogPostDataFactory.php +++ b/packages/framework/src/Framework/Factories/BlogPostDataFactory.php @@ -4,6 +4,7 @@ namespace Hyde\Framework\Factories; +use Illuminate\Support\Str; use Hyde\Framework\Factories\Concerns\CoreDataObject; use Hyde\Framework\Actions\ConvertsMarkdownToPlainText; use Hyde\Framework\Features\Blogging\Models\FeaturedImage; @@ -13,9 +14,6 @@ use Hyde\Markdown\Models\Markdown; use Hyde\Support\Models\DateString; -use function strlen; -use function substr; - /** * Streamlines the data construction specific to a blog post. * @@ -110,25 +108,14 @@ protected function makeImage(): ?FeaturedImage private function makeDescriptionFromMarkdownBody(): string { - return $this->getTruncatedMarkdown($this->stripMarkdownFromBody($this->markdown->body())); - } - - private function getTruncatedMarkdown(string $markdown): string - { - if (strlen($markdown) >= 128) { - return substr($markdown, 0, 125).'...'; - } - - return $markdown; - } - - private function stripMarkdownFromBody(string $body): string - { - return (new ConvertsMarkdownToPlainText($body))->execute(); + return Str::limit((new ConvertsMarkdownToPlainText($this->markdown->body()))->execute(), 125); } protected function getMatter(string $key): string|null|array { - return $this->matter->get($key); + /** @var string|null|array $value */ + $value = $this->matter->get($key); + + return $value; } } diff --git a/packages/framework/src/Framework/Factories/FeaturedImageFactory.php b/packages/framework/src/Framework/Factories/FeaturedImageFactory.php index a844ae1cf56..f2eae0188a1 100644 --- a/packages/framework/src/Framework/Factories/FeaturedImageFactory.php +++ b/packages/framework/src/Framework/Factories/FeaturedImageFactory.php @@ -91,6 +91,9 @@ protected static function normalizeLocalImagePath(string $path): string protected function getStringMatter(string $key): ?string { - return is_string($this->matter->get($key)) ? $this->matter->get($key) : null; + /** @var string|null $value */ + $value = $this->matter->get($key); + + return is_string($value) ? $value : null; } } diff --git a/packages/framework/src/Framework/Factories/HydePageDataFactory.php b/packages/framework/src/Framework/Factories/HydePageDataFactory.php index 0b41b26b486..4cfd5ed6ad6 100644 --- a/packages/framework/src/Framework/Factories/HydePageDataFactory.php +++ b/packages/framework/src/Framework/Factories/HydePageDataFactory.php @@ -28,10 +28,7 @@ class HydePageDataFactory extends Concerns\PageDataFactory implements PageSchema protected readonly string $title; protected readonly ?NavigationData $navigation; - private readonly string $routeKey; - private readonly string $outputPath; private readonly string $identifier; - private readonly string $pageClass; private readonly Markdown|false $markdown; private readonly FrontMatter $matter; @@ -39,10 +36,7 @@ public function __construct(private readonly CoreDataObject $pageData) { $this->matter = $this->pageData->matter; $this->markdown = $this->pageData->markdown; - $this->pageClass = $this->pageData->pageClass; $this->identifier = $this->pageData->identifier; - $this->outputPath = $this->pageData->outputPath; - $this->routeKey = $this->pageData->routeKey; $this->title = $this->makeTitle(); $this->navigation = $this->makeNavigation(); @@ -101,6 +95,9 @@ private function findTitleFromParentIdentifier(): ?string protected function getMatter(string $key): string|null { - return $this->matter->get($key); + /** @var ?string $value */ + $value = $this->matter->get($key); + + return $value; } } diff --git a/packages/framework/src/Framework/Factories/NavigationDataFactory.php b/packages/framework/src/Framework/Factories/NavigationDataFactory.php index adf2eacbb78..b7d4b905faf 100644 --- a/packages/framework/src/Framework/Factories/NavigationDataFactory.php +++ b/packages/framework/src/Framework/Factories/NavigationDataFactory.php @@ -125,7 +125,7 @@ private function searchForHiddenInConfigs(): ?bool : $this->isPageHiddenInNavigationConfiguration(); } - private function isPageHiddenInNavigationConfiguration(): ?bool + private function isPageHiddenInNavigationConfiguration(): bool { return in_array($this->routeKey, Config::getArray('hyde.navigation.exclude', ['404'])); } @@ -215,9 +215,13 @@ private function searchForPriorityInNavigationConfig(): ?int return $this->parseNavigationPriorityConfig($config, 'routeKey'); } - /** @param array|array $config */ + /** + * @param array|array $config + * @param 'routeKey'|'identifier' $pageKeyName + */ private function parseNavigationPriorityConfig(array $config, string $pageKeyName): ?int { + /** @var string $pageKey */ $pageKey = $this->{$pageKeyName}; // Check if the config entry is a flat array or a keyed array. @@ -256,7 +260,7 @@ protected function getSubdirectoryConfiguration(): string return Config::getString('hyde.navigation.subdirectories', 'hidden'); } - /** @param class-string $class */ + /** @param class-string<\Hyde\Pages\Concerns\HydePage> $class */ protected function isInstanceOf(string $class): bool { return is_a($this->pageClass, $class, true); @@ -274,6 +278,9 @@ protected function offset(?int $value, int $offset): ?int protected function getMatter(string $key): string|null|int|bool { - return $this->matter->get($key); + /** @var string|null|int|bool $value */ + $value = $this->matter->get($key); + + return $value; } } diff --git a/packages/framework/src/Framework/Features/Blogging/Models/FeaturedImage.php b/packages/framework/src/Framework/Features/Blogging/Models/FeaturedImage.php index 02b2ab3eb99..a8dcb492315 100644 --- a/packages/framework/src/Framework/Features/Blogging/Models/FeaturedImage.php +++ b/packages/framework/src/Framework/Features/Blogging/Models/FeaturedImage.php @@ -63,7 +63,7 @@ public function __construct( protected readonly ?string $licenseUrl = null, protected readonly ?string $copyrightText = null ) { - $this->type = $this->isRemote($source) ? self::TYPE_REMOTE : self::TYPE_LOCAL; + $this->type = self::isRemote($source) ? self::TYPE_REMOTE : self::TYPE_LOCAL; $this->source = $this->setSource($source); } @@ -224,7 +224,7 @@ protected function getContentLengthForLocalImage(): int protected function getContentLengthForRemoteImage(): int { - // Check if the --no-api flag is set when running the build command, and if so, skip the API call. + // API calls can be skipped in the config, or by setting the --no-api flag when running the build command. if (Config::getBool('hyde.api_calls', true)) { /** @var string[][] $headers */ $headers = Http::withHeaders([ diff --git a/packages/framework/src/Framework/Features/Documentation/SemanticDocumentationArticle.php b/packages/framework/src/Framework/Features/Documentation/SemanticDocumentationArticle.php index 3a093c51786..81116d00590 100644 --- a/packages/framework/src/Framework/Features/Documentation/SemanticDocumentationArticle.php +++ b/packages/framework/src/Framework/Features/Documentation/SemanticDocumentationArticle.php @@ -17,8 +17,7 @@ use function trim; /** - * Class to make Hyde documentation pages smarter, - * by dynamically enriching them with semantic HTML. + * Class to make Hyde documentation pages smarter by dynamically enriching them with semantic HTML. */ class SemanticDocumentationArticle { @@ -99,6 +98,7 @@ protected function getTokenizedDataArray(): array protected function normalizeBody(): void { // Remove possible trailing newlines added by the Markdown compiler to normalize the body. + $this->body = trim($this->body, "\n"); } @@ -140,9 +140,7 @@ protected function renderSourceLink(): string ])->render(); } - /** - * Do we satisfy the requirements to render an edit source button in the supplied position? - */ + /** Do we satisfy the requirements to render an edit source button in the supplied position? */ protected function canRenderSourceLink(string $inPosition): bool { $config = Config::getString('docs.edit_source_link_position', 'both'); @@ -151,9 +149,7 @@ protected function canRenderSourceLink(string $inPosition): bool return ($this->page->getOnlineSourcePath() !== false) && in_array($inPosition, $positions); } - /** - * Does the current document use Torchlight? - */ + /** Does the current document use Torchlight? */ public function hasTorchlight(): bool { return Features::hasTorchlight() && str_contains($this->html, 'Syntax highlighted by torchlight.dev'); diff --git a/packages/framework/src/Framework/Features/XmlGenerators/RssFeedGenerator.php b/packages/framework/src/Framework/Features/XmlGenerators/RssFeedGenerator.php index ca553194fbf..09ebc3db6d8 100644 --- a/packages/framework/src/Framework/Features/XmlGenerators/RssFeedGenerator.php +++ b/packages/framework/src/Framework/Features/XmlGenerators/RssFeedGenerator.php @@ -16,6 +16,9 @@ use Hyde\Framework\Features\Blogging\Models\FeaturedImage; use function date; +use function assert; +use function sprintf; +use function implode; /** * @see https://validator.w3.org/feed/docs/rss2.html @@ -33,8 +36,11 @@ public function generate(): static protected function constructBaseElement(): void { - $this->xmlElement = new SimpleXMLElement(' - '); + $this->xmlElement = new SimpleXMLElement(implode("\n", [ + '', + '', + ])); + $this->xmlElement->addChild('channel'); $this->addBaseChannelItems(); @@ -44,6 +50,7 @@ protected function constructBaseElement(): void protected function addItem(MarkdownPost $post): void { $item = $this->getChannel()->addChild('item'); + $this->addChild($item, 'title', $post->title); $this->addChild($item, 'description', $post->description); @@ -71,6 +78,7 @@ protected function addDynamicItemData(SimpleXMLElement $item, MarkdownPost $post if (isset($post->image)) { $image = $item->addChild('enclosure'); + $image->addAttribute('url', Hyde::url($post->image->getSource())); $image->addAttribute('type', $this->getImageType($post->image)); $image->addAttribute('length', $this->getImageLength($post->image)); @@ -92,6 +100,7 @@ protected function addBaseChannelItems(): void protected function addAtomLinkItem(): void { $atomLink = $this->getChannel()->addChild('atom:link', namespace: 'http://www.w3.org/2005/Atom'); + $atomLink->addAttribute('href', $this->escape(Hyde::url($this->getFilename()))); $atomLink->addAttribute('rel', 'self'); $atomLink->addAttribute('type', 'application/rss+xml'); @@ -115,11 +124,13 @@ public static function getFilename(): string public static function getDescription(): string { - return Config::getString('hyde.rss.description', Site::name().' RSS Feed'); + return Config::getString('hyde.rss.description', sprintf('%s RSS Feed', Site::name())); } protected function getChannel(): SimpleXMLElement { + assert($this->xmlElement->channel instanceof SimpleXMLElement); + return $this->xmlElement->channel; } } diff --git a/packages/framework/src/Framework/Services/ValidationService.php b/packages/framework/src/Framework/Services/ValidationService.php index 2e9f510a848..88deee3496b 100644 --- a/packages/framework/src/Framework/Services/ValidationService.php +++ b/packages/framework/src/Framework/Services/ValidationService.php @@ -14,7 +14,6 @@ use Hyde\Support\Models\ValidationResult as Result; use function count; -use function call_user_func; use function get_class_methods; use function array_intersect; use function file_exists; @@ -40,7 +39,10 @@ public static function checks(): array public function run(string $check): Result { - return call_user_func([$this, $check], new Result); + $result = new Result; + $this->{$check}($result); + + return $result; } public function check_validators_can_run(Result $result): Result diff --git a/packages/framework/src/Framework/Services/ViewDiffService.php b/packages/framework/src/Framework/Services/ViewDiffService.php index 1db349fd441..8edf7692cd7 100644 --- a/packages/framework/src/Framework/Services/ViewDiffService.php +++ b/packages/framework/src/Framework/Services/ViewDiffService.php @@ -18,6 +18,9 @@ * Helper methods to interact with the virtual filecache that is used to compare * published Blade views with the original Blade views in the Hyde Framework * so the user can be warned before overwriting their customizations. + * + * Since we currently never use this class more than one in the request cycle, + * there is no reason to cache the results of the file index in the instance. */ class ViewDiffService { diff --git a/packages/framework/src/Hyde.php b/packages/framework/src/Hyde.php index a526cb0dd9d..07d82d968fd 100644 --- a/packages/framework/src/Hyde.php +++ b/packages/framework/src/Hyde.php @@ -46,6 +46,7 @@ * @method static string trimSlashes(string $string) * @method static HtmlString markdown(string $text, bool $stripIndentation = false) * @method static string currentPage() + * @method static string currentRouteKey() * @method static string getBasePath() * @method static string getSourceRoot() * @method static string getOutputDirectory() diff --git a/packages/framework/src/Markdown/Models/Markdown.php b/packages/framework/src/Markdown/Models/Markdown.php index d5696a1323d..568ae22be2e 100644 --- a/packages/framework/src/Markdown/Models/Markdown.php +++ b/packages/framework/src/Markdown/Models/Markdown.php @@ -91,8 +91,13 @@ public static function fromFile(string $path): static */ public static function render(string $markdown, ?string $pageClass = null): string { - return $pageClass !== null - ? (new MarkdownService($markdown, $pageClass))->parse() - : (string) app(MarkdownConverter::class)->convert($markdown); + if ($pageClass !== null) { + return (new MarkdownService($markdown, $pageClass))->parse(); + } else { + /** @var MarkdownConverter $converter */ + $converter = app(MarkdownConverter::class); + + return (string) $converter->convert($markdown); + } } } diff --git a/packages/framework/src/Pages/Concerns/HydePage.php b/packages/framework/src/Pages/Concerns/HydePage.php index 64711bfb4bc..af8348d132a 100644 --- a/packages/framework/src/Pages/Concerns/HydePage.php +++ b/packages/framework/src/Pages/Concerns/HydePage.php @@ -399,8 +399,11 @@ public function navigationMenuGroup(): ?string public function getCanonicalUrl(): ?string { - if (! empty($this->matter('canonicalUrl'))) { - return $this->matter('canonicalUrl'); + /** @var ?string $value */ + $value = $this->matter('canonicalUrl'); + + if (! empty($value)) { + return $value; } if (Hyde::hasSiteUrl() && ! empty($this->identifier)) { diff --git a/packages/framework/src/Support/Models/RenderData.php b/packages/framework/src/Support/Models/RenderData.php index 5570c7f28b7..9a7b6376f15 100644 --- a/packages/framework/src/Support/Models/RenderData.php +++ b/packages/framework/src/Support/Models/RenderData.php @@ -53,7 +53,7 @@ public function shareToView(): void View::share($this->toArray()); } - public function share(string $key, mixed $value): void + public function share(string $key, HydePage|Route|string $value): void { if (property_exists($this, $key)) { $this->{$key} = $value; diff --git a/packages/framework/src/Support/Paginator.php b/packages/framework/src/Support/Paginator.php index 25692daa018..5fe84991747 100644 --- a/packages/framework/src/Support/Paginator.php +++ b/packages/framework/src/Support/Paginator.php @@ -71,13 +71,18 @@ public function getPaginatedItems(): Collection public function getItemsForPage(): Collection { - return $this->paginatedItems->get($this->currentPage - 1); + /** @var Collection $paginated */ + $paginated = $this->paginatedItems->get($this->currentPage - 1); + + return $paginated; } public function getPageLinks(): array { $array = []; + $pageRange = range(1, $this->totalPages()); + if (isset($this->routeBasename)) { foreach ($pageRange as $number) { $array[$number] = Routes::get("$this->routeBasename/page-$number") ?? Hyde::formatLink("$this->routeBasename/page-$number"); diff --git a/packages/framework/tests/Feature/Actions/GeneratesSidebarTableOfContentsTest.php b/packages/framework/tests/Feature/Actions/GeneratesSidebarTableOfContentsTest.php index cc4dc8b2e71..26c603b7b4d 100644 --- a/packages/framework/tests/Feature/Actions/GeneratesSidebarTableOfContentsTest.php +++ b/packages/framework/tests/Feature/Actions/GeneratesSidebarTableOfContentsTest.php @@ -14,10 +14,7 @@ */ class GeneratesSidebarTableOfContentsTest extends UnitTestCase { - public static function setUpBeforeClass(): void - { - self::mockConfig(); - } + protected static bool $needsConfig = true; public function testCanGenerateTableOfContents() { diff --git a/packages/framework/tests/Feature/AssetServiceTest.php b/packages/framework/tests/Feature/AssetServiceTest.php index b45d4d7b0f0..ae8661b8118 100644 --- a/packages/framework/tests/Feature/AssetServiceTest.php +++ b/packages/framework/tests/Feature/AssetServiceTest.php @@ -18,26 +18,33 @@ class AssetServiceTest extends TestCase public function testMediaLinkReturnsMediaPathWithCacheKey() { $service = new AssetService(); + $this->assertIsString($path = $service->mediaLink('app.css')); - $this->assertEquals('media/app.css?v='.md5_file(Hyde::path('_media/app.css')), $path); + $this->assertSame('media/app.css?v='.md5_file(Hyde::path('_media/app.css')), $path); } public function testMediaLinkReturnsMediaPathWithoutCacheKeyIfCacheBustingIsDisabled() { config(['hyde.enable_cache_busting' => false]); + $service = new AssetService(); - $this->assertIsString($path = $service->mediaLink('app.css')); - $this->assertEquals('media/app.css', $path); + $path = $service->mediaLink('app.css'); + + $this->assertIsString($path); + $this->assertSame('media/app.css', $path); } public function testMediaLinkSupportsCustomMediaDirectories() { $this->directory('_assets'); $this->file('_assets/app.css'); + Hyde::setMediaDirectory('_assets'); $service = new AssetService(); - $this->assertIsString($path = $service->mediaLink('app.css')); - $this->assertEquals('assets/app.css?v='.md5_file(Hyde::path('_assets/app.css')), $path); + $path = $service->mediaLink('app.css'); + + $this->assertIsString($path); + $this->assertSame('assets/app.css?v='.md5_file(Hyde::path('_assets/app.css')), $path); } } diff --git a/packages/framework/tests/Feature/BladeMatterParserTest.php b/packages/framework/tests/Feature/BladeMatterParserTest.php index d10deb88dbf..c7c07ca8d30 100644 --- a/packages/framework/tests/Feature/BladeMatterParserTest.php +++ b/packages/framework/tests/Feature/BladeMatterParserTest.php @@ -17,7 +17,8 @@ public function testCanParseFrontMatter() { $parser = new BladeMatterParser('@php($foo = "bar")'); $parser->parse(); - $this->assertEquals(['foo' => 'bar'], $parser->get()); + + $this->assertSame(['foo' => 'bar'], $parser->get()); } public function testParseStringHelperMethod() @@ -31,6 +32,7 @@ public function testParseStringHelperMethod() public function testParseFileHelperMethod() { $this->file('foo', 'foo'); + $this->assertSame( (new BladeMatterParser('foo'))->parse()->get(), BladeMatterParser::parseFile('foo') @@ -44,7 +46,8 @@ public function testCanParseMultipleFrontMatterLines() @php($bar = 'baz') @php($baz = 'qux') BLADE; - $this->assertEquals(['foo' => 'bar', 'bar' => 'baz', 'baz' => 'qux'], BladeMatterParser::parseString($document)); + + $this->assertSame(['foo' => 'bar', 'bar' => 'baz', 'baz' => 'qux'], BladeMatterParser::parseString($document)); } public function testCanParseFrontMatterWithVariousFormats() @@ -57,14 +60,15 @@ public function testCanParseFrontMatterWithVariousFormats() ]; foreach ($matrix as $input => $expected) { - $this->assertEquals($expected, BladeMatterParser::parseString($input)); + $this->assertSame($expected, BladeMatterParser::parseString($input)); } } public function testCanParseFrontMatterWithArray() { $document = "@php(\$foo = ['bar' => 'baz'])"; - $this->assertEquals(['foo' => ['bar' => 'baz']], BladeMatterParser::parseString($document)); + + $this->assertSame(['foo' => ['bar' => 'baz']], BladeMatterParser::parseString($document)); } public function testLineMatchesFrontMatter() @@ -126,12 +130,14 @@ public function testParseArrayString() public function testParseInvalidArrayString() { $this->expectException(RuntimeException::class); + ParserTestClass::parseArrayString('foo'); } public function testParseMultidimensionalArrayString() { $this->expectException(RuntimeException::class); + ParserTestClass::parseArrayString('["foo" => ["bar" => "baz"]]'); } } diff --git a/packages/framework/tests/Feature/ColoredBlockquoteShortcodesTest.php b/packages/framework/tests/Feature/ColoredBlockquoteShortcodesTest.php index 063429d9d10..dce752c8313 100644 --- a/packages/framework/tests/Feature/ColoredBlockquoteShortcodesTest.php +++ b/packages/framework/tests/Feature/ColoredBlockquoteShortcodesTest.php @@ -8,8 +8,6 @@ use Hyde\Testing\UnitTestCase; /** - * Class ColoredBlockquoteShortcodesTest. - * * @covers \Hyde\Markdown\Processing\ColoredBlockquotes */ class ColoredBlockquoteShortcodesTest extends UnitTestCase diff --git a/packages/framework/tests/Feature/CommandTest.php b/packages/framework/tests/Feature/CommandTest.php index 68424a5ebf0..8cb4c8ec03c 100644 --- a/packages/framework/tests/Feature/CommandTest.php +++ b/packages/framework/tests/Feature/CommandTest.php @@ -17,10 +17,7 @@ */ class CommandTest extends UnitTestCase { - public static function setUpBeforeClass(): void - { - self::needsKernel(); - } + protected static bool $needsKernel = true; public static function tearDownAfterClass(): void { @@ -185,19 +182,20 @@ public function testHandleCallsChildSafeHandle() public function testSafeHandleException() { self::mockConfig(); + $command = new SafeThrowingTestCommand(); + $output = Mockery::mock(\Illuminate\Console\OutputStyle::class); $output->shouldReceive('writeln')->once()->withArgs(function (string $message) { $condition = str_starts_with($message, 'Error: This is a test at '.__FILE__.':'); $this->assertTrue($condition); - return $condition; + return true; }); - $command->setOutput($output); - $code = $command->handle(); + $command->setOutput($output); - $this->assertSame(1, $code); + $this->assertSame(1, $command->handle()); } public function testCanEnableThrowOnException() @@ -206,13 +204,14 @@ public function testCanEnableThrowOnException() $this->expectExceptionMessage('This is a test'); self::mockConfig(['app.throw_on_console_exception' => true]); + $command = new SafeThrowingTestCommand(); + $output = Mockery::mock(\Illuminate\Console\OutputStyle::class); $output->shouldReceive('writeln')->once(); $command->setOutput($output); - $code = $command->handle(); - $this->assertSame(1, $code); + $this->assertSame(1, $command->handle()); } public function testAskForString() @@ -304,7 +303,7 @@ public function handle(): int return 0; } - public function setMockedOutput($output) + public function setMockedOutput($output): void { $this->output = $output; } diff --git a/packages/framework/tests/Feature/Commands/MakePageCommandTest.php b/packages/framework/tests/Feature/Commands/MakePageCommandTest.php index 182c3850b41..84fe56be89b 100644 --- a/packages/framework/tests/Feature/Commands/MakePageCommandTest.php +++ b/packages/framework/tests/Feature/Commands/MakePageCommandTest.php @@ -70,6 +70,7 @@ public function testCommandFailsIfUserSpecifiesInvalidPageType() $this->expectException(Exception::class); $this->expectExceptionMessage('The page type [invalid] is not supported.'); $this->expectExceptionCode(400); + $this->artisan('make:page "foo test page" --type=invalid')->assertExitCode(400); } @@ -92,6 +93,7 @@ public function testCommandCreatesDocumentationFile() $this->artisan('make:page "foo test page" --type="documentation"')->assertExitCode(0); $this->assertFileExists(Hyde::path('_docs/foo-test-page.md')); + Filesystem::unlink('_docs/foo-test-page.md'); } @@ -102,9 +104,10 @@ public function testCommandFailsIfFileAlreadyExists() $this->expectException(FileConflictException::class); $this->expectExceptionMessage('File [_pages/foo-test-page.md] already exists.'); $this->expectExceptionCode(409); + $this->artisan('make:page "foo test page"')->assertExitCode(409); - $this->assertEquals('This should not be overwritten', file_get_contents($this->markdownPath)); + $this->assertSame('This should not be overwritten', file_get_contents($this->markdownPath)); } public function testCommandOverwritesExistingFilesWhenForceOptionIsUsed() @@ -152,6 +155,7 @@ public function testPageTypeShorthandCanBeUsedToCreateDocumentationPages() ->assertExitCode(0); $this->assertFileExists(Hyde::path('_docs/foo-test-page.md')); + Filesystem::unlink('_docs/foo-test-page.md'); } } diff --git a/packages/framework/tests/Feature/Commands/PackageDiscoverCommandTest.php b/packages/framework/tests/Feature/Commands/PackageDiscoverCommandTest.php index e25bed1a5d4..28fdcd113e0 100644 --- a/packages/framework/tests/Feature/Commands/PackageDiscoverCommandTest.php +++ b/packages/framework/tests/Feature/Commands/PackageDiscoverCommandTest.php @@ -17,7 +17,7 @@ public function testPackageDiscoverCommandRegistersManifestPath() { $this->artisan('package:discover')->assertExitCode(0); - $this->assertEquals(Hyde::path('app/storage/framework/cache/packages.php'), + $this->assertSame(Hyde::path('app/storage/framework/cache/packages.php'), $this->app->make(PackageManifest::class)->manifestPath ); diff --git a/packages/framework/tests/Feature/Commands/PublishHomepageCommandTest.php b/packages/framework/tests/Feature/Commands/PublishHomepageCommandTest.php index bd0bdfc0e8d..f04a063227f 100644 --- a/packages/framework/tests/Feature/Commands/PublishHomepageCommandTest.php +++ b/packages/framework/tests/Feature/Commands/PublishHomepageCommandTest.php @@ -23,6 +23,10 @@ protected function setUp(): void protected function tearDown(): void { + if (Filesystem::exists('_pages/index.blade.php')) { + Filesystem::unlink('_pages/index.blade.php'); + } + $this->restoreDefaultPages(); parent::tearDown(); @@ -39,7 +43,7 @@ public function testCommandReturnsExpectedOutput() ->expectsConfirmation('Would you like to rebuild the site?') ->assertExitCode(0); - $this->assertFileExistsThenDeleteIt(); + $this->assertFileExists(Hyde::path('_pages/index.blade.php')); } public function testCommandReturnsExpectedOutputWithRebuild() @@ -50,7 +54,7 @@ public function testCommandReturnsExpectedOutputWithRebuild() ->expectsOutput('Site is built!') ->assertExitCode(0); - $this->assertFileExistsThenDeleteIt(); + $this->assertFileExists(Hyde::path('_pages/index.blade.php')); $this->resetSite(); } @@ -65,7 +69,7 @@ public function testCommandPromptsForOutput() ->expectsConfirmation('Would you like to rebuild the site?') ->assertExitCode(0); - $this->assertFileExistsThenDeleteIt(); + $this->assertFileExists(Hyde::path('_pages/index.blade.php')); } public function testCommandShowsFeedbackOutputWhenSupplyingAHomepageName() @@ -75,7 +79,7 @@ public function testCommandShowsFeedbackOutputWhenSupplyingAHomepageName() ->expectsConfirmation('Would you like to rebuild the site?', false) ->assertExitCode(0); - $this->assertFileExistsThenDeleteIt(); + $this->assertFileExists(Hyde::path('_pages/index.blade.php')); } public function testCommandHandlesErrorCode404() @@ -93,9 +97,9 @@ public function testCommandDoesNotOverwriteModifiedFilesWithoutForceFlag() $this->artisan('publish:homepage welcome') ->assertExitCode(409); - $this->assertEquals('foo', file_get_contents(Hyde::path('_pages/index.blade.php'))); + $this->assertSame('foo', file_get_contents(Hyde::path('_pages/index.blade.php'))); - $this->assertFileExistsThenDeleteIt(); + $this->assertFileExists(Hyde::path('_pages/index.blade.php')); } public function testCommandOverwritesModifiedFilesIfForceFlagIsSet() @@ -107,7 +111,7 @@ public function testCommandOverwritesModifiedFilesIfForceFlagIsSet() $this->assertNotEquals('foo', file_get_contents(Hyde::path('_pages/index.blade.php'))); - $this->assertFileExistsThenDeleteIt(); + $this->assertFileExists(Hyde::path('_pages/index.blade.php')); } public function testCommandDoesNotReturn409IfTheCurrentFileIsADefaultFile() @@ -117,12 +121,6 @@ public function testCommandDoesNotReturn409IfTheCurrentFileIsADefaultFile() $this->artisan('publish:homepage welcome --no-interaction') ->assertExitCode(0); - $this->assertFileExistsThenDeleteIt(); - } - - protected function assertFileExistsThenDeleteIt(): void - { $this->assertFileExists(Hyde::path('_pages/index.blade.php')); - Filesystem::unlink('_pages/index.blade.php'); } } diff --git a/packages/framework/tests/Feature/ConvertsArrayToFrontMatterTest.php b/packages/framework/tests/Feature/ConvertsArrayToFrontMatterTest.php index 77e6810f107..3eda88a7324 100644 --- a/packages/framework/tests/Feature/ConvertsArrayToFrontMatterTest.php +++ b/packages/framework/tests/Feature/ConvertsArrayToFrontMatterTest.php @@ -36,11 +36,11 @@ public function testActionConvertsAnArrayToFrontMatter() --- YAML; - $this->assertEquals(str_replace("\r", '', $expected), (new ConvertsArrayToFrontMatter)->execute($array)); + $this->assertSame(str_replace("\r", '', $expected), (new ConvertsArrayToFrontMatter)->execute($array)); } public function testActionReturnsEmptyStringIfArrayIsEmpty() { - $this->assertEquals('', (new ConvertsArrayToFrontMatter)->execute([])); + $this->assertSame('', (new ConvertsArrayToFrontMatter)->execute([])); } } diff --git a/packages/framework/tests/Feature/DataCollectionTest.php b/packages/framework/tests/Feature/DataCollectionTest.php index 524711c0495..df35e788f3f 100644 --- a/packages/framework/tests/Feature/DataCollectionTest.php +++ b/packages/framework/tests/Feature/DataCollectionTest.php @@ -68,7 +68,6 @@ public function testJsonCollectionsAsArrays() public function testFindMarkdownFilesMethodReturnsEmptyArrayIfTheSpecifiedDirectoryDoesNotExist() { - $class = new DataCollections(); $this->assertIsArray(DataCollections::markdown('foo')->keys()->toArray()); $this->assertEmpty(DataCollections::markdown('foo')->keys()->toArray()); } @@ -77,7 +76,6 @@ public function testFindMarkdownFilesMethodReturnsEmptyArrayIfNoFilesAreFoundInS { $this->directory('resources/collections/foo'); - $class = new DataCollections(); $this->assertIsArray(DataCollections::markdown('foo')->keys()->toArray()); $this->assertEmpty(DataCollections::markdown('foo')->keys()->toArray()); } diff --git a/packages/framework/tests/Feature/FeaturedImageTest.php b/packages/framework/tests/Feature/FeaturedImageTest.php index 540e2ae1dcf..ca252cd7852 100644 --- a/packages/framework/tests/Feature/FeaturedImageTest.php +++ b/packages/framework/tests/Feature/FeaturedImageTest.php @@ -47,7 +47,7 @@ public function testCanConstructFeaturedImage() $image = new FeaturedImage('_media/foo', ...$this->defaultArguments()); $this->assertInstanceOf(FeaturedImage::class, $image); - $this->assertEquals('media/foo', $image->getSource()); + $this->assertSame('media/foo', $image->getSource()); } public function testFeaturedImageGetContentLength() @@ -55,7 +55,7 @@ public function testFeaturedImageGetContentLength() $this->file('_media/foo', 'image'); $image = new FeaturedImage('_media/foo', ...$this->defaultArguments()); - $this->assertEquals(5, $image->getContentLength()); + $this->assertSame(5, $image->getContentLength()); } public function testFeaturedImageGetContentLengthWithRemoteSource() @@ -67,7 +67,7 @@ public function testFeaturedImageGetContentLengthWithRemoteSource() }); $image = new FeaturedImage('https://hyde.test/static/image.png', ...$this->defaultArguments()); - $this->assertEquals(16, $image->getContentLength()); + $this->assertSame(16, $image->getContentLength()); } public function testFeaturedImageGetContentLengthWithRemoteSourceAndNotFoundResponse() @@ -77,7 +77,7 @@ public function testFeaturedImageGetContentLengthWithRemoteSourceAndNotFoundResp }); $image = new FeaturedImage('https://hyde.test/static/image.png', ...$this->defaultArguments()); - $this->assertEquals(0, $image->getContentLength()); + $this->assertSame(0, $image->getContentLength()); } public function testFeaturedImageGetContentLengthWithRemoteSourceAndInvalidResponse() @@ -89,23 +89,23 @@ public function testFeaturedImageGetContentLengthWithRemoteSourceAndInvalidRespo }); $image = new FeaturedImage('https://hyde.test/static/image.png', ...$this->defaultArguments()); - $this->assertEquals(0, $image->getContentLength()); + $this->assertSame(0, $image->getContentLength()); } public function testGetSourceMethod() { - $this->assertEquals('media/foo', (new FeaturedImage('_media/foo', ...$this->defaultArguments()))->getSource()); + $this->assertSame('media/foo', (new FeaturedImage('_media/foo', ...$this->defaultArguments()))->getSource()); - $this->assertEquals('media/foo', FeaturedImageFactory::make(new FrontMatter(['image.source' => 'foo']))->getSource()); - $this->assertEquals('media/foo', FeaturedImageFactory::make(new FrontMatter(['image.source' => 'media/foo']))->getSource()); - $this->assertEquals('media/foo', FeaturedImageFactory::make(new FrontMatter(['image.source' => '_media/foo']))->getSource()); + $this->assertSame('media/foo', FeaturedImageFactory::make(new FrontMatter(['image.source' => 'foo']))->getSource()); + $this->assertSame('media/foo', FeaturedImageFactory::make(new FrontMatter(['image.source' => 'media/foo']))->getSource()); + $this->assertSame('media/foo', FeaturedImageFactory::make(new FrontMatter(['image.source' => '_media/foo']))->getSource()); - $this->assertEquals('media/foo', FeaturedImageFactory::make(new FrontMatter(['image.source' => 'foo']))->getSource()); - $this->assertEquals('//foo', FeaturedImageFactory::make(new FrontMatter(['image.source' => '//foo']))->getSource()); - $this->assertEquals('http', FeaturedImageFactory::make(new FrontMatter(['image.source' => 'http']))->getSource()); + $this->assertSame('media/foo', FeaturedImageFactory::make(new FrontMatter(['image.source' => 'foo']))->getSource()); + $this->assertSame('//foo', FeaturedImageFactory::make(new FrontMatter(['image.source' => '//foo']))->getSource()); + $this->assertSame('http', FeaturedImageFactory::make(new FrontMatter(['image.source' => 'http']))->getSource()); - $this->assertEquals('media/foo', FeaturedImageFactory::make(new FrontMatter(['image' => 'foo']))->getSource()); - $this->assertEquals('http', FeaturedImageFactory::make(new FrontMatter(['image' => 'http']))->getSource()); + $this->assertSame('media/foo', FeaturedImageFactory::make(new FrontMatter(['image' => 'foo']))->getSource()); + $this->assertSame('http', FeaturedImageFactory::make(new FrontMatter(['image' => 'http']))->getSource()); } protected function defaultArguments(): array diff --git a/packages/framework/tests/Feature/FileCollectionTest.php b/packages/framework/tests/Feature/FileCollectionTest.php index d90ce310abc..2bc4f1d66a4 100644 --- a/packages/framework/tests/Feature/FileCollectionTest.php +++ b/packages/framework/tests/Feature/FileCollectionTest.php @@ -38,8 +38,11 @@ public function testBootMethodCreatesNewPageCollectionAndDiscoversPagesAutomatic public function testGetFileReturnsParsedFileObjectForGivenFilePath() { $this->file('_pages/foo.blade.php'); - $this->assertEquals(new SourceFile('_pages/foo.blade.php', BladePage::class), - Files::getFile('_pages/foo.blade.php')); + + $this->assertEquals( + new SourceFile('_pages/foo.blade.php', BladePage::class), + Files::getFile('_pages/foo.blade.php') + ); } public function testGetFileThrowsExceptionWhenFileIsNotFound() @@ -63,7 +66,7 @@ public function testGetSourceFilesDoesNotIncludeNonPageSourceFiles() $this->withoutDefaultPages(); $this->file('_pages/foo.txt'); - $this->assertEquals([], Files::getFiles()->all()); + $this->assertSame([], Files::getFiles()->all()); $this->restoreDefaultPages(); } @@ -99,6 +102,7 @@ public function testDocumentationPagesAreDiscovered() { $this->file('_docs/foo.md'); $collection = FileCollection::init(Hyde::getInstance())->boot(); + $this->assertArrayHasKey('_docs/foo.md', $collection->toArray()); $this->assertEquals(new SourceFile('_docs/foo.md', DocumentationPage::class), $collection->get('_docs/foo.md')); } diff --git a/packages/framework/tests/Feature/FilesystemFacadeTest.php b/packages/framework/tests/Feature/FilesystemFacadeTest.php index 71d17c6556a..db00aefc30c 100644 --- a/packages/framework/tests/Feature/FilesystemFacadeTest.php +++ b/packages/framework/tests/Feature/FilesystemFacadeTest.php @@ -44,10 +44,11 @@ public function testSmartGlob() Hyde::path('baz'), ], Hyde::path('pattern/*.md'), 0); - $this->assertEquals( - Collection::make(['foo', 'bar', 'baz']), - Filesystem::smartGlob('pattern/*.md') - ); + $expected = Collection::make(['foo', 'bar', 'baz']); + $actual = Filesystem::smartGlob('pattern/*.md'); + + $this->assertEquals($expected, $actual); + $this->assertSame($expected->all(), $actual->all()); } public function testTouch() @@ -55,12 +56,14 @@ public function testTouch() Filesystem::touch('foo'); $this->assertFileExists(Hyde::path('foo')); + Filesystem::unlink('foo'); } public function testUnlink() { touch(Hyde::path('foo')); + Filesystem::unlink('foo'); $this->assertFileDoesNotExist(Hyde::path('foo')); @@ -69,6 +72,7 @@ public function testUnlink() public function testUnlinkIfExists() { touch(Hyde::path('foo')); + Filesystem::unlinkIfExists('foo'); $this->assertFileDoesNotExist(Hyde::path('foo')); @@ -437,6 +441,7 @@ public function testMethodWithMixedSequentialAndNamedArguments() public function testMethodWithMixedSequentialAndNamedArgumentsSkippingMiddleOne() { Filesystem::makeDirectory('foo', recursive: true); + $this->assertDirectoryExists(Hyde::path('foo')); rmdir(Hyde::path('foo')); diff --git a/packages/framework/tests/Feature/Foundation/FilesystemTest.php b/packages/framework/tests/Feature/Foundation/FilesystemTest.php index a21c3ccd041..6c2c2811cd8 100644 --- a/packages/framework/tests/Feature/Foundation/FilesystemTest.php +++ b/packages/framework/tests/Feature/Foundation/FilesystemTest.php @@ -27,10 +27,7 @@ class FilesystemTest extends UnitTestCase protected Filesystem $filesystem; - public static function setUpBeforeClass(): void - { - self::needsKernel(); - } + protected static bool $needsKernel = true; protected function setUp(): void { diff --git a/packages/framework/tests/Feature/GlobalMetadataBagTest.php b/packages/framework/tests/Feature/GlobalMetadataBagTest.php index a20c98890b0..ae90f018079 100644 --- a/packages/framework/tests/Feature/GlobalMetadataBagTest.php +++ b/packages/framework/tests/Feature/GlobalMetadataBagTest.php @@ -17,7 +17,7 @@ class GlobalMetadataBagTest extends TestCase { public function testSiteMetadataAddsConfigDefinedMetadata() { - $this->emptyConfig(); + $this->withEmptyConfig(); config(['hyde.meta' => [ Meta::link('foo', 'bar'), @@ -26,60 +26,66 @@ public function testSiteMetadataAddsConfigDefinedMetadata() 'foo' => 'bar', 'baz', ]]); - $this->assertEquals([ + + $expected = [ 'links:foo' => Meta::link('foo', 'bar'), 'metadata:foo' => Meta::name('foo', 'bar'), 'properties:foo' => Meta::property('foo', 'bar'), 'generics:0' => 'bar', 'generics:1' => 'baz', - ], GlobalMetadataBag::make()->get()); + ]; + + $actual = GlobalMetadataBag::make()->get(); + + $this->assertEquals($expected, $actual); + $this->assertSame(array_keys($expected), array_keys($actual)); } public function testSiteMetadataAutomaticallyAddsSitemapWhenEnabled() { - $this->emptyConfig(); + $this->withEmptyConfig(); config(['hyde.url' => 'foo']); config(['hyde.generate_sitemap' => true]); - $this->assertEquals('', GlobalMetadataBag::make()->render()); + $this->assertSame('', GlobalMetadataBag::make()->render()); } public function testSiteMetadataSitemapUsesConfiguredSiteUrl() { - $this->emptyConfig(); + $this->withEmptyConfig(); config(['hyde.url' => 'bar']); config(['hyde.generate_sitemap' => true]); - $this->assertEquals('', GlobalMetadataBag::make()->render()); + $this->assertSame('', GlobalMetadataBag::make()->render()); } public function testSiteMetadataAutomaticallyAddsRssFeedWhenEnabled() { - $this->emptyConfig(); + $this->withEmptyConfig(); config(['hyde.url' => 'foo']); config(['hyde.rss.enabled' => true]); $this->file('_posts/foo.md'); - $this->assertEquals('', GlobalMetadataBag::make()->render()); + $this->assertSame('', GlobalMetadataBag::make()->render()); } public function testSiteMetadataRssFeedUsesConfiguredSiteUrl() { - $this->emptyConfig(); + $this->withEmptyConfig(); config(['hyde.url' => 'bar']); config(['hyde.rss.enabled' => true]); $this->file('_posts/foo.md'); - $this->assertEquals('', GlobalMetadataBag::make()->render()); + $this->assertSame('', GlobalMetadataBag::make()->render()); } public function testSiteMetadataRssFeedUsesConfiguredSiteName() { - $this->emptyConfig(); + $this->withEmptyConfig(); config(['hyde.url' => 'foo']); config(['hyde.name' => 'Site']); @@ -89,12 +95,12 @@ public function testSiteMetadataRssFeedUsesConfiguredSiteName() config(['hyde' => $config]); $this->file('_posts/foo.md'); - $this->assertEquals('', GlobalMetadataBag::make()->render()); + $this->assertSame('', GlobalMetadataBag::make()->render()); } public function testSiteMetadataRssFeedUsesConfiguredRssFileName() { - $this->emptyConfig(); + $this->withEmptyConfig(); config(['hyde.url' => 'foo']); config(['hyde.rss.filename' => 'posts.rss']); @@ -109,7 +115,7 @@ public function testSiteMetadataRssFeedUsesConfiguredRssFileName() public function testMetadataExistingInTheCurrentPageIsNotAdded() { - $this->emptyConfig(); + $this->withEmptyConfig(); $duplicate = Meta::name('remove', 'me'); $keep = Meta::name('keep', 'this'); @@ -125,12 +131,12 @@ public function testMetadataExistingInTheCurrentPageIsNotAdded() Render::share('routeKey', 'foo'); Render::share('page', $page); - $this->assertEquals(['metadata:keep' => $keep], GlobalMetadataBag::make()->get()); + $this->assertSame(['metadata:keep' => $keep], GlobalMetadataBag::make()->get()); } public function testMetadataExistingInTheCurrentPageIsNotAddedRegardlessOfItsValue() { - $this->emptyConfig(); + $this->withEmptyConfig(); config(['hyde.meta' => [Meta::name('foo', 'bar')]]); @@ -140,10 +146,10 @@ public function testMetadataExistingInTheCurrentPageIsNotAddedRegardlessOfItsVal Render::share('routeKey', 'foo'); Render::share('page', $page); - $this->assertEquals([], GlobalMetadataBag::make()->get()); + $this->assertSame([], GlobalMetadataBag::make()->get()); } - protected function emptyConfig(): void + protected function withEmptyConfig(): void { config(['hyde.url' => null]); config(['hyde.meta' => []]); diff --git a/packages/framework/tests/Feature/HydeCoreExtensionTest.php b/packages/framework/tests/Feature/HydeCoreExtensionTest.php index 42859c6e968..4debb39d8d6 100644 --- a/packages/framework/tests/Feature/HydeCoreExtensionTest.php +++ b/packages/framework/tests/Feature/HydeCoreExtensionTest.php @@ -19,11 +19,8 @@ */ class HydeCoreExtensionTest extends UnitTestCase { - public static function setUpBeforeClass(): void - { - self::needsKernel(); - self::mockConfig(); - } + protected static bool $needsKernel = true; + protected static bool $needsConfig = true; public function testClassExtendsExtensionClass() { diff --git a/packages/framework/tests/Feature/HydeKernelTest.php b/packages/framework/tests/Feature/HydeKernelTest.php index ddfc83edb60..c52713e4eef 100644 --- a/packages/framework/tests/Feature/HydeKernelTest.php +++ b/packages/framework/tests/Feature/HydeKernelTest.php @@ -90,6 +90,7 @@ public function testCurrentRouteHelperReturnsCurrentRouteObject() { $expected = new Route(new MarkdownPage()); Render::share('route', $expected); + $this->assertInstanceOf(Route::class, Hyde::currentRoute()); $this->assertSame($expected, Hyde::currentRoute()); } @@ -98,6 +99,7 @@ public function testCurrentPageHelperReturnsCurrentPageObject() { $expected = new MarkdownPage(); Render::share('page', $expected); + $this->assertInstanceOf(HydePage::class, Hyde::currentPage()); $this->assertSame($expected, Hyde::currentPage()); } @@ -259,10 +261,6 @@ public function testFluentModelSourcePathHelpers() $this->assertSame(Hyde::path('_docs'), DocumentationPage::path()); $this->assertSame(Hyde::path('_media'), Hyde::mediaPath()); - $this->assertSame(Hyde::path('_pages'), BladePage::path()); - $this->assertSame(Hyde::path('_pages'), MarkdownPage::path()); - $this->assertSame(Hyde::path('_posts'), MarkdownPost::path()); - $this->assertSame(Hyde::path('_docs'), DocumentationPage::path()); $this->assertSame(Hyde::path('_site'), Hyde::sitePath()); $this->assertSame(Hyde::path('_site/media'), Hyde::siteMediaPath()); } @@ -289,18 +287,18 @@ public function testToArrayMethod() public function testJsonSerializeMethod() { - $this->assertEquals(Hyde::kernel()->jsonSerialize(), collect(Hyde::toArray())->toArray()); + $this->assertSame(Hyde::kernel()->jsonSerialize(), collect(Hyde::toArray())->toArray()); } public function testToJsonMethod() { - $this->assertEquals(Hyde::kernel()->toJson(), json_encode(Hyde::toArray())); + $this->assertSame(Hyde::kernel()->toJson(), json_encode(Hyde::toArray())); } public function testVersionConstantIsAValidSemverString() { - // https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-stringd $this->assertMatchesRegularExpression( + // https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string '/^(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)(?:-(?P(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/', HydeKernel::VERSION ); @@ -322,12 +320,14 @@ public function testVersionConstantIsUpToDateWithGit() try { $version = trim(shell_exec('git describe --abbrev=0 --tags')); } catch (Throwable) { + // Gracefully skip the test if the version cannot be fetched $this->markTestSkipped('Could not get version from Git'); } if ('v'.HydeKernel::VERSION === $version) { $this->assertSame('v'.HydeKernel::VERSION, $version); } else { + // Gracefully skip the test if the version is not up-to-date $this->markTestSkipped('Version constant does not match Git version!'); } } @@ -368,6 +368,7 @@ public function testCanGetOutputDirectory() public function testCanSetOutputDirectory() { Hyde::setOutputDirectory('foo'); + $this->assertSame('foo', Hyde::getOutputDirectory()); $this->assertSame(Hyde::path('foo'), Hyde::sitePath()); } @@ -375,6 +376,7 @@ public function testCanSetOutputDirectory() public function testCanSetOutputDirectoryToAbsoluteProjectPath() { Hyde::setOutputDirectory(Hyde::path('foo')); + $this->assertSame('foo', Hyde::getOutputDirectory()); $this->assertSame(Hyde::path('foo'), Hyde::sitePath()); } @@ -428,23 +430,28 @@ public function testGetSiteMediaOutputDirectoryUsesConfiguredSiteOutputDirectory { Hyde::setOutputDirectory(Hyde::path('foo')); Hyde::setMediaDirectory('bar'); + $this->assertSame(Hyde::path('foo/bar'), Hyde::siteMediaPath()); } public function testMediaOutputDirectoryCanBeChangedInConfiguration() { - $this->assertEquals('_media', Hyde::getMediaDirectory()); + $this->assertSame('_media', Hyde::getMediaDirectory()); config(['hyde.media_directory' => '_assets']); (new HydeServiceProvider($this->app))->register(); - $this->assertEquals('_assets', Hyde::getMediaDirectory()); + $this->assertSame('_assets', Hyde::getMediaDirectory()); } public function testCanAccessKernelFluentlyUsingTheFacade() { $this->assertInstanceOf(HydeKernel::class, Hyde::kernel()); $this->assertSame(HydeKernel::getInstance(), Hyde::kernel()); + } + + public function testCanAccessKernelSymbolsFluentlyUsingTheFacade() + { $this->assertSame(HydeKernel::VERSION, Hyde::kernel()->version()); } @@ -515,12 +522,13 @@ public function testCanUseBootingCallbacksToInjectCustomPages() $kernel = HydeKernel::getInstance(); $page = new InMemoryPage('foo'); + $kernel->booting(function (HydeKernel $kernel) use ($page): void { $kernel->pages()->addPage($page); }); $this->assertSame($page, Pages::getPage('foo')); - $this->assertEquals($page->getRoute(), Routes::getRoute('foo')); + $this->assertSame($page->getRoute(), Routes::getRoute('foo')); } public function testIsBootedReturnsFalseWhenNotBooted() @@ -533,6 +541,7 @@ public function testIsBootedReturnsTrueWhenBooted() { $kernel = new HydeKernel(); $kernel->boot(); + $this->assertTrue($kernel->isBooted()); } diff --git a/packages/framework/tests/Feature/HydePageTest.php b/packages/framework/tests/Feature/HydePageTest.php index 158e06e56c6..f9699867c17 100644 --- a/packages/framework/tests/Feature/HydePageTest.php +++ b/packages/framework/tests/Feature/HydePageTest.php @@ -39,66 +39,42 @@ class HydePageTest extends TestCase public function testBaseSourceDirectory() { - $this->assertSame( - '', - HydePage::sourceDirectory() - ); + $this->assertSame('', HydePage::sourceDirectory()); } public function testBaseOutputDirectory() { - $this->assertSame( - '', - HydePage::outputDirectory() - ); + $this->assertSame('', HydePage::outputDirectory()); } public function testBaseFileExtension() { - $this->assertSame( - '', - HydePage::fileExtension() - ); + $this->assertSame('', HydePage::fileExtension()); } public function testBaseSourcePath() { - $this->assertSame( - 'hello-world', - HydePage::sourcePath('hello-world') - ); + $this->assertSame('hello-world', HydePage::sourcePath('hello-world')); } public function testBaseOutputPath() { - $this->assertSame( - 'hello-world.html', - HydePage::outputPath('hello-world') - ); + $this->assertSame('hello-world.html', HydePage::outputPath('hello-world')); } public function testBasePath() { - $this->assertSame( - Hyde::path('hello-world'), - HydePage::path('hello-world') - ); + $this->assertSame(Hyde::path('hello-world'), HydePage::path('hello-world')); } public function testBasePathToIdentifier() { - $this->assertSame( - 'hello-world', - HydePage::pathToIdentifier('hello-world') - ); + $this->assertSame('hello-world', HydePage::pathToIdentifier('hello-world')); } public function testBaseBaseRouteKey() { - $this->assertSame( - HydePage::outputDirectory(), - HydePage::baseRouteKey() - ); + $this->assertSame(HydePage::outputDirectory(), HydePage::baseRouteKey()); } public function testBaseIsDiscoverable() @@ -110,58 +86,37 @@ public function testBaseIsDiscoverable() public function testSourceDirectory() { - $this->assertSame( - 'source', - TestPage::sourceDirectory() - ); + $this->assertSame('source', TestPage::sourceDirectory()); } public function testOutputDirectory() { - $this->assertSame( - 'output', - TestPage::outputDirectory() - ); + $this->assertSame('output', TestPage::outputDirectory()); } public function testFileExtension() { - $this->assertSame( - '.md', - TestPage::fileExtension() - ); + $this->assertSame('.md', TestPage::fileExtension()); } public function testSourcePath() { - $this->assertSame( - 'source/hello-world.md', - TestPage::sourcePath('hello-world') - ); + $this->assertSame('source/hello-world.md', TestPage::sourcePath('hello-world')); } public function testOutputPath() { - $this->assertSame( - 'output/hello-world.html', - TestPage::outputPath('hello-world') - ); + $this->assertSame('output/hello-world.html', TestPage::outputPath('hello-world')); } public function testPath() { - $this->assertSame( - Hyde::path('source/hello-world'), - TestPage::path('hello-world') - ); + $this->assertSame(Hyde::path('source/hello-world'), TestPage::path('hello-world')); } public function testBaseRouteKey() { - $this->assertSame( - TestPage::outputDirectory(), - TestPage::baseRouteKey() - ); + $this->assertSame(TestPage::outputDirectory(), TestPage::baseRouteKey()); } public function testIsDiscoverable() @@ -263,74 +218,81 @@ public function testToArray() public function testGetSourceDirectoryReturnsStaticProperty() { MarkdownPage::setSourceDirectory('foo'); - $this->assertEquals('foo', MarkdownPage::sourceDirectory()); + + $this->assertSame('foo', MarkdownPage::sourceDirectory()); $this->resetDirectoryConfiguration(); } public function testSetSourceDirectoryTrimsTrailingSlashes() { MarkdownPage::setSourceDirectory('/foo/\\'); - $this->assertEquals('foo', MarkdownPage::sourceDirectory()); + + $this->assertSame('foo', MarkdownPage::sourceDirectory()); $this->resetDirectoryConfiguration(); } public function testGetOutputDirectoryReturnsStaticProperty() { MarkdownPage::setOutputDirectory('foo'); - $this->assertEquals('foo', MarkdownPage::outputDirectory()); + + $this->assertSame('foo', MarkdownPage::outputDirectory()); $this->resetDirectoryConfiguration(); } public function testSetOutputDirectoryTrimsTrailingSlashes() { MarkdownPage::setOutputDirectory('/foo/\\'); - $this->assertEquals('foo', MarkdownPage::outputDirectory()); + + $this->assertSame('foo', MarkdownPage::outputDirectory()); $this->resetDirectoryConfiguration(); } public function testGetFileExtensionReturnsStaticProperty() { MarkdownPage::setFileExtension('.foo'); - $this->assertEquals('.foo', MarkdownPage::fileExtension()); + + $this->assertSame('.foo', MarkdownPage::fileExtension()); $this->resetDirectoryConfiguration(); } public function testSetFileExtensionForcesLeadingPeriod() { MarkdownPage::setFileExtension('foo'); - $this->assertEquals('.foo', MarkdownPage::fileExtension()); + + $this->assertSame('.foo', MarkdownPage::fileExtension()); $this->resetDirectoryConfiguration(); } public function testSetFileExtensionRemovesTrailingPeriod() { MarkdownPage::setFileExtension('foo.'); - $this->assertEquals('.foo', MarkdownPage::fileExtension()); + + $this->assertSame('.foo', MarkdownPage::fileExtension()); $this->resetDirectoryConfiguration(); } public function testGetIdentifierReturnsIdentifierProperty() { $page = new MarkdownPage('foo'); - $this->assertEquals('foo', $page->getIdentifier()); + $this->assertSame('foo', $page->getIdentifier()); } public function testSetSourceDirectory() { ConfigurableSourcesTestPage::setSourceDirectory('foo'); - $this->assertEquals('foo', ConfigurableSourcesTestPage::sourceDirectory()); + $this->assertSame('foo', ConfigurableSourcesTestPage::sourceDirectory()); } public function testSetOutputDirectory() { ConfigurableSourcesTestPage::setOutputDirectory('foo'); - $this->assertEquals('foo', ConfigurableSourcesTestPage::outputDirectory()); + $this->assertSame('foo', ConfigurableSourcesTestPage::outputDirectory()); } public function testSetFileExtension() { ConfigurableSourcesTestPage::setFileExtension('.foo'); - $this->assertEquals('.foo', ConfigurableSourcesTestPage::fileExtension()); + $this->assertSame('.foo', ConfigurableSourcesTestPage::fileExtension()); } public function testStaticGetMethodReturnsDiscoveredPage() @@ -349,7 +311,7 @@ public function testParseParsesSuppliedSlugIntoAPageModel() Filesystem::touch('_pages/foo.md'); $this->assertInstanceOf(MarkdownPage::class, $page = MarkdownPage::parse('foo')); - $this->assertEquals('foo', $page->identifier); + $this->assertSame('foo', $page->identifier); Filesystem::unlink('_pages/foo.md'); } @@ -357,118 +319,127 @@ public function testParseParsesSuppliedSlugIntoAPageModel() public function testFilesReturnsArrayOfSourceFiles() { Filesystem::touch('_pages/foo.md'); - $this->assertEquals(['foo'], MarkdownPage::files()); + + $this->assertSame(['foo'], MarkdownPage::files()); + Filesystem::unlink('_pages/foo.md'); } public function testAllReturnsCollectionOfAllParsedSourceFilesFromPageIndex() { Filesystem::touch('_pages/foo.md'); + $this->assertEquals( Pages::getPages(MarkdownPage::class), MarkdownPage::all() ); + $this->assertEquals( ['_pages/foo.md' => (new MarkdownPage('foo'))], MarkdownPage::all()->all() ); + Filesystem::unlink('_pages/foo.md'); } public function testQualifyBasenameProperlyExpandsBasenameForTheModel() { - $this->assertEquals('_pages/foo.md', MarkdownPage::sourcePath('foo')); + $this->assertSame('_pages/foo.md', MarkdownPage::sourcePath('foo')); } public function testQualifyBasenameTrimsSlashesFromInput() { - $this->assertEquals('_pages/foo.md', MarkdownPage::sourcePath('/foo/\\')); + $this->assertSame('_pages/foo.md', MarkdownPage::sourcePath('/foo/\\')); } public function testQualifyBasenameUsesTheStaticProperties() { MarkdownPage::setSourceDirectory('foo'); MarkdownPage::setFileExtension('txt'); - $this->assertEquals('foo/bar.txt', MarkdownPage::sourcePath('bar')); + + $this->assertSame('foo/bar.txt', MarkdownPage::sourcePath('bar')); + $this->resetDirectoryConfiguration(); } public function testPathReturnsAbsolutePathToSourceDirectoryWhenNoParameterIsSupplied() { - $this->assertSame( - Hyde::path('source'), TestPage::path() - ); + $this->assertSame(Hyde::path('source'), TestPage::path()); } public function testPathReturnsAbsolutePathToFileInSourceDirectoryWhenParameterIsSupplied() { - $this->assertSame( - Hyde::path('source/foo.md'), TestPage::path('foo.md') - ); + $this->assertSame(Hyde::path('source/foo.md'), TestPage::path('foo.md')); } public function testPathMethodRemovesTrailingSlashes() { - $this->assertSame( - Hyde::path('source/foo.md'), TestPage::path('/foo.md/') - ); + $this->assertSame(Hyde::path('source/foo.md'), TestPage::path('/foo.md/')); } public function testGetOutputLocationReturnsTheFileOutputPathForTheSuppliedBasename() { - $this->assertEquals('foo.html', MarkdownPage::outputPath('foo')); + $this->assertSame('foo.html', MarkdownPage::outputPath('foo')); } public function testGetOutputLocationReturnsTheConfiguredLocation() { MarkdownPage::setOutputDirectory('foo'); - $this->assertEquals('foo/bar.html', MarkdownPage::outputPath('bar')); + + $this->assertSame('foo/bar.html', MarkdownPage::outputPath('bar')); + $this->resetDirectoryConfiguration(); } public function testGetOutputLocationTrimsTrailingSlashesFromDirectorySetting() { MarkdownPage::setOutputDirectory('/foo/\\'); - $this->assertEquals('foo/bar.html', MarkdownPage::outputPath('bar')); + + $this->assertSame('foo/bar.html', MarkdownPage::outputPath('bar')); + $this->resetDirectoryConfiguration(); } public function testGetOutputLocationTrimsTrailingSlashesFromBasename() { - $this->assertEquals('foo.html', MarkdownPage::outputPath('/foo/\\')); + $this->assertSame('foo.html', MarkdownPage::outputPath('/foo/\\')); } - public function testGetCurrentPagePathReturnsOutputDirectoryAndBasename() + public function testGetRouteKeyReturnsOutputDirectoryAndBasename() { $page = new MarkdownPage('foo'); - $this->assertEquals('foo', $page->getRouteKey()); + $this->assertSame('foo', $page->getRouteKey()); } - public function testGetCurrentPagePathReturnsOutputDirectoryAndBasenameForConfiguredDirectory() + public function testGetRouteKeyReturnsOutputDirectoryAndBasenameForConfiguredDirectory() { MarkdownPage::setOutputDirectory('foo'); + $page = new MarkdownPage('bar'); - $this->assertEquals('foo/bar', $page->getRouteKey()); + $this->assertSame('foo/bar', $page->getRouteKey()); + $this->resetDirectoryConfiguration(); } - public function testGetCurrentPagePathTrimsTrailingSlashesFromDirectorySetting() + public function testGetRouteKeyTrimsTrailingSlashesFromDirectorySetting() { MarkdownPage::setOutputDirectory('/foo/\\'); + $page = new MarkdownPage('bar'); - $this->assertEquals('foo/bar', $page->getRouteKey()); + $this->assertSame('foo/bar', $page->getRouteKey()); + $this->resetDirectoryConfiguration(); } public function testGetOutputPathReturnsCurrentPagePathWithHtmlExtensionAppended() { $page = new MarkdownPage('foo'); - $this->assertEquals('foo.html', $page->getOutputPath()); + $this->assertSame('foo.html', $page->getOutputPath()); } public function testGetSourcePathReturnsQualifiedBasename() { - $this->assertEquals( + $this->assertSame( MarkdownPage::sourcePath('foo'), (new MarkdownPage('foo'))->getSourcePath() ); @@ -507,7 +478,8 @@ public function testAllPageModelsHaveConfiguredSourceDirectory() ]; foreach ($pages as $page => $expected) { - $this->assertEquals($expected, $page::sourceDirectory()); + assert(is_a($page, HydePage::class, true)); + $this->assertSame($expected, $page::sourceDirectory()); } } @@ -521,7 +493,8 @@ public function testAllPageModelsHaveConfiguredOutputDirectory() ]; foreach ($pages as $page => $expected) { - $this->assertEquals($expected, $page::outputDirectory()); + assert(is_a($page, HydePage::class, true)); + $this->assertSame($expected, $page::outputDirectory()); } } @@ -535,7 +508,8 @@ public function testAllPageModelsHaveConfiguredFileExtension() ]; foreach ($pages as $page => $expected) { - $this->assertEquals($expected, $page::fileExtension()); + assert(is_a($page, HydePage::class, true)); + $this->assertSame($expected, $page::fileExtension()); } } @@ -561,12 +535,13 @@ public function testAbstractMarkdownPageHasFileExtensionProperty() public function testAbstractMarkdownPageFileExtensionPropertyIsSetToMd() { - $this->assertEquals('.md', BaseMarkdownPage::fileExtension()); + $this->assertSame('.md', BaseMarkdownPage::fileExtension()); } public function testAbstractMarkdownPageConstructorArgumentsAreOptional() { $page = $this->mock(BaseMarkdownPage::class); + $this->assertInstanceOf(BaseMarkdownPage::class, $page); } @@ -574,6 +549,7 @@ public function testAbstractMarkdownPageConstructorAssignsMarkdownDocumentProper { $markdown = new Markdown(); $page = new MarkdownPage(markdown: $markdown); + $this->assertSame($markdown, $page->markdown); } @@ -593,13 +569,14 @@ public function testAbstractMarkdownPageMarkdownHelperReturnsTheConfiguredMarkdo { $markdown = new Markdown(); $page = new MarkdownPage(markdown: $markdown); + $this->assertSame($markdown, $page->markdown()); } public function testAbstractMarkdownPageMakeHelperConstructsDynamicTitleAutomatically() { $page = MarkdownPage::make('', ['title' => 'Foo']); - $this->assertEquals('Foo', $page->title); + $this->assertSame('Foo', $page->title); } public function testMarkdownBasedPagesExtendAbstractMarkdownPage() @@ -629,6 +606,7 @@ public function testGetRouteReturnsPageRoute() public function testGetRouteReturnsTheRouteObjectFromTheRouterIndex() { $this->file('_pages/foo.md'); + $page = MarkdownPage::parse('foo'); $this->assertSame(Routes::get('foo'), $page->getRoute()); } @@ -636,20 +614,21 @@ public function testGetRouteReturnsTheRouteObjectFromTheRouterIndex() public function testHtmlTitleReturnsSiteNamePlusPageTitle() { $make = MarkdownPage::make('', ['title' => 'Foo']); - $this->assertEquals('HydePHP - Foo', $make->title()); + $this->assertSame('HydePHP - Foo', $make->title()); } public function testHtmlTitleUsesConfiguredSiteName() { config(['hyde.name' => 'Foo Bar']); + $markdownPage = new MarkdownPage('Foo'); - $this->assertEquals('Foo Bar - Foo', $markdownPage->title()); + $this->assertSame('Foo Bar - Foo', $markdownPage->title()); } public function testBodyHelperReturnsMarkdownDocumentBodyInMarkdownPages() { $page = new MarkdownPage(markdown: new Markdown(body: '# Foo')); - $this->assertEquals('# Foo', $page->markdown->body()); + $this->assertSame('# Foo', $page->markdown->body()); } public function testShowInNavigationReturnsFalseForMarkdownPost() @@ -707,6 +686,7 @@ public function testShowInNavigationReturnsFalseIfSlugIsPresentInConfigHydeNavig $this->assertTrue($page->showInNavigation()); config(['hyde.navigation.exclude' => ['foo']]); + $page = MarkdownPage::make('foo'); $this->assertFalse($page->showInNavigation()); } @@ -726,111 +706,116 @@ public function testShowInNavigationDefaultsToTrueIfAllChecksPass() public function testNavigationMenuPriorityReturnsFrontMatterValueOfNavigationPriorityIfAbstractMarkdownPageAndNotNull() { $page = MarkdownPage::make('foo', ['navigation.priority' => 1]); - $this->assertEquals(1, $page->navigationMenuPriority()); + $this->assertSame(1, $page->navigationMenuPriority()); } public function testNavigationMenuPriorityCanBeSetUsingOrderProperty() { $page = MarkdownPage::make('foo', ['navigation.order' => 1]); - $this->assertEquals(1, $page->navigationMenuPriority()); + $this->assertSame(1, $page->navigationMenuPriority()); } public function testNavigationMenuPriorityReturnsSpecifiedConfigValueIfSlugExistsInConfigHydeNavigationOrder() { $page = MarkdownPage::make('foo'); - $this->assertEquals(999, $page->navigationMenuPriority()); + $this->assertSame(999, $page->navigationMenuPriority()); config(['hyde.navigation.order' => ['foo' => 1]]); + $page = MarkdownPage::make('foo'); - $this->assertEquals(1, $page->navigationMenuPriority()); + $this->assertSame(1, $page->navigationMenuPriority()); } public function testNavigationMenuPriorityGivesPrecedenceToFrontMatterOverConfigHydeNavigationOrder() { $page = MarkdownPage::make('foo', ['navigation.priority' => 1]); - $this->assertEquals(1, $page->navigationMenuPriority()); + $this->assertSame(1, $page->navigationMenuPriority()); config(['hyde.navigation.order' => ['foo' => 2]]); - $this->assertEquals(1, $page->navigationMenuPriority()); + + $page = MarkdownPage::make('foo', ['navigation.priority' => 1]); + $this->assertSame(1, $page->navigationMenuPriority()); } public function testNavigationMenuPriorityReturns999ForDocumentationPage() { $page = DocumentationPage::make('index'); - $this->assertEquals(999, $page->navigationMenuPriority()); + $this->assertSame(999, $page->navigationMenuPriority()); } public function testNavigationMenuPriorityReturns0IfSlugIsIndex() { $page = MarkdownPage::make('index'); - $this->assertEquals(0, $page->navigationMenuPriority()); + $this->assertSame(0, $page->navigationMenuPriority()); } public function testNavigationMenuPriorityReturns10IfSlugIsPosts() { $page = MarkdownPage::make('posts'); - $this->assertEquals(10, $page->navigationMenuPriority()); + $this->assertSame(10, $page->navigationMenuPriority()); } public function testNavigationMenuPriorityDefaultsTo999IfNoOtherConditionsAreMet() { $page = MarkdownPage::make('foo'); - $this->assertEquals(999, $page->navigationMenuPriority()); + $this->assertSame(999, $page->navigationMenuPriority()); } public function testNavigationMenuTitleReturnsNavigationTitleMatterIfSet() { $page = MarkdownPage::make('foo', ['navigation.label' => 'foo']); - $this->assertEquals('foo', $page->navigationMenuLabel()); + $this->assertSame('foo', $page->navigationMenuLabel()); } public function testNavigationMenuTitleReturnsTitleMatterIfSet() { $page = MarkdownPage::make('foo', ['title' => 'foo']); - $this->assertEquals('foo', $page->navigationMenuLabel()); + $this->assertSame('foo', $page->navigationMenuLabel()); } public function testNavigationMenuTitleNavigationTitleHasPrecedenceOverTitle() { $page = MarkdownPage::make('foo', ['title' => 'foo', 'navigation.label' => 'bar']); - $this->assertEquals('bar', $page->navigationMenuLabel()); + $this->assertSame('bar', $page->navigationMenuLabel()); } public function testNavigationMenuTitleReturnsDocsIfSlugIsIndexAndModelIsDocumentationPage() { $page = DocumentationPage::make('index'); - $this->assertEquals('Docs', $page->navigationMenuLabel()); + $this->assertSame('Docs', $page->navigationMenuLabel()); } public function testNavigationMenuTitleReturnsHomeIfSlugIsIndexAndModelIsNotDocumentationPage() { $page = MarkdownPage::make('index'); - $this->assertEquals('Home', $page->navigationMenuLabel()); + $this->assertSame('Home', $page->navigationMenuLabel()); } public function testNavigationMenuTitleReturnsTitleIfTitleIsSetAndNotEmpty() { $page = MarkdownPage::make('bar', ['title' => 'foo']); - $this->assertEquals('foo', $page->navigationMenuLabel()); + $this->assertSame('foo', $page->navigationMenuLabel()); } public function testNavigationMenuTitleFallsBackToHydeMakeTitleFromSlug() { $page = MarkdownPage::make('foo'); - $this->assertEquals('Foo', $page->navigationMenuLabel()); + $this->assertSame('Foo', $page->navigationMenuLabel()); } public function testNavigationMenuTitleCanBeSetInConfiguration() { config(['hyde.navigation.labels' => ['foo' => 'bar']]); + $page = MarkdownPage::make('foo'); - $this->assertEquals('bar', $page->navigationMenuLabel()); + $this->assertSame('bar', $page->navigationMenuLabel()); } public function testDocumentationPageCanBeHiddenFromNavigationUsingConfig() { config(['hyde.navigation.exclude' => ['docs/index']]); + $page = DocumentationPage::make('index'); $this->assertFalse($page->showInNavigation()); } @@ -838,67 +823,69 @@ public function testDocumentationPageCanBeHiddenFromNavigationUsingConfig() public function testGetCanonicalUrlReturnsUrlForTopLevelPage() { config(['hyde.url' => 'https://example.com']); - $page = new MarkdownPage('foo'); - $this->assertEquals('https://example.com/foo.html', $page->getCanonicalUrl()); + $page = new MarkdownPage('foo'); + $this->assertSame('https://example.com/foo.html', $page->getCanonicalUrl()); } public function testGetCanonicalUrlReturnsPrettyUrlForTopLevelPage() { config(['hyde.url' => 'https://example.com']); config(['hyde.pretty_urls' => true]); + $page = new MarkdownPage('foo'); - $this->assertEquals('https://example.com/foo', $page->getCanonicalUrl()); + $this->assertSame('https://example.com/foo', $page->getCanonicalUrl()); } public function testGetCanonicalUrlReturnsUrlForNestedPage() { config(['hyde.url' => 'https://example.com']); + $page = new MarkdownPage('foo/bar'); - $this->assertEquals('https://example.com/foo/bar.html', $page->getCanonicalUrl()); + $this->assertSame('https://example.com/foo/bar.html', $page->getCanonicalUrl()); } public function testGetCanonicalUrlReturnsUrlForDeeplyNestedPage() { config(['hyde.url' => 'https://example.com']); + $page = new MarkdownPage('foo/bar/baz'); - $this->assertEquals('https://example.com/foo/bar/baz.html', $page->getCanonicalUrl()); + $this->assertSame('https://example.com/foo/bar/baz.html', $page->getCanonicalUrl()); } public function testCanonicalUrlIsNotSetWhenIdentifierIsNull() { config(['hyde.url' => 'https://example.com']); + $page = new MarkdownPage(); + $this->assertNull($page->getCanonicalUrl()); - $this->assertStringNotContainsString( - 'metadata()->render() - ); + $this->assertStringNotContainsString('canonical', $page->metadata()->render()); + $this->assertStringNotContainsString('metadata()->render()); } public function testCanonicalUrlIsNotSetWhenSiteUrlIsNull() { config(['hyde.url' => null]); + $page = new MarkdownPage('foo'); + $this->assertNull($page->getCanonicalUrl()); - $this->assertStringNotContainsString( - 'metadata()->render() - ); + $this->assertStringNotContainsString('canonical', $page->metadata()->render()); + $this->assertStringNotContainsString('metadata()->render()); } public function testCustomCanonicalLinkCanBeSetInFrontMatter() { config(['hyde.url' => 'https://example.com']); + $page = MarkdownPage::make(matter: ['canonicalUrl' => 'foo/bar']); - $this->assertEquals('foo/bar', $page->getCanonicalUrl()); - $this->assertStringContainsString( - '', - $page->metadata()->render() - ); + + $this->assertSame('foo/bar', $page->getCanonicalUrl()); + $this->assertStringContainsString('', $page->metadata()->render()); } public function testCanCreateCanonicalUrlUsingBaseUrlFromConfig() @@ -923,6 +910,7 @@ public function testCanCreateCanonicalUrlUsingBaseUrlFromConfigUsingPrettyUrls() public function testCanonicalUrlIsNullWhenNoBaseUrlIsSet() { config(['hyde' => []]); + $this->assertNull((new MarkdownPage('foo'))->getCanonicalUrl()); } @@ -990,34 +978,42 @@ public function testMarkdownPagesCanBeSavedToDisk() { $page = new MarkdownPage('foo'); $page->save(); + $this->assertFileExists(Hyde::path('_pages/foo.md')); + Filesystem::unlink('_pages/foo.md'); } public function testSaveMethodConvertsFrontMatterArrayToYamlBlock() { MarkdownPage::make('foo', matter: ['foo' => 'bar'])->save(); - $this->assertEquals("---\nfoo: bar\n---\n", + + $this->assertSame("---\nfoo: bar\n---\n", file_get_contents(Hyde::path('_pages/foo.md')) ); + Filesystem::unlink('_pages/foo.md'); } public function testSaveMethodWritesPageBodyToFile() { MarkdownPage::make('foo', markdown: 'foo')->save(); - $this->assertEquals("foo\n", + + $this->assertSame("foo\n", file_get_contents(Hyde::path('_pages/foo.md')) ); + Filesystem::unlink('_pages/foo.md'); } public function testSaveMethodWritesPageBodyToFileWithFrontMatter() { MarkdownPage::make('foo', matter: ['foo' => 'bar'], markdown: 'foo bar')->save(); - $this->assertEquals("---\nfoo: bar\n---\n\nfoo bar\n", + + $this->assertSame("---\nfoo: bar\n---\n\nfoo bar\n", file_get_contents(Hyde::path('_pages/foo.md')) ); + Filesystem::unlink('_pages/foo.md'); } @@ -1039,8 +1035,8 @@ public function testExistingParsedMarkdownPagesCanBeSaved() $this->assertSame("bar\n", file_get_contents(Hyde::path('_pages/foo.md'))); - /** @var BaseMarkdownPage $parsed */ $parsed = Pages::getPage('_pages/foo.md'); + $this->assertInstanceOf(MarkdownPage::class, $parsed); $this->assertSame('bar', $parsed->markdown->body()); $parsed->markdown = new Markdown('baz'); @@ -1082,7 +1078,9 @@ public function testMarkdownPostsCanBeSaved() { $post = new MarkdownPost('foo'); $post->save(); + $this->assertFileExists(Hyde::path('_posts/foo.md')); + Filesystem::unlink('_posts/foo.md'); } @@ -1090,34 +1088,35 @@ public function testDocumentationPagesCanBeSaved() { $page = new DocumentationPage('foo'); $page->save(); + $this->assertFileExists(Hyde::path('_docs/foo.md')); + Filesystem::unlink('_docs/foo.md'); } public function testGetMethodCanAccessDataFromPage() { $page = MarkdownPage::make('foo', ['foo' => 'bar']); - $this->assertEquals('bar', $page->data('foo')); + $this->assertSame('bar', $page->data('foo')); } public function testGetMethodCanAccessNestedDataFromPage() { $page = MarkdownPage::make('foo', ['foo' => ['bar' => 'baz']]); - $this->assertEquals('baz', $page->data('foo')['bar']); + $this->assertSame('baz', $page->data('foo')['bar']); } public function testGetMethodCanAccessNestedDataFromPageWithDotNotation() { $page = MarkdownPage::make('foo', ['foo' => ['bar' => 'baz']]); - $this->assertEquals('baz', $page->data('foo.bar')); + $this->assertSame('baz', $page->data('foo.bar')); } public function testGetLinkWithPrettyUrls() { config(['hyde.pretty_urls' => true]); - $this->assertEquals('output/hello-world', - (new TestPage('hello-world'))->getLink() - ); + + $this->assertSame('output/hello-world', (new TestPage('hello-world'))->getLink()); } public function testGetLinkUsesHyperlinksHelper() @@ -1146,8 +1145,11 @@ public function testAllPagesAreRoutable() HtmlPage::class, ]; - /** @var HydePage $page */ foreach ($pages as $page) { + assert(is_a($page, HydePage::class, true)); + + Hyde::boot(); + $page = new $page('foo'); $this->assertInstanceOf(Route::class, $page->getRoute()); @@ -1161,13 +1163,13 @@ public function testAllPagesAreRoutable() $this->assertArrayHasKey($page->getRouteKey(), Hyde::routes()); unlink($page::sourcePath('foo')); - Hyde::boot(); } } public function testNavigationDataFactoryHidesPageFromNavigationWhenInASubdirectory() { $page = MarkdownPage::make('foo/bar'); + $this->assertFalse($page->showInNavigation()); $this->assertNull($page->navigationMenuGroup()); } @@ -1175,7 +1177,9 @@ public function testNavigationDataFactoryHidesPageFromNavigationWhenInASubdirect public function testNavigationDataFactoryHidesPageFromNavigationWhenInAAndConfigIsSetToHidden() { config(['hyde.navigation.subdirectories' => 'hidden']); + $page = MarkdownPage::make('foo/bar'); + $this->assertFalse($page->showInNavigation()); $this->assertNull($page->navigationMenuGroup()); } @@ -1183,7 +1187,9 @@ public function testNavigationDataFactoryHidesPageFromNavigationWhenInAAndConfig public function testNavigationDataFactoryDoesNotHidePageFromNavigationWhenInASubdirectoryAndAllowedInConfiguration() { config(['hyde.navigation.subdirectories' => 'flat']); + $page = MarkdownPage::make('foo/bar'); + $this->assertTrue($page->showInNavigation()); $this->assertNull($page->navigationMenuGroup()); } @@ -1191,9 +1197,11 @@ public function testNavigationDataFactoryDoesNotHidePageFromNavigationWhenInASub public function testNavigationDataFactoryAllowsShowInNavigationAndSetsGroupWhenDropdownIsSelectedInConfig() { config(['hyde.navigation.subdirectories' => 'dropdown']); + $page = MarkdownPage::make('foo/bar'); + $this->assertTrue($page->showInNavigation()); - $this->assertEquals('foo', $page->navigationMenuGroup()); + $this->assertSame('foo', $page->navigationMenuGroup()); } public function testIsDiscoverableMethodReturnsTrueForDiscoverablePages() @@ -1218,8 +1226,8 @@ public function testIsDiscoverableMethodRequiresSourceDirectoryToBeFilled() public function testAllCoreExtensionPagesAreDiscoverable() { - /** @var class-string $page */ foreach (HydeCoreExtension::getPageClasses() as $page) { + assert(is_a($page, HydePage::class, true)); $this->assertTrue($page::isDiscoverable()); } } @@ -1227,6 +1235,7 @@ public function testAllCoreExtensionPagesAreDiscoverable() public function testNestedIndexPagesShowUpInNavigation() { $page = MarkdownPage::make('foo/index'); + $this->assertTrue($page->showInNavigation()); $this->assertSame('Foo', $page->navigationMenuLabel()); } diff --git a/packages/framework/tests/Feature/HydeServiceProviderTest.php b/packages/framework/tests/Feature/HydeServiceProviderTest.php index c3b59226ee5..6904c5b11d6 100644 --- a/packages/framework/tests/Feature/HydeServiceProviderTest.php +++ b/packages/framework/tests/Feature/HydeServiceProviderTest.php @@ -75,17 +75,17 @@ public function testProviderRegistersSourceDirectories() MarkdownPost::setSourceDirectory(''); DocumentationPage::setSourceDirectory(''); - $this->assertEquals('', BladePage::sourceDirectory()); - $this->assertEquals('', MarkdownPage::sourceDirectory()); - $this->assertEquals('', MarkdownPost::sourceDirectory()); - $this->assertEquals('', DocumentationPage::sourceDirectory()); + $this->assertSame('', BladePage::sourceDirectory()); + $this->assertSame('', MarkdownPage::sourceDirectory()); + $this->assertSame('', MarkdownPost::sourceDirectory()); + $this->assertSame('', DocumentationPage::sourceDirectory()); $this->provider->register(); - $this->assertEquals('_pages', BladePage::sourceDirectory()); - $this->assertEquals('_pages', MarkdownPage::sourceDirectory()); - $this->assertEquals('_posts', MarkdownPost::sourceDirectory()); - $this->assertEquals('_docs', DocumentationPage::sourceDirectory()); + $this->assertSame('_pages', BladePage::sourceDirectory()); + $this->assertSame('_pages', MarkdownPage::sourceDirectory()); + $this->assertSame('_posts', MarkdownPost::sourceDirectory()); + $this->assertSame('_docs', DocumentationPage::sourceDirectory()); } public function testProviderRegistersOutputDirectories() @@ -95,17 +95,17 @@ public function testProviderRegistersOutputDirectories() MarkdownPost::setOutputDirectory('foo'); DocumentationPage::setOutputDirectory('foo'); - $this->assertEquals('foo', BladePage::outputDirectory()); - $this->assertEquals('foo', MarkdownPage::outputDirectory()); - $this->assertEquals('foo', MarkdownPost::outputDirectory()); - $this->assertEquals('foo', DocumentationPage::outputDirectory()); + $this->assertSame('foo', BladePage::outputDirectory()); + $this->assertSame('foo', MarkdownPage::outputDirectory()); + $this->assertSame('foo', MarkdownPost::outputDirectory()); + $this->assertSame('foo', DocumentationPage::outputDirectory()); $this->provider->register(); - $this->assertEquals('', BladePage::outputDirectory()); - $this->assertEquals('', MarkdownPage::outputDirectory()); - $this->assertEquals('posts', MarkdownPost::outputDirectory()); - $this->assertEquals('docs', DocumentationPage::outputDirectory()); + $this->assertSame('', BladePage::outputDirectory()); + $this->assertSame('', MarkdownPage::outputDirectory()); + $this->assertSame('posts', MarkdownPost::outputDirectory()); + $this->assertSame('docs', DocumentationPage::outputDirectory()); } public function testCustomSourceRootsAreAppliedToThePageModels() @@ -138,46 +138,46 @@ public function testSourceRootSetInConfigIsAssigned() public function testProviderRegistersSiteOutputDirectory() { - $this->assertEquals('_site', Hyde::getOutputDirectory()); + $this->assertSame('_site', Hyde::getOutputDirectory()); config(['hyde.output_directory' => 'foo']); $this->provider->register(); - $this->assertEquals('foo', Hyde::getOutputDirectory()); + $this->assertSame('foo', Hyde::getOutputDirectory()); } public function testProviderRegistersMediaDirectory() { - $this->assertEquals('_media', Hyde::getMediaDirectory()); + $this->assertSame('_media', Hyde::getMediaDirectory()); config(['hyde.media_directory' => 'foo']); $this->provider->register(); - $this->assertEquals('foo', Hyde::getMediaDirectory()); - $this->assertEquals('foo', Hyde::getMediaOutputDirectory()); + $this->assertSame('foo', Hyde::getMediaDirectory()); + $this->assertSame('foo', Hyde::getMediaOutputDirectory()); } public function testProviderRegistersBladeViewDiscoveryLocationForConfiguredBladeViewPath() { config(['view.paths' => []]); - $this->assertEquals([], config('view.paths')); + $this->assertSame([], config('view.paths')); $this->provider->register(); - $this->assertEquals([realpath(Hyde::path('_pages'))], config('view.paths')); + $this->assertSame([realpath(Hyde::path('_pages'))], config('view.paths')); } public function testBladeViewLocationsAreOnlyRegisteredOncePerKey() { config(['view.paths' => []]); - $this->assertEquals([], config('view.paths')); + $this->assertSame([], config('view.paths')); $this->provider->register(); $this->provider->register(); - $this->assertEquals([realpath(Hyde::path('_pages'))], config('view.paths')); + $this->assertSame([realpath(Hyde::path('_pages'))], config('view.paths')); } public function testProviderRegistersConsoleCommands() @@ -210,7 +210,7 @@ public function testProviderRegistersAllPageModelSourcePaths() $pages = HydeCoreExtension::getPageClasses(); // Assert we are testing all page models - $this->assertEquals([ + $this->assertSame([ HtmlPage::class, BladePage::class, MarkdownPage::class, @@ -258,11 +258,11 @@ public function testProviderRegistersSourceDirectoriesUsingOptionsInConfiguratio $this->provider->register(); - $this->assertEquals('foo', HtmlPage::sourceDirectory()); - $this->assertEquals('foo', BladePage::sourceDirectory()); - $this->assertEquals('foo', MarkdownPage::sourceDirectory()); - $this->assertEquals('foo', MarkdownPost::sourceDirectory()); - $this->assertEquals('foo', DocumentationPage::sourceDirectory()); + $this->assertSame('foo', HtmlPage::sourceDirectory()); + $this->assertSame('foo', BladePage::sourceDirectory()); + $this->assertSame('foo', MarkdownPage::sourceDirectory()); + $this->assertSame('foo', MarkdownPost::sourceDirectory()); + $this->assertSame('foo', DocumentationPage::sourceDirectory()); } public function testSourceDirectoriesCanBeSetUsingKebabCaseClassNames() @@ -277,11 +277,11 @@ public function testSourceDirectoriesCanBeSetUsingKebabCaseClassNames() $this->provider->register(); - $this->assertEquals('foo', HtmlPage::sourceDirectory()); - $this->assertEquals('foo', BladePage::sourceDirectory()); - $this->assertEquals('foo', MarkdownPage::sourceDirectory()); - $this->assertEquals('foo', MarkdownPost::sourceDirectory()); - $this->assertEquals('foo', DocumentationPage::sourceDirectory()); + $this->assertSame('foo', HtmlPage::sourceDirectory()); + $this->assertSame('foo', BladePage::sourceDirectory()); + $this->assertSame('foo', MarkdownPage::sourceDirectory()); + $this->assertSame('foo', MarkdownPost::sourceDirectory()); + $this->assertSame('foo', DocumentationPage::sourceDirectory()); } public function testProviderRegistersOutputDirectoriesUsingOptionsInConfiguration() @@ -296,11 +296,11 @@ public function testProviderRegistersOutputDirectoriesUsingOptionsInConfiguratio $this->provider->register(); - $this->assertEquals('foo', HtmlPage::outputDirectory()); - $this->assertEquals('foo', BladePage::outputDirectory()); - $this->assertEquals('foo', MarkdownPage::outputDirectory()); - $this->assertEquals('foo', MarkdownPost::outputDirectory()); - $this->assertEquals('foo', DocumentationPage::outputDirectory()); + $this->assertSame('foo', HtmlPage::outputDirectory()); + $this->assertSame('foo', BladePage::outputDirectory()); + $this->assertSame('foo', MarkdownPage::outputDirectory()); + $this->assertSame('foo', MarkdownPost::outputDirectory()); + $this->assertSame('foo', DocumentationPage::outputDirectory()); } public function testOutputDirectoriesCanBeSetUsingKebabCaseClassNames() @@ -315,11 +315,11 @@ public function testOutputDirectoriesCanBeSetUsingKebabCaseClassNames() $this->provider->register(); - $this->assertEquals('foo', HtmlPage::outputDirectory()); - $this->assertEquals('foo', BladePage::outputDirectory()); - $this->assertEquals('foo', MarkdownPage::outputDirectory()); - $this->assertEquals('foo', MarkdownPost::outputDirectory()); - $this->assertEquals('foo', DocumentationPage::outputDirectory()); + $this->assertSame('foo', HtmlPage::outputDirectory()); + $this->assertSame('foo', BladePage::outputDirectory()); + $this->assertSame('foo', MarkdownPage::outputDirectory()); + $this->assertSame('foo', MarkdownPost::outputDirectory()); + $this->assertSame('foo', DocumentationPage::outputDirectory()); } public function testCannotGetMainNavigationMenuFromContainerBeforeKernelIsBooted() diff --git a/packages/framework/tests/Feature/IncludesFacadeTest.php b/packages/framework/tests/Feature/IncludesFacadeTest.php index e35c2119eed..75ada517c31 100644 --- a/packages/framework/tests/Feature/IncludesFacadeTest.php +++ b/packages/framework/tests/Feature/IncludesFacadeTest.php @@ -17,7 +17,7 @@ class IncludesFacadeTest extends TestCase { public function testPathReturnsTheIncludesDirectory() { - $this->assertEquals( + $this->assertSame( Hyde::path('resources/includes'), Includes::path() ); @@ -25,7 +25,7 @@ public function testPathReturnsTheIncludesDirectory() public function testPathReturnsAPartialWithinTheIncludesDirectory() { - $this->assertEquals( + $this->assertSame( Hyde::path('resources/includes/partial.html'), Includes::path('partial.html') ); @@ -43,34 +43,34 @@ public function testGetReturnsPartial() { $expected = 'foo bar'; file_put_contents(Hyde::path('resources/includes/foo.txt'), $expected); - $this->assertEquals($expected, Includes::get('foo.txt')); + $this->assertSame($expected, Includes::get('foo.txt')); Filesystem::unlink('resources/includes/foo.txt'); } public function testGetReturnsDefaultValueWhenNotFound() { $this->assertNull(Includes::get('foo.txt')); - $this->assertEquals('default', Includes::get('foo.txt', 'default')); + $this->assertSame('default', Includes::get('foo.txt', 'default')); } public function testHtmlReturnsRenderedPartial() { $expected = '

foo bar

'; file_put_contents(Hyde::path('resources/includes/foo.html'), '

foo bar

'); - $this->assertEquals($expected, Includes::html('foo.html')); + $this->assertSame($expected, Includes::html('foo.html')); Filesystem::unlink('resources/includes/foo.html'); } public function testHtmlReturnsEfaultValueWhenNotFound() { $this->assertNull(Includes::html('foo.html')); - $this->assertEquals('

default

', Includes::html('foo.html', '

default

')); + $this->assertSame('

default

', Includes::html('foo.html', '

default

')); } public function testHtmlWithAndWithoutExtension() { file_put_contents(Hyde::path('resources/includes/foo.html'), '# foo bar'); - $this->assertEquals(Includes::html('foo.html'), Includes::html('foo')); + $this->assertSame(Includes::html('foo.html'), Includes::html('foo')); Filesystem::unlink('resources/includes/foo.html'); } @@ -78,20 +78,20 @@ public function testMarkdownReturnsRenderedPartial() { $expected = "

foo bar

\n"; file_put_contents(Hyde::path('resources/includes/foo.md'), '# foo bar'); - $this->assertEquals($expected, Includes::markdown('foo.md')); + $this->assertSame($expected, Includes::markdown('foo.md')); Filesystem::unlink('resources/includes/foo.md'); } public function testMarkdownReturnsRenderedDefaultValueWhenNotFound() { $this->assertNull(Includes::markdown('foo.md')); - $this->assertEquals("

default

\n", Includes::markdown('foo.md', '# default')); + $this->assertSame("

default

\n", Includes::markdown('foo.md', '# default')); } public function testMarkdownWithAndWithoutExtension() { file_put_contents(Hyde::path('resources/includes/foo.md'), '# foo bar'); - $this->assertEquals(Includes::markdown('foo.md'), Includes::markdown('foo')); + $this->assertSame(Includes::markdown('foo.md'), Includes::markdown('foo')); Filesystem::unlink('resources/includes/foo.md'); } @@ -99,20 +99,20 @@ public function testBladeReturnsRenderedPartial() { $expected = 'foo bar'; file_put_contents(Hyde::path('resources/includes/foo.blade.php'), '{{ "foo bar" }}'); - $this->assertEquals($expected, Includes::blade('foo.blade.php')); + $this->assertSame($expected, Includes::blade('foo.blade.php')); Filesystem::unlink('resources/includes/foo.blade.php'); } public function testBladeWithAndWithoutExtension() { file_put_contents(Hyde::path('resources/includes/foo.blade.php'), '# foo bar'); - $this->assertEquals(Includes::blade('foo.blade.php'), Includes::blade('foo')); + $this->assertSame(Includes::blade('foo.blade.php'), Includes::blade('foo')); Filesystem::unlink('resources/includes/foo.blade.php'); } public function testBladeReturnsRenderedDefaultValueWhenNotFound() { $this->assertNull(Includes::blade('foo.blade.php')); - $this->assertEquals('default', Includes::blade('foo.blade.php', '{{ "default" }}')); + $this->assertSame('default', Includes::blade('foo.blade.php', '{{ "default" }}')); } } diff --git a/packages/framework/tests/Feature/MarkdownFileParserTest.php b/packages/framework/tests/Feature/MarkdownFileParserTest.php index fa2ef4b51fd..2586eb70dab 100644 --- a/packages/framework/tests/Feature/MarkdownFileParserTest.php +++ b/packages/framework/tests/Feature/MarkdownFileParserTest.php @@ -44,9 +44,10 @@ public function testCanParseMarkdownFile() file_put_contents(Hyde::path('_posts/test-post.md'), 'Foo bar'); $document = MarkdownFileParser::parse('_posts/test-post.md'); - $this->assertInstanceOf(MarkdownDocument::class, $document); + $this->assertInstanceOf(MarkdownDocument::class, $document); $this->assertEquals('Foo bar', $document->markdown); + $this->assertSame('Foo bar', $document->markdown->body()); } public function testCanParseMarkdownFileWithFrontMatter() @@ -54,6 +55,7 @@ public function testCanParseMarkdownFileWithFrontMatter() $this->makeTestPost(); $document = MarkdownFileParser::parse('_posts/test-post.md'); + $this->assertInstanceOf(MarkdownDocument::class, $document); $this->assertEquals(FrontMatter::fromArray([ @@ -77,6 +79,7 @@ public function testParsedMarkdownPostContainsValidFrontMatter() $this->makeTestPost(); $post = MarkdownFileParser::parse('_posts/test-post.md'); + $this->assertSame('My New Post', $post->matter('title')); $this->assertSame('Mr. Hyde', $post->matter('author')); $this->assertSame('blog', $post->matter('category')); diff --git a/packages/framework/tests/Feature/MarkdownPostTest.php b/packages/framework/tests/Feature/MarkdownPostTest.php index 3de217ca75e..66c76b3a0ba 100644 --- a/packages/framework/tests/Feature/MarkdownPostTest.php +++ b/packages/framework/tests/Feature/MarkdownPostTest.php @@ -24,7 +24,7 @@ public function testConstructorCanCreateANewAuthorInstanceFromUsernameString() ])); $this->assertInstanceOf(PostAuthor::class, $post->author); - $this->assertEquals('John Doe', $post->author->username); + $this->assertSame('John Doe', $post->author->username); $this->assertNull($post->author->name); $this->assertNull($post->author->website); } @@ -40,9 +40,9 @@ public function testConstructorCanCreateANewAuthorInstanceFromUserArray() ])); $this->assertInstanceOf(PostAuthor::class, $post->author); - $this->assertEquals('john_doe', $post->author->username); - $this->assertEquals('John Doe', $post->author->name); - $this->assertEquals('https://example.com', $post->author->website); + $this->assertSame('john_doe', $post->author->username); + $this->assertSame('John Doe', $post->author->name); + $this->assertSame('https://example.com', $post->author->website); } public function testConstructorCanCreateANewImageInstanceFromAString() @@ -52,7 +52,7 @@ public function testConstructorCanCreateANewImageInstanceFromAString() ])); $this->assertInstanceOf(FeaturedImage::class, $post->image); - $this->assertEquals('https://example.com/image.jpg', $post->image->getSource()); + $this->assertSame('https://example.com/image.jpg', $post->image->getSource()); } public function testConstructorCanCreateANewImageInstanceFromAnArray() @@ -64,7 +64,7 @@ public function testConstructorCanCreateANewImageInstanceFromAnArray() ])); $this->assertInstanceOf(FeaturedImage::class, $post->image); - $this->assertEquals('https://example.com/image.jpg', $post->image->getSource()); + $this->assertSame('https://example.com/image.jpg', $post->image->getSource()); } public function testConstructorCanCreateANewDateStringInstanceFromMatter() @@ -74,7 +74,7 @@ public function testConstructorCanCreateANewDateStringInstanceFromMatter() ])); $this->assertInstanceOf(DateString::class, $post->date); - $this->assertEquals('Jan 1st, 2022', $post->date->short); + $this->assertSame('Jan 1st, 2022', $post->date->short); } public function testFeaturedImageCanBeConstructedReturnsNullWhenNoImageIsSetInThePageMatter() @@ -88,7 +88,7 @@ public function testFeaturedImageCanBeConstructedReturnsImageObjectWithLocalPath $page = MarkdownPost::make(matter: ['image' => 'foo.png']); $image = $page->image; $this->assertInstanceOf(FeaturedImage::class, $image); - $this->assertEquals('media/foo.png', $image->getSource()); + $this->assertSame('media/foo.png', $image->getSource()); } public function testFeaturedImageCanBeConstructedReturnsImageObjectWithRemotePathWhenMatterIsString() @@ -96,7 +96,7 @@ public function testFeaturedImageCanBeConstructedReturnsImageObjectWithRemotePat $page = MarkdownPost::make(matter: ['image' => 'https://example.com/foo.png']); $image = $page->image; $this->assertInstanceOf(FeaturedImage::class, $image); - $this->assertEquals('https://example.com/foo.png', $image->getSource()); + $this->assertSame('https://example.com/foo.png', $image->getSource()); } public function testFeaturedImageCanBeConstructedReturnsImageObjectWithSuppliedDataWhenMatterIsArray() @@ -104,7 +104,7 @@ public function testFeaturedImageCanBeConstructedReturnsImageObjectWithSuppliedD $page = MarkdownPost::make(matter: ['image' => ['source' => 'foo.png', 'titleText' => 'bar']]); $image = $page->image; $this->assertInstanceOf(FeaturedImage::class, $image); - $this->assertEquals('media/foo.png', $image->getSource()); - $this->assertEquals('bar', $image->getTitleText()); + $this->assertSame('media/foo.png', $image->getSource()); + $this->assertSame('bar', $image->getTitleText()); } } diff --git a/packages/framework/tests/Feature/MarkdownServiceTest.php b/packages/framework/tests/Feature/MarkdownServiceTest.php index aac0df233e0..4a56a66de94 100644 --- a/packages/framework/tests/Feature/MarkdownServiceTest.php +++ b/packages/framework/tests/Feature/MarkdownServiceTest.php @@ -22,7 +22,7 @@ public function testServiceCanParseMarkdownToHtml() $html = (new MarkdownService($markdown))->parse(); $this->assertIsString($html); - $this->assertEquals("

Hello World!

\n", $html); + $this->assertSame("

Hello World!

\n", $html); } public function testServiceCanParseMarkdownToHtmlWithPermalinks() @@ -32,7 +32,7 @@ public function testServiceCanParseMarkdownToHtmlWithPermalinks() $html = (new MarkdownService($markdown))->withPermalinks()->parse(); $this->assertIsString($html); - $this->assertEquals( + $this->assertSame( '

Hello World!

'."\n", $html @@ -72,7 +72,7 @@ public function testTorchlightIntegrationInjectsAttribution() public function testBladedownIsNotEnabledByDefault() { $service = new MarkdownService('[Blade]: {{ "Hello World!" }}'); - $this->assertEquals("

[Blade]: {{ "Hello World!" }}

\n", $service->parse()); + $this->assertSame("

[Blade]: {{ "Hello World!" }}

\n", $service->parse()); } public function testBladedownCanBeEnabled() @@ -80,7 +80,7 @@ public function testBladedownCanBeEnabled() config(['markdown.enable_blade' => true]); $service = new MarkdownService('[Blade]: {{ "Hello World!" }}'); $service->addFeature('bladedown')->parse(); - $this->assertEquals("Hello World!\n", $service->parse()); + $this->assertSame("Hello World!\n", $service->parse()); } public function testRawHtmlTagsAreStrippedByDefault() @@ -88,7 +88,7 @@ public function testRawHtmlTagsAreStrippedByDefault() $markdown = '

foo

'; $service = new MarkdownService($markdown); $html = $service->parse(); - $this->assertEquals("

foo

<style>bar</style><script>hat</script>\n", $html); + $this->assertSame("

foo

<style>bar</style><script>hat</script>\n", $html); } public function testRawHtmlTagsAreNotStrippedWhenExplicitlyEnabled() @@ -97,7 +97,7 @@ public function testRawHtmlTagsAreNotStrippedWhenExplicitlyEnabled() $markdown = '

foo

'; $service = new MarkdownService($markdown); $html = $service->parse(); - $this->assertEquals("

foo

\n", $html); + $this->assertSame("

foo

\n", $html); } public function testHasFeaturesArray() diff --git a/packages/framework/tests/Feature/MetadataTest.php b/packages/framework/tests/Feature/MetadataTest.php index c7b3c7ce690..b1186f87ad9 100644 --- a/packages/framework/tests/Feature/MetadataTest.php +++ b/packages/framework/tests/Feature/MetadataTest.php @@ -57,34 +57,37 @@ public function testMetadataObjectIsGeneratedAutomatically() $this->assertNotNull($page->metadata); $this->assertInstanceOf(MetadataBag::class, $page->metadata); - $this->assertEquals([], $page->metadata->get()); + $this->assertSame([], $page->metadata->get()); } public function testLinkItemModel() { $item = new LinkElement('rel', 'href'); - $this->assertEquals('rel', $item->uniqueKey()); - $this->assertEquals('', (string) $item); + + $this->assertSame('rel', $item->uniqueKey()); + $this->assertSame('', (string) $item); $item = new LinkElement('rel', 'href', ['attr' => 'value']); - $this->assertEquals('', (string) $item); + $this->assertSame('', (string) $item); } public function testMetadataItemModel() { $item = new MetadataElement('name', 'content'); - $this->assertEquals('name', $item->uniqueKey()); - $this->assertEquals('', (string) $item); + + $this->assertSame('name', $item->uniqueKey()); + $this->assertSame('', (string) $item); } public function testOpenGraphItemModel() { $item = new OpenGraphElement('property', 'content'); - $this->assertEquals('property', $item->uniqueKey()); - $this->assertEquals('', (string) $item); + + $this->assertSame('property', $item->uniqueKey()); + $this->assertSame('', (string) $item); $item = new OpenGraphElement('og:property', 'content'); - $this->assertEquals('', (string) $item); + $this->assertSame('', (string) $item); } public function testLinkItemCanBeAdded() @@ -157,12 +160,13 @@ public function testMultipleItemsOfSameKeyAndTypeOnlyKeepsLatest() public function testRenderReturnsHtmlStringOfImplodedMetadataArrays() { $page = new MarkdownPage(); + $page->metadata->add(Meta::link('foo', 'bar')); $page->metadata->add(Meta::name('foo', 'bar')); $page->metadata->add(Meta::property('foo', 'bar')); $page->metadata->add('foo'); - $this->assertEquals(implode("\n", [ + $this->assertSame(implode("\n", [ '', '', '', @@ -176,8 +180,10 @@ public function testCustomMetadataOverridesConfigDefinedMetadata() config(['hyde.meta' => [ Meta::name('foo', 'bar'), ]]); + $page = new MarkdownPage(); $page->metadata->add(Meta::name('foo', 'baz')); + $this->assertEquals([ 'metadata:foo' => Meta::name('foo', 'baz'), ], $page->metadata->get()); @@ -188,6 +194,7 @@ public function testDynamicMetadataOverridesConfigDefinedMetadata() config(['hyde.meta' => [ Meta::name('twitter:title', 'bar'), ]]); + $page = MarkdownPage::make(matter: ['title' => 'baz']); $this->assertEquals([ @@ -199,6 +206,7 @@ public function testDynamicMetadataOverridesConfigDefinedMetadata() public function testDoesNotAddCanonicalLinkWhenBaseUrlIsNotSet() { config(['hyde.url' => null]); + $page = MarkdownPage::make('bar'); $this->assertStringNotContainsString('metadata->render()); @@ -207,6 +215,7 @@ public function testDoesNotAddCanonicalLinkWhenBaseUrlIsNotSet() public function testDoesNotAddCanonicalLinkWhenIdentifierIsNotSet() { config(['hyde.url' => 'foo']); + $page = MarkdownPage::make(); $this->assertStringNotContainsString('metadata->render()); @@ -215,6 +224,7 @@ public function testDoesNotAddCanonicalLinkWhenIdentifierIsNotSet() public function testAddsCanonicalLinkWhenBaseUrlAndIdentifierIsSet() { config(['hyde.url' => 'foo']); + $page = MarkdownPage::make('bar'); $this->assertStringContainsString('', $page->metadata->render()); @@ -224,6 +234,7 @@ public function testCanonicalLinkUsesCleanUrlSetting() { config(['hyde.url' => 'foo']); config(['hyde.pretty_urls' => true]); + $page = MarkdownPage::make('bar'); $this->assertStringContainsString('', $page->metadata->render()); @@ -232,9 +243,11 @@ public function testCanonicalLinkUsesCleanUrlSetting() public function testCanOverrideCanonicalLinkWithFrontMatter() { config(['hyde.url' => 'foo']); + $page = MarkdownPage::make('bar', [ 'canonicalUrl' => 'canonical', ]); + $this->assertStringContainsString('', $page->metadata->render()); } @@ -242,7 +255,7 @@ public function testAddsTwitterAndOpenGraphTitleWhenTitleIsSet() { $page = MarkdownPage::make(matter: ['title' => 'Foo Bar']); - $this->assertEquals( + $this->assertSame( ''."\n". '', $page->metadata->render() @@ -253,80 +266,90 @@ public function testDoesNotAddTwitterAndOpenGraphTitleWhenNoTitleIsSet() { $page = MarkdownPage::make(matter: ['title' => null]); - $this->assertEquals('', - $page->metadata->render() - ); + $this->assertSame('', $page->metadata->render()); } public function testAddsDescriptionWhenDescriptionIsSetInPost() { $page = MarkdownPost::make(matter: ['description' => 'My Description']); + $this->assertPageHasMetadata($page, ''); } public function testDoesNotAddDescriptionWhenDescriptionIsNotSetInPost() { $page = new MarkdownPost(); + $this->assertPageDoesNotHaveMetadata($page, ''); } public function testAddsAuthorWhenAuthorIsSetInPost() { $page = MarkdownPost::make(matter: ['author' => 'My Author']); + $this->assertPageHasMetadata($page, ''); } public function testDoesNotAddAuthorWhenAuthorIsNotSetInPost() { $page = new MarkdownPost(); + $this->assertPageDoesNotHaveMetadata($page, ''); } public function testAddsKeywordsWhenCategoryIsSetInPost() { $page = MarkdownPost::make(matter: ['category' => 'My Category']); + $this->assertPageHasMetadata($page, ''); } public function testDoesNotAddKeywordsWhenCategoryIsNotSetInPost() { $page = new MarkdownPost(); + $this->assertPageDoesNotHaveMetadata($page, ''); } public function testAddsUrlPropertyWhenCanonicalUrlIsSetInPost() { $page = MarkdownPost::make(matter: ['canonicalUrl' => 'example.html']); + $this->assertPageHasMetadata($page, ''); } public function testDoesNotAddUrlPropertyWhenCanonicalUrlIsNotSetInPost() { $page = new MarkdownPost(); + $this->assertPageDoesNotHaveMetadata($page, ''); } public function testDoesNotAddUrlPropertyWhenCanonicalUrlIsNull() { $page = MarkdownPost::make(matter: ['canonicalUrl' => null]); + $this->assertPageDoesNotHaveMetadata($page, ''); } public function testAddsTitlePropertyWhenTitleIsSetInPost() { $page = MarkdownPost::make(matter: ['title' => 'My Title']); + $this->assertPageHasMetadata($page, ''); } public function testDoesNotAddTitlePropertyWhenTitleIsNotSetInPost() { $page = new MarkdownPost(); + $this->assertPageDoesNotHaveMetadata($page, ' '2022-01-01']); + $this->assertPageHasMetadata($page, ''); } @@ -339,6 +362,7 @@ public function testDoesNotAddPublishedTimePropertyWhenDateIsNotSetInPost() public function testAddsImagePropertyWhenImageIsSetInPost() { $page = MarkdownPost::make(matter: ['image' => 'image.jpg']); + $this->assertPageHasMetadata($page, ''); } @@ -351,13 +375,15 @@ public function testDoesNotAddImagePropertyWhenImageIsNotSetInPost() public function testAddsTypePropertyAutomatically() { $page = MarkdownPost::make(); + $this->assertPageHasMetadata($page, ''); } public function testDynamicPostMetaPropertiesReturnsBaseArrayWhenInitializedWithEmptyFrontMatter() { $page = MarkdownPost::make(); - $this->assertEquals('', $page->metadata->render()); + + $this->assertSame('', $page->metadata->render()); } public function testDynamicPostMetaPropertiesContainsImageMetadataWhenFeaturedImageSetToString() @@ -390,6 +416,7 @@ public function testDynamicPostMetaPropertiesContainsImageLinkThatIsAlwaysRelati public function testDynamicPostMetaPropertiesContainsImageLinkThatIsAlwaysRelativeForNestedOutputDirectories() { MarkdownPost::setOutputDirectory('_posts/foo'); + $page = MarkdownPost::make(matter: [ 'image' => 'foo.jpg', ]); @@ -400,6 +427,7 @@ public function testDynamicPostMetaPropertiesContainsImageLinkThatIsAlwaysRelati public function testDynamicPostMetaPropertiesContainsImageLinkThatIsAlwaysRelativeForNestedPostsAndNestedOutputDirectories() { MarkdownPost::setOutputDirectory('_posts/foo'); + $page = MarkdownPost::make('bar/baz', matter: [ 'image' => 'foo.jpg', ]); @@ -410,6 +438,7 @@ public function testDynamicPostMetaPropertiesContainsImageLinkThatIsAlwaysRelati public function testDynamicPostMetaPropertiesContainsImageLinkThatUsesTheConfiguredMediaDirectory() { Hyde::setMediaDirectory('assets'); + $page = MarkdownPost::make(matter: [ 'image' => 'foo.jpg', ]); @@ -446,6 +475,7 @@ public function testDynamicPostAuthorReturnsAuthorNameWhenAuthorSetToArrayUsingU 'username' => 'username', ], ]); + $this->assertPageHasMetadata($page, ''); } diff --git a/packages/framework/tests/Feature/NavigationDataTest.php b/packages/framework/tests/Feature/NavigationDataTest.php index 510040dbc96..1eaf47f6259 100644 --- a/packages/framework/tests/Feature/NavigationDataTest.php +++ b/packages/framework/tests/Feature/NavigationDataTest.php @@ -33,10 +33,10 @@ public function testConstruct() { $navigationData = new NavigationData('label', 1, true, 'group'); - $this->assertEquals('label', $navigationData->label); - $this->assertEquals('group', $navigationData->group); - $this->assertEquals(true, $navigationData->hidden); - $this->assertEquals(1, $navigationData->priority); + $this->assertSame('label', $navigationData->label); + $this->assertSame('group', $navigationData->group); + $this->assertSame(true, $navigationData->hidden); + $this->assertSame(1, $navigationData->priority); } public function testMake() @@ -61,6 +61,7 @@ protected function getImplementedSchema(string $class): array $reflection = new ReflectionClass($class); $schema = []; + foreach (get_class_vars($class) as $name => $void) { $schema[$name] = $reflection->getProperty($name)->getType()->getName(); } diff --git a/packages/framework/tests/Feature/PageModelConstructorsTest.php b/packages/framework/tests/Feature/PageModelConstructorsTest.php index c98d2988dae..ef823b5f8a2 100644 --- a/packages/framework/tests/Feature/PageModelConstructorsTest.php +++ b/packages/framework/tests/Feature/PageModelConstructorsTest.php @@ -25,7 +25,8 @@ public function testDynamicDataConstructorCanFindTitleFromFrontMatter() { $this->markdown('_pages/foo.md', '# Foo Bar', ['title' => 'My Title']); $page = MarkdownPage::parse('foo'); - $this->assertEquals('My Title', $page->title); + + $this->assertSame('My Title', $page->title); } public function testDynamicDataConstructorCanFindTitleFromH1Tag() @@ -33,7 +34,7 @@ public function testDynamicDataConstructorCanFindTitleFromH1Tag() $this->markdown('_pages/foo.md', '# Foo Bar'); $page = MarkdownPage::parse('foo'); - $this->assertEquals('Foo Bar', $page->title); + $this->assertSame('Foo Bar', $page->title); } public function testDynamicDataConstructorCanFindTitleFromSlug() @@ -41,15 +42,15 @@ public function testDynamicDataConstructorCanFindTitleFromSlug() $this->markdown('_pages/foo-bar.md'); $page = MarkdownPage::parse('foo-bar'); - $this->assertEquals('Foo Bar', $page->title); + $this->assertSame('Foo Bar', $page->title); } public function testDocumentationPageParserCanGetGroupFromFrontMatter() { $this->markdown('_docs/foo.md', '# Foo Bar', ['navigation.group' => 'foo']); - $page = DocumentationPage::parse('foo'); - $this->assertEquals('foo', $page->navigationMenuGroup()); + + $this->assertSame('foo', $page->navigationMenuGroup()); } public function testDocumentationPageParserCanGetGroupAutomaticallyFromNestedPage() @@ -57,9 +58,8 @@ public function testDocumentationPageParserCanGetGroupAutomaticallyFromNestedPag mkdir(Hyde::path('_docs/foo')); touch(Hyde::path('_docs/foo/bar.md')); - /** @var \Hyde\Pages\DocumentationPage $page */ $page = DocumentationPage::parse('foo/bar'); - $this->assertEquals('foo', $page->navigationMenuGroup()); + $this->assertSame('foo', $page->navigationMenuGroup()); Filesystem::unlink('_docs/foo/bar.md'); rmdir(Hyde::path('_docs/foo')); diff --git a/packages/framework/tests/Feature/PaginatorTest.php b/packages/framework/tests/Feature/PaginatorTest.php index cf4c10073bb..41587d0f942 100644 --- a/packages/framework/tests/Feature/PaginatorTest.php +++ b/packages/framework/tests/Feature/PaginatorTest.php @@ -22,14 +22,12 @@ public function testItCanBeInstantiated(): void public function testGetPaginatedPageCollection() { - $this->assertEquals(collect([]), (new Paginator())->getPaginatedItems()); + $this->assertEquals(collect(), (new Paginator())->getPaginatedItems()); } public function testGetPaginatedPageCollectionWithPages() { - $collection = (new Paginator( - range(1, 50), - ))->getPaginatedItems(); + $collection = (new Paginator(range(1, 50)))->getPaginatedItems(); $this->assertCount(2, $collection); $this->assertCount(25, $collection->first()); @@ -43,10 +41,7 @@ public function testGetPaginatedPageCollectionWithPages() public function testCollectionIsChunkedBySpecifiedSettingValue() { - $collection = (new Paginator( - range(1, 50), - 10) - )->getPaginatedItems(); + $collection = (new Paginator(range(1, 50), 10))->getPaginatedItems(); $this->assertCount(5, $collection); $this->assertCount(10, $collection->first()); @@ -66,11 +61,11 @@ public function testGetItemsForPageReturnsTheCorrectChunk() $this->assertCount(10, $paginator->setCurrentPage(4)->getItemsForPage()); $this->assertCount(10, $paginator->setCurrentPage(5)->getItemsForPage()); - $this->assertEquals(range(1, 10), $paginator->setCurrentPage(1)->getItemsForPage()->toArray()); - $this->assertEquals(array_combine(range(10, 19), range(11, 20)), $paginator->setCurrentPage(2)->getItemsForPage()->toArray()); - $this->assertEquals(array_combine(range(20, 29), range(21, 30)), $paginator->setCurrentPage(3)->getItemsForPage()->toArray()); - $this->assertEquals(array_combine(range(30, 39), range(31, 40)), $paginator->setCurrentPage(4)->getItemsForPage()->toArray()); - $this->assertEquals(array_combine(range(40, 49), range(41, 50)), $paginator->setCurrentPage(5)->getItemsForPage()->toArray()); + $this->assertSame(range(1, 10), $paginator->setCurrentPage(1)->getItemsForPage()->toArray()); + $this->assertSame(array_combine(range(10, 19), range(11, 20)), $paginator->setCurrentPage(2)->getItemsForPage()->toArray()); + $this->assertSame(array_combine(range(20, 29), range(21, 30)), $paginator->setCurrentPage(3)->getItemsForPage()->toArray()); + $this->assertSame(array_combine(range(30, 39), range(31, 40)), $paginator->setCurrentPage(4)->getItemsForPage()->toArray()); + $this->assertSame(array_combine(range(40, 49), range(41, 50)), $paginator->setCurrentPage(5)->getItemsForPage()->toArray()); } public function testCanGetCurrentPageNumber() @@ -83,12 +78,14 @@ public function testCanSetCurrentPageNumber() { $service = new Paginator(range(1, 50)); $service->setCurrentPage(2); + $this->assertSame(2, $service->currentPage()); } public function testSetCurrentPageNumberRequiresIntegerToBeGreaterThanNought() { $this->expectException(InvalidArgumentException::class); + $service = new Paginator(); $service->setCurrentPage(0); } @@ -96,16 +93,14 @@ public function testSetCurrentPageNumberRequiresIntegerToBeGreaterThanNought() public function testSetCurrentPageNumberRequiresIntegerToBeGreaterThanNought2() { $this->expectException(InvalidArgumentException::class); + $service = new Paginator(); $service->setCurrentPage(-1); } public function testSetCurrentPageNumberRequiresIntegerToBeLessThanTotalPages() { - $service = new Paginator( - range(1, 50), - 10 - ); + $service = new Paginator(range(1, 50), 10); $service->setCurrentPage(5); $this->assertSame(5, $service->currentPage()); @@ -117,11 +112,8 @@ public function testSetCurrentPageNumberRequiresIntegerToBeLessThanTotalPages() public function testCannotSetInvalidCurrentPageNumberInConstructor() { $this->expectException(InvalidArgumentException::class); - new Paginator( - range(1, 50), - 10, - currentPageNumber: 6 - ); + + new Paginator(range(1, 50), 10, currentPageNumber: 6); } public function testLastPageReturnsTheLastPageNumber() @@ -235,16 +227,13 @@ public function testNextNumberReturnsTheNextPageNumberWhenThereIsOne() public function testGetPageLinks() { - $this->assertSame( - [ - 1 => 'page-1.html', - 2 => 'page-2.html', - 3 => 'page-3.html', - 4 => 'page-4.html', - 5 => 'page-5.html', - ], - $this->makePaginator()->getPageLinks() - ); + $this->assertSame([ + 1 => 'page-1.html', + 2 => 'page-2.html', + 3 => 'page-3.html', + 4 => 'page-4.html', + 5 => 'page-5.html', + ], $this->makePaginator()->getPageLinks()); } public function testGetPageLinksWithBaseRoute() @@ -260,19 +249,18 @@ public function testGetPageLinksWithBaseRoute() } $paginator = new Paginator($pages, 2, paginationRouteBasename: 'pages'); - $this->assertSame( - [ - 1 => $pages[1]->getRoute(), - 2 => $pages[2]->getRoute(), - 3 => $pages[3]->getRoute(), - ], - $paginator->getPageLinks() - ); + + $this->assertSame([ + 1 => $pages[1]->getRoute(), + 2 => $pages[2]->getRoute(), + 3 => $pages[3]->getRoute(), + ], $paginator->getPageLinks()); } public function testFirstItemNumberOnPage() { $paginator = $this->makePaginator(); + $this->assertSame(1, $paginator->firstItemNumberOnPage()); $this->assertSame(11, $paginator->setCurrentPage(2)->firstItemNumberOnPage()); $this->assertSame(21, $paginator->setCurrentPage(3)->firstItemNumberOnPage()); @@ -280,6 +268,7 @@ public function testFirstItemNumberOnPage() $this->assertSame(41, $paginator->setCurrentPage(5)->firstItemNumberOnPage()); $paginator = $this->makePaginator(1, 100, 25); + $this->assertSame(1, $paginator->firstItemNumberOnPage()); $this->assertSame(26, $paginator->setCurrentPage(2)->firstItemNumberOnPage()); $this->assertSame(51, $paginator->setCurrentPage(3)->firstItemNumberOnPage()); diff --git a/packages/framework/tests/Feature/Services/BladeDownProcessorTest.php b/packages/framework/tests/Feature/Services/BladeDownProcessorTest.php index 797e22d2972..d6e55a0bc56 100644 --- a/packages/framework/tests/Feature/Services/BladeDownProcessorTest.php +++ b/packages/framework/tests/Feature/Services/BladeDownProcessorTest.php @@ -8,22 +8,19 @@ use Hyde\Testing\TestCase; /** - * Class BladeDownProcessorTest. - * * @covers \Hyde\Markdown\Processing\BladeDownProcessor */ class BladeDownProcessorTest extends TestCase { public function testItRendersBladeEchoSyntax() { - $this->assertEquals('Hello World!', BladeDownProcessor::render('[Blade]: {{ "Hello World!" }}')); + $this->assertSame('Hello World!', BladeDownProcessor::render('[Blade]: {{ "Hello World!" }}')); } public function testItRendersBladeWithinMultilineMarkdown() { - $this->assertEquals( + $this->assertSame( "Foo\nHello World!\nBar", - BladeDownProcessor::render("Foo\n[Blade]: {{ 'Hello World!' }}\nBar") ); } @@ -38,25 +35,25 @@ public function testItRendersBladeViews() 'views/hello.blade.php' ), 'Hello World!'); - $this->assertEquals('Hello World!', BladeDownProcessor::render('[Blade]: @include("hello")')); + $this->assertSame('Hello World!', BladeDownProcessor::render('[Blade]: @include("hello")')); unlink(resource_path('views/hello.blade.php')); } public function testDirectiveIsCaseInsensitive() { - $this->assertEquals('Hello World!', BladeDownProcessor::render('[blade]: {{ "Hello World!" }}')); + $this->assertSame('Hello World!', BladeDownProcessor::render('[blade]: {{ "Hello World!" }}')); } public function testDirectiveIsIgnoredIfItIsNotAtTheStartOfALine() { - $this->assertEquals('Example: [Blade]: {{ "Hello World!" }}', + $this->assertSame('Example: [Blade]: {{ "Hello World!" }}', BladeDownProcessor::render('Example: [Blade]: {{ "Hello World!" }}')); } public function testItRendersBladeEchoSyntaxWithVariables() { - $this->assertEquals('Hello World!', BladeDownProcessor::render('[Blade]: {{ $foo }}', ['foo' => 'Hello World!'])); + $this->assertSame('Hello World!', BladeDownProcessor::render('[Blade]: {{ $foo }}', ['foo' => 'Hello World!'])); } public function testItRendersBladeViewsWithVariables() @@ -65,18 +62,18 @@ public function testItRendersBladeViewsWithVariables() 'views/hello.blade.php' ), 'Hello {{ $name }}!'); - $this->assertEquals('Hello John!', BladeDownProcessor::render('[Blade]: @include("hello", ["name" => "John"])')); + $this->assertSame('Hello John!', BladeDownProcessor::render('[Blade]: @include("hello", ["name" => "John"])')); unlink(resource_path('views/hello.blade.php')); } public function testPreprocessMethodExpandsShortcode() { - $this->assertEquals('', BladeDownProcessor::preprocess('[Blade]: {{ $foo }}')); + $this->assertSame('', BladeDownProcessor::preprocess('[Blade]: {{ $foo }}')); } public function testProcessMethodRendersShortcode() { - $this->assertEquals('Hello World!', BladeDownProcessor::postprocess('', ['foo' => 'Hello World!'])); + $this->assertSame('Hello World!', BladeDownProcessor::postprocess('', ['foo' => 'Hello World!'])); } } diff --git a/packages/framework/tests/Feature/Services/BuildTaskServiceTest.php b/packages/framework/tests/Feature/Services/BuildTaskServiceTest.php index 5a78a5ebb06..61e067b1031 100644 --- a/packages/framework/tests/Feature/Services/BuildTaskServiceTest.php +++ b/packages/framework/tests/Feature/Services/BuildTaskServiceTest.php @@ -55,7 +55,7 @@ public function testGetPostBuildTasksReturnsArrayMergedWithConfig() $service = $this->makeService(); $tasks = $service->getRegisteredTasks(); - $this->assertEquals(1, count(array_keys($tasks, SecondBuildTask::class))); + $this->assertSame(1, count(array_keys($tasks, SecondBuildTask::class))); } public function testGetPostBuildTasksMergesDuplicateKeys() @@ -66,7 +66,7 @@ public function testGetPostBuildTasksMergesDuplicateKeys() $service = $this->makeService(); $tasks = $service->getRegisteredTasks(); - $this->assertEquals(1, count(array_keys($tasks, TestBuildTask::class))); + $this->assertSame(1, count(array_keys($tasks, TestBuildTask::class))); } public function testRunPostBuildTasksRunsConfiguredTasks() @@ -83,15 +83,13 @@ public function testRunPostBuildTasksRunsConfiguredTasks() public function testExceptionHandlerShowsErrorMessageAndExitsWithCode1WithoutThrowingException() { - $return = (new class extends BuildTask + $this->assertSame(1, (new class extends BuildTask { public function handle(): void { throw new Exception('foo', 1); } - })->run(); - - $this->assertEquals(1, $return); + })->run()); } public function testFindTasksInAppDirectoryMethodDiscoversTasksInAppDirectory() diff --git a/packages/framework/tests/Feature/Services/DocumentationSidebarTest.php b/packages/framework/tests/Feature/Services/DocumentationSidebarTest.php index a1971486787..9aa991223f8 100644 --- a/packages/framework/tests/Feature/Services/DocumentationSidebarTest.php +++ b/packages/framework/tests/Feature/Services/DocumentationSidebarTest.php @@ -121,7 +121,7 @@ public function testSidebarItemPriorityCanBeSetInFrontMatter() { $this->makePage('foo', ['navigation.priority' => 25]); - $this->assertEquals(25, NavigationMenuGenerator::handle(DocumentationSidebar::class)->getItems()->first()->getPriority()); + $this->assertSame(25, DocumentationSidebar::create()->items->first()->priority); } public function testSidebarItemPrioritySetInConfigOverridesFrontMatter() @@ -130,7 +130,7 @@ public function testSidebarItemPrioritySetInConfigOverridesFrontMatter() Config::set('docs.sidebar.order', ['foo']); - $this->assertEquals(25, NavigationMenuGenerator::handle(DocumentationSidebar::class)->getItems()->first()->getPriority()); + $this->assertSame(25, DocumentationSidebar::create()->items->first()->priority); } public function testSidebarPrioritiesCanBeSetInBothFrontMatterAndConfig() @@ -160,9 +160,7 @@ public function testGroupCanBeSetInFrontMatter() { $this->makePage('foo', ['navigation.group' => 'bar']); - /** @var NavigationItem $item */ - $item = collect(NavigationMenuGenerator::handle(DocumentationSidebar::class)->getItems()->first()->getItems())->first(); - $this->assertSame('bar', $item->getPage()->navigationMenuGroup()); + $this->assertSame('bar', DocumentationSidebar::create()->items->first()->getGroup()); } public function testHasGroupsReturnsFalseWhenThereAreNoGroups() @@ -191,7 +189,91 @@ public function testHasGroupsReturnsTrueWhenThereAreMultipleGroupsMixedWithDefau $this->makePage('bar', ['navigation.group' => 'baz']); $this->makePage('baz'); - $this->assertTrue(NavigationMenuGenerator::handle(DocumentationSidebar::class)->hasGroups()); + $this->assertTrue(DocumentationSidebar::create()->hasGroups()); + } + + public function testGetGroupsReturnsEmptyArrayWhenThereAreNoGroups() + { + $this->assertSame([], DocumentationSidebar::create()->getGroups()); + } + + public function testGetGroupsReturnsArrayOfGroupsWhenThereAreGroups() + { + $this->makePage('foo', ['navigation.group' => 'bar']); + + $this->assertSame(['bar'], DocumentationSidebar::create()->getGroups()); + } + + public function testGetGroupsReturnsArrayWithNoDuplicates() + { + $this->makePage('foo', ['navigation.group' => 'bar']); + $this->makePage('bar', ['navigation.group' => 'bar']); + $this->makePage('baz', ['navigation.group' => 'baz']); + + $this->assertSame(['bar', 'baz'], DocumentationSidebar::create()->getGroups()); + } + + public function testGroupsAreSortedByLowestFoundPriorityInEachGroup() + { + $this->makePage('foo', ['navigation.group' => 'bar', 'navigation.priority' => 100]); + $this->makePage('bar', ['navigation.group' => 'bar', 'navigation.priority' => 200]); + $this->makePage('baz', ['navigation.group' => 'baz', 'navigation.priority' => 10]); + + $this->assertSame(['baz', 'bar'], DocumentationSidebar::create()->getGroups()); + } + + public function testGetItemsInGroupReturnsEmptyCollectionWhenThereAreNoItems() + { + $this->assertEquals(collect(), DocumentationSidebar::create()->getItemsInGroup('foo')); + } + + public function testGetItemsInGroupReturnsCollectionOfItemsInGroup() + { + $this->makePage('foo', ['navigation.group' => 'bar']); + $this->makePage('bar', ['navigation.group' => 'bar']); + $this->makePage('baz', ['navigation.group' => 'baz']); + + $this->assertEquals( + collect([ + NavItem::fromRoute(Routes::get('docs/bar'), priority: 999), + NavItem::fromRoute(Routes::get('docs/foo'), priority: 999), + ]), + DocumentationSidebar::create()->getItemsInGroup('bar') + ); + + $this->assertEquals( + collect([ + NavItem::fromRoute(Routes::get('docs/baz'), priority: 999), + ]), + DocumentationSidebar::create()->getItemsInGroup('baz') + ); + } + + public function testGetItemsInGroupNormalizesGroupNameToSlugFormat() + { + $this->makePage('a', ['navigation.group' => 'foo bar']); + $this->makePage('b', ['navigation.group' => 'Foo Bar']); + $this->makePage('c', ['navigation.group' => 'foo-bar']); + + $this->assertEquals( + collect([ + NavItem::fromRoute(Routes::get('docs/a'), priority: 999), + NavItem::fromRoute(Routes::get('docs/b'), priority: 999), + NavItem::fromRoute(Routes::get('docs/c'), priority: 999), + ]), + DocumentationSidebar::create()->getItemsInGroup('Foo bar') + ); + } + + public function testGetItemsInGroupDoesNotIncludeItemsWithHiddenFrontMatter() + { + $this->makePage('a', ['navigation.hidden' => true, 'navigation.group' => 'foo']); + $this->makePage('b', ['navigation.group' => 'foo']); + + $this->assertEquals( + collect([NavItem::fromRoute(Routes::get('docs/b'), priority: 999)]), + DocumentationSidebar::create()->getItemsInGroup('foo') + ); } public function testGetItemsInGroupDoesNotIncludeDocsIndex() @@ -252,12 +334,10 @@ public function testIsGroupActiveReturnsTrueFirstGroupOfIndexPage() $this->makePage('baz', ['navigation.group' => 'baz']); Render::setPage(DocumentationPage::get('index')); - $mainNavigationMenu2 = NavigationMenuGenerator::handle(DocumentationSidebar::class); - $this->assertTrue('bar' === $this->getGroupKey($mainNavigationMenu2)); - $mainNavigationMenu1 = NavigationMenuGenerator::handle(DocumentationSidebar::class); - $this->assertFalse('foo' === $this->getGroupKey($mainNavigationMenu1)); - $mainNavigationMenu = NavigationMenuGenerator::handle(DocumentationSidebar::class); - $this->assertFalse('baz' === $this->getGroupKey($mainNavigationMenu)); + + $this->assertTrue(DocumentationSidebar::create()->isGroupActive('bar')); + $this->assertFalse(DocumentationSidebar::create()->isGroupActive('foo')); + $this->assertFalse(DocumentationSidebar::create()->isGroupActive('baz')); } public function testIsGroupActiveReturnsTrueFirstSortedGroupOfIndexPage() @@ -268,12 +348,10 @@ public function testIsGroupActiveReturnsTrueFirstSortedGroupOfIndexPage() $this->makePage('baz', ['navigation.group' => 'baz', 'navigation.priority' => 3]); Render::setPage(DocumentationPage::get('index')); - $mainNavigationMenu2 = NavigationMenuGenerator::handle(DocumentationSidebar::class); - $this->assertTrue('foo' === $this->getGroupKey($mainNavigationMenu2)); - $mainNavigationMenu1 = NavigationMenuGenerator::handle(DocumentationSidebar::class); - $this->assertFalse('bar' === $this->getGroupKey($mainNavigationMenu1)); - $mainNavigationMenu = NavigationMenuGenerator::handle(DocumentationSidebar::class); - $this->assertFalse('baz' === $this->getGroupKey($mainNavigationMenu)); + + $this->assertTrue(DocumentationSidebar::create()->isGroupActive('foo')); + $this->assertFalse(DocumentationSidebar::create()->isGroupActive('bar')); + $this->assertFalse(DocumentationSidebar::create()->isGroupActive('baz')); } public function testAutomaticIndexPageGroupExpansionRespectsCustomNavigationMenuSettings() @@ -284,12 +362,28 @@ public function testAutomaticIndexPageGroupExpansionRespectsCustomNavigationMenu $this->makePage('baz', ['navigation.group' => 'baz', 'navigation.priority' => 3]); Render::setPage(DocumentationPage::get('index')); - $mainNavigationMenu2 = NavigationMenuGenerator::handle(DocumentationSidebar::class); - $this->assertFalse('foo' === $this->getGroupKey($mainNavigationMenu2)); - $mainNavigationMenu1 = NavigationMenuGenerator::handle(DocumentationSidebar::class); - $this->assertFalse('bar' === $this->getGroupKey($mainNavigationMenu1)); - $mainNavigationMenu = NavigationMenuGenerator::handle(DocumentationSidebar::class); - $this->assertTrue('baz' === $this->getGroupKey($mainNavigationMenu)); + + $this->assertFalse(DocumentationSidebar::create()->isGroupActive('foo')); + $this->assertFalse(DocumentationSidebar::create()->isGroupActive('bar')); + $this->assertTrue(DocumentationSidebar::create()->isGroupActive('baz')); + } + + public function testMakeGroupTitleTurnsGroupKeyIntoTitle() + { + $this->assertSame('Hello World', DocumentationSidebar::create()->makeGroupTitle('hello world')); + $this->assertSame('Hello World', DocumentationSidebar::create()->makeGroupTitle('hello-world')); + $this->assertSame('Hello World', DocumentationSidebar::create()->makeGroupTitle('hello_world')); + $this->assertSame('Hello World', DocumentationSidebar::create()->makeGroupTitle('helloWorld')); + } + + public function testMakeGroupTitleUsesConfiguredSidebarGroupLabelsWhenAvailable() + { + Config::set('docs.sidebar_group_labels', [ + 'example' => 'Hello world!', + ]); + + $this->assertSame('Hello world!', DocumentationSidebar::create()->makeGroupTitle('example')); + $this->assertSame('Default', DocumentationSidebar::create()->makeGroupTitle('default')); } public function testCanHaveMultipleGroupedPagesWithTheSameNameLabels() @@ -356,6 +450,7 @@ public function testIndexPageAddedToSidebarWhenItIsTheOnlyPage() public function testIndexPageNotAddedToSidebarWhenOtherPagesExist() { $this->createTestFiles(1); + Filesystem::touch('_docs/index.md'); $sidebar = NavigationMenuGenerator::handle(DocumentationSidebar::class); @@ -369,15 +464,15 @@ public function testIndexPageNotAddedToSidebarWhenOtherPagesExist() protected function createTestFiles(int $count = 5): void { for ($i = 0; $i < $count; $i++) { - Filesystem::touch('_docs/test-'.$i.'.md'); + Filesystem::touch("_docs/test-{$i}.md"); } } - protected function makePage(string $name, ?array $matter = null): void + protected function makePage(string $name, array $matter = []): void { file_put_contents( - Hyde::path('_docs/'.$name.'.md'), - (new ConvertsArrayToFrontMatter)->execute($matter ?? []) + Hyde::path("_docs/{$name}.md"), + (new ConvertsArrayToFrontMatter)->execute($matter) ); } diff --git a/packages/framework/tests/Feature/Services/HydeSmartDocsTest.php b/packages/framework/tests/Feature/Services/HydeSmartDocsTest.php index 0ee6fdec3bd..cdf2540614a 100644 --- a/packages/framework/tests/Feature/Services/HydeSmartDocsTest.php +++ b/packages/framework/tests/Feature/Services/HydeSmartDocsTest.php @@ -46,24 +46,27 @@ public function testClassCanHandleEmptyDocument() $this->assertEquals('', $article->renderBody()); } + public function testRenderedContentIsHtmlable() + { + $article = $this->makeArticle("# Header Content \n\n Body Content"); + + $this->assertInstanceOf(HtmlString::class, $article->renderHeader()); + $this->assertInstanceOf(HtmlString::class, $article->renderBody()); + $this->assertInstanceOf(HtmlString::class, $article->renderFooter()); + } + public function testCreateHelperCreatesNewInstanceAndProcessesIt() { $article = $this->makeArticle(); $this->assertInstanceOf(SemanticDocumentationArticle::class, $article); - $this->assertSame( - '

Hello world.

', - $article->renderBody()->toHtml() - ); + $this->assertEquals('

Hello world.

', $article->renderBody()); } public function testRenderHeaderReturnsTheExtractedHeader() { - $this->assertSame( - '

Foo

', - $this->makeArticle()->renderHeader()->toHtml() - ); + $this->assertSame('

Foo

', $this->makeArticle()->renderHeader()->toHtml()); } public function testRenderHeaderReturnsTheExtractedHeaderWithVaryingNewlines() @@ -108,10 +111,7 @@ public function testRenderBodyReturnsTheExtractedBodyWithVaryingNewlines() public function testRenderFooterIsEmptyByDefault() { - $this->assertSame( - '', - $this->makeArticle()->renderFooter()->toHtml() - ); + $this->assertSame('', $this->makeArticle()->renderFooter()->toHtml()); } public function testAddDynamicHeaderContentAddsSourceLinkWhenConditionsAreMet() @@ -119,7 +119,7 @@ public function testAddDynamicHeaderContentAddsSourceLinkWhenConditionsAreMet() config(['docs.source_file_location_base' => 'https://example.com/']); config(['docs.edit_source_link_position' => 'header']); - $this->assertEqualsIgnoringNewlinesAndIndentation(<<<'HTML' + $this->assertSameIgnoringNewlinesAndIndentation(<<<'HTML'

Foo

HTML, $this->makeArticle()->renderHeader()); } @@ -129,7 +129,7 @@ public function testEditSourceLinkIsAddedToFooterWhenConditionsAreMet() config(['docs.source_file_location_base' => 'https://example.com/']); config(['docs.edit_source_link_position' => 'footer']); - $this->assertEqualsIgnoringNewlinesAndIndentation(<<<'HTML' + $this->assertSameIgnoringNewlinesAndIndentation(<<<'HTML' HTML, $this->makeArticle()->renderFooter()); } @@ -141,11 +141,11 @@ public function testEditSourceLinkCanBeAddedToBothHeaderAndFooter() $article = $this->makeArticle(); - $this->assertEqualsIgnoringNewlinesAndIndentation(<<<'HTML' + $this->assertSameIgnoringNewlinesAndIndentation(<<<'HTML'

Foo

HTML, $article->renderHeader()); - $this->assertEqualsIgnoringNewlinesAndIndentation(<<<'HTML' + $this->assertSameIgnoringNewlinesAndIndentation(<<<'HTML' HTML, $article->renderFooter()); } @@ -156,7 +156,7 @@ public function testEditSourceLinkTextCanBeCustomizedInHeader() config(['docs.edit_source_link_position' => 'both']); config(['docs.edit_source_link_text' => 'Go to Source']); - $this->assertEqualsIgnoringNewlinesAndIndentation(<<<'HTML' + $this->assertSameIgnoringNewlinesAndIndentation(<<<'HTML'

Foo

HTML, $this->makeArticle()->renderHeader()); } @@ -167,7 +167,7 @@ public function testEditSourceLinkTextCanBeCustomizedInFooter() config(['docs.edit_source_link_position' => 'both']); config(['docs.edit_source_link_text' => 'Go to Source']); - $this->assertEqualsIgnoringNewlinesAndIndentation(<<<'HTML' + $this->assertSameIgnoringNewlinesAndIndentation(<<<'HTML' HTML, $this->makeArticle()->renderFooter()); } @@ -228,9 +228,9 @@ protected function makePage(string $sourceFileContents = "# Foo\n\nHello world." return DocumentationPage::parse('foo'); } - protected function assertEqualsIgnoringNewlinesAndIndentation(string $expected, HtmlString $actual): void + protected function assertSameIgnoringNewlinesAndIndentation(string $expected, HtmlString $actual): void { - $this->assertEquals( + $this->assertSame( $this->stripNewlinesAndIndentation($expected), $this->stripNewlinesAndIndentation($actual->toHtml()), ); diff --git a/packages/framework/tests/Feature/Services/RssFeedServiceTest.php b/packages/framework/tests/Feature/Services/RssFeedServiceTest.php index 94f6bc0698e..7e5409e722c 100644 --- a/packages/framework/tests/Feature/Services/RssFeedServiceTest.php +++ b/packages/framework/tests/Feature/Services/RssFeedServiceTest.php @@ -1,9 +1,12 @@ assertInstanceOf('SimpleXMLElement', $service->getXmlElement()); + $this->assertInstanceOf(SimpleXMLElement::class, $service->getXmlElement()); } public function testXmlRootElementIsSetToRss20() @@ -32,7 +35,7 @@ public function testXmlRootElementIsSetToRss20() public function testXmlElementHasChannelElement() { $service = new RssFeedGenerator(); - $this->assertTrue(property_exists($service->getXmlElement(), 'channel')); + $this->assertObjectHasProperty('channel', $service->getXmlElement()); } public function testXmlChannelElementHasRequiredElements() @@ -42,9 +45,10 @@ public function testXmlChannelElementHasRequiredElements() config(['hyde.rss.description' => 'Test Blog RSS Feed']); $service = new RssFeedGenerator(); - $this->assertTrue(property_exists($service->getXmlElement()->channel, 'title')); - $this->assertTrue(property_exists($service->getXmlElement()->channel, 'link')); - $this->assertTrue(property_exists($service->getXmlElement()->channel, 'description')); + + $this->assertObjectHasProperty('title', $service->getXmlElement()->channel); + $this->assertObjectHasProperty('link', $service->getXmlElement()->channel); + $this->assertObjectHasProperty('description', $service->getXmlElement()->channel); $this->assertEquals('Test Blog', $service->getXmlElement()->channel->title); $this->assertEquals('https://example.com', $service->getXmlElement()->channel->link); @@ -56,14 +60,16 @@ public function testXmlChannelElementHasAdditionalElements() config(['hyde.url' => 'https://example.com']); $service = new RssFeedGenerator(); - $this->assertTrue(property_exists($service->getXmlElement()->channel, 'link')); + + $this->assertObjectHasProperty('link', $service->getXmlElement()->channel); $this->assertEquals('https://example.com', $service->getXmlElement()->channel->link); $this->assertEquals('https://example.com/feed.xml', - $service->getXmlElement()->channel->children('atom', true)->link->attributes()->href); + $service->getXmlElement()->channel->children('atom', true)->link->attributes()->href + ); - $this->assertTrue(property_exists($service->getXmlElement()->channel, 'language')); - $this->assertTrue(property_exists($service->getXmlElement()->channel, 'generator')); - $this->assertTrue(property_exists($service->getXmlElement()->channel, 'lastBuildDate')); + $this->assertObjectHasProperty('language', $service->getXmlElement()->channel); + $this->assertObjectHasProperty('generator', $service->getXmlElement()->channel); + $this->assertObjectHasProperty('lastBuildDate', $service->getXmlElement()->channel); } public function testXmlChannelDataCanBeCustomized() @@ -105,14 +111,16 @@ public function testMarkdownBlogPostsAreAddedToRssFeedThroughAutodiscovery() $this->assertCount(1, $service->getXmlElement()->channel->item); $item = $service->getXmlElement()->channel->item[0]; + $this->assertEquals('RSS', $item->title); $this->assertEquals('RSS description', $item->description); $this->assertEquals('https://example.com/posts/rss.html', $item->link); + $this->assertEquals(date(DATE_RSS, strtotime('2022-05-19T10:15:30+00:00')), $item->pubDate); $this->assertEquals('Hyde', $item->children('dc', true)->creator); $this->assertEquals('test', $item->category); - $this->assertTrue(property_exists($item, 'enclosure')); + $this->assertObjectHasProperty('enclosure', $item); $this->assertEquals('https://example.com/media/rss-test.jpg', $item->enclosure->attributes()->url); $this->assertEquals('image/jpeg', $item->enclosure->attributes()->type); $this->assertEquals('8', $item->enclosure->attributes()->length); @@ -135,8 +143,9 @@ public function testGenerateFeedHelperReturnsXmlString() public function testCanGenerateFeedHelperReturnsTrueIfHydeHasBaseUrl() { config(['hyde.url' => 'foo']); + $this->file('_posts/foo.md'); - $this->assertTrue(Features::hasRss()); + $this->assertTrue(Features::rss()); } public function testCanGenerateFeedHelperReturnsFalseIfHydeDoesNotHaveBaseUrl() @@ -150,6 +159,7 @@ public function testCanGenerateFeedHelperReturnsFalseIfFeedsAreDisabledInConfig( { config(['hyde.url' => 'foo']); config(['hyde.rss.enabled' => false]); - $this->assertFalse(Features::hasRss()); + + $this->assertFalse(Features::rss()); } } diff --git a/packages/framework/tests/Feature/Services/SitemapServiceTest.php b/packages/framework/tests/Feature/Services/SitemapServiceTest.php index d33a3830a68..d54b9711dfa 100644 --- a/packages/framework/tests/Feature/Services/SitemapServiceTest.php +++ b/packages/framework/tests/Feature/Services/SitemapServiceTest.php @@ -1,9 +1,12 @@ assertInstanceOf('SimpleXMLElement', $service->getXmlElement()); + $this->assertInstanceOf(SimpleXMLElement::class, $service->getXmlElement()); } public function testGenerateAddsDefaultPagesToXml() @@ -95,6 +99,7 @@ public function testGetXmlReturnsXmlString() { $service = new SitemapGenerator(); $service->generate(); + $xml = $service->getXml(); $this->assertIsString($xml); @@ -113,12 +118,14 @@ public function testUrlItemIsGeneratedCorrectly() { config(['hyde.pretty_urls' => false]); config(['hyde.url' => 'https://example.com']); + Filesystem::touch('_pages/0-test.blade.php'); $service = new SitemapGenerator(); $service->generate(); $url = $service->getXmlElement()->url[0]; + $this->assertEquals('https://example.com/0-test.html', $url->loc); $this->assertEquals('daily', $url->changefreq); $this->assertTrue(isset($url->lastmod)); @@ -130,6 +137,7 @@ public function testUrlItemIsGeneratedWithPrettyUrlsIfEnabled() { config(['hyde.pretty_urls' => true]); config(['hyde.url' => 'https://example.com']); + Filesystem::touch('_pages/0-test.blade.php'); $service = new SitemapGenerator(); @@ -144,6 +152,7 @@ public function testUrlItemIsGeneratedWithPrettyUrlsIfEnabled() public function testAllRouteTypesAreDiscovered() { config(['hyde.url' => 'foo']); + Filesystem::unlink(['_pages/index.blade.php', '_pages/404.blade.php']); $this->withoutDocumentationSearch(); diff --git a/packages/framework/tests/Feature/Services/ValidationServiceTest.php b/packages/framework/tests/Feature/Services/ValidationServiceTest.php index e6fbe88846e..d3210b43d1c 100644 --- a/packages/framework/tests/Feature/Services/ValidationServiceTest.php +++ b/packages/framework/tests/Feature/Services/ValidationServiceTest.php @@ -11,8 +11,6 @@ use Hyde\Testing\TestCase; /** - * Class ValidationServiceTest. - * * @covers \Hyde\Framework\Services\ValidationService * @covers \Hyde\Support\Models\ValidationResult * @@ -29,12 +27,12 @@ protected function setUp(): void $this->service = new ValidationService(); } - // Rather meta, but lets us know that the method assertions are correct, and gives us test coverage - protected function test(string $method, int $expectedStatusCode) + protected function testMethod(string $method, int $expectedStatusCode): void { $result = $this->service->run($method); + $this->assertInstanceOf(ValidationResult::class, $result); - $this->assertEquals($expectedStatusCode, $result->statusCode()); + $this->assertSame($expectedStatusCode, $result->statusCode()); } public function testChecksReturnsAnArrayOfValidationCheckMethods() @@ -51,112 +49,133 @@ public function testChecksReturnsAnArrayOfValidationCheckMethods() public function testCheckValidatorsCanRun() { - $this->test('check_validators_can_run', 0); + $this->testMethod('check_validators_can_run', 0); } public function testCheckSiteHasA404PageCanPass() { - $this->test('check_site_has_a_404_page', 0); + $this->testMethod('check_site_has_a_404_page', 0); } public function testCheckSiteHasA404PageCanFail() { rename(Hyde::path('_pages/404.blade.php'), Hyde::path('_pages/404.blade.php.bak')); - $this->test('check_site_has_a_404_page', 2); + + $this->testMethod('check_site_has_a_404_page', 2); + rename(Hyde::path('_pages/404.blade.php.bak'), Hyde::path('_pages/404.blade.php')); } public function testCheckDocumentationSiteHasAnIndexPageCanPass() { touch('_docs/index.md'); - $this->test('check_documentation_site_has_an_index_page', 0); + + $this->testMethod('check_documentation_site_has_an_index_page', 0); + unlink('_docs/index.md'); } public function testCheckDocumentationSiteHasAnIndexPageCanPassWithWarningWhenOnlyFindingReadme() { touch('_docs/README.md'); - $this->test('check_documentation_site_has_an_index_page', 2); + + $this->testMethod('check_documentation_site_has_an_index_page', 2); + $this->assertStringContainsString('a _docs/readme.md file was found', - $this->service->run('check_documentation_site_has_an_index_page')->tip()); + $this->service->run('check_documentation_site_has_an_index_page')->tip() + ); + unlink('_docs/README.md'); } public function testCheckDocumentationSiteHasAnIndexPageCanFail() { touch('_docs/foo.md'); - $this->test('check_documentation_site_has_an_index_page', 2); + + $this->testMethod('check_documentation_site_has_an_index_page', 2); + unlink('_docs/foo.md'); } public function testCheckDocumentationSiteHasAnIndexPageBeSkipped() { - $this->test('check_documentation_site_has_an_index_page', 1); + $this->testMethod('check_documentation_site_has_an_index_page', 1); } public function testCheckSiteHasAnIndexPageCanPass() { - $this->test('check_site_has_an_index_page', 0); + $this->testMethod('check_site_has_an_index_page', 0); } public function testCheckSiteHasAnIndexPageCanFail() { rename(Hyde::path('_pages/index.blade.php'), Hyde::path('_pages/index.blade.php.bak')); - $this->test('check_site_has_an_index_page', 2); + + $this->testMethod('check_site_has_an_index_page', 2); + rename(Hyde::path('_pages/index.blade.php.bak'), Hyde::path('_pages/index.blade.php')); } public function testCheckSiteHasAnAppCssStylesheetCanPass() { - $this->test('check_site_has_an_app_css_stylesheet', 0); + $this->testMethod('check_site_has_an_app_css_stylesheet', 0); } public function testCheckSiteHasAnAppCssStylesheetCanFail() { rename(Hyde::path('_media/app.css'), Hyde::path('_media/app.css.bak')); - $this->test('check_site_has_an_app_css_stylesheet', 2); + + $this->testMethod('check_site_has_an_app_css_stylesheet', 2); + rename(Hyde::path('_media/app.css.bak'), Hyde::path('_media/app.css')); } public function testCheckSiteHasABaseUrlSetCanPass() { config(['hyde.url' => 'https://example.com']); - $this->test('check_site_has_a_base_url_set', 0); + + $this->testMethod('check_site_has_a_base_url_set', 0); } public function testCheckSiteHasABaseUrlSetCanFail() { config(['hyde.url' => null]); - $this->test('check_site_has_a_base_url_set', 2); + + $this->testMethod('check_site_has_a_base_url_set', 2); } public function testCheckATorchlightApiTokenIsSetCanSkip() { config(['hyde.features' => []]); - $this->test('check_a_torchlight_api_token_is_set', 1); + + $this->testMethod('check_a_torchlight_api_token_is_set', 1); } public function testCheckATorchlightApiTokenIsSetCanPass() { config(['torchlight.token' => '12345']); - $this->test('check_a_torchlight_api_token_is_set', 0); + + $this->testMethod('check_a_torchlight_api_token_is_set', 0); } public function testCheckATorchlightApiTokenIsSetCanFail() { config(['torchlight.token' => null]); - $this->test('check_a_torchlight_api_token_is_set', 2); + + $this->testMethod('check_a_torchlight_api_token_is_set', 2); } public function testCheckForConflictsBetweenBladeAndMarkdownPagesCanPass() { - $this->test('check_for_conflicts_between_blade_and_markdown_pages', 0); + $this->testMethod('check_for_conflicts_between_blade_and_markdown_pages', 0); } public function testCheckForConflictsBetweenBladeAndMarkdownPagesCanFail() { Filesystem::touch('_pages/index.md'); - $this->test('check_for_conflicts_between_blade_and_markdown_pages', 2); + + $this->testMethod('check_for_conflicts_between_blade_and_markdown_pages', 2); + Filesystem::unlink('_pages/index.md'); } @@ -165,14 +184,16 @@ public function testCheckForConflictsBetweenBladeAndMarkdownPagesCanFail() public function testValidationResultMessageReturnsMessage() { $result = new ValidationResult(); - $this->assertEquals('Generic check', $result->message()); + $this->assertSame('Generic check', $result->message()); } public function testValidationResultPassedReturnsTrueWhenPassedIsTrue() { $result = new ValidationResult(); + $result->pass(); $this->assertTrue($result->passed()); + $result->fail(); $this->assertFalse($result->passed()); } @@ -180,8 +201,10 @@ public function testValidationResultPassedReturnsTrueWhenPassedIsTrue() public function testValidationResultFailedReturnsTrueWhenPassedIsFalse() { $result = new ValidationResult(); + $result->pass(); $this->assertFalse($result->failed()); + $result->fail(); $this->assertTrue($result->failed()); } @@ -189,16 +212,22 @@ public function testValidationResultFailedReturnsTrueWhenPassedIsFalse() public function testValidationResultSkippedReturnsTrueWhenSkippedIsTrue() { $result = new ValidationResult(); + $this->assertFalse($result->skipped()); + $result->skip(); + $this->assertTrue($result->skipped()); } public function testValidationResultTipReturnsMessageWhenSet() { $result = new ValidationResult(); + $this->assertFalse($result->tip()); + $result->withTip('foo'); - $this->assertEquals('foo', $result->tip()); + + $this->assertSame('foo', $result->tip()); } } diff --git a/packages/framework/tests/Feature/SourceDirectoriesCanBeChangedTest.php b/packages/framework/tests/Feature/SourceDirectoriesCanBeChangedTest.php index 5be594d3a8c..59deaf470ab 100644 --- a/packages/framework/tests/Feature/SourceDirectoriesCanBeChangedTest.php +++ b/packages/framework/tests/Feature/SourceDirectoriesCanBeChangedTest.php @@ -13,9 +13,6 @@ use Hyde\Pages\MarkdownPost; use Hyde\Testing\TestCase; -/** - * Class SourceDirectoriesCanBeChangedTest. - */ class SourceDirectoriesCanBeChangedTest extends TestCase { public static function tearDownAfterClass(): void @@ -27,11 +24,11 @@ public static function tearDownAfterClass(): void public function testBaselines() { - $this->assertEquals('_pages', HtmlPage::sourceDirectory()); - $this->assertEquals('_pages', BladePage::sourceDirectory()); - $this->assertEquals('_pages', MarkdownPage::sourceDirectory()); - $this->assertEquals('_posts', MarkdownPost::sourceDirectory()); - $this->assertEquals('_docs', DocumentationPage::sourceDirectory()); + $this->assertSame('_pages', HtmlPage::sourceDirectory()); + $this->assertSame('_pages', BladePage::sourceDirectory()); + $this->assertSame('_pages', MarkdownPage::sourceDirectory()); + $this->assertSame('_posts', MarkdownPost::sourceDirectory()); + $this->assertSame('_docs', DocumentationPage::sourceDirectory()); } public function testSourceDirectoriesCanBeChangedProgrammatically() @@ -42,11 +39,11 @@ public function testSourceDirectoriesCanBeChangedProgrammatically() MarkdownPost::setSourceDirectory('.source/posts'); DocumentationPage::setSourceDirectory('.source/docs'); - $this->assertEquals('.source/pages', HtmlPage::sourceDirectory()); - $this->assertEquals('.source/pages', BladePage::sourceDirectory()); - $this->assertEquals('.source/pages', MarkdownPage::sourceDirectory()); - $this->assertEquals('.source/posts', MarkdownPost::sourceDirectory()); - $this->assertEquals('.source/docs', DocumentationPage::sourceDirectory()); + $this->assertSame('.source/pages', HtmlPage::sourceDirectory()); + $this->assertSame('.source/pages', BladePage::sourceDirectory()); + $this->assertSame('.source/pages', MarkdownPage::sourceDirectory()); + $this->assertSame('.source/posts', MarkdownPost::sourceDirectory()); + $this->assertSame('.source/docs', DocumentationPage::sourceDirectory()); } public function testSourceDirectoriesCanBeChangedInConfig() @@ -61,21 +58,18 @@ public function testSourceDirectoriesCanBeChangedInConfig() (new HydeServiceProvider($this->app))->register(); - $this->assertEquals('.source/pages', HtmlPage::sourceDirectory()); - $this->assertEquals('.source/pages', BladePage::sourceDirectory()); - $this->assertEquals('.source/pages', MarkdownPage::sourceDirectory()); - $this->assertEquals('.source/posts', MarkdownPost::sourceDirectory()); - $this->assertEquals('.source/docs', DocumentationPage::sourceDirectory()); + $this->assertSame('.source/pages', HtmlPage::sourceDirectory()); + $this->assertSame('.source/pages', BladePage::sourceDirectory()); + $this->assertSame('.source/pages', MarkdownPage::sourceDirectory()); + $this->assertSame('.source/posts', MarkdownPost::sourceDirectory()); + $this->assertSame('.source/docs', DocumentationPage::sourceDirectory()); } public function testBuildServiceRecognizesChangedDirectory() { MarkdownPost::setSourceDirectory('_source/posts'); - $this->assertEquals( - '_source/posts', - MarkdownPost::sourceDirectory() - ); + $this->assertSame('_source/posts', MarkdownPost::sourceDirectory()); } public function testAutodiscoveryDiscoversPostsInCustomDirectory() @@ -85,10 +79,7 @@ public function testAutodiscoveryDiscoversPostsInCustomDirectory() MarkdownPost::setSourceDirectory('_source'); - $this->assertEquals( - ['test'], - MarkdownPost::files() - ); + $this->assertSame(['test'], MarkdownPost::files()); } public function testAutodiscoveryDiscoversPostsInCustomSubdirectory() @@ -98,9 +89,6 @@ public function testAutodiscoveryDiscoversPostsInCustomSubdirectory() MarkdownPost::setSourceDirectory('_source/posts'); - $this->assertEquals( - ['test'], - MarkdownPost::files() - ); + $this->assertSame(['test'], MarkdownPost::files()); } } diff --git a/packages/framework/tests/Feature/SourceFileParserTest.php b/packages/framework/tests/Feature/SourceFileParserTest.php index cf099e08d59..4593096fc51 100644 --- a/packages/framework/tests/Feature/SourceFileParserTest.php +++ b/packages/framework/tests/Feature/SourceFileParserTest.php @@ -23,8 +23,9 @@ public function testBladePageParser() $parser = new SourceFileParser(BladePage::class, 'foo'); $page = $parser->get(); + $this->assertInstanceOf(BladePage::class, $page); - $this->assertEquals('foo', $page->identifier); + $this->assertSame('foo', $page->identifier); } public function testMarkdownPageParser() @@ -33,10 +34,12 @@ public function testMarkdownPageParser() $parser = new SourceFileParser(MarkdownPage::class, 'foo'); $page = $parser->get(); + $this->assertInstanceOf(MarkdownPage::class, $page); - $this->assertEquals('foo', $page->identifier); + $this->assertSame('foo', $page->identifier); + $this->assertSame('Foo Bar Baz', $page->title); + $this->assertSame('# Foo Bar', $page->markdown->body()); $this->assertEquals('# Foo Bar', $page->markdown); - $this->assertEquals('Foo Bar Baz', $page->title); } public function testMarkdownPostParser() @@ -45,10 +48,12 @@ public function testMarkdownPostParser() $parser = new SourceFileParser(MarkdownPost::class, 'foo'); $page = $parser->get(); + $this->assertInstanceOf(MarkdownPost::class, $page); - $this->assertEquals('foo', $page->identifier); + $this->assertSame('foo', $page->identifier); + $this->assertSame('Foo Bar Baz', $page->title); + $this->assertSame('# Foo Bar', $page->markdown->body()); $this->assertEquals('# Foo Bar', $page->markdown); - $this->assertEquals('Foo Bar Baz', $page->title); } public function testDocumentationPageParser() @@ -57,10 +62,12 @@ public function testDocumentationPageParser() $parser = new SourceFileParser(DocumentationPage::class, 'foo'); $page = $parser->get(); + $this->assertInstanceOf(DocumentationPage::class, $page); - $this->assertEquals('foo', $page->identifier); + $this->assertSame('foo', $page->identifier); + $this->assertSame('Foo Bar Baz', $page->title); + $this->assertSame('# Foo Bar', $page->markdown->body()); $this->assertEquals('# Foo Bar', $page->markdown); - $this->assertEquals('Foo Bar Baz', $page->title); } public function testHtmlPageParser() @@ -69,29 +76,33 @@ public function testHtmlPageParser() $parser = new SourceFileParser(HtmlPage::class, 'foo'); $page = $parser->get(); + $this->assertInstanceOf(HtmlPage::class, $page); - $this->assertEquals('foo', $page->identifier); - $this->assertEquals('

Foo Bar

', $page->contents()); + $this->assertSame('foo', $page->identifier); + $this->assertSame('

Foo Bar

', $page->contents()); } public function testParsedPageIsRunThroughDynamicConstructor() { $this->markdown('_pages/foo.md', '# Foo Bar', ['title' => 'Foo Bar Baz']); $page = MarkdownPage::parse('foo'); - $this->assertEquals('Foo Bar Baz', $page->title); + + $this->assertSame('Foo Bar Baz', $page->title); } public function testBladePageDataIsParsedToFrontMatter() { $this->file('_pages/foo.blade.php', "@php(\$foo = 'bar')\n"); $page = BladePage::parse('foo'); - $this->assertEquals('bar', $page->data('foo')); + + $this->assertSame('bar', $page->data('foo')); } public function testBladePageMatterIsUsedForThePageTitle() { $this->file('_pages/foo.blade.php', "@php(\$title = 'Foo Bar')\n"); $page = BladePage::parse('foo'); - $this->assertEquals('Foo Bar', $page->data('title')); + + $this->assertSame('Foo Bar', $page->data('title')); } } diff --git a/packages/framework/tests/Feature/StaticSiteServiceTest.php b/packages/framework/tests/Feature/StaticSiteServiceTest.php index 981eb1f73e4..c5a172f8c64 100644 --- a/packages/framework/tests/Feature/StaticSiteServiceTest.php +++ b/packages/framework/tests/Feature/StaticSiteServiceTest.php @@ -9,6 +9,7 @@ use Hyde\Support\BuildWarnings; use Hyde\Testing\TestCase; use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Process; /** * @covers \Hyde\Console\Commands\BuildSiteCommand @@ -22,6 +23,8 @@ protected function setUp(): void parent::setUp(); $this->resetSite(); + + Process::preventStrayProcesses(); } protected function tearDown(): void @@ -127,11 +130,17 @@ public function testPrintInitialInformationAllowsApiToBeDisabled() public function testNodeActionOutputs() { + Process::fake(); + $this->artisan('build --run-prettier --run-dev --run-prod') ->expectsOutput('Prettifying code! This may take a second.') ->expectsOutput('Building frontend assets for development! This may take a second.') ->expectsOutput('Building frontend assets for production! This may take a second.') ->assertExitCode(0); + + Process::assertRan(fn ($process) => $process->command === 'npx prettier '.Hyde::pathToRelative(Hyde::sitePath()).'/**/*.html --write --bracket-same-line'); + Process::assertRan(fn ($process) => $process->command === 'npm run dev'); + Process::assertRan(fn ($process) => $process->command === 'npm run prod'); } public function testPrettyUrlsOptionOutput() diff --git a/packages/framework/tests/Feature/Support/MediaFileTest.php b/packages/framework/tests/Feature/Support/MediaFileTest.php index a320126f2a5..0782bfaf3bc 100644 --- a/packages/framework/tests/Feature/Support/MediaFileTest.php +++ b/packages/framework/tests/Feature/Support/MediaFileTest.php @@ -18,23 +18,24 @@ class MediaFileTest extends TestCase public function testCanConstruct() { $file = new MediaFile('foo'); + $this->assertInstanceOf(MediaFile::class, $file); $this->assertSame('foo', $file->path); } - public function can_make() + public function testCanMake() { $this->assertEquals(new MediaFile('foo'), MediaFile::make('foo')); } public function testCanConstructWithNestedPaths() { - $this->assertEquals('path/to/file.txt', MediaFile::make('path/to/file.txt')->path); + $this->assertSame('path/to/file.txt', MediaFile::make('path/to/file.txt')->path); } public function testAbsolutePathIsNormalizedToRelative() { - $this->assertEquals('foo', MediaFile::make(Hyde::path('foo'))->path); + $this->assertSame('foo', MediaFile::make(Hyde::path('foo'))->path); } public function testGetNameReturnsNameOfFile() @@ -85,6 +86,7 @@ public function testToArrayReturnsArrayOfFileProperties() public function testToArrayWithEmptyFileWithNoExtension() { $this->file('foo', 'foo bar'); + $this->assertSame([ 'name' => 'foo', 'path' => 'foo', @@ -97,12 +99,14 @@ public function testToArrayWithFileInSubdirectory() { mkdir(Hyde::path('foo')); touch(Hyde::path('foo/bar.txt')); + $this->assertSame([ 'name' => 'bar.txt', 'path' => 'foo/bar.txt', 'length' => 0, 'mimeType' => 'text/plain', ], MediaFile::make('foo/bar.txt')->toArray()); + Filesystem::unlink('foo/bar.txt'); rmdir(Hyde::path('foo')); } @@ -125,6 +129,7 @@ public function testGetContentLengthWithDirectory() $this->expectException(FileNotFoundException::class); $this->expectExceptionMessage('File [foo] not found.'); + MediaFile::make('foo')->getContentLength(); } @@ -132,6 +137,7 @@ public function testGetContentLengthWithNonExistentFile() { $this->expectException(FileNotFoundException::class); $this->expectExceptionMessage('File [foo] not found.'); + MediaFile::make('foo')->getContentLength(); } @@ -174,17 +180,18 @@ public function testAllHelperReturnsAllMediaFiles() public function testAllHelperDoesNotIncludeNonMediaFiles() { $this->file('_media/foo.blade.php'); + $this->assertEquals([ 'app.css' => new MediaFile('_media/app.css'), ], MediaFile::all()); } - public function testFilesHelper() + public function testFilesHelperReturnsAllMediaFiles() { $this->assertSame(['app.css'], MediaFile::files()); } - public function testGetIdentifier() + public function testGetIdentifierReturnsIdentifier() { $this->assertSame('foo', MediaFile::make('foo')->getIdentifier()); } diff --git a/packages/framework/tests/Feature/Support/SourceFileTest.php b/packages/framework/tests/Feature/Support/SourceFileTest.php index 62dde1f56a9..5a92e0075d0 100644 --- a/packages/framework/tests/Feature/Support/SourceFileTest.php +++ b/packages/framework/tests/Feature/Support/SourceFileTest.php @@ -34,25 +34,27 @@ public function testCanConstructWithModelClass() $this->assertSame(MarkdownPage::class, $file->pageClass); } - public function can_make() + public function testCanMake() { $this->assertEquals(new SourceFile('foo'), SourceFile::make('foo')); } public function testCanMakeWithModelClass() { - $this->assertEquals(new SourceFile('foo', MarkdownPage::class), - SourceFile::make('foo', MarkdownPage::class)); + $this->assertEquals( + new SourceFile('foo', MarkdownPage::class), + SourceFile::make('foo', MarkdownPage::class) + ); } public function testCanConstructWithNestedPaths() { - $this->assertEquals('path/to/file.txt', SourceFile::make('path/to/file.txt')->path); + $this->assertSame('path/to/file.txt', SourceFile::make('path/to/file.txt')->path); } public function testAbsolutePathIsNormalizedToRelative() { - $this->assertEquals('foo', SourceFile::make(Hyde::path('foo'))->path); + $this->assertSame('foo', SourceFile::make(Hyde::path('foo'))->path); } public function testGetNameReturnsNameOfFile() @@ -102,6 +104,7 @@ public function testToArrayReturnsArrayOfFileProperties() public function testToArrayWithEmptyFileWithNoExtension() { $this->file('foo'); + $this->assertSame([ 'name' => 'foo', 'path' => 'foo', @@ -113,11 +116,13 @@ public function testToArrayWithFileInSubdirectory() { mkdir(Hyde::path('foo')); touch(Hyde::path('foo/bar.txt')); + $this->assertSame([ 'name' => 'bar.txt', 'path' => 'foo/bar.txt', 'pageClass' => HydePage::class, ], SourceFile::make('foo/bar.txt')->toArray()); + Filesystem::unlink('foo/bar.txt'); rmdir(Hyde::path('foo')); } diff --git a/packages/framework/tests/Unit/BuildOutputDirectoryCanBeChangedTest.php b/packages/framework/tests/Unit/BuildOutputDirectoryCanBeChangedTest.php index 6bd0380a70f..8205f17dae7 100644 --- a/packages/framework/tests/Unit/BuildOutputDirectoryCanBeChangedTest.php +++ b/packages/framework/tests/Unit/BuildOutputDirectoryCanBeChangedTest.php @@ -11,9 +11,6 @@ use Hyde\Testing\TestCase; use Illuminate\Support\Facades\File; -/** - * Class BuildOutputDirectoryCanBeChangedTest. - */ class BuildOutputDirectoryCanBeChangedTest extends TestCase { public function testSiteOutputDirectoryCanBeChangedForSiteBuilds() @@ -48,25 +45,30 @@ public function testSiteOutputDirectoryCanBeChangedInStaticPageBuilder() public function testOutputDirectoryIsCreatedIfItDoesNotExistInStaticPageBuilder() { $this->file('_posts/test-post.md'); + File::deleteDirectory(Hyde::path('_site/build/foo')); Hyde::setOutputDirectory('_site/build/foo'); + StaticPageBuilder::handle(Pages::getPage('_posts/test-post.md')); $this->assertFileExists(Hyde::path('_site/build/foo/posts/test-post.html')); + File::deleteDirectory(Hyde::path('_site/build/foo')); } public function testSiteOutputDirectoryCanBeChangedInConfiguration() { - $this->assertEquals('_site', Hyde::kernel()->getOutputDirectory()); + $this->assertSame('_site', Hyde::kernel()->getOutputDirectory()); config(['hyde.output_directory' => '_site/build']); (new HydeServiceProvider($this->app))->register(); - $this->assertEquals('_site/build', Hyde::kernel()->getOutputDirectory()); + $this->assertSame('_site/build', Hyde::kernel()->getOutputDirectory()); $this->file('_posts/test-post.md'); + StaticPageBuilder::handle(Pages::getPage('_posts/test-post.md')); + $this->assertFileExists(Hyde::path('_site/build/posts/test-post.html')); File::deleteDirectory(Hyde::path('_site/build')); @@ -75,6 +77,7 @@ public function testSiteOutputDirectoryCanBeChangedInConfiguration() public function testSiteOutputDirectoryPathIsNormalizedToTrimTrailingSlashes() { Hyde::setOutputDirectory('foo/bar/'); - $this->assertEquals('foo/bar', Hyde::kernel()->getOutputDirectory()); + + $this->assertSame('foo/bar', Hyde::kernel()->getOutputDirectory()); } } diff --git a/packages/framework/tests/Unit/BuildTaskServiceUnitTest.php b/packages/framework/tests/Unit/BuildTaskServiceUnitTest.php index aea5acbc22b..97bd3f0b718 100644 --- a/packages/framework/tests/Unit/BuildTaskServiceUnitTest.php +++ b/packages/framework/tests/Unit/BuildTaskServiceUnitTest.php @@ -4,6 +4,7 @@ namespace Hyde\Framework\Testing\Unit; +use Closure; use Hyde\Foundation\HydeKernel; use Hyde\Foundation\Kernel\Filesystem; use Hyde\Framework\Actions\PostBuildTasks\GenerateBuildManifest; @@ -29,10 +30,7 @@ class BuildTaskServiceUnitTest extends UnitTestCase { protected BuildTaskService $service; - public static function setUpBeforeClass(): void - { - self::needsKernel(); - } + protected static bool $needsKernel = true; protected function setUp(): void { @@ -41,9 +39,17 @@ protected function setUp(): void 'generate_build_manifest' => false, 'transfer_media_assets' => false, ]]); + $this->createService(); } + protected function tearDown(): void + { + parent::tearDown(); + + $this->verifyMockeryExpectations(); + } + public function testConstruct() { $this->assertInstanceOf(BuildTaskService::class, new BuildTaskService()); @@ -145,16 +151,18 @@ public function testCanOverloadFrameworkTasks() $this->assertSame([GenerateSitemap::class], $this->service->getRegisteredTasks()); } - public function testSetOutputWithNull() + public function testCanSetOutputWithNull() { - $this->service->setOutput(null); - $this->markTestSuccessful(); + $this->can(function () { + $this->service->setOutput(null); + }); } - public function testSetOutputWithOutputStyle() + public function testCanSetOutputWithOutputStyle() { - $this->service->setOutput(Mockery::mock(OutputStyle::class)); - $this->markTestSuccessful(); + $this->can(function () { + $this->service->setOutput(Mockery::mock(OutputStyle::class)); + }); } public function testGenerateBuildManifestExtendsPostBuildTask() @@ -172,193 +180,200 @@ public function testGenerateSitemapExtendsPostBuildTask() $this->assertInstanceOf(PostBuildTask::class, new FrameworkGenerateSitemap()); } - public function testRunPreBuildTasks() + public function testCanRunPreBuildTasks() { - $this->service->runPreBuildTasks(); - $this->markTestSuccessful(); + $this->can($this->service->runPreBuildTasks(...)); } - public function testRunPostBuildTasks() + public function testCanRunPostBuildTasks() { - $this->service->runPostBuildTasks(); - $this->markTestSuccessful(); + $this->can($this->service->runPostBuildTasks(...)); } - public function testRunPreBuildTasksWithTasks() + public function testCanRunPreBuildTasksWithTasks() { - $this->service->registerTask(TestPreBuildTask::class); - $this->service->runPreBuildTasks(); - $this->markTestSuccessful(); + $this->can(function () { + $this->service->registerTask(TestPreBuildTask::class); + $this->service->runPreBuildTasks(); + }); } - public function testRunPostBuildTasksWithTasks() + public function testCanRunPostBuildTasksWithTasks() { - $this->service->registerTask(TestPostBuildTask::class); - $this->service->runPostBuildTasks(); - $this->markTestSuccessful(); + $this->can(function () { + $this->service->registerTask(TestPostBuildTask::class); + $this->service->runPostBuildTasks(); + }); } public function testRunPreBuildTasksCallsHandleMethods() { $task = Mockery::mock(TestPreBuildTask::class)->makePartial()->shouldReceive('handle')->once()->getMock(); + $this->service->registerTask($task); $this->service->runPreBuildTasks(); - $this->verifyMockeryExpectations(); } public function testRunPostBuildTasksCallsHandleMethods() { $task = Mockery::mock(TestPostBuildTask::class)->makePartial()->shouldReceive('handle')->once()->getMock(); + $this->service->registerTask($task); $this->service->runPostBuildTasks(); - $this->verifyMockeryExpectations(); } public function testRunPreBuildTasksCallsRunMethods() { $task = Mockery::mock(TestPreBuildTask::class)->makePartial()->shouldReceive('run')->once()->getMock(); + $this->service->registerTask($task); $this->service->runPreBuildTasks(); - $this->verifyMockeryExpectations(); } public function testRunPostBuildTasksCallsRunMethods() { $task = Mockery::mock(TestPostBuildTask::class)->makePartial()->shouldReceive('run')->once()->getMock(); + $this->service->registerTask($task); $this->service->runPostBuildTasks(); - $this->verifyMockeryExpectations(); } public function testRunPreBuildTasksCallsRunMethodsWithNullWhenServiceHasNoOutput() { $task = Mockery::mock(TestPreBuildTask::class)->makePartial()->shouldReceive('run')->with(null)->once()->getMock(); + $this->service->registerTask($task); $this->service->runPreBuildTasks(); - $this->verifyMockeryExpectations(); } public function testRunPostBuildTasksCallsRunMethodsWithNullWhenServiceHasNoOutput() { $task = Mockery::mock(TestPostBuildTask::class)->makePartial()->shouldReceive('run')->with(null)->once()->getMock(); + $this->service->registerTask($task); $this->service->runPostBuildTasks(); - $this->verifyMockeryExpectations(); } public function testRunPreBuildTasksCallsRunMethodsWithOutputWhenServiceHasOutput() { $output = Mockery::mock(OutputStyle::class)->makePartial(); $task = Mockery::mock(TestPreBuildTask::class)->makePartial()->shouldReceive('run')->with($output)->once()->getMock(); + $this->service->setOutput($output); $this->service->registerTask($task); $this->service->runPreBuildTasks(); - $this->verifyMockeryExpectations(); } public function testRunPostBuildTasksCallsRunMethodsWithOutputWhenServiceHasOutput() { $output = Mockery::mock(OutputStyle::class)->makePartial(); $task = Mockery::mock(TestPostBuildTask::class)->makePartial()->shouldReceive('run')->with($output)->once()->getMock(); + $this->service->setOutput($output); $this->service->registerTask($task); $this->service->runPostBuildTasks(); - $this->verifyMockeryExpectations(); } public function testServiceSearchesForTasksInAppDirectory() { - $kernel = HydeKernel::getInstance(); - $filesystem = Mockery::mock(Filesystem::class, [$kernel]) - ->makePartial()->shouldReceive('smartGlob')->once() - ->with('app/Actions/*BuildTask.php', 0) - ->andReturn(collect())->getMock(); + $this->mockKernelFilesystem(); - // Inject mock into Kernel (No better way to do this at the moment) - (new ReflectionClass($kernel))->getProperty('filesystem')->setValue($kernel, $filesystem); + $this->can($this->createService(...)); - $this->createService(); - $this->verifyMockeryExpectations(); - self::setupKernel(); + $this->assertSame([], $this->service->getRegisteredTasks()); + + $this->resetKernelInstance(); } public function testServiceFindsTasksInAppDirectory() { - $kernel = HydeKernel::getInstance(); - $filesystem = Mockery::mock(Filesystem::class, [$kernel])->makePartial() - ->shouldReceive('smartGlob')->once() - ->with('app/Actions/*BuildTask.php', 0) - ->andReturn(collect())->getMock(); + $files = [ + 'app/Actions/GenerateBuildManifestBuildTask.php' => GenerateBuildManifest::class, + 'app/Actions/GenerateRssFeedBuildTask.php' => GenerateRssFeed::class, + 'app/Actions/GenerateSearchBuildTask.php' => GenerateSearch::class, + ]; + $this->mockKernelFilesystem($files); - // Inject mock into Kernel - (new ReflectionClass($kernel))->getProperty('filesystem')->setValue($kernel, $filesystem); + $this->can($this->createService(...)); - $this->createService(); - $this->verifyMockeryExpectations(); - self::setupKernel(); + $this->assertSame([ + 'Hyde\Framework\Actions\PostBuildTasks\GenerateBuildManifest', + 'Hyde\Framework\Actions\PostBuildTasks\GenerateRssFeed', + 'Hyde\Framework\Actions\PostBuildTasks\GenerateSearch', + ], $this->service->getRegisteredTasks()); + + $this->resetKernelInstance(); } - protected function markTestSuccessful(): void + /** Assert that the given closure can be executed */ + protected function can(Closure $ability): void { + $ability(); + $this->assertTrue(true); } protected function createService(): BuildTaskService { - $this->service = new BuildTaskService(); - - return $this->service; + return tap(new BuildTaskService(), fn (BuildTaskService $service) => $this->service = $service); } protected function verifyMockeryExpectations(): void { $this->addToAssertionCount(Mockery::getContainer()->mockery_getExpectationCount()); + Mockery::close(); } + + protected function mockKernelFilesystem(array $files = []): void + { + $filesystem = Mockery::mock(Filesystem::class, [HydeKernel::getInstance()]) + ->makePartial()->shouldReceive('smartGlob')->once() + ->with('app/Actions/*BuildTask.php', 0) + ->andReturn(collect($files))->getMock(); + + // Inject mock into Kernel + (new ReflectionClass(HydeKernel::getInstance()))->getProperty('filesystem')->setValue(HydeKernel::getInstance(), $filesystem); + } + + protected function resetKernelInstance(): void + { + HydeKernel::setInstance(new HydeKernel()); + } } class InstantiableTestBuildTask extends BuildTask { - public function handle(): void - { - // - } + use VoidHandleMethod; } class TestBuildTask extends PostBuildTask { - public function handle(): void - { - // - } + use VoidHandleMethod; } class TestPreBuildTask extends PreBuildTask { - public function handle(): void - { - // - } + use VoidHandleMethod; } class TestPostBuildTask extends PostBuildTask { - public function handle(): void - { - // - } + use VoidHandleMethod; } class TestBuildTaskNotExtendingChildren extends BuildTask { - public function handle(): void - { - // - } + use VoidHandleMethod; } /** Test class to test overloading */ class GenerateSitemap extends FrameworkGenerateSitemap +{ + use VoidHandleMethod; +} + +trait VoidHandleMethod { public function handle(): void { diff --git a/packages/framework/tests/Unit/CustomExceptionsTest.php b/packages/framework/tests/Unit/CustomExceptionsTest.php index 5103307be25..684501c3b0c 100644 --- a/packages/framework/tests/Unit/CustomExceptionsTest.php +++ b/packages/framework/tests/Unit/CustomExceptionsTest.php @@ -21,10 +21,7 @@ */ class CustomExceptionsTest extends UnitTestCase { - public static function setUpBeforeClass(): void - { - self::needsKernel(); - } + protected static bool $needsKernel = true; public function testFileConflictExceptionWithDefaultMessage() { diff --git a/packages/framework/tests/Unit/DataCollectionUnitTest.php b/packages/framework/tests/Unit/DataCollectionUnitTest.php index 42ee13bcfce..fc4cfdea17b 100644 --- a/packages/framework/tests/Unit/DataCollectionUnitTest.php +++ b/packages/framework/tests/Unit/DataCollectionUnitTest.php @@ -18,10 +18,7 @@ */ class DataCollectionUnitTest extends UnitTestCase { - public static function setUpBeforeClass(): void - { - self::needsKernel(); - } + protected static bool $needsKernel = true; public function testClassHasStaticSourceDirectoryProperty() { diff --git a/packages/framework/tests/Unit/DateStringTest.php b/packages/framework/tests/Unit/DateStringTest.php index 5f5384707f6..602ce7b2ed8 100644 --- a/packages/framework/tests/Unit/DateStringTest.php +++ b/packages/framework/tests/Unit/DateStringTest.php @@ -16,7 +16,7 @@ class DateStringTest extends UnitTestCase public function testItCanParseDateString() { $dateString = new DateString('2020-01-01'); - $this->assertEquals('2020-01-01', $dateString->string); + $this->assertSame('2020-01-01', $dateString->string); } public function testItCanParseDateStringIntoDatetimeObject() @@ -28,24 +28,24 @@ public function testItCanParseDateStringIntoDatetimeObject() public function testItCanFormatDateStringIntoMachineReadableString() { $dateString = new DateString('2020-01-01 UTC'); - $this->assertEquals('2020-01-01T00:00:00+00:00', $dateString->datetime); + $this->assertSame('2020-01-01T00:00:00+00:00', $dateString->datetime); } public function testItCanFormatDateStringIntoHumanReadableString() { $dateString = new DateString('2020-01-01 UTC'); - $this->assertEquals('Wednesday Jan 1st, 2020, at 12:00am', $dateString->sentence); + $this->assertSame('Wednesday Jan 1st, 2020, at 12:00am', $dateString->sentence); } public function testItCanFormatDateStringIntoShortHumanReadableString() { $dateString = new DateString('2020-01-01 UTC'); - $this->assertEquals('Jan 1st, 2020', $dateString->short); + $this->assertSame('Jan 1st, 2020', $dateString->short); } public function testItCanFormatDateStringIntoShortHumanReadableStringUsingMagicMethod() { $dateString = new DateString('2022-01-01 UTC'); - $this->assertEquals('Jan 1st, 2022', (string) $dateString); + $this->assertSame('Jan 1st, 2022', (string) $dateString); } } diff --git a/packages/framework/tests/Unit/DocumentationPageTest.php b/packages/framework/tests/Unit/DocumentationPageTest.php index 9304a4955c1..06645054f53 100644 --- a/packages/framework/tests/Unit/DocumentationPageTest.php +++ b/packages/framework/tests/Unit/DocumentationPageTest.php @@ -31,7 +31,7 @@ public function testCanGenerateTableOfContents() public function testCanGetCurrentPagePath() { $page = DocumentationPage::make('foo'); - $this->assertEquals('docs/foo', $page->getRouteKey()); + $this->assertSame('docs/foo', $page->getRouteKey()); } public function testCanGetCurrentCustomPagePath() @@ -40,7 +40,7 @@ public function testCanGetCurrentCustomPagePath() (new HydeServiceProvider($this->app))->register(); $page = DocumentationPage::make('foo'); - $this->assertEquals('documentation/latest/foo', $page->getRouteKey()); + $this->assertSame('documentation/latest/foo', $page->getRouteKey()); } public function testCanGetCurrentPagePathWhenUsingFlattenedOutputPaths() @@ -48,13 +48,13 @@ public function testCanGetCurrentPagePathWhenUsingFlattenedOutputPaths() Config::set('docs.flattened_output_paths', true); $page = DocumentationPage::make('foo/bar'); - $this->assertEquals('docs/bar', $page->getRouteKey()); + $this->assertSame('docs/bar', $page->getRouteKey()); config(['hyde.output_directories.documentation-page' => 'documentation/latest/']); (new HydeServiceProvider($this->app))->register(); $page = DocumentationPage::make('foo/bar'); - $this->assertEquals('documentation/latest/bar', $page->getRouteKey()); + $this->assertSame('documentation/latest/bar', $page->getRouteKey()); } public function testCanGetCurrentPagePathWhenNotUsingFlattenedOutputPaths() @@ -62,13 +62,13 @@ public function testCanGetCurrentPagePathWhenNotUsingFlattenedOutputPaths() Config::set('docs.flattened_output_paths', false); $page = DocumentationPage::make('foo/bar'); - $this->assertEquals('docs/foo/bar', $page->getRouteKey()); + $this->assertSame('docs/foo/bar', $page->getRouteKey()); config(['hyde.output_directories.documentation-page' => 'documentation/latest/']); (new HydeServiceProvider($this->app))->register(); $page = DocumentationPage::make('foo/bar'); - $this->assertEquals('documentation/latest/foo/bar', $page->getRouteKey()); + $this->assertSame('documentation/latest/foo/bar', $page->getRouteKey()); } public function testCanGetOnlineSourcePath() @@ -80,8 +80,9 @@ public function testCanGetOnlineSourcePath() public function testCanGetOnlineSourcePathWithSourceFileLocationBase() { config(['docs.source_file_location_base' => 'docs.example.com/edit']); + $page = DocumentationPage::make('foo'); - $this->assertEquals('docs.example.com/edit/foo.md', $page->getOnlineSourcePath()); + $this->assertSame('docs.example.com/edit/foo.md', $page->getOnlineSourcePath()); } public function testCanGetOnlineSourcePathWithTrailingSlash() @@ -89,22 +90,23 @@ public function testCanGetOnlineSourcePathWithTrailingSlash() $page = DocumentationPage::make('foo'); config(['docs.source_file_location_base' => 'edit/']); - $this->assertEquals('edit/foo.md', $page->getOnlineSourcePath()); + $this->assertSame('edit/foo.md', $page->getOnlineSourcePath()); config(['docs.source_file_location_base' => 'edit']); - $this->assertEquals('edit/foo.md', $page->getOnlineSourcePath()); + $this->assertSame('edit/foo.md', $page->getOnlineSourcePath()); } public function testCanGetDocumentationOutputPath() { - $this->assertEquals('docs', DocumentationPage::outputDirectory()); + $this->assertSame('docs', DocumentationPage::outputDirectory()); } public function testCanGetDocumentationOutputPathWithCustomOutputDirectory() { config(['hyde.output_directories.documentation-page' => 'foo']); (new HydeServiceProvider($this->app))->register(); - $this->assertEquals('foo', DocumentationPage::outputDirectory()); + + $this->assertSame('foo', DocumentationPage::outputDirectory()); } public function testCanGetDocumentationOutputPathWithTrailingSlashes() @@ -120,13 +122,13 @@ public function testCanGetDocumentationOutputPathWithTrailingSlashes() foreach ($tests as $test) { config(['hyde.output_directories.documentation-page' => $test]); (new HydeServiceProvider($this->app))->register(); - $this->assertEquals('foo', DocumentationPage::outputDirectory()); + $this->assertSame('foo', DocumentationPage::outputDirectory()); } } public function testGetSourcePathReturnsQualifiedBasename() { - $this->assertEquals( + $this->assertSame( DocumentationPage::sourcePath('foo'), (new DocumentationPage(identifier: 'foo'))->getSourcePath() ); @@ -134,7 +136,7 @@ public function testGetSourcePathReturnsQualifiedBasename() public function testGetSourcePathReturnsQualifiedBasenameForNestedPage() { - $this->assertEquals( + $this->assertSame( DocumentationPage::sourcePath('foo/bar'), (new DocumentationPage(identifier: 'foo/bar'))->getSourcePath() ); @@ -148,8 +150,10 @@ public function testHomeMethodReturnsNullWhenThereIsNoIndexPage() public function testHomeMethodReturnsDocsIndexRouteWhenItExists() { Filesystem::touch('_docs/index.md'); + $this->assertInstanceOf(Route::class, DocumentationPage::home()); - $this->assertEquals(Routes::get('docs/index'), DocumentationPage::home()); + $this->assertSame(Routes::get('docs/index'), DocumentationPage::home()); + Filesystem::unlink('_docs/index.md'); } @@ -157,10 +161,13 @@ public function testHomeMethodFindsDocsIndexForCustomOutputDirectory() { config(['hyde.output_directories.documentation-page' => 'foo']); (new HydeServiceProvider($this->app))->register(); + mkdir(Hyde::path('foo')); Filesystem::touch('_docs/index.md'); + $this->assertInstanceOf(Route::class, DocumentationPage::home()); - $this->assertEquals(Routes::get('foo/index'), DocumentationPage::home()); + $this->assertSame(Routes::get('foo/index'), DocumentationPage::home()); + Filesystem::unlink('_docs/index.md'); File::deleteDirectory(Hyde::path('foo')); } @@ -169,11 +176,14 @@ public function testHomeMethodFindsDocsIndexForCustomNestedOutputDirectory() { config(['hyde.output_directories.documentation-page' => 'foo/bar']); (new HydeServiceProvider($this->app))->register(); + mkdir(Hyde::path('foo')); mkdir(Hyde::path('foo/bar')); Filesystem::touch('_docs/index.md'); + $this->assertInstanceOf(Route::class, DocumentationPage::home()); - $this->assertEquals(Routes::get('foo/bar/index'), DocumentationPage::home()); + $this->assertSame(Routes::get('foo/bar/index'), DocumentationPage::home()); + Filesystem::unlink('_docs/index.md'); File::deleteDirectory(Hyde::path('foo')); } @@ -205,21 +215,24 @@ public function testHasTableOfContents() public function testCompiledPagesOriginatingInSubdirectoriesGetOutputToRootDocsPath() { $page = DocumentationPage::make('foo/bar'); - $this->assertEquals('docs/bar.html', $page->getOutputPath()); + + $this->assertSame('docs/bar.html', $page->getOutputPath()); } public function testCompiledPagesOriginatingInSubdirectoriesGetOutputToRootDocsPathWhenUsingFlattenedOutputPaths() { Config::set('docs.flattened_output_paths', true); + $page = DocumentationPage::make('foo/bar'); - $this->assertEquals('docs/bar.html', $page->getOutputPath()); + $this->assertSame('docs/bar.html', $page->getOutputPath()); } public function testCompiledPagesOriginatingInSubdirectoriesRetainSubdirectoryStructureWhenNotUsingFlattenedOutputPaths() { Config::set('docs.flattened_output_paths', false); + $page = DocumentationPage::make('foo/bar'); - $this->assertEquals('docs/foo/bar.html', $page->getOutputPath()); + $this->assertSame('docs/foo/bar.html', $page->getOutputPath()); } public function testPageHasFrontMatter() @@ -230,10 +243,14 @@ public function testPageHasFrontMatter() 'baz' => 'qux', ], ]); + $page = DocumentationPage::parse('foo'); + $this->assertNotNull($page->matter()); $this->assertNotEmpty($page->matter()); + $this->assertEquals(new FrontMatter($expected), $page->matter()); + $this->assertSame($expected, $page->matter()->get()); } public function testPageCanBeHiddenFromSidebarUsingFrontMatter() @@ -243,6 +260,7 @@ public function testPageCanBeHiddenFromSidebarUsingFrontMatter() 'hidden' => true, ], ]); + $page = DocumentationPage::parse('foo'); $this->assertFalse($page->showInNavigation()); } @@ -250,6 +268,7 @@ public function testPageCanBeHiddenFromSidebarUsingFrontMatter() public function testPageIsVisibleInSidebarWithoutUsingFrontMatter() { $this->markdown('_docs/foo.md'); + $page = DocumentationPage::parse('foo'); $this->assertTrue($page->showInNavigation()); } @@ -261,8 +280,9 @@ public function testPageCanSetSidebarPriorityUsingFrontMatter() priority: 10 --- '); + $page = DocumentationPage::parse('foo'); - $this->assertEquals(10, $page->navigationMenuPriority()); + $this->assertSame(10, $page->navigationMenuPriority()); } public function testPageCanSetSidebarLabelUsingFrontMatter() @@ -272,7 +292,8 @@ public function testPageCanSetSidebarLabelUsingFrontMatter() label: Bar --- '); + $page = DocumentationPage::parse('foo'); - $this->assertEquals('Bar', $page->navigationMenuLabel()); + $this->assertSame('Bar', $page->navigationMenuLabel()); } } diff --git a/packages/framework/tests/Unit/Facades/RouteFacadeTest.php b/packages/framework/tests/Unit/Facades/RouteFacadeTest.php index 70632f490ec..a63a9b7669f 100644 --- a/packages/framework/tests/Unit/Facades/RouteFacadeTest.php +++ b/packages/framework/tests/Unit/Facades/RouteFacadeTest.php @@ -20,11 +20,8 @@ */ class RouteFacadeTest extends UnitTestCase { - public static function setUpBeforeClass(): void - { - self::needsKernel(); - self::mockConfig(); - } + protected static bool $needsKernel = true; + protected static bool $needsConfig = true; public function testRouteFacadeAllMethodReturnsAllRoutes() { @@ -34,6 +31,7 @@ public function testRouteFacadeAllMethodReturnsAllRoutes() public function testGetOrFailThrowsExceptionIfRouteIsNotFound() { $this->expectException(RouteNotFoundException::class); + Routes::getOrFail('not-found'); } @@ -55,22 +53,28 @@ public function testGetFromReturnsNullIfRouteIsNotFound() public function testGetSupportsDotNotation() { Hyde::routes()->add(new Route(new MarkdownPost('foo'))); + $this->assertSame(Routes::get('posts/foo'), Routes::get('posts.foo')); } public function testCurrentReturnsCurrentRoute() { $route = new Route(new MarkdownPage('foo')); + Render::shouldReceive('getRoute')->andReturn($route); + $this->assertSame($route, Routes::current()); - Render::swap(new RenderData()); + + $this->resetMockInstance(); } public function testCurrentReturnsNullIfRouteIsNotFound() { Render::shouldReceive('getRoute')->andReturn(null); + $this->assertNull(Routes::current()); - Render::swap(new RenderData()); + + $this->resetMockInstance(); } public function testExistsForExistingRoute() @@ -82,4 +86,9 @@ public function testExistsForNonExistingRoute() { $this->assertFalse(Routes::exists('not-found')); } + + protected function resetMockInstance(): void + { + Render::swap(new RenderData()); + } } diff --git a/packages/framework/tests/Unit/FeaturedImageUnitTest.php b/packages/framework/tests/Unit/FeaturedImageUnitTest.php index 3fae872b5e9..5ea286739a7 100644 --- a/packages/framework/tests/Unit/FeaturedImageUnitTest.php +++ b/packages/framework/tests/Unit/FeaturedImageUnitTest.php @@ -15,110 +15,169 @@ */ class FeaturedImageUnitTest extends UnitTestCase { - public static function setUpBeforeClass(): void - { - self::needsKernel(); - } + protected static bool $needsKernel = true; + + protected const ARGUMENTS = ['alt', 'title', 'author', 'authorUrl', 'copyright', 'license', 'licenseUrl']; public function testCanConstruct() { $this->assertInstanceOf(FeaturedImage::class, new FeaturedImage('foo')); } - public function testGetAltText() + public function testGetAltTextWithoutData() { $this->assertNull((new NullImage)->getAltText()); - $this->assertEquals('alt', (new FilledImage)->getAltText()); } - public function testGetTitleText() + public function testGetAltTextWithData() + { + $this->assertSame('alt', (new FilledImage)->getAltText()); + } + + public function testGetTitleTextWithoutData() { $this->assertNull((new NullImage)->getTitleText()); - $this->assertEquals('title', (new FilledImage)->getTitleText()); } - public function testGetAuthorName() + public function testGetTitleTextWithData() + { + $this->assertSame('title', (new FilledImage)->getTitleText()); + } + + public function testGetAuthorNameWithoutData() { $this->assertNull((new NullImage)->getAuthorName()); - $this->assertEquals('author', (new FilledImage)->getAuthorName()); } - public function testGetAuthorUrl() + public function testGetAuthorNameWithData() + { + $this->assertSame('author', (new FilledImage)->getAuthorName()); + } + + public function testGetAuthorUrlWithoutData() { $this->assertNull((new NullImage)->getAuthorUrl()); - $this->assertEquals('authorUrl', (new FilledImage)->getAuthorUrl()); } - public function testGetCopyrightText() + public function testGetAuthorUrlWithData() + { + $this->assertSame('authorUrl', (new FilledImage)->getAuthorUrl()); + } + + public function testGetCopyrightTextWithoutData() { $this->assertNull((new NullImage)->getCopyrightText()); - $this->assertEquals('copyright', (new FilledImage)->getCopyrightText()); } - public function testGetLicenseName() + public function testGetCopyrightTextWithData() + { + $this->assertSame('copyright', (new FilledImage)->getCopyrightText()); + } + + public function testGetLicenseNameWithoutData() { $this->assertNull((new NullImage)->getLicenseName()); - $this->assertEquals('license', (new FilledImage)->getLicenseName()); } - public function testGetLicenseUrl() + public function testGetLicenseNameWithData() + { + $this->assertSame('license', (new FilledImage)->getLicenseName()); + } + + public function testGetLicenseUrlWithoutData() { $this->assertNull((new NullImage)->getLicenseUrl()); - $this->assertEquals('licenseUrl', (new FilledImage)->getLicenseUrl()); } - public function testHasAltText() + public function testGetLicenseUrlWithData() + { + $this->assertSame('licenseUrl', (new FilledImage)->getLicenseUrl()); + } + + public function testHasAltTextWithoutData() { $this->assertFalse((new NullImage)->hasAltText()); + } + + public function testHasAltTextWithData() + { $this->assertTrue((new FilledImage)->hasAltText()); } - public function testHasTitleText() + public function testHasTitleTextWithoutData() { $this->assertFalse((new NullImage)->hasTitleText()); + } + + public function testHasTitleTextWithData() + { $this->assertTrue((new FilledImage)->hasTitleText()); } - public function testHasAuthorName() + public function testHasAuthorNameWithoutData() { $this->assertFalse((new NullImage)->hasAuthorName()); + } + + public function testHasAuthorNameWithData() + { $this->assertTrue((new FilledImage)->hasAuthorName()); } - public function testHasAuthorUrl() + public function testHasAuthorUrlWithoutData() { $this->assertFalse((new NullImage)->hasAuthorUrl()); + } + + public function testHasAuthorUrlWithData() + { $this->assertTrue((new FilledImage)->hasAuthorUrl()); } - public function testHasCopyrightText() + public function testHasCopyrightTextWithoutData() { $this->assertFalse((new NullImage)->hasCopyrightText()); + } + + public function testHasCopyrightTextWithData() + { $this->assertTrue((new FilledImage)->hasCopyrightText()); } - public function testHasLicenseName() + public function testHasLicenseNameWithoutData() { $this->assertFalse((new NullImage)->hasLicenseName()); + } + + public function testHasLicenseNameWithData() + { $this->assertTrue((new FilledImage)->hasLicenseName()); } - public function testHasLicenseUrl() + public function testHasLicenseUrlWithoutData() { $this->assertFalse((new NullImage)->hasLicenseUrl()); + } + + public function testHasLicenseUrlWithData() + { $this->assertTrue((new FilledImage)->hasLicenseUrl()); } - public function testGetType() + public function testGetTypeForLocalImage() { - $this->assertEquals('local', (new LocalImage)->getType()); - $this->assertEquals('remote', (new RemoteImage)->getType()); + $this->assertSame('local', (new LocalImage)->getType()); + } + + public function testGetTypeForRemoteImage() + { + $this->assertSame('remote', (new RemoteImage)->getType()); } public function testGetContentLength() { - $this->assertEquals(0, (new NullImage)->getContentLength()); - $this->assertEquals(0, (new FilledImage)->getContentLength()); + $this->assertSame(0, (new NullImage)->getContentLength()); + $this->assertSame(0, (new FilledImage)->getContentLength()); } public function testFeaturedImageGetContentLengthWithNoSource() @@ -126,29 +185,24 @@ public function testFeaturedImageGetContentLengthWithNoSource() $this->expectException(FileNotFoundException::class); $this->expectExceptionMessage('Featured image [_media/foo] not found.'); - $image = new FeaturedImage('_media/foo', ...$this->defaultArguments()); - $this->assertEquals(0, $image->getContentLength()); + $image = new FeaturedImage('_media/foo', ...self::ARGUMENTS); + $this->assertSame(0, $image->getContentLength()); } public function testCanConstructFeaturedImageWithRemoteSource() { - $image = new FeaturedImage('http/foo', ...$this->defaultArguments()); - $this->assertInstanceOf(FeaturedImage::class, $image); + $image = new FeaturedImage('http/foo', ...self::ARGUMENTS); - $this->assertEquals('http/foo', $image->getSource()); + $this->assertInstanceOf(FeaturedImage::class, $image); + $this->assertSame('http/foo', $image->getSource()); } public function testCanConstructFeaturedImageWithHttps() { - $image = new FeaturedImage('https/foo', ...$this->defaultArguments()); - $this->assertInstanceOf(FeaturedImage::class, $image); - - $this->assertEquals('https/foo', $image->getSource()); - } + $image = new FeaturedImage('https/foo', ...self::ARGUMENTS); - protected function defaultArguments(): array - { - return ['alt', 'title', 'author', 'authorUrl', 'copyright', 'license', 'licenseUrl']; + $this->assertInstanceOf(FeaturedImage::class, $image); + $this->assertSame('https/foo', $image->getSource()); } } diff --git a/packages/framework/tests/Unit/Foundation/HyperlinkFormatHtmlPathTest.php b/packages/framework/tests/Unit/Foundation/HyperlinkFormatHtmlPathTest.php index 2c4ad10058a..b92c4b133fe 100644 --- a/packages/framework/tests/Unit/Foundation/HyperlinkFormatHtmlPathTest.php +++ b/packages/framework/tests/Unit/Foundation/HyperlinkFormatHtmlPathTest.php @@ -12,11 +12,8 @@ */ class HyperlinkFormatHtmlPathTest extends UnitTestCase { - public static function setUpBeforeClass(): void - { - self::needsKernel(); - self::mockConfig(); - } + protected static bool $needsKernel = true; + protected static bool $needsConfig = true; public function testHelperReturnsStringAsIsIfPrettyUrlsIsNotTrue() { diff --git a/packages/framework/tests/Unit/Foundation/HyperlinksUrlPathHelpersTest.php b/packages/framework/tests/Unit/Foundation/HyperlinksUrlPathHelpersTest.php index 8da1536405d..be8fafa99c9 100644 --- a/packages/framework/tests/Unit/Foundation/HyperlinksUrlPathHelpersTest.php +++ b/packages/framework/tests/Unit/Foundation/HyperlinksUrlPathHelpersTest.php @@ -27,72 +27,84 @@ protected function setUp(): void public function testHasSiteUrlReturnsFalseWhenNoSiteUrlIsSet() { config(['hyde.url' => null]); + $this->assertFalse($this->class->hasSiteUrl()); } public function testHasSiteUrlReturnsTrueWhenSiteUrlIsSet() { config(['hyde.url' => 'https://example.com']); + $this->assertTrue($this->class->hasSiteUrl()); } public function testQualifiedUrlReturnsSiteUrlWhenNoPathIsGiven() { config(['hyde.url' => 'https://example.com']); - $this->assertEquals('https://example.com', $this->class->url()); + + $this->assertSame('https://example.com', $this->class->url()); } public function testQualifiedUrlReturnsSiteUrlPlusGivenPath() { config(['hyde.url' => 'https://example.com']); - $this->assertEquals('https://example.com/path', $this->class->url('path')); + + $this->assertSame('https://example.com/path', $this->class->url('path')); } public function testQualifiedUrlReturnsSiteUrlPlusGivenPathWithExtension() { config(['hyde.url' => 'https://example.com']); - $this->assertEquals('https://example.com/path.html', $this->class->url('path.html')); + + $this->assertSame('https://example.com/path.html', $this->class->url('path.html')); } public function testQualifiedUrlReturnsSiteUrlPlusGivenPathWithExtensionAndQueryString() { config(['hyde.url' => 'https://example.com']); - $this->assertEquals('https://example.com/path.html?query=string', $this->class->url('path.html?query=string')); + + $this->assertSame('https://example.com/path.html?query=string', $this->class->url('path.html?query=string')); } public function testQualifiedUrlTrimsTrailingSlashes() { config(['hyde.url' => 'https://example.com/']); - $this->assertEquals('https://example.com', $this->class->url()); - $this->assertEquals('https://example.com', $this->class->url('/')); - $this->assertEquals('https://example.com/foo', $this->class->url('/foo/')); + + $this->assertSame('https://example.com', $this->class->url()); + $this->assertSame('https://example.com', $this->class->url('/')); + $this->assertSame('https://example.com/foo', $this->class->url('/foo/')); } public function testQualifiedUrlAcceptsMultipleSchemes() { config(['hyde.url' => 'http://example.com']); - $this->assertEquals('http://example.com', $this->class->url()); + + $this->assertSame('http://example.com', $this->class->url()); } public function testQualifiedUrlThrowsExceptionWhenNoSiteUrlIsSet() { config(['hyde.url' => null]); + $this->expectException(BaseUrlNotSetException::class); $this->expectExceptionMessage('No site URL has been set in config (or .env).'); + $this->class->url(); } public function testHelperReturnsExpectedStringWhenSiteUrlIsSet() { config(['hyde.url' => 'https://example.com']); - $this->assertEquals('https://example.com/foo/bar.html', $this->class->url('foo/bar.html')); + + $this->assertSame('https://example.com/foo/bar.html', $this->class->url('foo/bar.html')); } public function testHelperReturnsExpectedStringWhenPrettyUrlsAreEnabled() { config(['hyde.url' => 'https://example.com', 'hyde.pretty_urls' => true]); - $this->assertEquals('https://example.com', $this->class->url('index.html')); - $this->assertEquals('https://example.com/foo', $this->class->url('foo.html')); - $this->assertEquals('https://example.com/docs', $this->class->url('docs/index.html')); + + $this->assertSame('https://example.com', $this->class->url('index.html')); + $this->assertSame('https://example.com/foo', $this->class->url('foo.html')); + $this->assertSame('https://example.com/docs', $this->class->url('docs/index.html')); } } diff --git a/packages/framework/tests/Unit/FoundationFacadesTest.php b/packages/framework/tests/Unit/FoundationFacadesTest.php index 96350f6fc30..fa56fe0742a 100644 --- a/packages/framework/tests/Unit/FoundationFacadesTest.php +++ b/packages/framework/tests/Unit/FoundationFacadesTest.php @@ -20,11 +20,8 @@ */ class FoundationFacadesTest extends UnitTestCase { - public static function setupBeforeClass(): void - { - self::needsKernel(); - self::mockConfig(); - } + protected static bool $needsKernel = true; + protected static bool $needsConfig = true; public function testFilesFacade() { diff --git a/packages/framework/tests/Unit/FrontMatterModelTest.php b/packages/framework/tests/Unit/FrontMatterModelTest.php index fa566a31964..09e6c1344d5 100644 --- a/packages/framework/tests/Unit/FrontMatterModelTest.php +++ b/packages/framework/tests/Unit/FrontMatterModelTest.php @@ -24,25 +24,27 @@ public function testConstructorArgumentsAreOptional() public function testConstructorArgumentsAreAssigned() { - $this->assertEquals(['foo' => 'bar'], (new FrontMatter(['foo' => 'bar']))->toArray()); + $this->assertSame(['foo' => 'bar'], (new FrontMatter(['foo' => 'bar']))->toArray()); } public function testStaticFromArrayMethodCreatesNewFrontMatterModel() { $matter = FrontMatter::fromArray(['foo' => 'bar']); + $this->assertInstanceOf(FrontMatter::class, $matter); - $this->assertEquals(['foo' => 'bar'], $matter->toArray()); + $this->assertSame(['foo' => 'bar'], $matter->toArray()); } public function testToStringMagicMethodConvertsModelArrayIntoYamlFrontMatter() { $matter = new FrontMatter(['foo' => 'bar']); - $this->assertEquals("---\nfoo: bar\n---\n", (string) (new FrontMatter(['foo' => 'bar']))); + + $this->assertSame("---\nfoo: bar\n---\n", (string) (new FrontMatter(['foo' => 'bar']))); } public function testMagicGetMethodReturnsFrontMatterProperty() { - $this->assertEquals('bar', (new FrontMatter(['foo' => 'bar']))->foo); + $this->assertSame('bar', (new FrontMatter(['foo' => 'bar']))->foo); } public function testMagicGetMethodReturnsNullIfPropertyDoesNotExist() @@ -68,22 +70,24 @@ public function testGetMethodReturnsNullIfSpecifiedFrontMatterKeyDoesNotExist() public function testGetMethodReturnsSpecifiedDefaultValueIfPropertyDoesNotExist() { $matter = new FrontMatter(); - $this->assertEquals('default', $matter->get('bar', 'default')); + + $this->assertSame('default', $matter->get('bar', 'default')); } public function testGetMethodReturnsSpecifiedFrontMatterValueIfKeyIsSpecified() { - $this->assertEquals('bar', (new FrontMatter(['foo' => 'bar']))->get('foo')); + $this->assertSame('bar', (new FrontMatter(['foo' => 'bar']))->get('foo')); } public function testSetMethodSetsFrontMatterProperty() { - $this->assertEquals('bar', (new FrontMatter())->set('foo', 'bar')->get('foo')); + $this->assertSame('bar', (new FrontMatter())->set('foo', 'bar')->get('foo')); } public function testSetMethodReturnsSelf() { $matter = new FrontMatter(); + $this->assertSame($matter, $matter->set('foo', 'bar')); } @@ -99,6 +103,6 @@ public function testHasMethodReturnsFalseIfPropertyDoesNotExist() public function testToArrayReturnsFrontMatterArray() { - $this->assertEquals(['foo' => 'bar'], (new FrontMatter(['foo' => 'bar']))->toArray()); + $this->assertSame(['foo' => 'bar'], (new FrontMatter(['foo' => 'bar']))->toArray()); } } diff --git a/packages/framework/tests/Unit/GenerateBuildManifestTest.php b/packages/framework/tests/Unit/GenerateBuildManifestTest.php index f3ffc9fd849..8b2ec50c140 100644 --- a/packages/framework/tests/Unit/GenerateBuildManifestTest.php +++ b/packages/framework/tests/Unit/GenerateBuildManifestTest.php @@ -15,11 +15,8 @@ */ class GenerateBuildManifestTest extends UnitTestCase { - public static function setUpBeforeClass(): void - { - self::needsKernel(); - self::mockConfig(); - } + protected static bool $needsKernel = true; + protected static bool $needsConfig = true; public function testActionGeneratesBuildManifest() { @@ -41,13 +38,13 @@ public function testActionGeneratesBuildManifest() $this->assertArrayHasKey('source_hash', $manifest['pages'][404]); $this->assertArrayHasKey('output_hash', $manifest['pages'][404]); - $this->assertEquals('_pages/404.blade.php', $manifest['pages'][404]['source_path']); - $this->assertEquals('_pages/index.blade.php', $manifest['pages']['index']['source_path']); + $this->assertSame('_pages/404.blade.php', $manifest['pages'][404]['source_path']); + $this->assertSame('_pages/index.blade.php', $manifest['pages']['index']['source_path']); - $this->assertEquals('404.html', $manifest['pages'][404]['output_path']); - $this->assertEquals('index.html', $manifest['pages']['index']['output_path']); + $this->assertSame('404.html', $manifest['pages'][404]['output_path']); + $this->assertSame('index.html', $manifest['pages']['index']['output_path']); - $this->assertEquals(unixsum_file(Hyde::path('_pages/404.blade.php')), $manifest['pages'][404]['source_hash']); + $this->assertSame(unixsum_file(Hyde::path('_pages/404.blade.php')), $manifest['pages'][404]['source_hash']); $this->assertNull($manifest['pages'][404]['output_hash']); } } diff --git a/packages/framework/tests/Unit/GetLatestMarkdownPostsTest.php b/packages/framework/tests/Unit/GetLatestMarkdownPostsTest.php index 5cbfb808f7c..d82edd83e49 100644 --- a/packages/framework/tests/Unit/GetLatestMarkdownPostsTest.php +++ b/packages/framework/tests/Unit/GetLatestMarkdownPostsTest.php @@ -21,12 +21,13 @@ public function testMarkdownPageGetLatestHelperReturnsSortedMarkdownPageCollecti file_put_contents(Hyde::path('_posts/old.md'), "---\ndate: '2021-01-01 12:00'\n---\n"); $collection = MarkdownPost::getLatestPosts(); + $this->assertCount(2, $collection); $this->assertInstanceOf(Collection::class, $collection); $this->assertContainsOnlyInstancesOf(MarkdownPost::class, $collection); - $this->assertEquals('new', $collection->first()->identifier); - $this->assertEquals('old', $collection->last()->identifier); + $this->assertSame('new', $collection->first()->identifier); + $this->assertSame('old', $collection->last()->identifier); Filesystem::unlink('_posts/new.md'); Filesystem::unlink('_posts/old.md'); diff --git a/packages/framework/tests/Unit/HasTableOfContentsTest.php b/packages/framework/tests/Unit/HasTableOfContentsTest.php index 9e0b1316223..2995b0b509e 100644 --- a/packages/framework/tests/Unit/HasTableOfContentsTest.php +++ b/packages/framework/tests/Unit/HasTableOfContentsTest.php @@ -4,24 +4,24 @@ namespace Hyde\Framework\Testing\Unit; -use Hyde\Markdown\Models\Markdown; use Hyde\Pages\DocumentationPage; -use Hyde\Testing\TestCase; +use Hyde\Testing\UnitTestCase; /** - * Class HasTableOfContentsTest. - * * @covers \Hyde\Pages\DocumentationPage * * @see \Hyde\Framework\Testing\Feature\Actions\GeneratesSidebarTableOfContentsTest */ -class HasTableOfContentsTest extends TestCase +class HasTableOfContentsTest extends UnitTestCase { + protected static bool $needsKernel = true; + protected static bool $needsConfig = true; + public function testConstructorCreatesTableOfContentsString() { - $page = new DocumentationPage(); - - $page->markdown = new Markdown('## Title'); - $this->assertEquals('', str_replace("\n", '', $page->getTableOfContents())); + $this->assertSame( + '', + str_replace("\n", '', (new DocumentationPage(markdown: '## Title'))->getTableOfContents()) + ); } } diff --git a/packages/framework/tests/Unit/HydeBasePathCanBeChangedTest.php b/packages/framework/tests/Unit/HydeBasePathCanBeChangedTest.php index 9e40d9ff1da..c4e266e5cd5 100644 --- a/packages/framework/tests/Unit/HydeBasePathCanBeChangedTest.php +++ b/packages/framework/tests/Unit/HydeBasePathCanBeChangedTest.php @@ -5,39 +5,26 @@ namespace Hyde\Framework\Testing\Unit; use Hyde\Hyde; -use Hyde\Testing\TestCase; +use Hyde\Testing\UnitTestCase; /** - * Class HydeBasePathCanBeChangedTest. - * * @covers \Hyde\Foundation\HydeKernel::getBasePath * @covers \Hyde\Foundation\HydeKernel::setBasePath * @covers \Hyde\Foundation\HydeKernel::path */ -class HydeBasePathCanBeChangedTest extends TestCase +class HydeBasePathCanBeChangedTest extends UnitTestCase { - protected string $basePath; + protected static bool $needsKernel = true; - protected function setUp(): void + public function testHydeBasePathCanBeChanged() { - parent::setUp(); + $basePath = Hyde::getBasePath(); - if (! isset($this->basePath)) { - $this->basePath = Hyde::getBasePath(); - } - } + Hyde::setBasePath('/foo/bar'); - protected function tearDown(): void - { - Hyde::setBasePath($this->basePath); + $this->assertSame('/foo/bar', Hyde::getBasePath()); + $this->assertSame('/foo/bar', Hyde::path()); - parent::tearDown(); - } - - public function testHydeBasePathCanBeChanged() - { - Hyde::setBasePath('/foo/bar'); - $this->assertEquals('/foo/bar', Hyde::getBasePath()); - $this->assertEquals('/foo/bar', Hyde::path()); + Hyde::setBasePath($basePath); } } diff --git a/packages/framework/tests/Unit/HydeFileHelpersTest.php b/packages/framework/tests/Unit/HydeFileHelpersTest.php index b5838e93b87..7bb1974bf1d 100644 --- a/packages/framework/tests/Unit/HydeFileHelpersTest.php +++ b/packages/framework/tests/Unit/HydeFileHelpersTest.php @@ -17,18 +17,18 @@ class HydeFileHelpersTest extends TestCase public function testCurrentPageReturnsCurrentPageViewProperty() { Render::share('routeKey', 'foo'); - $this->assertEquals('foo', Hyde::currentRouteKey()); + $this->assertSame('foo', Hyde::currentRouteKey()); } - public function testCurrentPageFallsBackToEmptyStringIfCurrentPageViewPropertyIsNotSet() + public function testCurrentPageFallsBackToNullStringIfCurrentPageViewPropertyIsNotSet() { - $this->assertEquals('', Hyde::currentRouteKey()); + $this->assertNull(Hyde::currentRouteKey()); } public function testCurrentRouteReturnsCurrentRouteViewProperty() { Render::share('route', Routes::get('index')); - $this->assertEquals(Routes::get('index'), Hyde::currentRoute()); + $this->assertSame(Routes::get('index'), Hyde::currentRoute()); } public function testCurrentRouteFallsBackToNullIfCurrentRouteViewPropertyIsNotSet() diff --git a/packages/framework/tests/Unit/HydeGetBasePathHasFallbackTest.php b/packages/framework/tests/Unit/HydeGetBasePathHasFallbackTest.php index dab5596d1d5..32de083a97e 100644 --- a/packages/framework/tests/Unit/HydeGetBasePathHasFallbackTest.php +++ b/packages/framework/tests/Unit/HydeGetBasePathHasFallbackTest.php @@ -5,21 +5,22 @@ namespace Hyde\Framework\Testing\Unit; use Hyde\Hyde; -use Hyde\Testing\TestCase; +use Hyde\Testing\UnitTestCase; /** - * Class HydeGetBasePathHasFallbackTest. - * * @covers \Hyde\Foundation\HydeKernel::getBasePath */ -class HydeGetBasePathHasFallbackTest extends TestCase +class HydeGetBasePathHasFallbackTest extends UnitTestCase { - public function testHydeGetBasePathFallsBackToGetcwd() + protected static bool $needsKernel = true; + + public function testHydeGetBasePathFallsBackToCurrentWorkingDirectory() { $mock = new class extends Hyde { public static string $basePath; }; - $this->assertEquals(getcwd(), $mock::getBasePath()); + + $this->assertSame(getcwd(), $mock::getBasePath()); } } diff --git a/packages/framework/tests/Unit/HydePageDataFactoryTest.php b/packages/framework/tests/Unit/HydePageDataFactoryTest.php index fa7594dcec8..8c8f2a8676a 100644 --- a/packages/framework/tests/Unit/HydePageDataFactoryTest.php +++ b/packages/framework/tests/Unit/HydePageDataFactoryTest.php @@ -16,11 +16,8 @@ */ class HydePageDataFactoryTest extends UnitTestCase { - public static function setUpBeforeClass(): void - { - self::needsKernel(); - self::mockConfig(); - } + protected static bool $needsKernel = true; + protected static bool $needsConfig = true; protected function tearDown(): void { diff --git a/packages/framework/tests/Unit/InteractsWithDirectoriesConcernTest.php b/packages/framework/tests/Unit/InteractsWithDirectoriesConcernTest.php index e8210d71776..d788f101506 100644 --- a/packages/framework/tests/Unit/InteractsWithDirectoriesConcernTest.php +++ b/packages/framework/tests/Unit/InteractsWithDirectoriesConcernTest.php @@ -10,8 +10,6 @@ use Illuminate\Support\Facades\File; /** - * Class InteractsWithDirectoriesConcernTest. - * * @covers \Hyde\Framework\Concerns\InteractsWithDirectories */ class InteractsWithDirectoriesConcernTest extends TestCase @@ -57,6 +55,7 @@ public function testNeedsDirectoryHandlesExistingDirectory() { $this->needsDirectory('foo'); $this->needsDirectory('foo'); + $this->assertDirectoryExists(Hyde::path('foo')); } @@ -69,6 +68,7 @@ public function testNeedsDirectoriesCreatesSingleDirectory() public function testNeedsDirectoriesCreatesMultipleDirectories() { $this->needsDirectories(['foo', 'bar']); + $this->assertDirectoryExists(Hyde::path('foo')); $this->assertDirectoryExists(Hyde::path('bar')); diff --git a/packages/framework/tests/Unit/LoadConfigurationTest.php b/packages/framework/tests/Unit/LoadConfigurationTest.php index 4358e8bfd6e..ff3e966f8fc 100644 --- a/packages/framework/tests/Unit/LoadConfigurationTest.php +++ b/packages/framework/tests/Unit/LoadConfigurationTest.php @@ -66,6 +66,6 @@ public function __construct(array $env) protected function getEnv(string $name): string|false|null { - return $this->env[$name]; + return $this->env[$name] ?? null; } } diff --git a/packages/framework/tests/Unit/MarkdownDocumentTest.php b/packages/framework/tests/Unit/MarkdownDocumentTest.php index dce948cd7c2..ae88a4a464c 100644 --- a/packages/framework/tests/Unit/MarkdownDocumentTest.php +++ b/packages/framework/tests/Unit/MarkdownDocumentTest.php @@ -20,80 +20,92 @@ class MarkdownDocumentTest extends TestCase public function testConstructorCreatesNewMarkdownDocument() { $document = new MarkdownDocument([], ''); + $this->assertInstanceOf(MarkdownDocument::class, $document); } public function testConstructorArgumentsAreOptional() { $document = new MarkdownDocument(); + $this->assertInstanceOf(MarkdownDocument::class, $document); } public function testConstructorArgumentsAreAssigned() { $document = new MarkdownDocument(['foo' => 'bar'], 'Hello, world!'); + $this->assertEquals(FrontMatter::fromArray(['foo' => 'bar']), $document->matter); } public function testMagicToStringMethodReturnsBody() { $document = new MarkdownDocument(['foo' => 'bar'], 'Hello, world!'); - $this->assertEquals('Hello, world!', (string) $document); + + $this->assertSame('Hello, world!', (string) $document); } public function testCompileMethodReturnsRenderedHtml() { $document = new MarkdownDocument([], 'Hello, world!'); - $this->assertEquals("

Hello, world!

\n", $document->markdown->compile()); + + $this->assertSame("

Hello, world!

\n", $document->markdown->compile()); } public function testToHtmlMethodReturnsRenderedAsHtmlString() { $document = new MarkdownDocument([], 'Hello, world!'); + $this->assertInstanceOf(HtmlString::class, $document->markdown->toHtml()); - $this->assertEquals("

Hello, world!

\n", (string) $document->markdown->toHtml()); + $this->assertSame("

Hello, world!

\n", (string) $document->markdown->toHtml()); } public function testParseMethodParsesAFileUsingTheMarkdownFileService() { file_put_contents('_pages/foo.md', "---\nfoo: bar\n---\nHello, world!"); + $document = MarkdownDocument::parse('_pages/foo.md'); + $this->assertInstanceOf(MarkdownDocument::class, $document); - $this->assertEquals('Hello, world!', $document->markdown()->body()); + $this->assertSame('Hello, world!', $document->markdown()->body()); $this->assertEquals(FrontMatter::fromArray(['foo' => 'bar']), $document->matter()); + Filesystem::unlink('_pages/foo.md'); } public function testToArrayMethodReturnsArrayMarkdownBodyLines() { $document = new MarkdownDocument(body: "foo\nbar\nbaz"); - $this->assertEquals(['foo', 'bar', 'baz'], $document->markdown->toArray()); + $this->assertSame(['foo', 'bar', 'baz'], $document->markdown->toArray()); } public function testFromFileMethodReturnsNewMarkdownDocument() { file_put_contents('_pages/foo.md', "---\nfoo: bar\n---\nHello, world!"); + $markdown = Markdown::fromFile('_pages/foo.md'); + $this->assertInstanceOf(Markdown::class, $markdown); - $this->assertEquals('Hello, world!', $markdown->body()); + $this->assertSame('Hello, world!', $markdown->body()); + Filesystem::unlink('_pages/foo.md'); } - public function end_of_markdown_body_is_trimmed() + public function testEndOfMarkdownBodyIsTrimmed() { $markdown = new Markdown("Hello, world!\n\r\t "); - $this->assertEquals('Hello, world!', $markdown->body()); + $this->assertSame('Hello, world!', $markdown->body()); } public function testCarriageReturnsAreNormalized() { $markdown = new Markdown("foo\rbar"); - $this->assertEquals("foo\rbar", $markdown->body()); + $this->assertSame("foo\rbar", $markdown->body()); $markdown = new Markdown("foo\r\nbar"); - $this->assertEquals("foo\nbar", $markdown->body()); + $this->assertSame("foo\nbar", $markdown->body()); $markdown = new Markdown("foo\nbar"); - $this->assertEquals("foo\nbar", $markdown->body()); + $this->assertSame("foo\nbar", $markdown->body()); } } diff --git a/packages/framework/tests/Unit/MarkdownFacadeTest.php b/packages/framework/tests/Unit/MarkdownFacadeTest.php index 2f17ee603a5..88531f35744 100644 --- a/packages/framework/tests/Unit/MarkdownFacadeTest.php +++ b/packages/framework/tests/Unit/MarkdownFacadeTest.php @@ -4,23 +4,19 @@ namespace Hyde\Framework\Testing\Unit; +use Hyde\Testing\UnitTestCase; use Hyde\Markdown\Models\Markdown; -use PHPUnit\Framework\TestCase; /** - * Class MarkdownConverterTest. - * * @covers \Hyde\Markdown\Models\Markdown */ -class MarkdownFacadeTest extends TestCase +class MarkdownFacadeTest extends UnitTestCase { public function testRender(): void { - $markdown = '# Hello World!'; - - $html = Markdown::render($markdown); + $html = Markdown::render('# Hello World!'); $this->assertIsString($html); - $this->assertEquals("

Hello World!

\n", $html); + $this->assertSame("

Hello World!

\n", $html); } } diff --git a/packages/framework/tests/Unit/NavigationItemIsActiveHelperTest.php b/packages/framework/tests/Unit/NavigationItemIsActiveHelperTest.php index e747d0b9f0f..06c81846a9b 100644 --- a/packages/framework/tests/Unit/NavigationItemIsActiveHelperTest.php +++ b/packages/framework/tests/Unit/NavigationItemIsActiveHelperTest.php @@ -20,11 +20,8 @@ */ class NavigationItemIsActiveHelperTest extends UnitTestCase { - public static function setUpBeforeClass(): void - { - self::needsKernel(); - self::mockConfig(); - } + protected static bool $needsKernel = true; + protected static bool $needsConfig = true; protected function tearDown(): void { diff --git a/packages/framework/tests/Unit/Pages/MarkdownPostHelpersTest.php b/packages/framework/tests/Unit/Pages/MarkdownPostHelpersTest.php index 721c575eb86..8bbcc8a97d9 100644 --- a/packages/framework/tests/Unit/Pages/MarkdownPostHelpersTest.php +++ b/packages/framework/tests/Unit/Pages/MarkdownPostHelpersTest.php @@ -15,44 +15,44 @@ class MarkdownPostHelpersTest extends TestCase public function testGetCurrentPagePathReturnsLocalUriPathForPostSlug() { $post = new MarkdownPost('foo-bar'); - $this->assertEquals('posts/foo-bar', $post->getRouteKey()); + $this->assertSame('posts/foo-bar', $post->getRouteKey()); } public function testGetCanonicalLinkReturnsCanonicalUriPathForPostSlug() { config(['hyde.url' => 'https://example.com']); $post = new MarkdownPost('foo-bar'); - $this->assertEquals('https://example.com/posts/foo-bar.html', $post->getCanonicalUrl()); + $this->assertSame('https://example.com/posts/foo-bar.html', $post->getCanonicalUrl()); } public function testGetCanonicalLinkReturnsPrettyUrlWhenEnabled() { config(['hyde.url' => 'https://example.com', 'hyde.pretty_urls' => true]); $post = new MarkdownPost('foo-bar'); - $this->assertEquals('https://example.com/posts/foo-bar', $post->getCanonicalUrl()); + $this->assertSame('https://example.com/posts/foo-bar', $post->getCanonicalUrl()); } public function testGetPostDescriptionReturnsPostDescriptionWhenSetInFrontMatter() { $post = MarkdownPost::make('foo-bar', ['description' => 'This is a post description']); - $this->assertEquals('This is a post description', $post->description); + $this->assertSame('This is a post description', $post->description); } public function testGetPostDescriptionReturnsPostBodyWhenNoDescriptionSetInFrontMatter() { $post = MarkdownPost::make('foo-bar', [], 'This is a post body'); - $this->assertEquals('This is a post body', $post->description); + $this->assertSame('This is a post body', $post->description); } public function testDynamicDescriptionIsTruncatedWhenLongerThan128Characters() { $post = MarkdownPost::make('foo-bar', [], str_repeat('a', 128)); - $this->assertEquals(str_repeat('a', 125).'...', $post->description); + $this->assertSame(str_repeat('a', 125).'...', $post->description); } public function testDynamicDescriptionStripsMarkdown() { $post = MarkdownPost::make('foo-bar', [], '## This is a **bold** description with [a link](https://example.com) and more'); - $this->assertEquals('This is a bold description with a link and more', $post->description); + $this->assertSame('This is a bold description with a link and more', $post->description); } } diff --git a/packages/framework/tests/Feature/RenderHelperTest.php b/packages/framework/tests/Unit/RenderHelperTest.php similarity index 70% rename from packages/framework/tests/Feature/RenderHelperTest.php rename to packages/framework/tests/Unit/RenderHelperTest.php index b7d553eac4d..ee0cc280ecb 100644 --- a/packages/framework/tests/Feature/RenderHelperTest.php +++ b/packages/framework/tests/Unit/RenderHelperTest.php @@ -2,21 +2,36 @@ declare(strict_types=1); -namespace Hyde\Framework\Testing\Feature; +namespace Hyde\Framework\Testing\Unit; +use Mockery; +use TypeError; use Hyde\Pages\MarkdownPage; +use Illuminate\View\Factory; +use InvalidArgumentException; +use Hyde\Support\Models\Route; +use Hyde\Testing\UnitTestCase; use Hyde\Support\Facades\Render; use Hyde\Support\Models\RenderData; -use Hyde\Testing\TestCase; use Illuminate\Support\Facades\View; -use InvalidArgumentException; /** * @covers \Hyde\Support\Models\RenderData * @covers \Hyde\Support\Facades\Render */ -class RenderHelperTest extends TestCase +class RenderHelperTest extends UnitTestCase { + protected static bool $needsKernel = true; + protected static bool $needsConfig = true; + + protected function setUp(): void + { + parent::setUp(); + + Render::swap(new RenderData()); + View::swap(Mockery::mock(Factory::class)->makePartial()); + } + public function testSetAndGetPage() { $this->assertNull(Render::getPage()); @@ -62,12 +77,33 @@ public function testShareToView() $this->assertSame($page->getRouteKey(), View::shared('routeKey')); } - public function testShare() + public function testShareRouteKey() { $this->assertNull(Render::getRouteKey()); - Render::share('routeKey', 'bar'); - $this->assertSame('bar', Render::getRouteKey()); + Render::share('routeKey', 'foo'); + + $this->assertSame('foo', Render::getRouteKey()); + } + + public function testShareRoute() + { + $this->assertNull(Render::getRoute()); + + $route = new Route(new MarkdownPage()); + Render::share('route', $route); + + $this->assertSame($route, Render::getRoute()); + } + + public function testSharePage() + { + $this->assertNull(Render::getPage()); + + $page = new MarkdownPage(); + Render::share('page', $page); + + $this->assertSame($page, Render::getPage()); } public function testShareInvalidProperty() @@ -78,6 +114,22 @@ public function testShareInvalidProperty() Render::share('foo', 'bar'); } + public function testShareInvalidType() + { + $this->expectException(TypeError::class); + $this->expectExceptionMessage('Hyde\Support\Models\RenderData::share(): Argument #2 ($value) must be of type Hyde\Pages\Concerns\HydePage|Hyde\Support\Models\Route|string, array given'); + + Render::share('route', ['foo']); + } + + public function testShareInvalidTypeForProperty() + { + $this->expectException(TypeError::class); + $this->expectExceptionMessage('Cannot assign string to property Hyde\Support\Models\RenderData::$route of type Hyde\Support\Models\Route'); + + Render::share('route', 'bar'); + } + public function testShareCascadesDataToView() { $this->assertNull(View::shared('routeKey')); diff --git a/packages/framework/tests/Unit/SchemaContractsTest.php b/packages/framework/tests/Unit/SchemaContractsTest.php index 270c1f2ce5a..2d78f740b47 100644 --- a/packages/framework/tests/Unit/SchemaContractsTest.php +++ b/packages/framework/tests/Unit/SchemaContractsTest.php @@ -15,6 +15,7 @@ /** * A state test to ensure the schemas can't be changed without breaking the tests. + * * This requires contributors to consider the impact of their changes as schema changes are rarely backwards compatible. * * @see \Hyde\Markdown\Contracts\FrontMatter\PageSchema @@ -96,7 +97,7 @@ public function testAllSchemasAreTested() $schemas = array_values($schemas); - $this->assertEquals(self::SCHEMAS, $schemas); + $this->assertSame(self::SCHEMAS, $schemas); } public function testAllSchemasExtendFrontMatterSchemaInterface() @@ -128,7 +129,7 @@ public function testEachInterfaceOnlyHasOneSchema() } } - private function assertClassHasConstant(string $constant, string $schema) + protected function assertClassHasConstant(string $constant, string $schema): void { $this->assertTrue( defined("$schema::$constant"), diff --git a/packages/framework/tests/Unit/SerializableContractTest.php b/packages/framework/tests/Unit/SerializableContractTest.php index 97d1b60ad6e..a19c2402082 100644 --- a/packages/framework/tests/Unit/SerializableContractTest.php +++ b/packages/framework/tests/Unit/SerializableContractTest.php @@ -4,16 +4,16 @@ namespace Hyde\Framework\Testing\Unit; +use Hyde\Testing\UnitTestCase; use Hyde\Support\Contracts\SerializableContract; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Support\Jsonable; use JsonSerializable; -use PHPUnit\Framework\TestCase; /** * @see \Hyde\Support\Contracts\SerializableContract */ -class SerializableContractTest extends TestCase +class SerializableContractTest extends UnitTestCase { public function testInterface() { diff --git a/packages/framework/tests/Unit/ServeCommandOptionsUnitTest.php b/packages/framework/tests/Unit/ServeCommandOptionsUnitTest.php index 86cf267463d..f08d9cd0d60 100644 --- a/packages/framework/tests/Unit/ServeCommandOptionsUnitTest.php +++ b/packages/framework/tests/Unit/ServeCommandOptionsUnitTest.php @@ -41,12 +41,14 @@ public function testGetHostSelectionWithHostOption() public function testGetHostSelectionWithConfigOption() { self::mockConfig(['hyde.server.host' => 'foo']); + $this->assertSame('foo', $this->getMock()->getHostSelection()); } public function testGetHostSelectionWithHostOptionAndConfigOption() { self::mockConfig(['hyde.server.host' => 'foo']); + $this->assertSame('bar', $this->getMock(['host' => 'bar'])->getHostSelection()); } @@ -63,12 +65,14 @@ public function testGetPortSelectionWithPortOption() public function testGetPortSelectionWithConfigOption() { self::mockConfig(['hyde.server.port' => 8082]); + $this->assertSame(8082, $this->getMock()->getPortSelection()); } public function testGetPortSelectionWithPortOptionAndConfigOption() { self::mockConfig(['hyde.server.port' => 8082]); + $this->assertSame(8081, $this->getMock(['port' => 8081])->getPortSelection()); } @@ -230,6 +234,7 @@ protected function openInBrowser(): void }; $command->safeHandle(); + $this->assertTrue($command->openInBrowserCalled); } diff --git a/packages/framework/tests/Unit/SourceFilesInCustomDirectoriesCanBeCompiledTest.php b/packages/framework/tests/Unit/SourceFilesInCustomDirectoriesCanBeCompiledTest.php index f5208611fe0..087d49f29b1 100644 --- a/packages/framework/tests/Unit/SourceFilesInCustomDirectoriesCanBeCompiledTest.php +++ b/packages/framework/tests/Unit/SourceFilesInCustomDirectoriesCanBeCompiledTest.php @@ -15,16 +15,13 @@ use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\File; -/** - * Class SourceFilesInCustomDirectoriesCanBeCompiledTest. - */ class SourceFilesInCustomDirectoriesCanBeCompiledTest extends TestCase { protected function setUp(): void { parent::setUp(); - is_dir(Hyde::path('testSourceDir')) || mkdir(Hyde::path('testSourceDir')); + is_dir(Hyde::path('testSourceDir')) || Filesystem::makeDirectory('testSourceDir'); } protected function tearDown(): void @@ -36,7 +33,7 @@ protected function tearDown(): void public function testMarkdownPostsInChangedDirectoryCanBeCompiled() { - mkdir(Hyde::path('testSourceDir/blog')); + Filesystem::makeDirectory('testSourceDir/blog'); Filesystem::touch('testSourceDir/blog/test.md'); MarkdownPost::setSourceDirectory('testSourceDir/blog'); @@ -44,12 +41,13 @@ public function testMarkdownPostsInChangedDirectoryCanBeCompiled() StaticPageBuilder::handle(MarkdownPost::parse('test')); $this->assertFileExists(Hyde::path('_site/posts/test.html')); + Filesystem::unlink('_site/posts/test.html'); } public function testMarkdownPagesInChangedDirectoryCanBeCompiled() { - mkdir(Hyde::path('testSourceDir/pages')); + Filesystem::makeDirectory('testSourceDir/pages'); Filesystem::touch('testSourceDir/pages/test.md'); MarkdownPage::setSourceDirectory('testSourceDir/pages'); @@ -62,7 +60,7 @@ public function testMarkdownPagesInChangedDirectoryCanBeCompiled() public function testDocumentationPagesInChangedDirectoryCanBeCompiled() { - mkdir(Hyde::path('testSourceDir/documentation')); + Filesystem::makeDirectory('testSourceDir/documentation'); Filesystem::touch('testSourceDir/documentation/test.md'); DocumentationPage::setSourceDirectory('testSourceDir/documentation'); @@ -70,12 +68,13 @@ public function testDocumentationPagesInChangedDirectoryCanBeCompiled() StaticPageBuilder::handle(DocumentationPage::parse('test')); $this->assertFileExists(Hyde::path('_site/docs/test.html')); + Filesystem::unlink('_site/docs/test.html'); } public function testBladePagesInChangedDirectoryCanBeCompiled() { - mkdir(Hyde::path('testSourceDir/blade')); + Filesystem::makeDirectory('testSourceDir/blade'); Filesystem::touch('testSourceDir/blade/test.blade.php'); BladePage::setSourceDirectory('testSourceDir/blade'); @@ -84,6 +83,7 @@ public function testBladePagesInChangedDirectoryCanBeCompiled() StaticPageBuilder::handle(BladePage::parse('test')); $this->assertFileExists(Hyde::path('_site/test.html')); + Filesystem::unlink('_site/test.html'); } } diff --git a/packages/framework/tests/Unit/TestBuildStaticSiteCommandFlagToEnablePrettyUrlsTest.php b/packages/framework/tests/Unit/TestBuildStaticSiteCommandFlagToEnablePrettyUrlsTest.php index b9e3638b7d2..1e4dffa2780 100644 --- a/packages/framework/tests/Unit/TestBuildStaticSiteCommandFlagToEnablePrettyUrlsTest.php +++ b/packages/framework/tests/Unit/TestBuildStaticSiteCommandFlagToEnablePrettyUrlsTest.php @@ -8,9 +8,6 @@ use Hyde\Testing\TestCase; use Illuminate\Support\Facades\File; -/** - * Class TestBuildStaticSiteCommandFlagToEnablePrettyUrlsTest. - */ class TestBuildStaticSiteCommandFlagToEnablePrettyUrlsTest extends TestCase { public function testPrettyUrlsCanBeEnabledWithFlag() diff --git a/packages/framework/tests/Unit/UnixsumTest.php b/packages/framework/tests/Unit/UnixsumTest.php index b72b3eefab1..968c1d0d5f1 100644 --- a/packages/framework/tests/Unit/UnixsumTest.php +++ b/packages/framework/tests/Unit/UnixsumTest.php @@ -4,15 +4,14 @@ namespace Hyde\Framework\Testing\Unit; -use Hyde\Foundation\HydeKernel; +use Hyde\Testing\UnitTestCase; use Illuminate\Filesystem\Filesystem; use Mockery; -use PHPUnit\Framework\TestCase; use function Hyde\unixsum; use function Hyde\unixsum_file; -class UnixsumTest extends TestCase +class UnixsumTest extends UnitTestCase { public function testMethodReturnsString() { @@ -21,7 +20,7 @@ public function testMethodReturnsString() public function testMethodReturnsStringWithLengthOf32() { - $this->assertEquals(32, strlen(unixsum('foo'))); + $this->assertSame(32, strlen(unixsum('foo'))); } public function testMethodReturnsStringMatchingExpectedFormat() @@ -31,7 +30,7 @@ public function testMethodReturnsStringMatchingExpectedFormat() public function testMethodReturnsSameValueForSameStringUsingNormalMethod() { - $this->assertEquals(md5('foo'), unixsum('foo')); + $this->assertSame(md5('foo'), unixsum('foo')); } public function testMethodReturnsDifferentValueForDifferentString() @@ -51,27 +50,27 @@ public function testFunctionIsSpaceSensitive() public function testMethodReturnsSameValueRegardlessOfEndOfLineSequence() { - $this->assertEquals(unixsum('foo'), unixsum('foo')); - $this->assertEquals(unixsum("foo\n"), unixsum("foo\n")); - $this->assertEquals(unixsum("foo\n"), unixsum("foo\r")); - $this->assertEquals(unixsum("foo\n"), unixsum("foo\r\n")); + $this->assertSame(unixsum('foo'), unixsum('foo')); + $this->assertSame(unixsum("foo\n"), unixsum("foo\n")); + $this->assertSame(unixsum("foo\n"), unixsum("foo\r")); + $this->assertSame(unixsum("foo\n"), unixsum("foo\r\n")); } public function testMethodReturnsSameValueForStringWithMixedEndOfLineSequences() { - $this->assertEquals(unixsum("foo\nbar\r\nbaz\r\n"), - unixsum("foo\nbar\nbaz\n")); + $this->assertSame(unixsum("foo\nbar\r\nbaz\r\n"), unixsum("foo\nbar\nbaz\n")); } public function testMethodReturnsSameValueWhenLoadedFromFileUsingShorthand() { + self::needsKernel(); + $string = "foo\nbar\r\nbaz\r\n"; - HydeKernel::setInstance(new HydeKernel()); - $filesystem = Mockery::mock(Filesystem::class); - $filesystem->shouldReceive('get')->andReturn($string); - app()->instance(Filesystem::class, $filesystem); + app()->instance(Filesystem::class, Mockery::mock(Filesystem::class, [ + 'get' => $string, + ])); - $this->assertEquals(unixsum($string), unixsum_file('foo')); + $this->assertSame(unixsum($string), unixsum_file('foo')); } } diff --git a/packages/framework/tests/Feature/Services/ViewDiffServiceTest.php b/packages/framework/tests/Unit/ViewDiffServiceTest.php similarity index 58% rename from packages/framework/tests/Feature/Services/ViewDiffServiceTest.php rename to packages/framework/tests/Unit/ViewDiffServiceTest.php index ae16dd1f3f6..fc0cbface66 100644 --- a/packages/framework/tests/Feature/Services/ViewDiffServiceTest.php +++ b/packages/framework/tests/Unit/ViewDiffServiceTest.php @@ -2,11 +2,11 @@ declare(strict_types=1); -namespace Hyde\Framework\Testing\Feature\Services; +namespace Hyde\Framework\Testing\Unit; -use Hyde\Framework\Services\ViewDiffService; use Hyde\Hyde; -use Hyde\Testing\TestCase; +use Hyde\Testing\UnitTestCase; +use Hyde\Framework\Services\ViewDiffService; use function Hyde\unixsum; use function Hyde\unixsum_file; @@ -14,12 +14,13 @@ /** * @covers \Hyde\Framework\Services\ViewDiffService */ -class ViewDiffServiceTest extends TestCase +class ViewDiffServiceTest extends UnitTestCase { + protected static bool $needsKernel = true; + public function testGetFilecache() { - $fileCacheService = new ViewDiffService(); - $fileCache = $fileCacheService->getViewFileHashIndex(); + $fileCache = ViewDiffService::getViewFileHashIndex(); $this->assertIsArray($fileCache); $this->assertArrayHasKey('resources/views/layouts/app.blade.php', $fileCache); @@ -29,26 +30,21 @@ public function testGetFilecache() public function testGetChecksums() { - $fileCacheService = new ViewDiffService(); - $checksums = $fileCacheService->getChecksums(); + $checksums = ViewDiffService::getChecksums(); $this->assertIsArray($checksums); - $this->assertEquals(32, strlen($checksums[0])); + $this->assertSame(32, strlen($checksums[0])); } public function testChecksumMatchesAny() { - $fileCacheService = new ViewDiffService(); - - $this->assertTrue($fileCacheService->checksumMatchesAny( + $this->assertTrue(ViewDiffService::checksumMatchesAny( unixsum_file(Hyde::vendorPath('resources/views/layouts/app.blade.php')) )); } public function testChecksumMatchesAnyFalse() { - $fileCacheService = new ViewDiffService(); - - $this->assertFalse($fileCacheService->checksumMatchesAny(unixsum('foo'))); + $this->assertFalse(ViewDiffService::checksumMatchesAny(unixsum('foo'))); } } diff --git a/packages/publications/src/Commands/MakePublicationCommand.php b/packages/publications/src/Commands/MakePublicationCommand.php index bd55c179331..0c5e61a5dcf 100644 --- a/packages/publications/src/Commands/MakePublicationCommand.php +++ b/packages/publications/src/Commands/MakePublicationCommand.php @@ -151,14 +151,15 @@ protected function captureMediaFieldInput(PublicationFieldDefinition $field): ?P $mediaFiles = Publications::getMediaForType($this->publicationType); if ($mediaFiles->isEmpty()) { - return $this->handleEmptyMediaFilesCollection($field); + $this->handleEmptyMediaFilesCollection($field); + + return null; } return new PublicationFieldValue(PublicationFieldTypes::Media, $this->choice('Which file would you like to use?', $mediaFiles->toArray())); } - /** @return null */ - protected function handleEmptyMediaFilesCollection(PublicationFieldDefinition $field) + protected function handleEmptyMediaFilesCollection(PublicationFieldDefinition $field): void { $directory = sprintf('directory %s/%s/', Hyde::getMediaDirectory(), $this->publicationType->getIdentifier() @@ -172,7 +173,7 @@ protected function handleEmptyMediaFilesCollection(PublicationFieldDefinition $f $this->warn("Warning: No media files found in $directory"); if ($this->confirm('Would you like to skip this field?', true)) { // We could have a choice here, where 0 skips, and 1 reloads the media files - return null; + return; } else { throw new InvalidArgumentException('Unable to locate any media files for this publication type'); } diff --git a/packages/publications/src/Commands/MakePublicationTypeCommand.php b/packages/publications/src/Commands/MakePublicationTypeCommand.php index c8de642489e..d4f24fb0f79 100644 --- a/packages/publications/src/Commands/MakePublicationTypeCommand.php +++ b/packages/publications/src/Commands/MakePublicationTypeCommand.php @@ -161,7 +161,7 @@ protected function getPageSize(): int ); } - protected function checkIfFieldIsDuplicate($name): bool + protected function checkIfFieldIsDuplicate(string $name): bool { if ($this->fields->where('name', $name)->count() > 0) { $this->error("Field name [$name] already exists!"); diff --git a/packages/publications/src/Commands/ValidatePublicationTypesCommand.php b/packages/publications/src/Commands/ValidatePublicationTypesCommand.php index 31de77058e1..26cbb56527a 100644 --- a/packages/publications/src/Commands/ValidatePublicationTypesCommand.php +++ b/packages/publications/src/Commands/ValidatePublicationTypesCommand.php @@ -125,7 +125,7 @@ protected function displayFieldDefinitionErrors(array $schemaFields): void } } - protected function outputSummary($timeStart): void + protected function outputSummary(float $timeStart): void { $this->newLine(); $this->info(sprintf('All done in %sms using %sMB peak memory!', diff --git a/packages/publications/src/Models/PublicationType.php b/packages/publications/src/Models/PublicationType.php index ae29dc6b114..fc3a31f1c3d 100644 --- a/packages/publications/src/Models/PublicationType.php +++ b/packages/publications/src/Models/PublicationType.php @@ -134,6 +134,7 @@ public function toArray(): array return $array; } + /** @param int $options */ public function toJson($options = JSON_PRETTY_PRINT): string { return json_encode($this->toArray(), $options); diff --git a/packages/realtime-compiler/tests/RealtimeCompilerTest.php b/packages/realtime-compiler/tests/RealtimeCompilerTest.php index 5c2cec606c3..43d6bf146ad 100644 --- a/packages/realtime-compiler/tests/RealtimeCompilerTest.php +++ b/packages/realtime-compiler/tests/RealtimeCompilerTest.php @@ -21,7 +21,7 @@ putenv('SERVER_LIVE_EDIT=false'); }); -test('handle routes index page', function () { +it('handles routes index page', function () { putenv('SERVER_DASHBOARD=false'); mockRoute(''); @@ -40,7 +40,7 @@ Filesystem::unlink('_site/index.html'); }); -test('handle routes custom pages', function () { +it('handles routes custom pages', function () { mockRoute('foo'); Filesystem::put('_pages/foo.md', '# Hello World!'); @@ -58,7 +58,7 @@ Filesystem::unlink('_site/foo.html'); }); -test('handle routes pages with .html extension', function () { +it('handles routes pages with .html extension', function () { mockRoute('foo.html'); Filesystem::put('_pages/foo.md', '# Hello World!'); @@ -76,7 +76,7 @@ Filesystem::unlink('_site/foo.html'); }); -test('handle routes static assets', function () { +it('handles routes static assets', function () { mockRoute('media/app.css'); $kernel = new HttpKernel(); @@ -89,14 +89,14 @@ expect($response->body)->toBe(file_get_contents(\Hyde\Hyde::path('_media/app.css'))); }); -test('handle throws route not found exception for missing route', function () { +it('handles throws route not found exception for missing route', function () { mockRoute('missing'); $kernel = new HttpKernel(); $kernel->handle(new Request()); })->throws(RouteNotFoundException::class, 'Route [missing] not found'); -test('handle sends 404 error response for missing asset', function () { +it('handles sends 404 error response for missing asset', function () { mockRoute('missing.css'); $kernel = new HttpKernel(); diff --git a/packages/testing/src/TestCase.php b/packages/testing/src/TestCase.php index aede20a5b2d..60cef134a4b 100644 --- a/packages/testing/src/TestCase.php +++ b/packages/testing/src/TestCase.php @@ -4,16 +4,14 @@ namespace Hyde\Testing; -use function config; -use function file_get_contents; - use Hyde\Hyde; - -use function Hyde\normalize_newlines; - use Illuminate\View\Component; use LaravelZero\Framework\Testing\TestCase as BaseTestCase; +use function Hyde\normalize_newlines; +use function file_get_contents; +use function config; + abstract class TestCase extends BaseTestCase { use CreatesApplication;