jesseschutt / token-replacer
Define tokens and replace the occurrences in strings.
Requires
- php: ^8.2
- laravel/framework: ^10.0|^11.0
- phpunit/phpunit: ^10.0|^11.0
Requires (Dev)
- laravel/pint: ^1.17
- orchestra/testbench: ^9.3
This package is auto-updated.
Last update: 2024-12-17 19:50:59 UTC
README
Credit
This package is a fork of the original, which was created by Jamie Holly of HollyIT.
Installation
composer require jesseschutt/token-replacer
Configuration
You can publish the configuration file by running the following command:
php artisan vendor:publish --provider="JesseSchutt\TokenReplacer\TokenReplacerServiceProvider"
This will create a token-replacer.php
file in your config
directory. Here you can set the default token start and end characters, the default token separator, and the default transformers.
Instructions
This package allows you to define tokens that can be replaced in strings. Instead of a simple str_replace
, Token Replacer lets you add options to each token. Let's start with an example.
use \JesseSchutt\TokenReplacer\Facades\TokenReplacer;
use \JesseSchutt\TokenReplacer\Transformers\DateTransformer;
$input="Today is {{ date:m }}/{{ date:d }}/{{ date:y }}.";
echo TokenReplacer::from($input)->with('date', DateTransformer::class)
// Results in: Today is 11/11/21.
There is a certain anatomy to tokens, so let's take a look at the {{ date:m }}
. This is a default token format, but this format is configurable globally and per instance.
Transformers
The replacement of tokens is handled via a transformer. A transformer can be a closure or a simple class.
Transformers can be added to each instance of the TokenReplacer or added globally by adding them to the default_transformers
array in the configuration file.
Note: Global transformers do not receive any data when instantiated. DateTransformer
and AuthTransformer
are the only two built-in transformers that are eligible for global use.
Per instance tokens are added via $instance->with({token name}, {class name, transformer instance or closure});
For closure based transformers the signature is:
function(string $options)
Included Transformers
All these transformers live under the \JesseSchutt\TokenReplacer\Transformers
namespace.
There are also special Laravel transformers residing in \JesseSchutt\TokenReplacer\Transformers\Laravel
Post-processing
None of the transformers do any further processing except extracting the item. If you want to do further processing, such as escaping the replacements, you can define an onReplace
callback:
$replacer->onReplace(function(string $result, string $token, string $options){
return strtoupper($result);
});
This callback will run for every token occurrence found, so you can further filter down what tokens
to operate on by checking the $token
property.
Invalid or missing tokens
By default, invalid and missing tokens will remain in the string. To prevent this, you can set removeEmpty()
on the TokenReplacer.