PHP code example of aklump / token-engine

1. Go to this page and download the library: Download aklump/token-engine library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

aklump / token-engine example snippets


$tokens = \AKlump\TokenEngine\TokenCollection::createFromKeyValueArray([
  'first' => 'Peter',
]);
$replace_tokens = (new \AKlump\TokenEngine\ReplaceTokens($tokens, new \AKlump\TokenEngine\Styles\AtStyle()));

'Welcome Mary Smith,' === $replace_tokens('Hello @first,');

// Create a new token collection.
$tokens = new \AKlump\TokenEngine\TokenCollection();

// Create a token with a callable value.
$callable_token = new \AKlump\TokenEngine\Token('first|toUpperCase');
$callable_token->setValue(function (array $context) {

  // Oversimplified, but it makes the point of callables and context.
  return strtoupper($context['first']);
});
$tokens->add($callable_token);

// Use that token in a string template.
$template = 'HEY {{ first|toUpperCase }}!';

// Create the styleized replacer.
$replace = (new \AKlump\TokenEngine\ReplaceTokens($tokens, new \AKlump\TokenEngine\Styles\TwigStyle()));

// Replace the token with runtime context.
$runtime_context = ['first' => 'Peter'];
$shout = $replace($template, $runtime_context);

'HEY PETER!' === $shout;

$string = 'lorem';
$stylized = (new \AKlump\TokenEngine\Helpers\StylizeString(new \AKlump\TokenEngine\Styles\TwigStyle()))($string);
'{{ lorem }}' === $stylized;

$array = ['foo' => 'bar'];
$stylized = (new \AKlump\TokenEngine\Helpers\ArrayStylizeKeys(new \AKlump\TokenEngine\Styles\TwigStyle()))($array);
['{{ foo }}' => 'bar'] === $stylized;

$array = ['foo' => 'bar'];
$stylized = (new \AKlump\TokenEngine\Helpers\ArrayStylizeValues(new \AKlump\TokenEngine\Styles\TwigStyle()))($array);
['foo' => '{{ bar }}'] === $stylized;

$examples = \Foo\Bar::getExampleTokens()->toKeyValueArray();
$examples = (new \AKlump\TokenEngine\Helpers\ArrayStylizeKeys(new TwigStyle()))($examples);
$help_text = sprintf('Available tokens: %s', implode(', ', array_keys($examples)));

// Combine two different token collections.
$collection = GetContextTokens::getExampleTokens();
$collection = $collection->merge(GetBudgetTokens::getExampleTokens());

// Sort them by their tokens.
$collection = $collection->sort('token');

// We want to the documentation to show the styled token.
$styler = new \AKlump\TokenEngine\Helpers\StylizeString(new \AKlump\TokenEngine\Styles\AtStyle());

// Iterate on the combined collection and access token properties.
$table_data = [];
foreach ($collection as $token) {
  $table_data[] = [
    'token' => $styler($token->token()),
    'description' => $token->description(),
    'example' => $token->value(),
  ];
}
$table = (new CreateTable())($table_data);