pangora/classnames

Elegant classlist builder with conditionals

1.0.1 2021-02-18 12:35 UTC

This package is auto-updated.

Last update: 2024-11-18 20:45:37 UTC


README

Classnames banner

Classnames for PHP

Latest Version on Packagist Build Status Total Downloads

This package replicates the functionality of the popular JS package JedWatson/classnames, allowing you to easily build HTML classlists using strings, stringable objects and arrays with conditions, like this:

Classnames::from(
    'btn',
    ['btn-primary'],
    ['btn-secondary' => false],
    ['btn-wide' => true],
    new StringableObject('btn-lg')
);
// => 'btn btn-primary btn-wide btn-lg'

Installation

You can install the package via composer:

composer require pangora/classnames

Usage

Classnames accepts multiple arguments through the static from method and it'll respect the argument order when building the classlist. The from method won't remove duplicates, but you may use the static dedupeFrom, which works the same way, while also removing duplicates.

The allowed argument types are:

  • string
  • int (will be converted to string)
  • Any "stringable" object implementing the magic __toString() method.
  • Sequential arrays
  • Associative arrays where the key represents the value and the value represent the condition.

Arguments of other types will be ignored, except for multidimensional array which will throw an exception.

Classnames::from('btn btn-primary');
// => 'btn btn-primary'

Classnames::from('btn', 'btn-primary');
// => 'btn btn-primary'

Classnames::from('   lots of ', ' space  ');
// => 'lots of space'

Classnames::from('btn', ['btn-primary']);
// => 'btn btn-primary'

Classnames::from([
    'btn' => false,
    'btn-secondary' => false,
    'btn-primary' => true,
]);
// => 'btn btn-primary'

Classnames::from(
    'card',
    new StringableObject('card-lg')
);
// => 'card card-lg'

You may also deduplicate the classlist using dedupefrom:

Classnames::dedupeFrom('a btn b btn c');
// => 'a btn b c'

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email jarand@pangora.no instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.