Collection class in Iconify JSON Tools

This article is for deprecated Iconify JSON Tools.

Iconify JSON Tools has been replced with Iconify Utils

Iconify JSON Tools is a lightweight library for working with icon sets in Iconify JSON format. See Iconify JSON Tools documentation.

Collection class represents an icon set.

To include it use this code:

Node.js
const { Collection } = require('@iconify/json-tools');
PHP
use \Iconify\JSONTools\Collection;

What can Collection class do?

  • Read and write JSON collections.
  • Add, remove, list icons in an icon set.
  • Retrieve icon data.
  • Create icon bundles for Iconify icon sets.

Initializing Collection instance

There are two ways to create an instance: with icon set prefix and without icon set prefix.

You can skip icon set prefix in the constructor if you are going to load data from a JSON file because JSON files contain icon set prefix.

Node.js
let collection = new Collection();
PHP
$collection = new Collection();
Node.js
let collectionWithPrefix = new Collection('custom-icons');
PHP
$collectionWithPrefix = new Collection('custom-icons');

Loading JSON data

There are several functions to load an icon set from JSON file:

  • loadFromFile() loads collection synchronously.
  • loadFromFileAsync() loads collection asynchronously (not available in PHP version).
  • loadJSON() loads JSON data from string or object.
  • loadIconifyCollection() loads Iconify collection from @iconify/json NPM repository (Node.js) or iconify/json Packagist repository (PHP).

loadFromFile()

This function loads an icon set from a JSON file.

Function parameters:

  • file, string file to load data from.
  • defaultPrefix, string optional default prefix in case if JSON file does not have it.
  • (PHP only) cacheFile, string cache file for a parsed icon set. Use this to speed up loading.

Function returns boolean value: true on success, false on failure.

Node.js
let collection = new Collection();
if (!collection.loadFromFile('json/custom-icons.json')) {
   console.error('Failed to load custom-icons.json');
}
PHP
$collection = new Collection();
if (!$collection->loadFromFile('json/custom-icons.json')) {
   throw new \Exception('Failed to load custom-icons.json');
}
PHP with cache
$collection = new Collection();
if (!$collection->loadFromFile('json/custom-icons.json', null, 'cache/custom-icons.php')) {
   throw new \Exception('Failed to load custom-icons.json');
}
Cache should be located in writable directory.

loadFromFileAsync()

This function is similar to loadFromFile(), but it returns Promise and loads file asynchronously.

This function is not available in PHP version of this library.

Node.js
let collection = new Collection();
collection
   .loadFromFileAsync('json/custom-icons.json')
   .then((collection) => {
       console.log('Loaded custom-icons.json');
   })
   .catch((err) => {
       console.error('Failed to load custom-icons.json');
   });

loadJSON()

This function loads an icon set from a string or an object (array for PHP).

Function parameters:

  • data, IconifyJSON or string JSON string or object.
  • prefix, string optional prefix if JSON file doesn't include one.

Function returns boolean value: true on success, false on failure.

Node.js
let collection = new Collection();
if (!collection.loadJSON(data)) {
   console.error('Failed to load JSON data');
}
PHP
$collection = new Collection();
if (!$collection->loadJSON($data)) {
   throw new \Exception('Failed to load JSON data');
}

loadIconifyCollection()

This function loads Iconify icon set from @iconify/json repository.

Function parameters:

  • name, string name of the icon set.
  • dir, string optional root directory of Iconify icon set. Use this option if you want to load Iconify icon set from a custom directory instead of the @iconify/json repository.

Function returns boolean value: true on success, false on failure.

Node.js
let collection = new Collection();
if (!collection.loadIconifyCollection('mdi')) {
   console.error('Failed to load Material Design Icons');
}
PHP
$collection = new Collection();
if (!$collection->loadIconifyCollection('mdi')) {
   throw new \Exception('Failed to load Material Design Icons');
}

Unless you are using second parameter to point to a custom directory where icon sets are located, make sure that @iconify/json is installed before using this function. To install it, run this:

Node.js
npm install @iconify/json --save
PHP
composer require iconify/json

Caching icon sets

This section applies only to PHP version of library.

PHP loads icon sets on every page load, so it makes sense not to parse the same data many times. This is why PHP version of the library has caching functions.

loadFromCache()

This function loads icon set from the cache.

Function parameters:

  • $filename, string cached filename.
  • $time, number time stamp (retrieved with filemtime() function) of the original JSON file. This parameter is used to invalidate cache if JSON file has been updated since the last time cache was saved.

Function returns boolean value: true on success, false on failure.

PHP
$collection = new Collection();

// Locate file
$file = Collection::findIconifyCollection('mdi');

// Attempt to load cached file
if (!$collection->loadFromCache('cache/mdi.php', filemtime($file))) {

   // Failed. Attempt to load from JSON file
   if (!$collection->loadFromFile($file)) {
       throw new \Exception('Cannot load Material Design Icons');
   }

   // Store cache for next loadFromCache() call
   $collection->saveCache('cache/mdi.php', filemtime($file));
}

saveCache()

Stores icon set data in the cache.

This function does not return anything.

For a usable example, see loadFromCache() example above.

Getting icon data

Several functions can be used to retrieve icon data from an icon set:

  • getIconData() returns full data for one icon. It can be used to generate SVG (see SVG class documentation) or for Iconify components.
  • getIcons() returns JSON data for icons, which can be used to import to another JSON collection or can be added to Iconify SVG framework using Iconify.addCollection().
  • scriptify() returns JavaScript bundle file that can be used to load icons in browser with Iconify SVG Framework.

getIconData()

This function returns JSON data for one icon. It returns full data that can be used to generate SVG.

Function parameters:

  • name, string icon name.
  • normalize, boolean optional parameter. If false, result will not include optional fields. If true (default value), result will include optional data. Set to false if you are exporting data to use in Iconify components, such as Iconify for React, set to true if you are exporting data to create SVG class instance.

Function returns IconifyIcon object.

Node.js
let data = collection.getIconData('arrow-left');
let svg = new SVG(data);
containerNode.innerHTML = svg.getSVG({});
PHP
$data = $collection->getIconData('arrow-left');
$svg = new SVG($data);
echo $svg->getSVG();

getIcons()

This function returns JSON data for selected icons. If used without parameters, it returns JSON data for an entire icon set.

Function parameters:

  • icons, string[] array of icon names.

Function returns IconifyJSON object.

Node.js
let data = collection.getIcons(['arrow-left', 'arrow-right', 'home']);
fs.writeFileSync('bundle.json', JSON.stringify(data), 'utf8');
PHP
$data = $collection->getIcons(['arrow-left', 'arrow-right', 'home']);
file_put_contents('bundle.json', json_encode($data));

This function can also be used to copy collection.

Node.js
let data = collection.getIcons();
let newCollection = new Collection();
newCollection.loadJSON(data);
PHP
$data = $collection->getIcons();
$newCollection = new Collection();
$newCollection->loadJSON($data);

Using getIcons() without parameters is the same as accessing collection.items object in Node.js or $collection->items array in PHP.

Warning: In Node.js if you use getIcons() without parameters, editing result object will affect data stored in collection instance. getIcons() does not make a copy of the object if you request an entire collection. This does not apply to PHP version of this library.

To make a proper copy of collection in Node.js, you should serialize and unserialize data:

Node.js
let data = collection.getIcons();
let newCollection = new Collection();
newCollection.loadJSON(JSON.parse(JSON.stringify(data)));
This does not apply to PHP version.

scriptify()

This is similar to getIcons(), but it generates a JavaScript file instead of JSON data and uses different parameters.

Function parameters:

  • options options object.

Options object properties:

  • icons, string[] an array of icons to retrieve. If not set or null, all icons will be retrieved.
  • optimize, boolean. If set to true, JSON data will be optimized to make output smaller.
  • pretty, boolean. If set to true, JSON data will include white spaces that make output easy to read.
  • callback, string. JavaScript callback to wrap JSON data in. The default value is "Iconify.addCollection" for use with Iconify SVG Framework.

Code to create a bundle with selected icons from one collection (repeat same code for different collections to make bundle of all icons used on website):

Node.js
const fs = require('fs');
const { Collection } = require('@iconify/json-tools');

// Load collection
let collection = new Collection();
if (!collection.loadIconifyCollection('mdi')) {
   throw new Error('Cannot load Material Design Icons');
}

// Create bundle
let code = collection.scriptify({
   icons: ['account', 'account-alert', 'home', 'book-open'],
   pretty: false,
   optimize: true,
});

// Save bundle
fs.writeFileSync('bundle-mdi.js', code, 'utf8');
PHP
<?php

// Import Collection class
use \Iconify\JSONTools\Collection;

// Load collection
$collection = new Collection();
if (!$collection->loadIconifyCollection('mdi')) {
   throw new \Exception('Cannot load Material Design Icons');
}

// Create bundle
$code = $collection->scriptify([
   'icons' => ['account', 'account-alert', 'home', 'book-open'],
   'pretty' => false,
   'optimize' => true
]);

// Save bundle
file_put_contents('bundle-mdi.js', $code);

Manipulating icons

There are several functions for manipulating icons:

  • addIcon() adds a new icon.
  • addAlias() adds an alias for an existing icon.
  • setDefaultValue() sets default value for an icon property.
  • removeIcon() removes an icon or an alias.
  • iconExists() checks if an icon or an alias exists.
  • listIcons() lists all icons.

addIcon()

This function adds a new icon to the icon set.

Function parameters:

Function returns:

Function returns boolean value: true on success, false on failure. Failure is possible if an icon is missing body property of if the icon set has no prefix.

Node.js
let collection = new Collection('custom-icons');
collection.addIcon('stop', {
   body: '<path d="M18 18H6V6h12v12z" fill="currentColor"/>',
   width: 24,
   height: 24,
});
PHP
$collection = new Collection('custom-icons');
$collection->addIcon('stop', [
   'body' => '<path d="M18 18H6V6h12v12z" fill="currentColor"/>',
   'width' => 24,
   'height' => 24
]);

addAlias

This function adds an alias for an existing icon.

Function parameters:

  • name, string icon name.
  • parent, string parent icon name.
  • data, IconifyIcon icon data.

Function returns boolean value: true on success, false on failure. Failure is possible if the parent icon is missing.

Node.js
let collection = new Collection('custom-icons');
collection.addIcon('caret-up', {
   body: '<path d="M18 18H6V6h12v12z" fill="currentColor"/>',
   width: 24,
   height: 24,
});
collection.addAlias('caret-down', 'caret-up', {
   vFlip: true,
});
collection.addAlias('caret-down-alias', 'caret-down');
PHP
$collection = new Collection('custom-icons');
$collection->addIcon('caret-up', [
   'body' => '<path d="M18 18H6V6h12v12z" fill="currentColor"/>',
   'width' => 24,
   'height' => 24
]);
$collection->addAlias('caret-down', 'caret-up', [
   'vFlip' => true
]);
$collection->addAlias('caret-down-alias', 'caret-down');

setDefaultIconValue()

Set default value for a property for all icons.

Function parameters:

  • key, string property name.
  • value property value.
Node.js
collection.setDefaultIconValue('height', 24);
PHP
$collection->setDefaultIconValue('height', 24);

This function is used to set a property for all icons that are missing that property. It affects icons added before and after setDefaultIconValue() call.

For example, if an icon set has only 24x24 icons, you can set default width and height to 24 and add icons without width and height:

Node.js
// Create new collection
let collection = new Collection('mdi');

// Set width and height of icons to 24
collection.setDefaultIconValue('width', 24);
collection.setDefaultIconValue('height', 24);

// Add few icons
collection.addIcon('menu-up', {
   body: '<path d="M7 15l5-5l5 5H7z" fill="currentColor"/>',
});
collection.addAlias('menu-down', 'menu-up', {
   vFlip: true,
});
collection.addIcon('stop', {
   body: '<path d="M18 18H6V6h12v12z" fill="currentColor"/>',
});
PHP
// Create new collection
$collection = new Collection();

// Set width and height of icons to 24
$collection->setDefaultIconValue('width', 24);
$collection->setDefaultIconValue('height', 24);

// Add few icons
$collection->addIcon('menu-up', [
   'body' => '<path d="M7 15l5-5l5 5H7z" fill="currentColor"/>',
]);
$collection->addAlias('menu-down', 'menu-up', [
   'vFlip' => true,
]);
$collection->addIcon('stop', [
   'body' => '<path d="M18 18H6V6h12v12z" fill="currentColor"/>',
]);

removeIcon()

Removes an icon or an alias from the icon set.

Function parameters:

  • name, string icon name.
  • checkAliases, boolean, optional. If true, the icon set will be checked for aliases that use the removed icon as parent icon and those aliases will be removed too. Set to false if you know for sure there are no aliases referencing this icon, otherwise set to true.
Node.js
let collection = new Collection();
collection.loadIconifyCollection('fa-solid');
collection.removeIcon('home');
PHP
$collection = new Collection();
$collection->loadIconifyCollection('fa-solid');
$collection->removeIcon('home');

iconExists()

Checks if an icon or an alias exists.

Function parameters:

  • name, string icon name.

Function returns boolean value: true if icon exists, false if not.

Node.js
if (!collection.iconExists('home')) {
   throw new Error('Missing "home" icon!');
}
PHP
if (!$collection->iconExists('home')) {
   throw new \Exception('Missing "home" icon!');
}

listIcons()

Lists all icons in an icon set.

Function parameters:

  • includeAliases, boolean. Value is true if function should list all icon aliases, false if not. The default value is false.

Function returns string[] array of icon names.

Node.js
let collection = new Collection();
collection.loadIconifyCollection('vaadin');
console.log(
   'Available icons in vaadin collection:',
   collection.listIcons(true)
);
PHP
$collection = new Collection();
$collection->loadIconifyCollection('vaadin');
echo 'Available icons in vaadin collection: ', implode(', ', $collection->listIcons(true)), "\n";

Other functions and properties

There are several functions and properties that do not fall in mentioned above sections:

items

This is a property, not a function. You can use it to have access to raw JSON data, making it easy to modify internal data.

Due to differences between PHP and Node.js, in Node.js version items value is the same as using getIcons() without parameters.

prefix()

Returns the icon set prefix, false if the icon set has no prefix.

Node.js
let prefix = collection.prefix();
if (prefix !== false) {
   console.log('Collection has prefix:', prefix);
}
PHP
$prefix = $collection->prefix();
if ($prefix !== false) {
   echo 'Collection has prefix: ', $prefix, "\n";
}

findIconifyCollection()

This is a static function locates Iconify icon set from @iconify/json repository.

Function parameters:

  • name, string name of the icon set.
  • dir, string optional root directory of Iconify icon set. Use this option if you want to load Iconify icon set from a custom directory instead of the @iconify/json repository.

Function returns string value: location of JSON file. On error function will throw an exception.

Node.js
console.log(
   'fa-solid.json can be found at',
   Colleciton.findIconifyCollection('fa-solid')
);
PHP
echo 'fa-solid.json can be found at ', Collection::findIconifyCollection('fa-solid'), "\n";

optimize()

Optimize is a static function that optimizes JSON data. It modifies the object passed in the first parameter.

Function parameters:

  • data, IconifyJSON raw data.
  • props, string[] optional list of properties to optimize. Ignore this parameter unless you need to optimize a custom property.

This function modifies variable passed as first parameter.

Node.js
let data = JSON.parse(JSON.stringify(collection.getIcons()));
Collection.optimize(data);
PHP
$data = $collection->getIcons();
Collection::optimize($data);

deOptimize()

Opposite of the previous function. It converts optimized JSON data into full JSON data, making it easy to retrieve data for each icon.

Function parameters:

This function modifies variable passed as first parameter.

Node.js
let data = JSON.parse(fs.readFileSync('ant-design.json', 'utf8'));
Collection.deOptimize(data);
PHP
$data = json_decode(file_get_contents('ant-design.json'), true);
Collection::deOptimize($data);