Skip to content

Commit

Permalink
feat: allow validating missing keys
Browse files Browse the repository at this point in the history
  • Loading branch information
SychO9 committed Dec 6, 2024
1 parent e43449c commit eb1063e
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 37 deletions.
31 changes: 0 additions & 31 deletions extensions/package-manager/src/AllValidatorRules.php

This file was deleted.

2 changes: 1 addition & 1 deletion extensions/package-manager/src/ConfigureAuthValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

class ConfigureAuthValidator extends AbstractValidator
{
use AllValidatorRules;
protected bool $validateMissingKeys = true;

protected array $rules = [
'github-oauth' => ['sometimes', 'array'],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

class ConfigureComposerValidator extends AbstractValidator
{
use AllValidatorRules;
protected bool $validateMissingKeys = true;

protected array $rules = [
'minimum-stability' => ['sometimes', 'in:stable,RC,beta,alpha,dev'],
Expand Down
26 changes: 22 additions & 4 deletions framework/core/src/Foundation/AbstractValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,12 @@ abstract class AbstractValidator
*/
protected array $configuration = [];

/**
* @var array
*/
protected array $rules = [];

protected ?Validator $laravelValidator = null;

protected bool $validateMissingKeys = false;

public function __construct(
protected Factory $validator,
protected TranslatorInterface $translator
Expand All @@ -54,6 +53,16 @@ public function assertValid(array $attributes): void
}
}

/**
* Whether to validate missing keys or to only validate provided data keys.
*/
public function validateMissingKeys(bool $validateMissingKeys = true): static
{
$this->validateMissingKeys = $validateMissingKeys;

return $this;
}

public function prepare(array $attributes): static
{
$this->laravelValidator ??= $this->makeValidator($attributes);
Expand All @@ -71,14 +80,23 @@ protected function getRules(): array
return $this->rules;
}

protected function getActiveRules(array $attributes): array
{
$rules = $this->getRules();

return $this->validateMissingKeys
? $rules
: Arr::only($rules, array_keys($attributes));
}

protected function getMessages(): array
{
return [];
}

protected function makeValidator(array $attributes): Validator
{
$rules = Arr::only($this->getRules(), array_keys($attributes));
$rules = $this->getActiveRules($attributes);

$validator = $this->validator->make($attributes, $rules, $this->getMessages());

Expand Down

0 comments on commit eb1063e

Please sign in to comment.