Skip to content

Commit

Permalink
Refactored protected method names and updated descriptions in Field
Browse files Browse the repository at this point in the history
… class
  • Loading branch information
tabuna committed Aug 11, 2024
1 parent bf47345 commit 21a7c58
Showing 1 changed file with 116 additions and 70 deletions.
186 changes: 116 additions & 70 deletions src/Screen/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ class Field implements Fieldable, Htmlable
protected $view;

/**
* All attributes that are available to the field.
* An array containing all attributes available to the field.
* Attributes are used to configure the HTML form element.
*
* @var array
*/
Expand Down Expand Up @@ -120,6 +121,13 @@ class Field implements Fieldable, Htmlable
*/
protected $inlineAttributes = [];

/**
* Type of the form layout, either vertical or horizontal.
*
* @var Closure|string|null
*/
protected $typeForm;

/**
* @param string $method
* @param array $parameters
Expand All @@ -142,19 +150,22 @@ public function __call(string $method, array $parameters)
}

/**
* @param mixed $value
* Sets the 'value' attribute of the field.
*
* @return static
* @param mixed $value The value to be set for the 'value' attribute.
*/
public function value($value): self
public function value(mixed $value): self
{
return $this->set('value', $value);
}

/**
* @param mixed $value
* Sets the value for the specified attribute of the field.
*
* @return static
* @param string $key The name of the attribute to set.
* @param mixed $value The value of the attribute. Defaults to true.
*
* @return static Returns the current instance for method chaining.
*/
public function set(string $key, $value = true): self
{
Expand All @@ -164,11 +175,13 @@ public function set(string $key, $value = true): self
}

/**
* @throws Throwable
* Validates that all required attributes are present in the field.
*
* @return static
* @throws FieldRequiredAttributeException if any required attribute is missing.
*
* @return static Returns the current instance for method chaining.
*/
protected function checkRequired(): self
protected function ensureRequiredAttributesArePresent(): self
{
collect($this->required)
->filter(fn ($attribute) => ! array_key_exists($attribute, $this->attributes))
Expand All @@ -180,6 +193,8 @@ protected function checkRequired(): self
}

/**
* Renders the field.
*
* @throws Throwable
*
* @return Factory|View|mixed
Expand All @@ -191,36 +206,30 @@ public function render()
}

$this
->checkRequired()
->modifyName()
->modifyValue()
->ensureRequiredAttributesArePresent()
->customizeFieldName()
->updateFieldValue()
->runBeforeRender()
->translate()
->checkError();

$id = $this->getId();
$this->set('id', $id);

$errors = $this->getErrorsMessage();
->translateAttributes()
->markFieldWithError()
->generateId();

return view($this->view, array_merge($this->getAttributes(), [
'attributes' => $this->getAllowAttributes(),
'dataAttributes' => $this->getAllowDataAttributes(),
'id' => $id,
'old' => $this->getOldValue(),
'slug' => $this->getSlug(),
'oldName' => $this->getOldName(),
'typeForm' => $this->typeForm ?? $this->vertical()->typeForm,
]))
->withErrors($errors);
->withErrors($this->getErrorsMessage());
}

/**
* Localization of fields.
* Translates the field's attributes if necessary.
*
* @return static
*/
private function translate(): self
private function translateAttributes(): self
{
$lang = $this->get('lang');

Expand All @@ -234,11 +243,21 @@ private function translate(): self
return $this;
}

/**
* Gets the field's attributes.
*
* @return array
*/
public function getAttributes(): array
{
return $this->attributes;
}

/**
* Gets the allowed attributes for the field.
*
* @return ComponentAttributeBag
*/
protected function getAllowAttributes(): ComponentAttributeBag
{
$allow = array_merge($this->universalAttributes, $this->inlineAttributes);
Expand All @@ -247,31 +266,41 @@ protected function getAllowAttributes(): ComponentAttributeBag
->filter(fn ($value, $attribute) => Str::is($allow, $attribute))
->toArray();

return (new ComponentAttributeBag)
return (new ComponentAttributeBag())
->merge($attributes);
}

/**
* Gets the allowed data attributes for the field.
*
* @return ComponentAttributeBag
*/
protected function getAllowDataAttributes(): ComponentAttributeBag
{
return $this->getAllowAttributes()->filter(fn ($value, $key) => Str::startsWith($key, 'data-'));
}

/**
* @return string
* Generates a field ID if not already set.
*
* @param string $defaultId The default ID to set if none is provided.
*
* @return static Returns the current instance for method chaining.
*/
protected function getId(): ?string
public function generateId(): self
{
$id = $this->get('id');

if ($id !== null) {
return (string) $id;
if (! empty($this->get('id'))) {
return $this;
}

$lang = $this->get('lang');
$slug = $this->get('name');
$hash = sha1(json_encode($this->getAttributes()));
$slug = collect([
'field',
$this->get('lang'),
$this->get('name'),
sha1(json_encode($this->getAttributes())),
])->implode('-');

return Str::slug("field-$lang-$slug-$hash");
return $this->set('id', Str::slug($slug));
}

/**
Expand All @@ -284,11 +313,6 @@ public function get(string $key, $value = null)
return $this->attributes[$key] ?? $value;
}

protected function getSlug(): string
{
return Str::slug($this->get('name'));
}

/**
* Get the old value of the field.
*
Expand All @@ -299,6 +323,11 @@ public function getOldValue()
return old($this->getOldName());
}

/**
* Gets the old value of the field.
*
* @return mixed
*/
public function getOldName(): string
{
return Str::of($this->get('name'))
Expand All @@ -309,11 +338,14 @@ public function getOldName(): string
}

/**
* Checking for errors and filling css class.
* Marks the field as having an error by appending the 'is-invalid' CSS class.
*
* @return $this
* If the field has an error (determined by the hasError() method),
* it appends the 'is-invalid' class to the existing 'class' attribute.
*
* @return static Returns the current instance for method chaining.
*/
private function checkError(): self
private function markFieldWithError(): self
{
if (! $this->hasError()) {
return $this;
Expand All @@ -324,15 +356,26 @@ private function checkError(): self
return $this->set('class', $class.' is-invalid');
}

/**
* Checks if the field has an error.
*
* @return bool
*/
private function hasError(): bool
{
return optional(session('errors'))->has($this->getOldName()) ?? false;
}

/**
* @return static
* Modifies the 'name' attribute of the field by adding a prefix and/or language identifier if they are set.
*
* If both prefix and language are set, the name will be modified as "prefix[lang]name".
* If only the prefix is set, the name will be modified as "prefixname".
* If only the language is set, the name will be modified as "lang[name]".
*
* @return static Returns the current instance for method chaining.
*/
protected function modifyName()
protected function customizeFieldName(): self
{
$name = $this->get('name');
$prefix = $this->get('prefix');
Expand All @@ -354,9 +397,14 @@ protected function modifyName()
}

/**
* @return static
* Modifies the 'value' attribute of the field.
*
* Retrieves the old value using the getOldValue() method, falling back to the current 'value' attribute if no old value is found.
* If the value is a Closure, it will be executed with the current attributes and its result will be used as the value.
*
* @return static Returns the current instance for method chaining.
*/
protected function modifyValue(): self
protected function updateFieldValue(): self
{
$value = $this->getOldValue() ?? $this->get('value');

Expand Down Expand Up @@ -428,6 +476,10 @@ public function hr(): self
}

/**
* Adds a closure to be executed before rendering the field.
*
* @param Closure $closure The closure to be executed before rendering.
*
* @return static
*/
public function addBeforeRender(Closure $closure)
Expand All @@ -438,9 +490,10 @@ public function addBeforeRender(Closure $closure)
}

/**
* Alternately performs all tasks.
* Performs all tasks added to be executed before rendering the field.
*
* @return $this
* This method iterates over each closure added via addBeforeRender() method
* and executes them in the context of the current field instance.
*/
public function runBeforeRender(): self
{
Expand All @@ -451,15 +504,23 @@ public function runBeforeRender(): self
return $this;
}

private function getErrorsMessage(): array
/**
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*
* @return \Closure|mixed|object|null
*/
private function getErrorsMessage()
{
$errors = session()->get('errors', new MessageBag);

return $errors->getMessages();
return session()->get('errors', new MessageBag());
}

/**
* Converts the field to a string by rendering it.
*
* @throws Throwable
*
* @return string
*/
public function __toString(): string
{
Expand All @@ -477,24 +538,9 @@ public function __toString(): string
}

/**
* Apply the callback if the value is truthy.
*
* @param bool $condition
* @param callable $callback
* Converts the field to an HTML string.
*
* @return $this
*/
public function when(bool $condition, callable $callback)
{
if ($condition) {
$callback($this);
}

return $this;
}

/**
* @throws \Throwable
* @throws Throwable
*
* @return string
*/
Expand Down

0 comments on commit 21a7c58

Please sign in to comment.