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

Simplify publication tag handling #770

Merged
merged 20 commits into from
Dec 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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 @@ -33,14 +33,16 @@ class MakePublicationCommand extends ValidatingCommand
/** @var string */
protected $description = 'Create a new publication item';

protected PublicationType $pubType;

public function safeHandle(): int
{
$this->title('Creating a new Publication!');

$pubType = $this->getPubTypeSelection($this->getPublicationTypes());
$fieldData = $this->collectFieldData($pubType);
$this->pubType = $this->getPubTypeSelection($this->getPublicationTypes());
$fieldData = $this->collectFieldData($this->pubType);

$creator = new CreatesNewPublicationPage($pubType, $fieldData, $this->hasForceOption(), $this->output);
$creator = new CreatesNewPublicationPage($this->pubType, $fieldData, $this->hasForceOption(), $this->output);
if ($creator->hasFileConflict()) {
$this->error('Error: A publication already exists with the same canonical field value');
if ($this->confirm('Do you wish to overwrite the existing file?')) {
Expand Down Expand Up @@ -172,7 +174,7 @@ protected function captureTagFieldInput(PublicationField $field)
$this->output->writeln($field->name.' (enter 0 to reload tag definitions)');
do {
$offset = 0;
$tagsForGroup = PublicationService::getAllTags()->{$field->tagGroup};
$tagsForGroup = PublicationService::getAllTags()->{$this->pubType->name};
foreach ($tagsForGroup as $index => $value) {
$offset = $index + 1;
$this->output->writeln(" $offset: $value");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public function safeHandle(): int
foreach ($publication->type->fields as $field) {
$countFields++;
$fieldName = $field['name'];
$pubTypeField = new PublicationField($field['type'], $fieldName, $field['tagGroup'] ?? null);
$pubTypeField = new PublicationField($field['type'], $fieldName);

try {
if ($verbose) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ protected function generateFieldData(PublicationField $field): string|int|float|
'image' => 'https://picsum.photos/id/'.rand(1, 1000).'/400/400',
'integer' => rand(-100000, 100000),
'string' => substr($this->fakeSentence(10), 0, rand(0, 255)),
'tag' => $this->getTags($field),
'tag' => $this->getTags(),
'text' => $this->getTextValue(rand(3, 20)),
'url' => $this->fakeUrl(),
};
Expand Down Expand Up @@ -128,9 +128,9 @@ protected function getArrayItems(): array
return $arrayItems;
}

protected function getTags(PublicationField $field): string
protected function getTags(): string
{
$tags = PublicationService::getValuesForTagName($field->tagGroup, false);
$tags = PublicationService::getValuesForTagName($this->pubType->getIdentifier());

return $tags->isEmpty() ? '' : $tags->random();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,17 @@ class PublicationField implements SerializableContract

public readonly PublicationFieldTypes $type;
public readonly string $name;
public readonly ?string $tagGroup;
public readonly array $rules;

public static function fromArray(array $array): static
{
return new static(...$array);
}

public function __construct(PublicationFieldTypes|string $type, string $name, ?string $tagGroup = null, array $rules = [])
public function __construct(PublicationFieldTypes|string $type, string $name, array $rules = [])
{
$this->type = $type instanceof PublicationFieldTypes ? $type : PublicationFieldTypes::from(strtolower($type));
$this->name = Str::kebab($name);
$this->tagGroup = $tagGroup;
$this->rules = $rules;
}

Expand All @@ -48,7 +46,6 @@ public function toArray(): array
return array_filter([
'type' => $this->type->value,
'name' => $this->name,
'tagGroup' => $this->tagGroup,
'rules' => $this->rules,
]);
}
Expand All @@ -75,7 +72,7 @@ public function getValidationRules(?PublicationType $publicationType = null): Co
$fieldRules->add("in:$valueList");
break;
case 'tag':
$tagValues = PublicationService::getValuesForTagName($this->tagGroup) ?? collect([]);
$tagValues = PublicationService::getValuesForTagName($publicationType?->getIdentifier() ?? '') ?? collect([]);
$valueList = $tagValues->implode(',');
$fieldRules->add("in:$valueList");
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Hyde\Framework\Features\Publications;

use function file_exists;
use Hyde\Framework\Actions\SourceFileParser;
use Hyde\Framework\Features\Publications\Models\PublicationType;
use Hyde\Hyde;
Expand Down Expand Up @@ -57,46 +58,18 @@ public static function getMediaForPubType(PublicationType $pubType): Collection

/**
* Get all available tags.
*
* @param bool $reload Reload the tags from the filesystem
* @return \Rgasch\Collection\Collection
*
* @throws \Safe\Exceptions\FilesystemException
* @throws \Safe\Exceptions\JsonException
*/
public static function getAllTags(bool $reload = true): Collection
public static function getAllTags(): Collection
{
$filename = Hyde::path('tags.json');
if (! file_exists($filename)) {
return Collection::create();
}

static $tags = null;
if (! $tags || $reload) {
$tags = Collection::create(json_decode(file_get_contents($filename), true))->sortKeys();
}

return $tags;
return Collection::create(self::parseTagsFile())->sortKeys();
}

/**
* Get all values for a given tag name.
*
* @param string $tagName
* @param bool $reload Reload the tags from the filesystem
* @return \Rgasch\Collection\Collection
*
* @throws \Safe\Exceptions\FilesystemException
* @throws \Safe\Exceptions\JsonException
*/
public static function getValuesForTagName(string $tagName, bool $reload = true): Collection
public static function getValuesForTagName(string $tagName): Collection
{
$tags = self::getAllTags($reload);
if (! $tags->get($tagName)) {
return Collection::create();
}

return $tags->$tagName;
return self::getAllTags()->get($tagName) ?? Collection::create();
}

/**
Expand Down Expand Up @@ -131,4 +104,13 @@ protected static function getMediaFiles(string $directory, string $extensions =
{
return glob(Hyde::path("_media/$directory/*.$extensions"), GLOB_BRACE);
}

protected static function parseTagsFile(): array
{
if (file_exists(Hyde::path('tags.json'))) {
return json_decode(file_get_contents(Hyde::path('tags.json')), true);
}

return [];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -131,17 +131,17 @@ public function testWithStringType()

public function testWithTagType()
{
$tags = ['foo' => ['foo', 'bar', 'baz']];
$tags = ['test-publication' => ['foo', 'bar', 'baz']];
$this->file('tags.json', json_encode($tags));
$this->updateSchema('tag', 'tag', tagGroup: 'foo');
$this->updateSchema('tag', 'tag');
(new SeedsPublicationFiles($this->pubType))->create();

$publication = $this->firstPublication();

$this->assertBaseline($publication);
$this->assertNotEmpty($publication->matter('tag'));
$this->assertIsString($publication->matter('tag'));
$this->assertTrue(in_array($publication->matter('tag'), $tags['foo']));
$this->assertTrue(in_array($publication->matter('tag'), $tags['test-publication']));
}

public function testWithTextType()
Expand Down Expand Up @@ -182,10 +182,10 @@ protected function firstPublication(): MarkdownDocument
return MarkdownDocument::parse(Hyde::pathToRelative($this->getPublicationFiles()[0]));
}

protected function updateSchema(string $type, string $name, ?string $tagGroup = null): void
protected function updateSchema(string $type, string $name): void
{
$this->pubType->fields = [
(new PublicationField($type, $name, tagGroup: $tagGroup))->toArray(),
(new PublicationField($type, $name))->toArray(),
];
$this->pubType->save();
}
Expand Down
10 changes: 6 additions & 4 deletions packages/framework/tests/Feature/PublicationFieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,8 @@ public function test_can_get_field_with_optional_properties_as_array()
$this->assertSame([
'type' => 'string',
'name' => 'test',
'tagGroup' => 'foo',
'rules' => ['required'],
], (new PublicationField('string', 'test', 'foo', ['required']))->toArray());
], (new PublicationField('string', 'test', ['required']))->toArray());
}

public function test_can_encode_field_as_json()
Expand All @@ -63,7 +62,10 @@ public function test_can_encode_field_as_json()

public function test_can_get_field_with_optional_properties_as_json()
{
$this->assertSame('{"type":"string","name":"test","tagGroup":"foo","rules":["required"]}', json_encode(new PublicationField('string', 'test', 'foo', ['required'])));
$this->assertSame('{"type":"string","name":"test","rules":["required"]}', json_encode(new PublicationField('string',
'test',
['required']
)));
}

public function test_can_construct_type_using_enum_case()
Expand Down Expand Up @@ -225,7 +227,7 @@ public function testGetRulesForImage()

public function testGetRulesForTag()
{
$rules = (new PublicationField('tag', 'myTag', tagGroup: 'foo'))->getValidationRules();
$rules = (new PublicationField('tag', 'myTag'))->getValidationRules();
$this->assertSame(['in:'], $rules->toArray());
}

Expand Down