Skip to content

Instantly share code, notes, and snippets.

@pryley
Last active August 14, 2020 06:10
Show Gist options
  • Select an option

  • Save pryley/782c2653fe0245099f671a959adaa8a0 to your computer and use it in GitHub Desktop.

Select an option

Save pryley/782c2653fe0245099f671a959adaa8a0 to your computer and use it in GitHub Desktop.
Add additional attribute to non-local links
<?php
namespace App\Modifiers;
use Illuminate\Support\Str;
use Statamic\Modifiers\Modifier;
class IsLocalUrl extends Modifier
{
/**
* Modify a value.
*
* @param mixed $value The value to be modified
* @param array $params Any parameters used in the modifier
* @param array $context Contextual values
* @return mixed
*/
public function index($value, $params, $context)
{
if (Str::startsWith($value, 'http')) {
return Str::contains($value, request()->root());
}
return true;
}
}
@leganz

leganz commented Aug 13, 2020

Copy link
Copy Markdown

i recommend a null check otherwise that might cause a exception

if ($value != null && Str::startsWith($value, 'http')) {
   return Str::contains($value, request()->root());
}
return true;

@pryley

pryley commented Aug 13, 2020

Copy link
Copy Markdown
Author

Passing null to the strncmp string function (which is what Str uses under the hood) will not throw an Exception.

You can always cast the value to a string if you prefer:

Str::startsWith((string) $value, 'http')

@leganz

leganz commented Aug 14, 2020

Copy link
Copy Markdown

Ah didn't know that - thx for providing that information :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment