GithubHelp home page GithubHelp logo

icanboogie / inflector Goto Github PK

View Code? Open in Web Editor NEW
214.0 6.0 22.0 146 KB

A multilingual inflector that transforms words from singular to plural, underscore to camel case, and formats strings in various ways.

License: Other

Makefile 0.95% PHP 98.16% Dockerfile 0.89%
inflector camelcase underscore pluralization

inflector's Introduction

Inflector

Release Code Quality Code Coverage Packagist

A multilingual inflector that transforms words from singular to plural, underscore to camel case, and formats strings in various ways. Inflections are localized, the default english inflections for pluralization, singularization, and uncountable words are kept in lib/Inflections/en.php.

Inflections are currently available for the following languages:

  • English (en)
  • French (fr)
  • Norwegian Bokmal (nb)
  • Portuguese (pt)
  • Spanish (es)
  • Turkish (tr)

Installation

composer require icanboogie/inflector

Usage

These are some examples of the inflector with the en locale (default).

<?php

use ICanBoogie\Inflector;

$inflector = Inflector::get(Inflector::DEFAULT_LOCALE);
# or
$inflector = Inflector::get('en');
# or
$inflector = Inflector::get();

# pluralize

$inflector->pluralize('post');                       // "posts"
$inflector->pluralize('child');                      // "children"
$inflector->pluralize('sheep');                      // "sheep"
$inflector->pluralize('words');                      // "words"
$inflector->pluralize('CamelChild');                 // "CamelChildren"

# singularize

$inflector->singularize('posts');                    // "post"
$inflector->singularize('children');                 // "child"
$inflector->singularize('sheep');                    // "sheep"
$inflector->singularize('word');                     // "word"
$inflector->singularize('CamelChildren');            // "CamelChild"

# camelize

$inflector->camelize('active_model', Inflector::UPCASE_FIRST_LETTER);
# or
$inflector->camelize('active_model');
// 'ActiveModel'

$inflector->camelize('active_model', Inflector::DOWNCASE_FIRST_LETTER);
// 'activeModel'

$inflector->camelize('active_model/errors');
// 'ActiveModel\Errors'

$inflector->camelize('active_model/errors', Inflector::DOWNCASE_FIRST_LETTER);
// 'activeModel\Errors'

# underscore

$inflector->underscore('ActiveModel');               // 'active_model'
$inflector->underscore('ActiveModel\Errors');        // 'active_model/errors'
$inflector->underscore('Less Active Phrase');        // 'less_active_phrase'
$inflector->underscore('Number 1 Test');             // 'number_1_test'
$inflector->underscore('Johnny5 Still Alive');       // 'johnny5_still_alive'
$inflector->underscore('Lots   of   Spaces');        // 'lots_of_spaces'

# humanize

$inflector->humanize('employee_salary');             // "Employee salary"
$inflector->humanize('author_id');                   // "Author"

# titleize

$inflector->titleize('man from the boondocks');      // "Man From The Boondocks"
$inflector->titleize('x-men: the last stand');       // "X Men: The Last Stand"
$inflector->titleize('TheManWithoutAPast');          // "The Man Without A Past"
$inflector->titleize('raiders_of_the_lost_ark');     // "Raiders Of The Lost Ark"

# ordinal

$inflector->ordinal(1);                              // "st"
$inflector->ordinal(2);                              // "nd"
$inflector->ordinal(1002);                           // "nd"
$inflector->ordinal(1003);                           // "rd"
$inflector->ordinal(-11);                            // "th"
$inflector->ordinal(-1021);                          // "st"

# ordinalize

$inflector->ordinalize(1);                           // "1st"
$inflector->ordinalize(2);                           // "2nd"
$inflector->ordinalize(1002);                        // "1002nd"
$inflector->ordinalize(1003);                        // "1003rd"
$inflector->ordinalize(-11);                         // "-11th"
$inflector->ordinalize(-1021);                       // "-1021st"

# uncountable

$inflector->is_uncountable("advice");                // true
$inflector->is_uncountable("weather");               // true
$inflector->is_uncountable("cat");                   // false

Helpers makes it easy to use default locale inflections.

<?php

namespace ICanBoogie;

echo pluralize('child');                             // "children"
echo pluralize('genou', 'fr');                       // "genoux"
echo singularize('lærere', 'nb');                    // "lærer"
echo pluralize('üçgen', 'tr');                       // "üçgenler"

About inflections

Inflections are localized, the configurators are kept in lib/Inflections/en.php. Since v2.1, these configurators are auto-loaded classes, which means, in theory, you could add your own or overwrite those already defined by specifying another ICanBoogie\\Inflections\\ in your composer.json file.

Acknowledgements

Most of the code and documentation was adapted from Ruby On Rails's Inflector and David Celis' inflections.

Significant differences:

  • Better support of accentuated characters.
  • The Ruby module separator :: as been replaced by the PHP namespace separator \.
  • The plural of "octopus" is "octopuses" (not "octopi"), the plural of "virus" is "viruses" (not viri) and the pural of "cow" is "cows" (not "kine").
  • The following methods have been removed: tableize, classify, demodulize, constantize, deconstantize and foreign_key. They can be easily implemented in specific inflectors.
  • Added the hyphenate method, which is a combination of underscore and dasherize.
  • One specifies true rather than false to camelize() to downcase the first letter of the camel cased string.

Getting started

Inflector expects to work in UTF-8, which is the default encoding character set starting PHP 5.6, for older versions please use mb_internal_encoding() as follows:

<?php

namespace ICanBoogie;

// …

mb_internal_encoding('UTF-8');

titleize("été_aux_âmes_inouïes"); // Été Aux Âmes Inouïes

Continuous Integration

The project is continuously tested by GitHub actions.

Tests Static Analysis Code Style

Code of Conduct

This project adheres to a Contributor Code of Conduct. By participating in this project and its community, you are expected to uphold this code.

Contributing

Please see CONTRIBUTING for details.

License

icanboogie/inflector is released under the BSD-3-Clause.

inflector's People

Contributors

alexking avatar calcinai avatar chriseverson avatar donatj avatar ferhatelmas avatar grahamcampbell avatar hkdobrev avatar josimarlemos avatar justin-schroeder avatar luketlancaster avatar olvlvl avatar pdscopes avatar petah avatar yani- avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

inflector's Issues

Spanish Singlularize don't work correctly with words which plural ends in 'ces'

For example, the plural of Luz is luces. but when you're turning back, it return luc instead of luz.

echo $inflector->pluralize('luz') // luces
echo $inflector->singularize('luces')  // luc

i've seen a little bit of the code and in the file lib/inflections/es.php it seems to declare the rules for inflection.

i've added $inflect->singular('/ces$/', 'z'); and it worked for me.

Hope it helps you.

Pluralize error

Hello there, Can you please have a look at the attached image? I am facing an error.
BTW, Thanks for the package. :)
screenshot from 2017-04-24 16-21-49

Hyphenate expectations

I don't want to consider this a bug, but more an initial talking point for discussion. Given that hyphenate is described as a combination of underscore and dasherize, this may affect other expectations.

Firstly, it would seem to me that hyphenate should do more than simply insert hyphens on case differences, which is all it appears to do at current. If I want to hyphenate the string "I expect more than 2 hyphens here", I'd think the result should be more like "i-expect-more-than-2-hyphens-here" -- what really happens is essentially nothing without some initial prep work.

For starters, I need to ucwords. Secondly, I need to then strip spaces (and perhaps many more characters). Lastly, even once I do that, I still won't get a hyphen between the "than" and the "2" because 2 doesn't seem to be recognized in the same way a capital letter would be.

I'd be happy to submit a pull request to improve this with respect to English, but I wanted to confirm that the idea as to what "hyphenate" should be is shared before wasting my time and yours.

Inflections->human() using curly braces to access array

When running PHP 8.0.3, I encountered the following error:

PHP Fatal error: Array and string offset access syntax with curly braces is no longer supported in /home/....../shoot-noir-api/app/vendor/icanboogie/inflector/lib/inflections.php on line 331

Line 331 (currently): $r0 = $rule{0};

When I altered the line to $r0 = $rule[0];, the error went away. I will submit a pull request first things in the morning.

Switch to enable words to retain deliberate capitals when camelizing

It'd be nice to be able to retain partially camelized words when calling this method. For example, I'm working with this:

/defintions/securityDefinitions

Which after camelizing, results in

\Definitions\Securitydefinitions

Losing the capital D. The current workaround is to underscore() it first, like this:

$class = $inflector->camelize($inflector->underscore($fragment));

I assume it was a deliberate choice to use capitalize() over ucfirst(), but in some cases (like above) I think it's less desirable. What do you think?

Pluralize should take a value to determine whether to pluralize or not

Hi

This is more of a feature request, or something to save me having to do a lot of "if" statements around my app. It may not be your intention for the library. And it may not be as simple as this...

/**
 * Returns the plural form of the word in the string.
 *
 * <pre>
 * $this->pluralize('post');       // "posts"
 * $this->pluralize('children');   // "child"
 * $this->pluralize('sheep');      // "sheep"
 * $this->pluralize('words');      // "words"
 * $this->pluralize('CamelChild'); // "CamelChild"
 * </pre>
 *
 * @param string $word
 * @param int $number    used to determine whether to pluralize or not
 *
 * @return string
 */
public function pluralize($word, $number = 2)
{
    if($number < 2) {
        return $word;
    }
    return $this->apply_inflections($word, $this->inflections->plurals);
}

Regards
Marcus

FR: Unavailable locales

Calling Inflector::get('de') will trigger the following PHP warning:

PHP Warning:  require(.../vendor/icanboogie/inflector/lib/inflections/de.php): failed to open stream: No such file or directory in .../vendor/icanboogie/inflector/lib/inflections.php on line 52

Could we handle this in a better way? Perhaps by throwing an Exception or adding an additional method in the Inflector class to list available locales in an array?

Many thanks!

Testing whether a word is plural or not

Since you can convert a word from its singular form to plural form and visa versa, is there a way to test if a word is plural or singular?

If not could I submit a pull request to do this? I would guess there could be issues with ambiguous words, e.g. sheep.

    /**
     * Returns true if the word is plural, false otherwise.
     * Ambiguous words return true.
     *
     * <pre>
     * $this->isPlural('post');       // false
     * $this->isPlural('children');   // true
     * $this->isPlural('sheep');      // true
     * $this->isPlural('words');      // true
     * $this->isPlural('CamelChild'); // false
     * </pre>
     *
     * @param string $word
     *
     * @return string
     */
    public function isPlural($word)
    {
        return $word == $this->apply_inflections($word, $this->inflections->plurals);
    }

    /**
     * Returns true if the word is plural, false otherwise.
     * Ambiguous words return true.
     *
     * <pre>
     * $this->isSingular('post');       // true
     * $this->isSingular('children');   // false
     * $this->isSingular('sheep');      // true
     * $this->isSingular('words');      // false
     * $this->isSingular('CamelChild'); // true
     * </pre>
     *
     * @param string $word
     *
     * @return string
     */
    public function isSingular($word)
    {
        return $word == $this->apply_inflections($word, $this->inflections->singulars);
    }

Add optional `$count` param to `pluralize` method

This is something that I've seen in other inflection classes, and it'd be helpful for me to be able to continue using it. Thing I'm not sure about is the effect it would have on locales other than en? If it's something you're interested in I could push up a PR and go from there!

Upgrading

Is there any backward breaking changes when moving form v1.5.0 to v2?

I was going to submit a PR regarding the use {} to access array key zero in the human() method of the inflectors.php file however this appears to be fixed in v2.

Anyway, I'd like to know if there is anything I should be aware of before I upgrade.

Thanks!

PHP 7.4

Hi. I dont have a time for now about commit, but at PHP 7.4 there is an error

Array and string offset access syntax with curly braces is deprecated in vendor/icanboogie/inflector/lib/inflections.php on line 350

Just replace to

$r0 = $rule[0];

Prevent lib/helpers.php to be autoloaded in every request

Is there any special reason to autoload lib/helpers.php using the "files" method in composer.json? Every request load those functions even when they are not intended to be used, with the performance penalty it implies.

Moving those helpers functions to some class loaded with the same "psr-4" methods as the others should do the job and prevent this issue.

Pluralize french not totally working

If I put something like: "Objet de Marine" it returns "Objet de Marines" it should be in that case "Objets de Marine". I'm doing a PR for that

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.