Add snippet code

This commit is contained in:
kolaente 2020-12-13 18:14:55 +01:00
parent e4472b4c2e
commit f741b47e60
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
2 changed files with 49 additions and 0 deletions

View File

@ -0,0 +1,36 @@
<?php
namespace Kolaente\Snippet\Modifiers;
use Statamic\Modifiers\Modifier;
class TextSnippet extends Modifier
{
protected static $handle = 'snippet';
/**
* Creates a text snippet of a given string. A snippet is an "intelligent substring": It will try to end the
* snippet at the end of a sentence (after a dot) within a given boundary. If no sentence ends within the
* boundary, it will end after the first word in the boundary and add "..." to the end of the snippet.
* This will avoid having words cut off in the middle after a fixed boundary.
*
* @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)
{
$lengthMin = $params[0] ?? 200;
$lengthMax = $params[1] ?? 250;
$firstSentenceEnd = strpos($value, '.', $lengthMin);
if ($firstSentenceEnd <= $lengthMax) {
return substr($value, 0, $firstSentenceEnd + 1);
}
$firstSpace = strpos($value, ' ', $lengthMin) ?? $lengthMax;
return substr($value, 0, $firstSpace + 1) . '...';
}
}

13
src/ServiceProvider.php Normal file
View File

@ -0,0 +1,13 @@
<?php
namespace Kolaente\Snippet;
use Kolaente\Snippet\Modifiers\TextSnippet;
use Statamic\Providers\AddonServiceProvider;
class ServiceProvider extends AddonServiceProvider
{
protected $modifiers = [
TextSnippet::class,
];
}