Skip to content

Instantly share code, notes, and snippets.

@pryley
Last active August 14, 2020 06:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pryley/782c2653fe0245099f671a959adaa8a0 to your computer and use it in GitHub Desktop.
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
Copy link

leganz commented Aug 13, 2020

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
Copy link
Author

pryley commented Aug 13, 2020

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
Copy link

leganz commented Aug 14, 2020

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