Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix and refactor make:publicationType command and add tests for it #678

Merged
merged 19 commits into from
Nov 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@

namespace Hyde\Console\Commands;

use Exception;
use Hyde\Console\Commands\Interfaces\CommandHandleInterface;
use Hyde\Framework\Actions\CreatesNewPublicationTypeSchema;
use Hyde\Framework\Features\Publications\PublicationHelper;
use InvalidArgumentException;
use LaravelZero\Framework\Commands\Command;
use Rgasch\Collection\Collection;

/**
* Hyde Command to create a new publication type.
*
* @see \Hyde\Framework\Testing\Feature\Commands\MakePageCommandTest
* @see \Hyde\Framework\Testing\Feature\Commands\MakePublicationTypeCommandTest
*/
class MakePublicationTypeCommand extends Command implements CommandHandleInterface
{
Expand All @@ -30,17 +32,18 @@ public function handle(): int

$title = $this->argument('title');
if (! $title) {
$title = trim(PublicationHelper::askWithValidation($this, 'nanme', 'Publication type name', ['required', 'string']));
$title = trim(PublicationHelper::askWithValidation($this, 'name', 'Publication type name', ['required', 'string']));
$dirname = PublicationHelper::formatNameForStorage($title);
if (file_exists($dirname)) {
throw new \InvalidArgumentException("Storage path [$dirname] already exists");
throw new InvalidArgumentException("Storage path [$dirname] already exists");
}
}

$fields = $this->captureFieldsDefinitions();

$this->output->writeln('<bg=magenta;fg=white>Choose the default field you wish to sort by:</>');
$this->line(' 0: dateCreated (meta field)');
$offset = 0;
foreach ($fields as $k => $v) {
$offset = $k + 1;
$this->line(" $offset: $v[name]");
Expand Down Expand Up @@ -74,7 +77,7 @@ public function handle(): int

$this->output->writeln('<bg=magenta;fg=white>Choose a canonical name field (the values of this field have to be unique!):</>');
foreach ($fields as $k => $v) {
if ($fields->type != 'image') {
if ($fields->first()->type != 'image') {
$offset = $k + 1;
$this->line(" $offset: $v->name");
}
Expand All @@ -85,7 +88,7 @@ public function handle(): int
try {
$creator = new CreatesNewPublicationTypeSchema($title, $fields, $canonicalField, $sortField, $sortDirection, $pagesize, $prevNextLinks);
$creator->create();
} catch (\Exception $e) {
} catch (Exception $e) {
$this->error('Error: '.$e->getMessage().' at '.$e->getFile().':'.$e->getLine());

return Command::FAILURE;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace Hyde\Framework\Features\Publications;

use Carbon\Carbon;
use Hyde\Foundation\HydeKernel;
use Hyde\Framework\Features\Publications\Models\PublicationType;
use Hyde\Hyde;
use Hyde\Pages\PublicationPage;
Expand All @@ -24,11 +23,11 @@ class PublicationHelper
* @param Command $command
* @param string $name
* @param string $message
* @param array $rules
* @param array $rules
* @return mixed $default
* @param \Rgasch\Collection\Collection|array $rules
* @param mixed|null $default
* @return mixed
*/
public static function askWithValidation(Command $command, string $name, string $message, Collection|array $rules = [], mixed $default = null)
public static function askWithValidation(Command $command, string $name, string $message, Collection|array $rules = [], mixed $default = null): mixed
{
if ($rules instanceof Collection) {
$rules = $rules->toArray();
Expand All @@ -49,23 +48,10 @@ public static function askWithValidation(Command $command, string $name, string
return self::askWithValidation($command, $name, $message, $rules);
}

/**
* Get the available HydeKernel instance.
*
* @return \Hyde\Foundation\HydeKernel
*/
public static function getKernel(): HydeKernel
{
return app(HydeKernel::class);
}

/**
* Format the publication type name to a suitable representation for file storage.
*
* @param string $pubTypeNameRaw
* @return string
*/
public static function formatNameForStorage(string $pubTypeNameRaw)
public static function formatNameForStorage(string $pubTypeNameRaw): string
{
return Str::slug($pubTypeNameRaw);
}
Expand Down Expand Up @@ -96,9 +82,6 @@ public static function getPublicationTypes(): Collection
/**
* Return all publications for a given pub type, optionally sorted by the publication's sortField.
*
* @param PublicationType $pubType
* @return Collection
*
* @throws \Safe\Exceptions\FilesystemException
*/
public static function getPublicationsForPubType(PublicationType $pubType, $sort = true): Collection
Expand All @@ -122,15 +105,10 @@ public static function getPublicationsForPubType(PublicationType $pubType, $sort

/**
* Return all media items for a given publication type.
*
* @param PublicationType $pubType
* @return Collection
*
* @throws \Safe\Exceptions\FilesystemException
*/
public static function getMediaForPubType(PublicationType $pubType, $sort = true): Collection
{
$root = base_path();
$root = Hyde::path();
$files = glob("$root/_media/{$pubType->directory}/*.{jpg,jpeg,png,gif,pdf}", GLOB_BRACE);

$media = Collection::create();
Expand All @@ -148,8 +126,7 @@ public static function getMediaForPubType(PublicationType $pubType, $sort = true
/**
* Read an MD file and return the parsed data.
*
* @param string $fileData
* @return Collection
* @throws \Safe\Exceptions\FilesystemException
*/
public static function getPublicationData(string $mdFileName): PublicationPage
{
Expand All @@ -174,10 +151,6 @@ public static function getPublicationData(string $mdFileName): PublicationPage
/**
* Check whether a given publication type exists.
*
* @param string $pubTypeName
* @param bool $isRaw
* @return bool
*
* @throws \Exception
*/
public static function publicationTypeExists(string $pubTypeName, bool $isRaw = true): bool
Expand All @@ -188,15 +161,4 @@ public static function publicationTypeExists(string $pubTypeName, bool $isRaw =

return self::getPublicationTypes()->has($pubTypeName);
}

/**
* Remove trailing slashes from the start and end of a string.
*
* @param string $string
* @return string
*/
public static function unslash(string $string): string
{
return trim($string, '/\\');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

namespace Hyde\Framework\Testing\Feature\Commands;

use function deleteDirectory;
use Hyde\Hyde;
use Hyde\Testing\TestCase;

/**
* @covers \Hyde\Console\Commands\MakePublicationTypeCommand
*/
class MakePublicationTypeCommandTest extends TestCase
{
public function test_command_creates_publication()
{
$this->artisan('make:publicationType')
->expectsQuestion('Publication type name', 'Test Publication')
->expectsQuestion('Field name', 'Title')
->expectsQuestion('Field type (1-7)', 1)
->expectsQuestion('Min value (for strings, this refers to string length)', 'default')
->expectsQuestion('Max value (for strings, this refers to string length)', 'default')
->expectsQuestion('Add another field (y/n)', 'n')
->expectsQuestion('Sort field (0-1)', 0)
->expectsQuestion('Sort field (1-2)', 1)
->expectsQuestion('Enter the pagesize (0 for no limit)', 10)
->expectsQuestion('Generate previous/next links in detail view (y/n)', 'n')
->expectsQuestion('Canonical field (1-1)', 1)
->expectsOutputToContain('Creating a new Publication Type!')
->expectsOutput('Choose the default field you wish to sort by:')
->expectsOutput('Choose the default sort direction:')
// ->expectsOutput('Publication type created successfully!')
// ->expectsOutput('Saving publicationType data to [test-publication/schema.json]')
->assertExitCode(0);

$this->assertFileExists(Hyde::path('test-publication/schema.json'));
$this->assertEquals(
file_get_contents(Hyde::path('test-publication/schema.json')),
<<<'JSON'
{
"name": "Test Publication",
"canonicalField": "Title",
"sortField": "__createdAt",
"sortDirection": "ASC",
"pagesize": 10,
"prevNextLinks": true,
"detailTemplate": "test-publication_detail",
"listTemplate": "test-publication_list",
"fields": [
{
"name": "Title",
"min": "default",
"max": "default",
"type": "string"
}
]
}
JSON
);

// TODO: Assert Blade templates were created?

deleteDirectory(Hyde::path('test-publication'));
}
}