2016-05-12 82 views
1

我正在使用這個庫,並且遇到了一個我沒有解決的問題。這可能限制fzaninotto上的一些字符串格式化器Faker

我喜歡限制大小的一些字段,例如userName(Faker \ Provider \ Internet)。我認爲ot不是好主意使用字符串與255這個領域,並像限制到15.

在我的表的種子生成一些崩潰後,我讀代碼。

protected static $userNameFormats = array(
     '{{lastName}}.{{firstName}}', 
     '{{firstName}}.{{lastName}}', 
     '{{firstName}}##', 
     '?{{lastName}}', 
    ); 
public function userName() 
    { 
     $format = static::randomElement(static::$userNameFormats); 
     $username = static::bothify($this->generator->parse($format)); 

     return strtolower(static::transliterate($username)); 
    } 

用於我的程序,我認爲創建一個分叉。在這個分支修改代碼

protected static $userNickFormats = array(
     '{{firstName}}', 
     '{{firstName}}#', 
     '{{firstName}}##', 
     '{{firstName}}###', 
     '?{{lastName}}##', 
    ); 


public function userNick($limit = 15) 
    { 
     $format = static::randomElement(static::$userNickFormats); 
     $username = static::bothify($this->generator->parse($format)); 
     while (strlen($username) > $limit) { 
      $username = static::bothify($this->generator->parse($format)); 
     } 

     return strtolower(static::transliterate($username)); 
    } 

我認爲這是一個最好的方法。

回答

1

我不確定Faker的分叉是最簡單的方法。

考慮只創建自己的Provider類並將其添加到faker。 見the documentation

在你的情況下,它可能會是這個樣子(代碼從文檔複製招搖):

userNickProvider.php

<?php 

class UserNick extends \Faker\Provider\Base 
{ 
    protected static $userNickFormats = array(
     '{{firstName}}', 
     '{{firstName}}#', 
     '{{firstName}}##', 
     '{{firstName}}###', 
     '?{{lastName}}##', 
    ); 


    public function userNick() 
    { 
     $format = static::randomElement(static::$userNickFormats); 
     $username = static::bothify($this->generator->parse($format)); 

     return strtolower(static::transliterate($username)); 
    }  
} 

至於你所需要的限制,有一個叫做修改valid()您可以使用任何faker方法。你只需提供一個函數返回一個布爾值,判斷生成的值是否是有效值,否則就會生成另一個值等等。所以你不必在你的提供者函數中這樣做。

首先驗證:

$max15 = function($string) { 
    return mb_strlen($string) <= 15; 
}; 

然後你可以使用它像這樣:

$faker = new Faker\Generator(); 
$faker->addProvider(new UserNick($faker)); 

$name = $faker->valid($max15)->userNick; 

總結:
您不必到餐桌法克爾得到你想要什麼,只是編寫你自己的提供者。