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

Refactor publication validation helpers to single class #800

Merged
merged 66 commits into from
Jan 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
66 commits
Select commit Hold shift + click to select a range
99c7d7b
Create ValidatesPublications.php
caendesilva Jan 2, 2023
77e8a84
Create ValidatesPublicationsTest.php
caendesilva Jan 2, 2023
a9c0076
Rename class ValidatesPublications to ValidatesPublicationField
caendesilva Jan 2, 2023
4f52925
Apply fixes from StyleCI
StyleCIBot Jan 2, 2023
faab575
Set up class properties and constructor
caendesilva Jan 2, 2023
554b72e
Copy over validation methods from PublicationFieldDefinition
caendesilva Jan 2, 2023
1b6dea8
Deprecate validation methods in PublicationFieldDefinition
caendesilva Jan 2, 2023
db6e0ff
Move validation helpers from PublicationFieldService to ValidatesPubl…
caendesilva Jan 2, 2023
c3e35b9
Apply fixes from StyleCI
StyleCIBot Jan 2, 2023
8123c87
Refactor getValidationRules to be object oriented
caendesilva Jan 2, 2023
03c0a87
Refactor validate to be object oriented
caendesilva Jan 2, 2023
a07eda7
Split comma-separated values into multiple lines
caendesilva Jan 2, 2023
d001a1f
Update PublicationFieldDefinition getValidationRules method to defer …
caendesilva Jan 2, 2023
22f559a
PublicationFieldDefinition::getValidationRules now no longer accepts …
caendesilva Jan 2, 2023
40ad993
Mock the publication type in test
caendesilva Jan 2, 2023
e39540f
Update PublicationFieldDefinition validate method to defer to service
caendesilva Jan 2, 2023
a716a94
PublicationFieldDefinition::validate now no longer accepts null for t…
caendesilva Jan 2, 2023
fb52827
Reorder PublicationFieldDefinition::validate method arguments to put …
caendesilva Jan 2, 2023
58929d8
Revert deprecations as methods now no longer contain logic
caendesilva Jan 2, 2023
6d38d20
Mock the publication type in test
caendesilva Jan 2, 2023
c211920
Extract testing helper method
caendesilva Jan 2, 2023
8869ce1
Apply fixes from StyleCI
StyleCIBot Jan 2, 2023
d0d46fb
Move tests for moved logic to the new test class
caendesilva Jan 2, 2023
6e23e2c
Remove redundant arguments in test
caendesilva Jan 2, 2023
791ab22
Remove unnecessary argument identifiers in test
caendesilva Jan 2, 2023
8e0f62e
Apply fixes from StyleCI
StyleCIBot Jan 2, 2023
169d229
Deprecate the $fieldRules argument as it should not be necessary
caendesilva Jan 2, 2023
ef98b5b
Merge branch 'refactor-publication-validation' of github.com:hydephp/…
caendesilva Jan 2, 2023
9aa6955
Deprecate dynamic logic in static method to reduce complexity
caendesilva Jan 2, 2023
4b4ffd7
Deprecate parameters only needed for deprecated code
caendesilva Jan 2, 2023
a8b884d
Apply fixes from StyleCI
StyleCIBot Jan 2, 2023
50db626
Remove deprecated $fieldRules argument to reduce complexity
caendesilva Jan 2, 2023
62c6b7b
Deprecate validation helpers outside of scope
caendesilva Jan 2, 2023
4751950
Use the new ValidatesPublicationField helper
caendesilva Jan 2, 2023
fab7b15
Apply fixes from StyleCI
StyleCIBot Jan 2, 2023
b66c336
No longer include dynamic data in static method
caendesilva Jan 2, 2023
27b50da
Remove unused deprecated parameter
caendesilva Jan 2, 2023
8bf38be
Protect previously protected public helper method
caendesilva Jan 2, 2023
d2577b6
Reorder methods
caendesilva Jan 2, 2023
e534d51
Import used function
caendesilva Jan 2, 2023
ba9487b
Make deprecated public static method protected instance
caendesilva Jan 2, 2023
7664b86
Merge in dynamic rules when using instance method
caendesilva Jan 2, 2023
ced525f
Apply fixes from StyleCI
StyleCIBot Jan 2, 2023
da83796
Refactor helper method to utilize instance properties
caendesilva Jan 2, 2023
6c33e54
Unwrap already evaluated conditions
caendesilva Jan 2, 2023
08ee4a2
Unwrap unnecessary evaluation
caendesilva Jan 2, 2023
c66e3ea
Reorder methods
caendesilva Jan 2, 2023
4ff77c4
Inline helper methods only used within the file
caendesilva Jan 2, 2023
71d3ab2
Add simple method to get the merged rules on the field definition
caendesilva Jan 2, 2023
a8fb99d
Use the getRules method
caendesilva Jan 2, 2023
c485e5d
Inline getValidationRulesForPublicationFieldDefinition method
caendesilva Jan 2, 2023
d019b83
Apply fixes from StyleCI
StyleCIBot Jan 2, 2023
acac6ee
Update test annotation
caendesilva Jan 2, 2023
5d2c29e
Display summary as a subtitle
caendesilva Jan 2, 2023
a795c05
Remove unused variable
caendesilva Jan 2, 2023
c1d16e3
Inline deprecated method with only one usage
caendesilva Jan 2, 2023
a1c6daf
Apply fixes from StyleCI
StyleCIBot Jan 2, 2023
98e71aa
Remove deprecated method only used in tests
caendesilva Jan 2, 2023
ce7ef4b
Remove unused deprecated method
caendesilva Jan 2, 2023
377d7fb
Test the getRules method
caendesilva Jan 2, 2023
778ea47
Update PHPDoc comment
caendesilva Jan 2, 2023
0102e70
Apply fixes from StyleCI
StyleCIBot Jan 2, 2023
6f0fef5
Update helper to return array instead of Collection as it's only used…
caendesilva Jan 2, 2023
b80bc1d
Shorten helper method name
caendesilva Jan 2, 2023
33d8c41
Extract method
caendesilva Jan 2, 2023
bd3f57a
Apply fixes from StyleCI
StyleCIBot Jan 2, 2023
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 @@ -178,7 +178,7 @@ protected function captureTagFieldInput(PublicationFieldDefinition $field): ?Pub

protected function captureOtherFieldInput(PublicationFieldDefinition $field): ?PublicationFieldValue
{
$selection = $this->askForFieldData($field->name, $field->getValidationRules()->toArray());
$selection = $this->askForFieldData($field->name, $field->getRules());
if (empty($selection)) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@
use Hyde\Console\Concerns\ValidatingCommand;
use Hyde\Framework\Features\Publications\Models\PublicationFieldDefinition;
use Hyde\Framework\Features\Publications\PublicationService;
use Hyde\Framework\Features\Publications\ValidatesPublicationField;
use InvalidArgumentException;
use LaravelZero\Framework\Commands\Command;
use function str_repeat;
use function strlen;

/**
* Hyde Command to validate one or all publications.
*
* @see \Hyde\Framework\Testing\Feature\Commands\ValidatePublicationTypeCommandTest
* @see \Hyde\Framework\Testing\Feature\Commands\ValidatePublicationsCommandTest
*
* @todo Add JSON output option?
*/
Expand Down Expand Up @@ -57,7 +60,6 @@ public function safeHandle(): int
$countPubTypes++;
$publications = PublicationService::getPublicationsForPubType($pubType);
$this->output->write("<fg=yellow>Validating publication type [$name]</>");
$publicationFieldRules = $pubType->getFieldRules(false);

/** @var \Hyde\Pages\PublicationPage $publication */
foreach ($publications as $publication) {
Expand All @@ -79,11 +81,7 @@ public function safeHandle(): int
throw new Exception("Field [$fieldName] is missing from publication");
}

$pubTypeField->validate(
$publication->matter->get($fieldName),
$publicationFieldRules->get($fieldName),
$pubType
);
(new ValidatesPublicationField($pubType, $pubTypeField))->validate($publication->matter->get($fieldName));
$this->output->writeln(" <fg=green>$checkmark</>");
} catch (Exception $e) {
$countErrors++;
Expand All @@ -102,7 +100,7 @@ public function safeHandle(): int

$warnColor = $countWarnings ? 'yellow' : 'green';
$errorColor = $countErrors ? 'red' : 'green';
$this->title('Summary:');
$this->subtitle('Summary:');
$this->output->writeln("<fg=green>Validated $countPubTypes Publication Types, $countPubs Publications, $countFields Fields</>");
$this->output->writeln("<fg=$warnColor>Found $countWarnings Warnings</>");
$this->output->writeln("<fg=$errorColor>Found $countErrors Errors</>");
Expand All @@ -112,4 +110,19 @@ public function safeHandle(): int

return Command::SUCCESS;
}

/*
* Displays the given string as subtitle.
*/
public function subtitle(string $title): Command
{
$size = strlen($title);
$spaces = str_repeat(' ', $size);

$this->output->newLine();
$this->output->writeln("<bg=blue;fg=white>$spaces$title$spaces</>");
$this->output->newLine();

return $this;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,10 @@
namespace Hyde\Framework\Features\Publications\Models;

use function array_filter;
use function collect;
use function Hyde\evaluate_arrayable;
use Hyde\Framework\Features\Publications\PublicationFieldService;
use function array_merge;
use Hyde\Framework\Features\Publications\PublicationFieldTypes;
use Hyde\Support\Concerns\Serializable;
use Hyde\Support\Contracts\SerializableContract;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use function str_starts_with;
use function strtolower;
Expand Down Expand Up @@ -53,18 +49,12 @@ public function toArray(): array
}

/**
* @param \Hyde\Framework\Features\Publications\Models\PublicationType|null $publicationType Required only when using the 'image' type.
* Get the validation rules for this field.
*
* @return array<string> The type default rules merged with any custom rules.
*/
public function getValidationRules(?PublicationType $publicationType = null): Collection
public function getRules(): array
{
return collect(PublicationFieldService::getValidationRulesForPublicationFieldDefinition($publicationType, $this));
}

/** @param \Hyde\Framework\Features\Publications\Models\PublicationType|null $publicationType Required only when using the 'image' type. */
public function validate(mixed $input = null, Arrayable|array|null $fieldRules = null, ?PublicationType $publicationType = null): array
{
$rules = evaluate_arrayable($fieldRules ?? $this->getValidationRules($publicationType));

return validator([$this->name => $input], [$this->name => $rules])->validate();
return array_merge($this->type->rules(), $this->rules);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -106,16 +106,6 @@ public function getFields(): Collection
return Collection::make($result);
}

/** @return \Illuminate\Support\Collection<string, \Illuminate\Support\Collection> */
public function getFieldRules(): Collection
{
return Collection::make(
$this->getFields()->mapWithKeys(function (PublicationFieldDefinition $field) {
return [$field->name => $field->getValidationRules($this)];
})
);
}

public function getFieldDefinition(string $fieldName): PublicationFieldDefinition
{
return $this->getFields()->filter(fn (PublicationFieldDefinition $field): bool => $field->name === $fieldName)->firstOrFail();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,60 +4,10 @@

namespace Hyde\Framework\Features\Publications;

use function array_merge;
use function collect;
use Hyde\Framework\Features\Publications\Models\PublicationFieldDefinition;
use Hyde\Framework\Features\Publications\Models\PublicationType;

/**
* @see \Hyde\Framework\Testing\Feature\PublicationFieldServiceTest
*/
class PublicationFieldService
{
public static function getValidationRulesForPublicationFieldDefinition(?PublicationType $publicationType, PublicationFieldDefinition $fieldDefinition): array
{
return array_merge(
self::getDefaultRulesForFieldType($fieldDefinition->type),
self::makeDynamicValidationRulesForPublicationFieldEntry($fieldDefinition, $publicationType),
self::getCustomRulesFromPublicationTypeSchema($fieldDefinition)
);
}

protected static function makeDynamicValidationRulesForPublicationFieldEntry(
Models\PublicationFieldDefinition $fieldDefinition, ?PublicationType $publicationType
): array {
if ($fieldDefinition->type == PublicationFieldTypes::Image) {
if ($publicationType !== null) {
$mediaFiles = PublicationService::getMediaForPubType($publicationType);
$valueList = $mediaFiles->implode(',');
} else {
$valueList = '';
}

return ["in:$valueList"];
}

if ($fieldDefinition->type == PublicationFieldTypes::Tag) {
if ($publicationType !== null) {
$tagValues = PublicationService::getValuesForTagName($publicationType->getIdentifier()) ?? collect([]);
$valueList = $tagValues->implode(',');
} else {
$valueList = '';
}

return ["in:$valueList"];
}

return [];
}

protected static function getDefaultRulesForFieldType(PublicationFieldTypes $type): array
{
return $type->rules();
}

protected static function getCustomRulesFromPublicationTypeSchema(PublicationFieldDefinition $fieldDefinition): array
{
return $fieldDefinition->rules;
}
//
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

declare(strict_types=1);

namespace Hyde\Framework\Features\Publications;

use function array_merge;
use function collect;
use Hyde\Framework\Features\Publications\Models\PublicationFieldDefinition;
use Hyde\Framework\Features\Publications\Models\PublicationType;
use Illuminate\Contracts\Validation\Validator;
use function validator;

/**
* @see \Hyde\Framework\Testing\Feature\ValidatesPublicationsTest
*/
class ValidatesPublicationField
{
protected PublicationType $publicationType;
protected PublicationFieldDefinition $fieldDefinition;

public function __construct(PublicationType $publicationType, PublicationFieldDefinition $fieldDefinition)
{
$this->publicationType = $publicationType;
$this->fieldDefinition = $fieldDefinition;
}

public function getValidationRules(): array
{
return array_merge(
$this->fieldDefinition->getRules(),
$this->makeDynamicRules()
);
}

public function validate(mixed $input = null): array
{
return $this->makeValidator($input, $this->getValidationRules())->validate();
}

protected function makeDynamicRules(): array
{
if ($this->fieldDefinition->type == PublicationFieldTypes::Image) {
$mediaFiles = PublicationService::getMediaForPubType($this->publicationType);
$valueList = $mediaFiles->implode(',');

return ["in:$valueList"];
}

if ($this->fieldDefinition->type == PublicationFieldTypes::Tag) {
$tagValues = PublicationService::getValuesForTagName($this->publicationType->getIdentifier()) ?? collect([]);
$valueList = $tagValues->implode(',');

return ["in:$valueList"];
}

return [];
}

protected function makeValidator(mixed $input, array $rules): Validator
{
return validator(
[$this->fieldDefinition->name => $input],
[$this->fieldDefinition->name => $rules]
);
}
}
Loading