Skip to content

Instantly share code, notes, and snippets.

@pryley

pryley/IsLocalUrl.php

Last active Aug 14, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@leganz 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

This comment has been minimized.

Copy link
Owner Author

@pryley 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

This comment has been minimized.

Copy link

@leganz 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