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

Implement Tag Store Validations Through Existing TagUpdateRequest #167

Open
wants to merge 12 commits into
base: develop
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions app/Http/Controllers/TagsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ public function create(): View|ViewContract
/**
* Save the tag in the database.
*/
public function store(Request $request): RedirectResponse
public function store(TagUpdateRequest $request): RedirectResponse
{
Tag::findOrCreate(preg_split('/\r\n|\r|\n/', $request->tag_name ?? ''), $request->tag_type);
Tag::findOrCreate(preg_split('/\r\n|\r|\n/', $request->name ?? ''), $request->type);

return redirect()->route('tags.table')
->with('flash_message', 'Added tags');
Expand Down
28 changes: 20 additions & 8 deletions app/Http/Requests/TagUpdateRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@

namespace App\Http\Requests;

use App\Rules\EachIsUnique;
use App\Student;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class TagUpdateRequest extends FormRequest
{
public $tag_types = [];

/**
* Determine if the user is authorized to make this request.
*
Expand All @@ -24,27 +28,35 @@ public function authorize()
*/
public function rules()
{
$this->tag_types[] = "App\\Profile";
$locale = app()->getLocale();

foreach (Student::participatingSchools() as $shortname => $name) {
$this->tag_types[]= "App\\Student\\{$shortname}";
}

return [
'type' => 'required',
'name' => [
'type' => [
'required',
'string',
Rule::in($this->tag_types),
],
'name' => [
'required',
'string',
'max:100',
Rule::unique('tags', 'name->'.$locale)
->where('type', $this->input('type'))
->ignore($this->input('id'))
(new EachIsUnique('/\r\n|\r|\n/', 'tags', 'name->'.$locale, ['type', $this->input('type')]))
->ignore($this->route()->parameters['tag'] ?? null),
],
];
}

public function messages()
{
$types_allowed = implode(', ', $this->tag_types);

return [
'name.required' => 'The tag name is required.',
'name.unique' => 'The tag name provided already exists.',
'name.max' => 'The tag name provided exceeds maximum length of 100 characters.',
'type.in' => "The tag types allowed are: {$types_allowed}",
];
}

Expand Down
83 changes: 83 additions & 0 deletions app/Rules/EachIsUnique.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Validation\Rule;
use Illuminate\Support\Str;

class EachIsUnique implements ValidationRule
{
protected string $delimiter;
protected string $table;
protected string $column;
protected array $constraint;
protected $ignore_id;
protected $ignore_column;

/**
* Create a new validation rule instance.
*
* @param string $delimiter Delimiter to split the field under validation into individual elements.
* @param string $table Table where the uniqueness check will be performed.
* @param string $column Column in the table where uniqueness will be checked.
* @param array $constraint Constraint for the where method to apply when checking uniqueness in the format of ['column', 'value'].
*/
public function __construct($delimiter, $table, $column, $constraint = null)
{
$this->delimiter = $delimiter;
$this->table = $table;
$this->column = $column;
$this->constraint = $constraint;
}

/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$values = $errors = [];

$values = is_string($value) ? preg_split($this->delimiter, $value) : [];

$rule = Rule::unique($this->table, $this->column);

if (isset($this->constraint)) {

Check failure on line 48 in app/Rules/EachIsUnique.php

View workflow job for this annotation

GitHub Actions / Profiles Tests (PHP 8.3)

RedundantPropertyInitializationCheck

app/Rules/EachIsUnique.php:48:13: RedundantPropertyInitializationCheck: Property $this->constraint with type array<array-key, mixed> should already be set in the constructor (see https://psalm.dev/261)
$rule->where($this->constraint[0], $this->constraint[1]);
}

if (isset($this->ignore_id)) {
$rule->ignore($this->ignore_id, $this->ignore_column);
}

foreach ($values as $value) {
$valid = !validator([$attribute => $value], [$attribute => $rule])->fails();

if (!$valid) {
$errors[] = "The {$value} tag already exists for the {$this->constraint[1]} {$this->constraint[0]}.";
}
}

foreach ($errors as $error) {
$fail($error);
}
}

/**
* Set values to be excluded or ignored by the unique checks.
*
* @param mixed $id - the ID or model instance of the record to ignore
* @param string|null $id_column - The column name of the primary key, if it's other than the ID
*/
public function ignore($id, $idColumn = null)
{
$this->ignore_id = $id;
$this->ignore_column = $idColumn;

return $this;
}

}
9 changes: 5 additions & 4 deletions resources/views/tags/create.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,18 @@
<div class="container">
<h1><i class="fas fa-tags" aria-hidden="true"></i> Add Tags</h1>

@include('errors/list')
{!! Form::open(['route' => 'tags.store']) !!}

<div class="mb-3">
{!! Form::label('tag_name', 'Tag name(s)', ['class' => 'form-label']) !!}
{!! Form::label('name', 'Tag name(s)', ['class' => 'form-label']) !!}
<small class="text-muted">One tag per line</small>
{!! Form::textarea('tag_name', null, ['class' => 'form-control', 'required']) !!}
{!! Form::textarea('name', null, ['class' => 'form-control', 'required']) !!}
</div>
<div class="mb-3">
{!! Form::label('tag_type', 'Tag type', ['class' => 'form-label']) !!}
{!! Form::label('type', 'Tag type', ['class' => 'form-label']) !!}
<small class="text-muted">e.g. App\Profile, App\Student, and etc.</small>
{!! Form::text('tag_type', null, ['class' => 'form-control', 'required']) !!}
{!! Form::text('type', null, ['class' => 'form-control', 'required']) !!}
</div>

<button type="submit" class="btn btn-primary edit-button">Submit</button>
Expand Down
2 changes: 1 addition & 1 deletion resources/views/tags/edit.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
<div class="container">
<h1><i class="fas fa-tags" aria-hidden="true"></i> Edit Tag {{ $tag->name }}</h1>

@include('errors/has')
@include('errors/list')

{!! Form::model($tag, ['method' => 'PATCH','route' => ['tags.updateTag', $tag], 'class' => 'form-horizontal' ]) !!}

Expand Down
Loading