PHP code example of trych / kirby-field-composer

1. Go to this page and download the library: Download trych/kirby-field-composer 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/ */

    

trych / kirby-field-composer example snippets


$page->title()->merge($page->author(), $page->year());
// => Chasing Starlight, Jane Doe, 2008

$page->publisher()->prefix('Publisher: ');
// => Publisher: Kirby Press

// assuming we have two variables $artwork and $artist holding content on both
field(
  [
    $artist->name()->or('Unknown'),
    field($artist->born(), $artist->died(), '-')
      ->prefix('*', when: $artist->died()->isEmpty()),
    $artist->birthplace()
  ],
  [
    $artwork->title()->or('Untitled'),
    $artwork->year()
  ],
  [
    $artwork->material(),
    $artwork->width()->merge($artwork->height(), ' × ')
      ->when($artwork->width(), $artwork->height())
      ->suffix(' cm')
      ->wrap('(', ')'),
    ''
  ],
  $artwork->collection(),
  $artwork->description(),
  '; '
);

$page->title()->merge($page->year());
// => Haze, 2014

$page->title()->merge($page->artist())->upper();
// => HAZE, JIL NASH

$page->title()->merge($page->artist(), 'Oil on canvas', $page->year());
// => Haze, Jil Nash, Oil on canvas, 2014

$page->title()->merge($page->artist(), $page->info(), $page->year());
// => Haze, Jil Nash, 2014

$page->title()->merge($page->artist(), $page->year(), ' / ');
// => Haze / Jil Nash / 2014

// 🚫 this will use the string 'Sold' as a separator
$page->title()->merge($page->artist(), $page->year(), 'Sold');
// => HazeSoldJil NashSold2014

// ✅ pass the separator explicitly as the last argument instead
$page->title()->merge($page->artist(), $page->year(), 'Sold', ', ');
// => Haze, Jil Nash, 2014, Sold

$page->title()->upper()->merge($page->year(), $page->artist(), $page->museum(), 2);
// => 2014, Jil Nash, HAZE, Tate

$page->title()->upper()->merge($page->year(), $page->artist(), $page->museum(), -1);
// => 2014, Jil Nash, Tate, HAZE

$page->title()->merge($page->year(), $page->artist(), $page->museum(), false);
// => 2014, Jil Nash, Tate

$page->title()->upper()->merge($page->artist(), $page->year(), $page->museum(), ' / ', 2);
// => Jil Nash / 2014 / HAZE / Tate

$page->title()->upper()->merge(
  [$page->artist(), $page->year()], // arguments will be merged separated by the default by ', '
  [$page->description(), $page->info(), $page->museum(), ' | '], // arguments will be merged separated by ' | '
  'Sold',
  '; ' // separator, top level arguments will be merged separated by `; `
);
// => HAZE; Jil Nash, 2014; Faint shapes lost in mist | Tate; Sold

$page->title()->prefix('Title: ');
// => Title: Haze

$page->info()->prefix('Additional info: ');
// => [returns an empty field, as the info field is also empty]

$page->title()->prefix($page->artist(), ': ');
// => Jil Nash: Haze

$artist->born()->prefix('*', '', $artist->died()->isEmpty());
// => *1982

// if you do not like to pass redundant arguments or like to be explicit
// you can also pass named arguments
$artist->born()->prefix('*', when: $artist->died()->isEmpty());
// => *1982

$page->width()->suffix(' cm');
// => 48.2 cm

$page->width()->merge($page->height(), $page->depth(), ' × ')
  ->prefix('Dimensions: ')
  ->suffix(' cm');
// => Dimensions: 48.2 × 67 cm

$page->title()->wrap('»', '«');
// => »Haze«

$page->artist()->wrap($page->title(), $page->info(), ' | ');
// => Haze | Jil Nash

$page->title()->tag('h1');
// => <h1>Haze</h1>

$page->description()->tag('p', ['class' => 'description']);
// => <p class="description">Faint shapes lost in mist.</p>

// 🚫 Incorrect output: inner <em> tags will be encoded and shown as text
$page->artist()->tag('em')->tag('p');

// 🚫 Insecure: encoding is disabled on both `tag()` calls.
//              The artist field's content is not sanitized.
$page->artist()->tag('em', encode: false)
               ->tag('p', encode: false);

// ✅ Secure: First tag encodes content, outer tag preserves HTML
$page->artist()->tag('em')  // inner tag encodes user content
               ->tag('p', encode: false);  // outer tag preserves HTML

// 🚫 Insecure: Even though inner tag encodes initial content,
//              merging additional content between tag calls breaks the security chain
$page->artist()->tag('em')  // this encodes artist content
               ->merge($page->description())  // description content is raw
               ->tag('p', encode: false);  // preserves HTML, but now 

// just pass the dimensions, if both the `width` and the `height` are given
$page->width()->merge($page->height(), ' × ')->suffix(' cm')
  ->when($page->width(), $page->height());
// => 48.2 × 67 cm

// just pass the museum, if either `artist` or `info` are given
$page->museum()->prefix('Gallery: ', '')->whenAny($page->artist(), $page->info());
// => Gallery: Tate

// shows the `description` only if `info` is empty
$page->description()->notWhen($page->info());
// => Faint shapes lost in mist.

// do not pass museum if either `artist` or `info` are given
$page->museum()->notWhenAny($page->artist(), $page->info());
// => [empty, as `artist` is given]

// Basic matching with fallback
$page->museum()->match([
  'Tate' => 'Tate Gallery',
  'MoMA' => 'Museum of Modern Art',
  'Louvre' => 'Musée du Louvre',
  'default' => 'Unknown gallery'
]);
// => 'Tate Gallery'

// remove all vowels from a string
$page->description()->format(function($value) {
  return preg_replace('/[aeiou]/i', '', $value);
});
// => Fnt shps lst n mst.

// Simple list from comma-separated string
$page->keywords()->list(',');
// => red, blue, green

// Custom join separator
$page->keywords()->list(',', '|');
// => red|blue|green

// List with conjunction
$page->keywords()->list(',', null, 'or')->upper();
// => RED, BLUE OR GREEN

// List with conjunction and Oxford comma
$page->keywords()->list(',', null, 'and', true);
// => red, blue, and green

// Splitting a files field and listing the file names by using a callback
$page->slideshow()->list(
  each: fn($img) => $img->filename() . ' (' . $img->dimensions() . ' px)'
);
// => photo1.jpg (720 × 640 px), photo2.webp (600 × 400 px), photo3.jpg (1280 × 720 px)

// If `false` or an empty string `''` is returned for an item, this item does not get listed
$page->slideshow()->list(
  each: fn($img) => $img->extension() === 'jpg' ? $img->filename() : false;
);
// => photo1.jpg, photo3.jpg

// List structure field values
$page->team()->list(each: fn($member) => $member->name());
// => John Doe, Jane Smith, Alex Johnson

// List block types
$page->blocks()->list(each: fn($block) => $block->type());
// => text, gallery, text, quote, image, text

// Sort items alphabetically before joining
$page->tags()->list(
    each: fn($tag) => $tag->name(),
    all: fn($items) => sort($items)
);
// => art, culture, design, photography

// Outputting all types used in a blocks field with unique, sorted values
$page->article()->list(
  each: fn($item) => $item->type(),
  all: fn($types) => sort(array_unique($types))
);
// => gallery, image, quote, text

// Count items in a simple comma-separated field
$page->keywords()->count();
// => 3

// Count items in a structure field and count only the items
// that have an entry in the `street` column
$page->addresses()->count(null, fn($address) => $address->zip() );
// => 12 (number of addresses with a given zip code)

// Count images wider than 1000px in a slideshow field
$page->slideshow()->count(null, fn($file) => $file->width() > 1000 );
// => 5 (number of images wider than 1000px)

// Count unique types used in a blocks field
$page->article()->list(
  each: fn($item) => $item->type(),
  all: fn($types) => array_unique($types)
);
// => 4 (number of unique types)

// Change the field's value to camel case
$page->artist()->str('camel');
// => jilNash

// Adds -1 to the field's value or increments the ending number to allow -2, -3, etc.
$page->title()->lower()->str('increment');
// => haze-1

// Simple dump
$page->artist()->dump();

// With prefix
$page->artist()->dump('artist value: ');

// With template
$page->artist()->dump('The artist known as {{ val }}!!');

// Return dump result instead of echoing
$page->artist()->dump('Artist: ', false)->upper();
// => "ARTIST: JIL NASH"

// Dump entire field object
$page->artist()->dump('artist field: ', true, true);

// Simple log
$page->artist()->log();
// => [2024-11-10 14:30:22] Jil Nash

// With prefix
$page->artist()->log('Artist: ');
// => [2024-11-10 14:30:22] Artist: Jil Nash

// With template
$page->artist()->log('Found artist {{ val }} in page');
// => [2024-11-10 14:30:22] Found artist Jil Nash in page

// Custom log file
$page->artist()->log('Artist: ', 'artist_logs');
// => creates/appends to site/logs/artist_logs.log

// Log entire field object
$page->artist()->log('Artist field: ', 'field_logs', true);
// => logs the full field object in dump format to site/logs/field_logs.log

field($page->title(), $page->artist(), 'sold', ', ')->upper()
// => HAZE, JIL NASH, SOLD

field(
  [$page->title()->tag('em'), $page->year()],
  $page->artist(),
  field($page->width(), $page->height(), ' × ')->suffix(' cm')
    ->when($page->width(), $page->height()),
  $page->description()->prefix('Subject: '),
  $page->info()->prefix('Info: '),
  '; ' // separator for the top level
);
// => <em>Haze</em>, 2014; Jil Nash; 48.2 × 67 cm; Subject: Faint shapes lost in mist.

// /index.php



define('KIRBY_HELPER_FIELD', false);
define('KIRBY_HELPER_F', false);


// /site/config/config.php

return [
  'trych.field-composer' => [
    'mergeSeparator' => ' | ',
    'affixSeparator' => ' ',
    'listJoinSeparator' => '/',
    'listConjunction' => fn() => t('and')  // returns "and", "und", "et" etc. based on current language
  ]
];

$page->title()->merge($page->artist(), $page->year(), ' / ');

$page->title()->prefix($page->artist(), ': ');

$page->keywords()->list(join: ' | ');

$page->members()->list(conjunction: '&');