talesoft/tale-inflector

一个可以将字符串转换为多种格式的库

0.2.0 2018-05-10 00:07 UTC

This package is auto-updated.

Last update: 2024-09-12 10:37:07 UTC


README

Packagist License CI Coverage

Tale Inflector

什么是 Tale Inflector?

Tale inflector 可以将字符串转换为不同的命名风格。常见的用例包括将类名或属性名转换为表名,或将标题转换为 URL 的 slug。

它还可以生成字符串的复数或单数形式,或对数字进行序数化。

安装

composer require talesoft/tale-inflector

用法

use Tale\Inflector;

$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

可用的策略/静态方法

camelize

Tale\Inflector\Strategy\CamelCaseStrategy

some Random string = SomeRandomString

dasherize

Tale\Inflector\Strategy\DashRejoinStrategy

some Random string = some-Random-string

canonicalize

Tale\Inflector\Strategy\KebabCaseStrategy

some Random string = some-random-string

variableize

Tale\Inflector\Strategy\LowerCamelCaseStrategy

some Random string = someRandomString

constantize

Tale\Inflector\Strategy\MacroCaseStrategy

some Random string = SOME_RANDOM_STRING

tableize

Tale\Inflector\Strategy\SnakeCaseStrategy

some Random string = some_random_string

underscorize

Tale\Inflector\Strategy\UnderscoreRejoinStrategy

some Random string = some_Random_string

humanize

Tale\Inflector\Strategy\UppercaseWordsStrategy

some Random string = Some Random String

ordinalize

Tale\Inflector\Strategy\NumberOrdinalStrategy

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

pluralize

Tale\Inflector\Strategy\MacroCaseStrategy

rabbit = rabbits
car = cars
house = houses

singularize

Tale\Inflector\Strategy\MacroCaseStrategy

rabbits = rabbit
cars = car
houses = house

自定义

use Tale\Inflector\StrategyInterface;

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

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

您可以注册自己的短名称

use Tale\Inflector\StrategyInterface;

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

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