# cnBolt-Extensions-Basics Collection of services and functions for use inside bolt. ## Installation This extension is hosted in a private git repository and has to be installed manually or via the satis.condenastdigital.de server. ``` composer require cnd/basics ``` Installing or updating via the Bolt admin interface is also possible but would require the web-server's user to have proper access to the GitHup repository. This is usually not the case. # New Twig Filters ## ArrayLibrary ### splice Insert one or more items into the source array. * **Item** Add item or array of items into source array * **Position** (Optional) insert at position (zero based index) * **Length** (Optional) remove number of items from target array at position before inserting ``` {% set newArray = ["one","two","three","four"]|splice("added", 2) %} ``` ## FileLibrary ### fimemtime Return file modification time of a file inside the "/files" folder ``` {% set time = record.value.myfile.file|filemtime %} ``` ### filesize Return file size of a file inside the "/files" folder ``` {% set size = record.value.myfile.file|filesize %} ``` ## CollectionLibrary A port of the Topolis/Collection class. This library needs the sf2 package topolis/function-library. ### collection_get get a value from a multidimensional array ``` {% set value = {one: 'a', two: {three: 'c'}} | collection_get('two.three', 'default value') %} ``` ### collection_set set a value inside a multidimensional array ``` {% set value = {one: 'a', two: {three: 'c'}} | collection_set('two.three', 'new value') %} ``` ### collection_sort sort a multidimensional array by one of it's element's values ``` {% set value = [{name: 'aron', age: 12},{name: 'betty', age: 15}] | collection_sort('name', true, 'age', false) %} ``` ### collection_remove delete a value from a multidimensional array ``` {% set value = {one: 'a', two: {three: 'c'}} | collection_set('two.three') %} ``` ### collection_add add a value to a multidimensional array ``` {% set value = {one: 'a', two: {three: 'c'}} | collection_set('two.four', 'new value') %} ``` ### collection_find find a value inside a multidimensional array ``` {% set value = {people: [{name: 'aron', age: 12},{name: 'betty', age: 15}]} | collection_find('people', 'aron', 'name', 'none found') %} ``` ### collection_first return first value from a multidimensional array ``` {% set value = {people: [{name: 'aron', age: 12},{name: 'betty', age: 15}]} | collection_find('people', 'none found') %} ``` ## StorageLibrary ### selectContent A filter to select content objects with more features than the normal bolt method. Available Parameters: * **contenttypes** Required - Array of contenttypes (singular_slug) * **order** Optional - Array of columnt => direction pairs (Default is {"datepublished": false} * **taxonomy** Optional - Array of taxonomytype => name pairs * **filter** Optional - Array of field => value pairs * **operator** Optional - Array of field => operator pairs for above filters (Default is "equals") * **limit** Optional - Number of items to return (Maximum is 1000, default 10) * **offset** Optional - Number of items to start results (Default 0) * **options** Optional - Additional option => true/false pairs Available operators: * **equals** field equals value * **notequals** field is not equal to value * **starts** field starts with value * **ends** field ends with value * **contains** field contains value * **greater** field is numerical greater than value * **less** field is numerical lesser than value * **in** field is in value array (needs value to be of type array) * **isnull** field is logical null * **notnull** field is logical other than null * **range** field is between first and second value (needs value to be an array of two values) ``` {% set records = selectContent({ "contenttypes": ["article", "teaser"], "order": {"datepublish": false, "title": true}, "taxonomy": {"category": "Architektur", "tag": "Holz", "tag": "Stein"}, "filter": {"title": "Unsichtbares"}, "operator": {"title": "starts"}, "limit": 20, "offset": 0, "options": {"showquery": true, "showparams": true, "showtiming": true} }) %} ``` ### selectContentLastTotal Returns the un-pages total ammount of the last executed selectContent call ``` {% set records = selectContent({...}) %} {% set total = selectContentLastTotal() %} ``` ## StringLibrary ### shorten Shorten a text to maximum of **length** characters, cutting at word boundary closest to length. * **Length** Cut at word boundary closest to this number of letters ``` {% set text = "This is a test text with to many letters!"|shorten(10) %} ``` ### xpathQuery execute an xpacth query on a value containing valid html * **query** the xpath query to execute ``` {% set results = "
one
two
"|xpathQuery('//p') %} ``` ### preg_replace Execute PHP's preg_replace function. Can also use arrays for pattern and replace variables. ``` {% set result = input|preg_replace('/pattern/', 'replace') %} {% set result = input|preg_replace(['/1/','/2/'], ['A','B']) %} ``` ### preg_match Execute PHP's preg_match function. Can also use an array for pattern, first match returns true. ``` {% set result = input|preg_match('/pattern/') %} ``` ### cleanLink Remove any characters from the link, that aren't allowed. Supported umlaut's will be converted to ascii. ``` {% set result = input|cleanLink %} ``` ### base64Encode Execute PHP's base64_encode function. ``` {% set result = input|base64Encode %} ``` ### base64Decode Execute PHP's base64_decode function. ``` {% set result = input|base64Decode %} ``` ## TwigLibrary ### hasFilter Check if twig has a certain filter available. * **name** name of filter ``` {% if hasFilter("myfunction") %} ``` ### hasFunction Check if twig has a certain function available. Warning, this function's result is cached/scoped and potentially contains the wrong result during runtime! See callIfExists for an alternative solution. * **name** name of function ``` {% if hasFunction("myfunction") %} ``` ### hasExtension Check if twig has a certain extension available. * **name** name of extension ``` {% if hasExtension("myextension") %} ``` ### callIfExists Check if twig has a certain function available and execute if so. This function is not called in wrong scopes and will check exactly where it's called inside the template. ``` {% set result = callIfExists("myfunction", param1, param2, param3...) %} ``` ### generateTeaser Generate a generic teaser from any kind of known record object. Supports **Bolt Records** and **Kraken Content**. ``` {% set teaser = generateTeaser(object, { teaserImageSize: {size: [300,200], crop: 'c'} or teaserImageSize: alias }}) %} ``` It is also possible to specify an alternative attribute map as `map` according to the specifications of the `extractValue` method above for custom Bolt content. ## BoltLibrary ### getTaxonomy Load a taxonomy from database including it's name and usage statistics. Can be used to load names from tag like taxonomies. * **type** the slug of the taxonomy type. (Example: `tags`) * **slug** the slug of the taxonomy. (Example: `somthing-interesting`) ``` {% set tagdata = getTaxonomy('tags','something-special') %} ``` This will return an array of the following form: ``` { "config": {the config entry for this taxonomy from the taxonomy.yml} "slug": slug of the taxonomy as given in call "name": the name of this taxonomy as loaded from the database "usage": { content type: number of linked items in the database } } ``` ### extractValue Extract the contents of a record's value. Supports various different types of fields. * **key** the name of the attribute to extract * **type** the type of the attribute (See below) * **config** optional additional parameters for this attribute type Available field types: * **static** returns a static string as specified in `key` * **field** returns the value of this record's attribute with name in `key` * **location** returns a mongo compatible array of type 'point' from data stored in this record's attribute with name in `key` * **taxonomy** returns an array of slugs from this record's taxonomy with name in `key` * **relation** returns the value from a record's attribute with name in `config.field` that is related to this record as `key` * **selectsingle** returns the values from a list of record's attributes with name specified in `config.field` that are linked via this record's attribute of type 'select' with name in $key and contenttype in `config.contenttype`. This field supports only select fields with only one possible contenttype! * **taxonomy** returns an array of slugs from this record's taxonomy with name in `key` * **image** returns the image url from this record's image field with name in `key`. Specify desired sizes or alias in `config.alias` or `config.width`, `config.height`, `config.crop` * **imageservice** returns the first image url from this record's imageservice field with name in `key`. Specify desired sizes or alias in `config.alias` or `config.width`, `config.height`, `config.crop` * **link** returns the records link by calling it's `link()` method ``` {% set value = record|extractValue(key, type, config) ``` ## CompetitionsLibrary Filters and methods optimized for our competions bolts. ### competitionStatus Return the status of a competition: * future * today * now * past * false ## KrakenLibrary Selects content from Kraken via the API. This library requires the package `cnd/kraken-sdk` to be installed. The Twig method uses the Bolt extension `cnd/library` and it's KrakenService. The configuration is done in that extensions configuration file. ### Configuration This is the required configuration for the `cnd/library` extension. The keys can and should be shared with the sso extension, if present. ``` kraken: auth: key-private: bolt-private.key key-public: bolt-public.key api: client-uid: 1234567890abcdef url: https://kraken.condenastdigital.de/ verify-cert: false ``` ### Usage The twig filter contains a parameters array. **Warning** The filter will not contain any default conditions for unpublished contents or special flags. You need to add these to your filter on your own. This sample already contains publishing filters and flags among other things. ``` {% set items = selectKraken({ "filters": { "type": {"$in":["article"]}, "source.name": {"$in":["vogue"]}, "control.flags": {"$nin":["advertorial"]}, "control.publishDate": {"$lte":"$cndCurrentDate"}, "$or":[ {"control.unpublishDate":{"$gte":"$cndCurrentDate"}}, {"control.unpublishDate":{"$eq":null}} ], }, "order": { "control.publishDate": false }, "limit": 10, "offset": 0 }) %} ``` ### Images from Kraken (Schrimp) You can also use the *krakenThumb* twig function that gets an kraken image object as a parameter, finds the variation that suits sove given size constrains and transorms it to fit them. To scale the images, the library uses our Schrimp service which needs to be configured. The configuration is as follows: ``` schrimp: endpoint: https://shrimp.condenastdigital.de/{your-project-subpath}/ secret: {your-project-secret} ``` In twig you can transform an image like this ``` {% set image_url = krakenThumb(kraken_image, 640, 480, 'c' ) %} ``` This is the definition of the function and its defaults: ```krakenThumb(image_object, width, height, cropping="c", quality=80, format="jpg" )``` The cropping follows the standart Bolt cropping options. The function can output JPEGs PNGs and GIFs