A library that can inflect strings to many formats

A library that can inflect strings to many formats

README

Packagist
License
CI
Coverage

Tale Inflector

What is Tale Inflector?

Tale inflector bends strings into different naming styles.
A common use-case would be the converting of class-names or property-names to table-names or titles to slugs for URLs.

It can also generate the plural or singular of a string or ordinalize numbers.

Installation

composer require talesoft/tale-inflector

Usage

use TaleInflector;

$inflector = new Inflector();

//Table generation
$inflector->inflect('ProductAttribute', ['tableize', 'pluralize']); //product_attributes
$inflector->inflect('someProperty', ['tableize']); //some_property

//Canonicalization / slugs
$inflector->inflect('Some title I inserted', ['canonicalize']); //some-title-i-inserted
$inflector->inflect('Was höre ich da?', ['canonicalize']); //was-hore-ich-da

//Or just use the static methods for quick access
Inflector::canonicalize('Some random title'); //some-random-title

Available strategies/static methods

camelize

TaleInflectorStrategyCamelCaseStrategy

some Random string = SomeRandomString

dasherize

TaleInflectorStrategyDashRejoinStrategy

some Random string = some-Random-string

canonicalize

TaleInflectorStrategyKebabCaseStrategy

some Random string = some-random-string

variableize

TaleInflectorStrategyLowerCamelCaseStrategy

some Random string = someRandomString

constantize

TaleInflectorStrategyMacroCaseStrategy

some Random string = SOME_RANDOM_STRING

tableize

TaleInflectorStrategySnakeCaseStrategy

some Random string = some_random_string

underscorize

TaleInflectorStrategyUnderscoreRejoinStrategy

some Random string = some_Random_string

humanize

TaleInflectorStrategyUppercaseWordsStrategy

some Random string = Some Random String

ordinalize

TaleInflectorStrategyNumberOrdinalStrategy

1 = 1st
12 = 12th
23 = 23rd

pluralize

TaleInflectorStrategyMacroCaseStrategy

rabbit = rabbits
car = cars
house = houses

singularize

TaleInflectorStrategyMacroCaseStrategy

rabbits = rabbit
cars = car
houses = house

Roll your own

use TaleInflectorStrategyInterface;

class MyInflectionStrategy implements StrategyInterface
{
   public function inflect(string $string): string
   {
       return "!! {$string} !!";
   }
}

$inflector->inflect('Test', [MyInflectionStrategy::class]); //!! Test !!

You can register your own short names

use TaleInflectorStrategyInterface;

class MyInflectionStrategy implements StrategyInterface
{
    public function inflect(string $string): string
    {
        return "!! {$string} !!";
    }
}

$inflector->addNamedStrategy('exlamize', MyInflectionStrategy::class);
$inflector->inflect('House', ['pluralize', 'exclamize']); //!! Houses !!

Source

Add a Comment

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *