Doctrine Inflector

repository·2.1.x·Indexed 11 days ago

https://github.com/doctrine/inflector

A lightweight PHP library for linguistic string manipulations, including changing word casing and converting between singular and plural forms. It supports multiple languages such as English, French, Italian, and Spanish, and provides methods like tableize(), classify(), camelize(), pluralize(), and singularize().

Tokens
3.4K
Snippets
12
Records
19
Agent score
94%

What's inside Doctrine Inflector

  1. Initialize an Inflector using InflectorFactory

    2.1.x

    The recommended way to create an Inflector instance is through the Doctrine\ eflector\InflectorFactory class. By default, the factory creates an English inflector.

    use Doctrine\Inflector\InflectorFactory;
    
    $inflector = InflectorFactory::create()->build();
  2. English language inflection rules in Inflectible

    2.1.x

    The Doctrine\Inflector\Rules\English\Inflectible class provides the core rules for English language inflection. It defines how words are transformed between singular and plural forms using three types of rules:

    1. Singular Transformations: Rules applied to convert a plural word to its singular form using regex patterns.
    2. Plural Transformations: Rules applied to convert a singular word to its plural form using regex patterns.
    3. Irregular Substitutions: Direct mappings for words that do not follow standard pattern-based rules (e.g., man -> men).

    While these methods are primarily used internally by the Inflector engine to build its rule sets, they represent the authoritative definition of English inflection logic within the library.

  3. Configure custom singular and plural rules

    2.1.x

    You can define custom inflection rules (transformations, patterns, and substitutions) using the InflectorFactory before building the instance. This allows for fine-grained control over how words are transformed.

    use Doctrine\Inflector\InflectorFactory;
    use Doctrine\Inflector\Rules\Pattern;
    use Doctrine\Inflector\Rules\Patterns;
    use Doctrine\Inflector\Rules\Ruleset;
    use Doctrine\Inflector\Rules\Substitution;
    use Doctrine\Inflector\Rules\Substitutions;
    use Doctrine\Inflector\Rules\Transformation;
    use Doctrine\Inflector\Rules\Transformations;
    use Doctrine\Inflector\Rules\Word;
    
    $inflector = InflectorFactory::create()
        ->withSingularRules(
            new Ruleset(
                new Transformations(
                    new Transformation(new Pattern('/^(bil)er$/i'), '\1'),
                    new Transformation(new Pattern('/^(inflec|contribu)tors$/i'), '\1ta')
                ),
                new Patterns(new Pattern('singulars')),
                new Substitutions(new Substitution(new Word('spins'), new Word('spinor')))
            )
        )
        ->withPluralRules(
            new Ruleset(
                new Transformations(
                    new Transformation(new Pattern('^(bil)er$'), '\1'),
                    new Transformation(new Pattern('^(inflec|contribu)tors$'), '\1ta')
                ),
                new Patterns(new Pattern('noflect'), new Pattern('abtuse')),
                new Substitutions(
                    new Substitution(new Word('amaze'), new Word('amazable')),
                    new Substitution(new Word('phone'), new Word('phonezes'))
                )
            )
        )
        ->build();
  4. How RulesetInflector handles multiple rulesets

    2.1.x

    The RulesetInflector implements the WordInflector interface and allows you to combine multiple Ruleset objects. When inflecting a word, it follows a specific priority order across the provided rulesets:

    1. Uninflected Check: For each ruleset, it first checks if the word matches any uninflected word patterns. If it matches, the word is returned immediately without further inflection.
    2. Irregular Inflection: If no uninflected pattern matches, it attempts to apply the ruleset's irregular inflection rules. The first ruleset that produces a result different from the original word wins.
    3. Regular Inflection: If no irregular inflection is applied, it attempts to apply the ruleset's regular inflection rules. The first ruleset that produces a result different from the original word wins.
    4. Fallback: If no rulesets produce a change, the original word is returned as-is.

    This allows you to layer language rules (e.g., applying English rules first, then falling back to a more generic ruleset).

    // Example of composing multiple rulesets
    $inflector = new RulesetInflector($englishRuleset, $genericRuleset);
    $result = $inflector->inflect('word');
  5. Create an Inflector for a specific language

    2.1.x

    To use a language other than English, use the createForLanguage() method on the factory with a constant from the Doctrine\Inflector\Language class.

    Supported languages include:

    • Language::ENGLISH
    • Language::ESPERANTO
    • Language::FRENCH
    • Language::ITALIAN
    • Language::NORWEGIAN_BOKMAL
    • Language::PORTUGUESE
    • Language::SPANISH
    • Language::TURKISH
    use Doctrine\Inflector\InflectorFactory;
    use Doctrine\Inflector\Language;
    
    $inflector = InflectorFactory::createForLanguage(Language::SPANISH)->build();
  6. Transform text with Inflector methods

    2.1.x

    The Inflector class provides several methods for text transformation:

    • tableize($string): Converts ModelName to model_name.
    • classify($string): Converts model_name to ModelName.
    • camelize($string): Converts model_name to modelName (uses classify then lowercases the first character).
    • capitalize($string, $delimiters = ' '): Capitalizes all words. Unlike PHP's ucwords, you can specify custom delimiters.
    • pluralize($string): Returns the plural form of a word.
    • singularize($string): Returns the singular form of a word.
    • urlize($string): Generates a URL-friendly string (e.g., my-first-blog-post).
    • unaccent($string): Removes accents from a string (e.g., año becomes ano).
  7. Manually construct an Inflector

    2.1.x

    If you prefer not to use the factory, you can manually instantiate the Inflector by providing a singular and a plural word inflector. This typically involves using CachedWordInflector and RulesetInflector with specific language rules.

    use Doctrine\Inflector\Inflector;
    use Doctrine\Inflector\CachedWordInflector;
    use Doctrine\Inflector\RulesetInflector;
    use Doctrine\Inflector\Rules\English;
    
    $inflector = new Inflector(
        new CachedWordInflector(new RulesetInflector(
            English\Rules::getSingularRuleset()
        )),
        new CachedWordInflector(new RulesetInflector(
            English\Rules::getPluralRuleset()
        ))
    );
  8. Use a No-operation (Noop) inflector

    2.1.x

    If you need an inflector that performs no changes (returning the input as output), use Doctrine\Inflector\NoopWordInflector. This is useful for implementing the Null Object pattern.

    use Doctrine\Inflector\Inflector;
    use Doctrine\Inflector\NoopWordInflector;
    
    $inflector = new Inflector(new NoopWordInflector(), new NoopWordInflector());
  9. Get English singular transformations

    2.1.x

    The getSingular() method returns an iterable of Transformation objects used to derive singular forms from plural words in English. Each transformation uses a Pattern (regex) and a replacement string.

    // Returns Transformation[]
    Doctrine\Inflector\Rules\English\Inflectible::getSingular();
  10. RulesetInflector class

    2.1.x

    The RulesetInflector class is used to perform word inflection by iterating through a collection of Ruleset objects. It implements the WordInflector interface.

    Constructor

    public function __construct(Ruleset $ruleset, Ruleset ...$rulesets) Requires at least one Ruleset object. Subsequent Ruleset objects are appended to the internal list and processed in the order they are provided.

    Methods

    public function inflect(string $word): string Inflects the given string based on the prioritized rulesets. Returns an empty string if the input is empty.

    use Doctrine\Inflector\RulesetInflector;
    use Doctrine\Inflector\Rules\Ruleset;
    
    // Assuming $ruleset is an instance of Ruleset
    $inflector = new RulesetInflector($ruleset);
    $inflectedWord = $inflector->inflect('some_word');