Skip to content

Commit

Permalink
URL field
Browse files Browse the repository at this point in the history
  • Loading branch information
iamgergo committed Nov 24, 2023
1 parent c3617a1 commit b9f7f2c
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions src/Fields/URL.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,17 @@
namespace Cone\Root\Fields;

use Closure;
use Cone\Root\Root;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class URL extends Text
{
/**
* The text resolver callback.
*/
protected Closure $textResolver;

/**
* Create a new field instance.
*/
Expand All @@ -14,5 +22,59 @@ public function __construct(string $label, Closure|string $modelAttribute = null
parent::__construct($label, $modelAttribute);

$this->type('url');

$this->textResolver = fn (): string => 'URL';
}

/**
* Set the text resolver callback.
*/
public function text(Closure|string $value): static
{
if (is_string($value)) {
$value = fn (): string => $value;
}

$this->textResolver = $value;

return $this;
}

/**
* {@inheritdoc}
*/
public function resolveFormat(Request $request, Model $model): mixed
{
if (is_null($this->formatResolver)) {
$this->formatResolver = function (Request $request, Model $model, mixed $value): ?string {
if (is_null($value)) {
return $value;
}

return sprintf(
'<a href="%s"%s>%s</a>',
$value,
$this->isExternal($value) ? ' data-turbo="false" target="_blank"' : '',
call_user_func_array($this->textResolver, [$model])
);
};
}

return parent::resolveFormat($request, $model);
}

/**
* Determine if the given URL is external.
*/
protected function isExternal(string $value): bool
{
$root = Root::instance();

[$domain, $path] = [$root->getDomain(), $root->getPath()];

$url = parse_url($value);

return $domain !== ($url['host'] ?? null)
|| ! str_starts_with(ltrim($url['path'], '/'), ltrim($path, '/'));
}
}

0 comments on commit b9f7f2c

Please sign in to comment.