From ce612d8d0462ec26c14d4ccb86e43fbae1864fce Mon Sep 17 00:00:00 2001 From: Mihai Zaharie Date: Sun, 5 Jan 2014 12:48:39 +0200 Subject: [PATCH 1/7] Add Personal Numerical Code formatter --- src/Faker/Provider/ro_RO/Person.php | 118 +++++++++++++++++++++++ test/Faker/Provider/ro_RO/PersonTest.php | 95 ++++++++++++++++++ 2 files changed, 213 insertions(+) create mode 100644 test/Faker/Provider/ro_RO/PersonTest.php diff --git a/src/Faker/Provider/ro_RO/Person.php b/src/Faker/Provider/ro_RO/Person.php index 242bfc6c..69b8d30c 100644 --- a/src/Faker/Provider/ro_RO/Person.php +++ b/src/Faker/Provider/ro_RO/Person.php @@ -85,6 +85,18 @@ class Person extends \Faker\Provider\Person protected static $prefixMale = array('dl.', 'ing.', 'dr.'); protected static $prefixFemale = array('d-na.', 'd-șoara', 'ing.', 'dr.'); + protected static $cnpCountyCodes = array( + 'AB' => '01', 'AR' => '02', 'AG' => '03', 'B' => '40', 'BC' => '04', 'BH' => '05', + 'BN' => '06', 'BT' => '07', 'BV' => '08', 'BR' => '09', 'BZ' => '10', 'CS' => '11', + 'CL' => '51', 'CJ' => '12', 'CT' => '13', 'CV' => '14', 'DB' => '15', 'DJ' => '16', + 'GL' => '17', 'GR' => '52', 'GJ' => '18', 'HR' => '19', 'HD' => '20', 'IL' => '21', + 'IS' => '22', 'IF' => '23', 'MM' => '24', 'MH' => '25', 'MS' => '26', 'NT' => '27', + 'OT' => '28', 'PH' => '29', 'SM' => '30', 'SJ' => '31', 'SB' => '32', 'SV' => '33', + 'TR' => '34', 'TM' => '35', 'TL' => '36', 'VS' => '37', 'VL' => '38', 'VN' => '39', + + 'B1' => '41', 'B2' => '42', 'B3' => '43', 'B4' => '44', 'B5' => '45', 'B6' => '46' + ); + /** * @example 'Ion Popescu' */ @@ -128,4 +140,110 @@ class Person extends \Faker\Provider\Person { return static::randomElement(static::$prefixFemale); } + + /** + * Personal Numerical Code (CNP) + * + * @link http://ro.wikipedia.org/wiki/Cod_numeric_personal + * @example 1111111111118 + * + * @param string $gender Valid values: m, f, 1, 2 + * @param integer $century Valid values: 1800, 1900, 2000, 1, 2, 3, 4, 5, 6 + * @param string $county Valid values: 2 letter ISO 3166-2:RO county codes and B1-B6 for Bucharest's 6 sectors + * @return string + * + */ + public function cnp($gender = null, $century = null, $county = null) + { + if (is_null($county) || !array_key_exists($county, static::$cnpCountyCodes)) + { + $countyCode = static::randomElement(array_values(static::$cnpCountyCodes)); + } + else + { + $countyCode = static::$cnpCountyCodes[$county]; + } + + $cnp = (string) static::cnpFirstDigit($gender, $century) + . static::numerify('##') + . sprintf('%02d', $this->generator->month()) + . sprintf('%02d', $this->generator->dayOfMonth()) + . $countyCode + . static::numerify('##%') + ; + + $cnp = static::cnpAddChecksum($cnp); + + return $cnp; + } + + /** + * Calculates the first digit for the Personal Numerical Code (CNP) based on + * the gender and century + * + * @param string $gender Valid values: m, f, 1, 2 + * @param integer $century Valid values: 1800, 1900, 2000, 1, 2, 3, 4, 5, 6 + * @return integer + */ + protected static function cnpFirstDigit($gender = null, $century = null) + { + switch ($century) + { + case 1800: + case 3: + case 4: + $centuryCode = 2; + break; + case 1900: + case 1: + case 2: + $centuryCode = 0; + break; + case 2000: + case 5: + case 6: + $centuryCode = 4; + break; + default: + $centuryCode = static::randomElement(array(0, 2, 4, 6, 9)); + } + + switch (strtolower($gender)) + { + case 'm': + case 1: + $genderCode = 1; + break; + case 'f': + case 2: + $genderCode = 2; + break; + default: + $genderCode = static::randomElement(array(1, 2)); + } + + $firstDigit = $centuryCode + $genderCode; + + return ($firstDigit > 9) ? 9 : $firstDigit; + } + + /** + * Calculates a checksum for the Personal Numerical Code (CNP). + * + * @param string $cnp Randomly generated CNP + * @return string CNP with the last digit altered to a proper checksum + */ + protected static function cnpAddChecksum($cnp) + { + $checkNumber = 279146358279; + + $checksum = 0; + foreach (range(0, 11) as $digit) + { + $checksum += substr($cnp, $digit, 1) * substr($checkNumber, $digit, 1); + } + $checksum = $checksum % 11; + + return substr($cnp, 0, 12) . ($checksum == 10 ? 1 : $checksum); + } } diff --git a/test/Faker/Provider/ro_RO/PersonTest.php b/test/Faker/Provider/ro_RO/PersonTest.php new file mode 100644 index 00000000..6fe89ebe --- /dev/null +++ b/test/Faker/Provider/ro_RO/PersonTest.php @@ -0,0 +1,95 @@ +addProvider(new DateTime($faker)); + $faker->addProvider(new Person($faker)); + $this->faker = $faker; + } + + public function testCnpReturnsValidCnp() + { + $cnp = $this->faker->cnp; + $this->assertTrue($this->isValidCnp($cnp)); + } + + public function testCnpReturnsMaleCnp() + { + $cnp = $this->faker->cnp('m'); + $this->assertRegExp('/^[1357]\d{12}$/', $cnp); + } + + public function testCnpReturnsFemaleCnp() + { + $cnp = $this->faker->cnp('f'); + $this->assertRegExp('/^[2468]\d{12}$/', $cnp); + } + + public function testCnpReturns1800sCnp() + { + $cnp = $this->faker->cnp(null, 1800); + $this->assertRegExp('/^[34]\d{12}$/', $cnp); + } + + public function testCnpReturns1900sCnp() + { + $cnp = $this->faker->cnp(null, 1900); + $this->assertRegExp('/^[12]\d{12}$/', $cnp); + } + + public function testCnpReturns2000sCnp() + { + $cnp = $this->faker->cnp(null, 2000); + $this->assertRegExp('/^[56]\d{12}$/', $cnp); + } + + public function testCnpReturnsBrasovCnp() + { + $cnp = $this->faker->cnp(null, null, 'BV'); + $this->assertRegExp('/^\d{7}08\d{4}$/', $cnp); + } + + public function testCnpReturns2000sClujFemaleCnp() + { + $cnp = $this->faker->cnp('f', 2000, 'CJ'); + $this->assertRegExp('/^6\d{6}12\d{4}$/', $cnp); + } + + protected function isValidCnp($cnp) + { + if ( + is_string($cnp) + && (bool) preg_match(static::TEST_CNP_REGEX, $cnp) + && checkdate(substr($cnp, 3, 2), substr($cnp, 5, 2), substr($cnp, 1, 2)) + ){ + $checkNumber = 279146358279; + + $checksum = 0; + foreach (range(0, 11) as $digit) + { + $checksum += substr($cnp, $digit, 1) * substr($checkNumber, $digit, 1); + } + $checksum = $checksum % 11; + + if ( + ($checksum < 10 && $checksum == substr($cnp, -1)) + || ($checksum == 10 && substr($cnp, -1) == 1) + ){ + return true; + } + } + + return false; + } +} From 8b4c0cdb4e939888b1cb177643c1e674cae7074f Mon Sep 17 00:00:00 2001 From: Mihai Zaharie Date: Sun, 5 Jan 2014 14:11:35 +0200 Subject: [PATCH 2/7] Add phone number (landline/mobile, toll-free, premium-rate) formatters --- src/Faker/Provider/ro_RO/PhoneNumber.php | 64 +++++++++++++++++++ test/Faker/Provider/ro_RO/PhoneNumberTest.php | 31 +++++++++ 2 files changed, 95 insertions(+) create mode 100644 src/Faker/Provider/ro_RO/PhoneNumber.php create mode 100644 test/Faker/Provider/ro_RO/PhoneNumberTest.php diff --git a/src/Faker/Provider/ro_RO/PhoneNumber.php b/src/Faker/Provider/ro_RO/PhoneNumber.php new file mode 100644 index 00000000..812736db --- /dev/null +++ b/src/Faker/Provider/ro_RO/PhoneNumber.php @@ -0,0 +1,64 @@ + array( + '021#######', // Bucharest + '023#######', + '024#######', + '025#######', + '026#######', + '027#######', // non-geographic + '031#######', // Bucharest + '033#######', + '034#######', + '035#######', + '036#######', + '037#######', // non-geographic + ), + 'mobile' => array( + '07########', + ) + ); + + protected static $specialFormats = array( + 'toll-free' => array( + '0800######', + '0801######', // shared-cost numbers + '0802######', // personal numbering + '0806######', // virtual cards + '0807######', // pre-paid cards + '0870######', // internet dial-up + ), + 'premium-rate' => array( + '0900######', + '0903######', // financial information + '0906######', // adult entertainment + ) + ); + + /** + * @link http://en.wikipedia.org/wiki/Telephone_numbers_in_Romania#Last_years + */ + public static function phoneNumber() + { + $type = static::randomElement(array_keys(static::$normalFormats)); + $number = static::numerify(static::randomElement(static::$normalFormats[$type])); + return $number; + } + + public static function tollFreePhoneNumber() + { + $number = static::numerify(static::randomElement(static::$specialFormats['toll-free'])); + return $number; + } + + public static function premiumRatePhoneNumber() + { + $number = static::numerify(static::randomElement(static::$specialFormats['premium-rate'])); + return $number; + } +} diff --git a/test/Faker/Provider/ro_RO/PhoneNumberTest.php b/test/Faker/Provider/ro_RO/PhoneNumberTest.php new file mode 100644 index 00000000..97314d5f --- /dev/null +++ b/test/Faker/Provider/ro_RO/PhoneNumberTest.php @@ -0,0 +1,31 @@ +addProvider(new PhoneNumber($faker)); + $this->faker = $faker; + } + + public function testPhoneNumberReturnsNormalPhoneNumber() + { + $this->assertRegExp('/^0(?:[23][13-7]|7\d)\d{7}$/', $this->faker->phoneNumber()); + } + + public function testTollFreePhoneNumberReturnsTollFreePhoneNumber() + { + $this->assertRegExp('/^08(?:0[1267]|70)\d{6}$/', $this->faker->tollFreePhoneNumber()); + } + + public function testPremiumRatePhoneNumberReturnsPremiumRatePhoneNumber() + { + $this->assertRegExp('/^090[036]\d{6}$/', $this->faker->premiumRatePhoneNumber()); + } +} From d40861fbdcaac864999a04ae732ad49e7c51ad47 Mon Sep 17 00:00:00 2001 From: Mihai Zaharie Date: Mon, 6 Jan 2014 11:03:40 +0200 Subject: [PATCH 3/7] Make PSR (all) compliant through PHP CS Fixer --- src/Faker/Provider/ro_RO/Person.php | 18 ++++++------------ src/Faker/Provider/ro_RO/PhoneNumber.php | 3 +++ test/Faker/Provider/ro_RO/PersonTest.php | 3 +-- 3 files changed, 10 insertions(+), 14 deletions(-) diff --git a/src/Faker/Provider/ro_RO/Person.php b/src/Faker/Provider/ro_RO/Person.php index 69b8d30c..27723c23 100644 --- a/src/Faker/Provider/ro_RO/Person.php +++ b/src/Faker/Provider/ro_RO/Person.php @@ -155,12 +155,9 @@ class Person extends \Faker\Provider\Person */ public function cnp($gender = null, $century = null, $county = null) { - if (is_null($county) || !array_key_exists($county, static::$cnpCountyCodes)) - { + if (is_null($county) || !array_key_exists($county, static::$cnpCountyCodes)) { $countyCode = static::randomElement(array_values(static::$cnpCountyCodes)); - } - else - { + } else { $countyCode = static::$cnpCountyCodes[$county]; } @@ -187,8 +184,7 @@ class Person extends \Faker\Provider\Person */ protected static function cnpFirstDigit($gender = null, $century = null) { - switch ($century) - { + switch ($century) { case 1800: case 3: case 4: @@ -208,8 +204,7 @@ class Person extends \Faker\Provider\Person $centuryCode = static::randomElement(array(0, 2, 4, 6, 9)); } - switch (strtolower($gender)) - { + switch (strtolower($gender)) { case 'm': case 1: $genderCode = 1; @@ -231,15 +226,14 @@ class Person extends \Faker\Provider\Person * Calculates a checksum for the Personal Numerical Code (CNP). * * @param string $cnp Randomly generated CNP - * @return string CNP with the last digit altered to a proper checksum + * @return string CNP with the last digit altered to a proper checksum */ protected static function cnpAddChecksum($cnp) { $checkNumber = 279146358279; $checksum = 0; - foreach (range(0, 11) as $digit) - { + foreach (range(0, 11) as $digit) { $checksum += substr($cnp, $digit, 1) * substr($checkNumber, $digit, 1); } $checksum = $checksum % 11; diff --git a/src/Faker/Provider/ro_RO/PhoneNumber.php b/src/Faker/Provider/ro_RO/PhoneNumber.php index 812736db..9e3c07fe 100644 --- a/src/Faker/Provider/ro_RO/PhoneNumber.php +++ b/src/Faker/Provider/ro_RO/PhoneNumber.php @@ -47,18 +47,21 @@ class PhoneNumber extends \Faker\Provider\PhoneNumber { $type = static::randomElement(array_keys(static::$normalFormats)); $number = static::numerify(static::randomElement(static::$normalFormats[$type])); + return $number; } public static function tollFreePhoneNumber() { $number = static::numerify(static::randomElement(static::$specialFormats['toll-free'])); + return $number; } public static function premiumRatePhoneNumber() { $number = static::numerify(static::randomElement(static::$specialFormats['premium-rate'])); + return $number; } } diff --git a/test/Faker/Provider/ro_RO/PersonTest.php b/test/Faker/Provider/ro_RO/PersonTest.php index 6fe89ebe..1c8ecfc6 100644 --- a/test/Faker/Provider/ro_RO/PersonTest.php +++ b/test/Faker/Provider/ro_RO/PersonTest.php @@ -76,8 +76,7 @@ class PersonTest extends \PHPUnit_Framework_TestCase $checkNumber = 279146358279; $checksum = 0; - foreach (range(0, 11) as $digit) - { + foreach (range(0, 11) as $digit) { $checksum += substr($cnp, $digit, 1) * substr($checkNumber, $digit, 1); } $checksum = $checksum % 11; From eca0754f3a22234a42f21c020fc8241a73eb9c99 Mon Sep 17 00:00:00 2001 From: Mihai Zaharie Date: Mon, 6 Jan 2014 11:08:32 +0200 Subject: [PATCH 4/7] Add PSR (all) compliance through PHP CS Fixer --- src/Faker/Provider/ro_RO/Person.php | 18 ++++++------------ src/Faker/Provider/ro_RO/PhoneNumber.php | 3 +++ test/Faker/Provider/ro_RO/PersonTest.php | 3 +-- 3 files changed, 10 insertions(+), 14 deletions(-) diff --git a/src/Faker/Provider/ro_RO/Person.php b/src/Faker/Provider/ro_RO/Person.php index 69b8d30c..27723c23 100644 --- a/src/Faker/Provider/ro_RO/Person.php +++ b/src/Faker/Provider/ro_RO/Person.php @@ -155,12 +155,9 @@ class Person extends \Faker\Provider\Person */ public function cnp($gender = null, $century = null, $county = null) { - if (is_null($county) || !array_key_exists($county, static::$cnpCountyCodes)) - { + if (is_null($county) || !array_key_exists($county, static::$cnpCountyCodes)) { $countyCode = static::randomElement(array_values(static::$cnpCountyCodes)); - } - else - { + } else { $countyCode = static::$cnpCountyCodes[$county]; } @@ -187,8 +184,7 @@ class Person extends \Faker\Provider\Person */ protected static function cnpFirstDigit($gender = null, $century = null) { - switch ($century) - { + switch ($century) { case 1800: case 3: case 4: @@ -208,8 +204,7 @@ class Person extends \Faker\Provider\Person $centuryCode = static::randomElement(array(0, 2, 4, 6, 9)); } - switch (strtolower($gender)) - { + switch (strtolower($gender)) { case 'm': case 1: $genderCode = 1; @@ -231,15 +226,14 @@ class Person extends \Faker\Provider\Person * Calculates a checksum for the Personal Numerical Code (CNP). * * @param string $cnp Randomly generated CNP - * @return string CNP with the last digit altered to a proper checksum + * @return string CNP with the last digit altered to a proper checksum */ protected static function cnpAddChecksum($cnp) { $checkNumber = 279146358279; $checksum = 0; - foreach (range(0, 11) as $digit) - { + foreach (range(0, 11) as $digit) { $checksum += substr($cnp, $digit, 1) * substr($checkNumber, $digit, 1); } $checksum = $checksum % 11; diff --git a/src/Faker/Provider/ro_RO/PhoneNumber.php b/src/Faker/Provider/ro_RO/PhoneNumber.php index 812736db..9e3c07fe 100644 --- a/src/Faker/Provider/ro_RO/PhoneNumber.php +++ b/src/Faker/Provider/ro_RO/PhoneNumber.php @@ -47,18 +47,21 @@ class PhoneNumber extends \Faker\Provider\PhoneNumber { $type = static::randomElement(array_keys(static::$normalFormats)); $number = static::numerify(static::randomElement(static::$normalFormats[$type])); + return $number; } public static function tollFreePhoneNumber() { $number = static::numerify(static::randomElement(static::$specialFormats['toll-free'])); + return $number; } public static function premiumRatePhoneNumber() { $number = static::numerify(static::randomElement(static::$specialFormats['premium-rate'])); + return $number; } } diff --git a/test/Faker/Provider/ro_RO/PersonTest.php b/test/Faker/Provider/ro_RO/PersonTest.php index 6fe89ebe..1c8ecfc6 100644 --- a/test/Faker/Provider/ro_RO/PersonTest.php +++ b/test/Faker/Provider/ro_RO/PersonTest.php @@ -76,8 +76,7 @@ class PersonTest extends \PHPUnit_Framework_TestCase $checkNumber = 279146358279; $checksum = 0; - foreach (range(0, 11) as $digit) - { + foreach (range(0, 11) as $digit) { $checksum += substr($cnp, $digit, 1) * substr($checkNumber, $digit, 1); } $checksum = $checksum % 11; From 6a933280af3ee2a27fa3f71cc10851d04943715d Mon Sep 17 00:00:00 2001 From: Mihai Zaharie Date: Mon, 6 Jan 2014 11:34:35 +0200 Subject: [PATCH 5/7] Add ro_RO Person and PhoneNumber formatters --- readme.md | 1551 +++++++++++++++++++++++++++-------------------------- 1 file changed, 796 insertions(+), 755 deletions(-) diff --git a/readme.md b/readme.md index d9a55dbe..725991fe 100644 --- a/readme.md +++ b/readme.md @@ -1,755 +1,796 @@ -# Faker # - -Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you. - -Faker is heavily inspired by Perl's [Data::Faker](http://search.cpan.org/~jasonk/Data-Faker-0.07/), and by ruby's [Faker](http://faker.rubyforge.org/). - -Faker requires PHP >= 5.3.3. - -[![Build Status](https://secure.travis-ci.org/fzaninotto/Faker.png)](http://travis-ci.org/fzaninotto/Faker) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/eceb78a9-38d4-4ad5-8b6b-b52f323e3549/mini.png)](https://insight.sensiolabs.com/projects/eceb78a9-38d4-4ad5-8b6b-b52f323e3549) - -## Basic Usage - -Use `Faker\Factory::create()` to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want. - -```php -name; - // 'Lucy Cechtelar'; -echo $faker->address; - // "426 Jordy Lodge - // Cartwrightshire, SC 88120-6700" -echo $faker->text; - // Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi - // beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt - // amet quidem. Iusto deleniti cum autem ad quia aperiam. - // A consectetur quos aliquam. In iste aliquid et aut similique suscipit. Consequatur qui - // quaerat iste minus hic expedita. Consequuntur error magni et laboriosam. Aut aspernatur - // voluptatem sit aliquam. Dolores voluptatum est. - // Aut molestias et maxime. Fugit autem facilis quos vero. Eius quibusdam possimus est. - // Ea quaerat et quisquam. Deleniti sunt quam. Adipisci consequatur id in occaecati. - // Et sint et. Ut ducimus quod nemo ab voluptatum. -``` - -Even if this example shows a property access, each call to `$faker->name` yields a different (random) result. This is because Faker uses `__get()` magic, and forwards `Faker\Generator->$property` calls to `Faker\Generator->format($property)`. - -```php -name, "\n"; -} - // Adaline Reichel - // Dr. Santa Prosacco DVM - // Noemy Vandervort V - // Lexi O'Conner - // Gracie Weber - // Roscoe Johns - // Emmett Lebsack - // Keegan Thiel - // Wellington Koelpin II - // Ms. Karley Kiehn V -``` - -## Formatters - -Each of the generator properties (like `name`, `address`, and `lorem`) are called "formatters". A faker generator has many of them, packaged in "providers". Here is a list of the bundled formatters in the default locale. - -### `Faker\Provider\en_US\Person` - - prefix // 'Ms.' - suffix // 'Jr.' - name // 'Dr. Zane Stroman' - firstName // 'Maynard' - lastName // 'Zulauf' - -### `Faker\Provider\en_US\Address` - - cityPrefix // 'Lake' - secondaryAddress // 'Suite 961' - state // 'NewMexico' - stateAbbr // 'OH' - citySuffix // 'borough' - streetSuffix // 'Keys' - buildingNumber // '484' - city // 'West Judge' - streetName // 'Keegan Trail' - streetAddress // '439 Karley Loaf Suite 897' - postcode // '17916' - address // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473' - country // 'Falkland Islands (Malvinas)' - latitude // '77.147489' - longitude // '86.211205' - -### `Faker\Provider\en_US\PhoneNumber` - - phoneNumber // '132-149-0269x3767' - -### `Faker\Provider\en_US\Company` - - catchPhrase // 'Monitored regional contingency' - bs // 'e-enable robust architectures' - company // 'Bogan-Treutel' - companySuffix // 'and Sons' - -### `Faker\Provider\Payment` - - creditCardType // 'MasterCard' - creditCardNumber // '4485480221084675' - creditCardExpirationDate // 04/13 - creditCardExpirationDateString // '04/13' - creditCardDetails // array('MasterCard', '4485480221084675', 'Aleksander Nowak', '04/13') - -### `Faker\Provider\Lorem` - - word // 'aut' - words($nb = 3) // array('porro', 'sed', 'magni') - sentence($nbWords = 6) // 'Sit vitae voluptas sint non voluptates.' - sentences($nb = 3) // array('Optio quos qui illo error.', 'Laborum vero a officia id corporis.', 'Saepe provident esse hic eligendi.') - paragraph($nbSentences = 3) // 'Ut ab voluptas sed a nam. Sint autem inventore aut officia aut aut blanditiis. Ducimus eos odit amet et est ut eum.' - paragraphs($nb = 3) // array('Quidem ut sunt et quidem est accusamus aut. Fuga est placeat rerum ut. Enim ex eveniet facere sunt.', 'Aut nam et eum architecto fugit repellendus illo. Qui ex esse veritatis.', 'Possimus omnis aut incidunt sunt. Asperiores incidunt iure sequi cum culpa rem. Rerum exercitationem est rem.') - text($maxNbChars = 200) // 'Fuga totam reiciendis qui architecto fugiat nemo. Consequatur recusandae qui cupiditate eos quod.' - -### `Faker\Provider\Internet` - - email // 'tkshlerin@collins.com' - safeEmail // 'king.alford@example.org' - freeEmail // 'bradley72@gmail.com' - companyEmail // 'russel.durward@mcdermott.org' - freeEmailDomain // 'yahoo.com' - safeEmailDomain // 'example.org' - userName // 'wade55' - domainName // 'wolffdeckow.net' - domainWord // 'feeney' - tld // 'biz' - url // 'http://www.strackeframi.com/' - ipv4 // '109.133.32.252' - ipv6 // '8e65:933d:22ee:a232:f1c1:2741:1f10:117c' - -### `Faker\Provider\DateTime` - - unixTime // 58781813 - dateTime // DateTime('2008-04-25 08:37:17') - dateTimeAD // DateTime('1800-04-29 20:38:49') - iso8601 // '1978-12-09T10:10:29+0000' - date($format = 'Y-m-d') // '1979-06-09' - time($format = 'H:i:s') // '20:49:42' - dateTimeBetween($startDate = '-30 years', $endDate = 'now') // DateTime('2003-03-15 02:00:49') - dateTimeThisCentury // DateTime('1915-05-30 19:28:21') - dateTimeThisDecade // DateTime('2007-05-29 22:30:48') - dateTimeThisYear // DateTime('2011-02-27 20:52:14') - dateTimeThisMonth // DateTime('2011-10-23 13:46:23') - amPm // 'pm' - dayOfMonth // '04' - dayOfWeek // 'Friday' - month // '06' - monthName // 'January' - year // '1993' - century // 'VI' - timezone // 'Europe/Paris' - -### `Faker\Provider\Miscellaneous` - - boolean($chanceOfGettingTrue = 50) // true - md5 // 'de99a620c50f2990e87144735cd357e7' - sha1 // 'f08e7f04ca1a413807ebc47551a40a20a0b4de5c' - sha256 // '0061e4c60dac5c1d82db0135a42e00c89ae3a333e7c26485321f24348c7e98a5' - locale // en_UK - countryCode // UK - languageCode // en - -### `Faker\Provider\Base` - - randomDigit // 7 - randomDigitNotNull // 5 - randomNumber($nbDigits = NULL) // 79907610 - randomNumber($from, $to) // 39049 - randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932 - randomLetter // 'b' - randomElement($array = array ('a','b','c')) // 'b' - numerify($string = '###') // '609' - lexify($string = '????') // 'wgts' - bothify($string = '## ??') // '42 jz' - -### `Faker\Provider\UserAgent` - - userAgent // 'Mozilla/5.0 (Windows CE) AppleWebKit/5350 (KHTML, like Gecko) Chrome/13.0.888.0 Safari/5350' - chrome // 'Mozilla/5.0 (Macintosh; PPC Mac OS X 10_6_5) AppleWebKit/5312 (KHTML, like Gecko) Chrome/14.0.894.0 Safari/5312' - firefox // 'Mozilla/5.0 (X11; Linuxi686; rv:7.0) Gecko/20101231 Firefox/3.6' - safari // 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_7_1 rv:3.0; en-US) AppleWebKit/534.11.3 (KHTML, like Gecko) Version/4.0 Safari/534.11.3' - opera // 'Opera/8.25 (Windows NT 5.1; en-US) Presto/2.9.188 Version/10.00' - internetExplorer // 'Mozilla/5.0 (compatible; MSIE 7.0; Windows 98; Win 9x 4.90; Trident/3.0)' - -### `Faker\Provider\Uuid` - - uuid // '7e57d004-2b97-0e7a-b45f-5387367791cd' - -### `Faker\Provider\File` - - fileExtension // 'avi' - mimeType // 'video/x-msvideo' - -### `Faker\Provider\Color` - - hexcolor // '#fa3cc2' - rgbcolor // '0,255,122' - rgbColorAsArray // array(0,255,122) - rgbCssColor // 'rgb(0,255,122)' - safeColorName // 'fuchsia' - colorName // 'Gainsbor' - -### `Faker\Provider\Image` - - /** - * Image generation provided by LoremPixel (http://lorempixel.com/) - * - * @param $dir An absolute path to a local directory - * @param $width/$height Size (in pixel) of the generated image (defaults to 640x480) - * @param $category One of 'abstract','animals','business','cats','city','food','nightlife','fashion','people','nature','sports','technics', and 'transport' - */ - image($dir) // '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg' - image($dir, $width, $height) // '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg' - image($dir, $width, $height, $category) // '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg' - imageUrl // 'http://lorempixel.com/640/480/' - imageUrl($width, $height) // 'http://lorempixel.com/800/600/' - imageUrl($width, $height, $category) // 'http://lorempixel.com/800/600/person/' - -### `Faker\Provider\Payment` - - creditCardType // 'MasterCard' - creditCardNumber($type = null) // '4485480221084675' - creditCardExpirationDate($valid = true) // DateTime('2014-10-23 13:46:23') - creditCardExpirationDateString($valid = true) // '10/14' - -## Unique and Optional modifiers - -Faker provides two special providers, `unique()` and `optional()`, to be called before any provider. `optional()` can be useful for seeding non-required fields, like a mobile telephone number ; `unique()` is required to populate fields that cannot accept twice the same value, like primary identifiers. - -```php -// unique() forces providers to return unique values -$values = array(); -for ($i=0; $i < 10; $i++) { - // get a random digit, but always a new one, to avoid duplicates - $values []= $faker->unique()->randomDigit; -} -print_r($values); // [4, 1, 8, 5, 0, 2, 6, 9, 7, 3] - -// providers with a limited range will throw an exception when no new unique value can be generated -$values = array(); -try { - for ($i=0; $i < 10; $i++) { - $values []= $faker->unique()->randomDigitNotNull; - } -} catch (\OverflowException $e) { - echo "There are only 9 unique digits not null, Faker can't generate 10 of them!"; -} - -// you can reset the unique modifier for all providers by passing true as first argument -$faker->unique($reset = true)->randomDigitNotNull; // will not throw OverflowException since unique() was reset -// tip: unique() keeps one array of values per provider - -// optional() sometimes bypasses the provider to return null instead -$values = array(); -for ($i=0; $i < 10; $i++) { - // get a random digit, but also null sometimes - $values []= $faker->optional()->randomDigit; -} -print_r($values); // [1, 4, null, 9, 5, null, null, 4, 6, null] - -// optional takes a weight argument to make the null occurrence impossible (value 0) or systematic (value 1) -$faker->optional($weight = 0.1)->randomDigit; // 10% chance to get null -$faker->optional($weight = 0.9)->randomDigit; // 90% chance to get null -// the default $weight value is 0.5 -``` - -## Localization - -`Faker\Factory` can take a locale as an argument, to return localized data. If no localized provider is found, the factory fallbacks to the default locale (en_EN). - -```php -name, "\n"; -} - // Luce du Coulon - // Auguste Dupont - // Roger Le Voisin - // Alexandre Lacroix - // Jacques Humbert-Roy - // Thérèse Guillet-Andre - // Gilles Gros-Bodin - // Amélie Pires - // Marcel Laporte - // Geneviève Marchal -``` - -You can check available Faker locales in the source code, [under the `Provider` directory](https://github.com/fzaninotto/Faker/tree/master/src/Faker/Provider). The localization of Faker is an ongoing process, for which we need your help. Don't hesitate to create localized providers to your own locale and submit a PR! - -## Populating Entities Using an ORM or an ODM - -Faker provides adapters for Object-Relational and Object-Document Mappers (currently, [Propel](http://www.propelorm.org), [Doctrine2](http://www.doctrine-project.org/projects/orm/2.0/docs/en), and [Mandango](https://github.com/mandango/mandango) are supported). These adapters ease the population of databases through the Entity classes provided by an ORM library (or the population of document stores using Document classes provided by an ODM library). - -To populate entities, create a new populator class (using a generator instance as parameter), then list the class and number of all the entities that must be generated. To launch the actual data population, call the `execute()` method. - -Here is an example showing how to populate 5 `Author` and 10 `Book` objects: - -```php -addEntity('Author', 5); -$populator->addEntity('Book', 10); -$insertedPKs = $populator->execute(); -``` - -The populator uses name and column type guessers to populate each column with relevant data. For instance, Faker populates a column named `first_name` using the `firstName` formatter, and a column with a `TIMESTAMP` type using the `dateTime` formatter. The resulting entities are therefore coherent. If Faker misinterprets a column name, you can still specify a custom closure to be used for populating a particular column, using the third argument to `addEntity()`: - -```php -addEntity('Book', 5, array( - 'ISBN' => function() use ($generator) { return $generator->randomNumber(13); } -)); -``` - -In this example, Faker will guess a formatter for all columns except `ISBN`, for which the given anonymous function will be used. - -**Tip**: To ignore some columns, specify `null` for the column names in the third argument of `addEntity()`. This is usually necessary for columns added by a behavior: - -```php -addEntity('Book', 5, array( - 'CreatedAt' => null, - 'UpdatedAt' => null, -)); -``` - -Of course, Faker does not populate autoincremented primary keys. In addition, `Faker\ORM\Propel\Populator::execute()` returns the list of inserted PKs, indexed by class: - -```php - (34, 35, 36, 37, 38), -// 'Book' => (456, 457, 458, 459, 470, 471, 472, 473, 474, 475) -// ) -``` - -In the previous example, the `Book` and `Author` models share a relationship. Since `Author` entities are populated first, Faker is smart enough to relate the populated `Book` entities to one of the populated `Author` entities. - -Lastly, if you want to execute an arbitrary function on an entity before insertion, use the fourth argument of the `addEntity()` method: - -```php -addEntity('Book', 5, array(), array( - function($book) { $book->publish(); }, -)); -``` - -## Seeding the Generator - -You may want to get always the same generated data - for instance when using Faker for unit testing purposes. The generator offers a `seed()` method, which seeds the random number generator. Calling the same script twice with the same seed produces the same results. - -```php -seed(1234); - -echo $faker->name; // 'Jess Mraz I'; -``` - -## Faker Internals: Understanding Providers - -A `Faker\Generator` alone can't do much generation. It needs `Faker\Provider` objects to delegate the data generation to them. `Faker\Factory::create()` actually creates a `Faker\Generator` bundled with the default providers. Here is what happens under the hood: - -```php -addProvider(new Faker\Provider\en_US\Person($faker)); -$faker->addProvider(new Faker\Provider\en_US\Address($faker)); -$faker->addProvider(new Faker\Provider\en_US\PhoneNumber($faker)); -$faker->addProvider(new Faker\Provider\en_US\Company($faker)); -$faker->addProvider(new Faker\Provider\Lorem($faker)); -$faker->addProvider(new Faker\Provider\Internet($faker)); -```` - -Whenever you try to access a property on the `$faker` object, the generator looks for a method with the same name in all the providers attached to it. For instance, calling `$faker->name` triggers a call to `Faker\Provider\Person::name()`. And since Faker starts with the last provider, you can easily override existing formatters: just add a provider containing methods named after the formatters you want to override. - -That means that you can easily add your own providers to a `Faker\Generator` instance. A provider is usually a class extending `\Faker\Provider\Base`. This parent class allows you to use methods like `lexify()` or `randomNumber()`; it also gives you access to formatters of other providers, through the protected `$generator` property. The new formatters are the public methods of the provider class. - -Here is an example provider for populating Book data: - -```php -generator->sentence($nbWords); - return substr($sentence, 0, strlen($sentence) - 1); - } - - public function ISBN() - { - return $this->generator->randomNumber(13); - } -} -``` - -To register this provider, just add a new instance of `\Faker\Provider\Book` to an existing generator: - -```php -addProvider(new \Faker\Provider\Book($faker)); -``` - -Now you can use the two new formatters like any other Faker formatter: - -```php -setTitle($faker->title); -$book->setISBN($faker->ISBN); -$book->setSummary($faker->text); -$book->setPrice($faker->randomNumber(2)); -``` - -**Tip**: A provider can also be a Plain Old PHP Object. In that case, all the public methods of the provider become available to the generator. - -## Real Life Usage - -The following script generates a valid XML document: - -```php - - - - - - -boolean(25)): ?> - - -
- streetAddress ?> - city ?> - postcode ?> - state ?> -
- -boolean(33)): ?> - bs ?> - -boolean(33)): ?> - - - -boolean(15)): ?> -
-text(400) ?> -]]> -
- -
- -
-``` - -Running this script produces a document looking like: - -```xml - - - - -
- 182 Harrison Cove - North Lloyd - 45577 - Alabama -
- - orchestrate compelling web-readiness - -
- -
-
- - -
- 90111 Hegmann Inlet - South Geovanymouth - 69961-9311 - Colorado -
- - -
- - -
- 9791 Nona Corner - Harberhaven - 74062-8191 - RhodeIsland -
- - -
- - -
- 11161 Schultz Via - Feilstad - 98019 - NewJersey -
- - - -
- -
-
- - -
- 6106 Nader Village Suite 753 - McLaughlinstad - 43189-8621 - Missouri -
- - expedite viral synergies - - -
- - -
- 7546 Kuvalis Plaza - South Wilfrid - 77069 - Georgia -
- - -
- - - -
- 478 Daisha Landing Apt. 510 - West Lizethhaven - 30566-5362 - WestVirginia -
- - orchestrate dynamic networks - - -
- -
-
- - -
- 1251 Koelpin Mission - North Revastad - 81620 - Maryland -
- - -
- - -
- 6396 Langworth Hills Apt. 446 - New Carlos - 89399-0268 - Wyoming -
- - - -
- - - -
- 2246 Kreiger Station Apt. 291 - Kaydenmouth - 11397-1072 - Wyoming -
- - grow sticky portals - -
- -
-
-
-``` - -## Language specific formatters - - -### `Faker\Provider\fr_FR\Company` - -```php -siren; // 082 250 104 - -// Generates a random SIRET number -echo $faker->siret; // 347 355 708 00224 - -// Generates a random SIRET number (controlling the number of sequential digits) -echo $faker->siret(3); // 438 472 611 01513 - -``` - -### `Faker\Provider\fr_FR\Address` - -```php -departmentName; // "Haut-Rhin" - -// Generates a random department number -echo $faker->departmentNumber; // "2B" - -// Generates a random department info (department number => department name) -$faker->department; // array('18' => 'Cher'); - -// Generates a random region -echo $faker->region; // "Saint-Pierre-et-Miquelon" - -``` - -### `Faker\Provider\da_DK\Person` - -```php -cpr; // "051280-2387" - -``` - -### `Faker\Provider\da_DK\Address` - -```php -kommune; // "Frederiksberg" - -// Generates a random region name -echo $faker->region; // "Region Sjælland" - -``` - -### `Faker\Provider\da_DK\Company` - -```php -cvr; // "32458723" - -// Generates a random P number -echo $faker->p; // "5398237590" - -``` - -### `Faker\Provider\pl_PL\Person` - -```php -pesel; // "40061451555" -// Generates a random personal identity card number -echo $faker->personalIdentityNumber; // "AKX383360" -// Generates a random taxpayer identification number (NIP) -echo $faker->taxpayerIdentificationNumber; // '8211575109' - -``` - -### `Faker\Provider\pl_PL\Company` - -```php -regon; // "714676680" -// Generates a random local REGON number -echo $faker->regonLocal; // "15346111382836" - -``` - -### `Faker\Provider\pl_PL\Payment` - -```php -bank; // "Narodowy Bank Polski" -// Generates a random bank account number -echo $faker->bankAccountNumber; // "PL14968907563953822118075816" - -``` - -### `Faker\Provider\ja_JP\Person` - -```php -kanaName; // "アオタ ナオコ" - -// Generates a 'kana' first name -echo $faker->firstKanaName; // "トモミ" - -// Generates a 'kana' last name -echo $faker->lastKanaName; // "ナギサ" -``` - -## License - -Faker is released under the MIT Licence. See the bundled LICENSE file for details. +# Faker # + +Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you. + +Faker is heavily inspired by Perl's [Data::Faker](http://search.cpan.org/~jasonk/Data-Faker-0.07/), and by ruby's [Faker](http://faker.rubyforge.org/). + +Faker requires PHP >= 5.3.3. + +[![Build Status](https://secure.travis-ci.org/fzaninotto/Faker.png)](http://travis-ci.org/fzaninotto/Faker) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/eceb78a9-38d4-4ad5-8b6b-b52f323e3549/mini.png)](https://insight.sensiolabs.com/projects/eceb78a9-38d4-4ad5-8b6b-b52f323e3549) + +## Basic Usage + +Use `Faker\Factory::create()` to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want. + +```php +name; + // 'Lucy Cechtelar'; +echo $faker->address; + // "426 Jordy Lodge + // Cartwrightshire, SC 88120-6700" +echo $faker->text; + // Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi + // beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt + // amet quidem. Iusto deleniti cum autem ad quia aperiam. + // A consectetur quos aliquam. In iste aliquid et aut similique suscipit. Consequatur qui + // quaerat iste minus hic expedita. Consequuntur error magni et laboriosam. Aut aspernatur + // voluptatem sit aliquam. Dolores voluptatum est. + // Aut molestias et maxime. Fugit autem facilis quos vero. Eius quibusdam possimus est. + // Ea quaerat et quisquam. Deleniti sunt quam. Adipisci consequatur id in occaecati. + // Et sint et. Ut ducimus quod nemo ab voluptatum. +``` + +Even if this example shows a property access, each call to `$faker->name` yields a different (random) result. This is because Faker uses `__get()` magic, and forwards `Faker\Generator->$property` calls to `Faker\Generator->format($property)`. + +```php +name, "\n"; +} + // Adaline Reichel + // Dr. Santa Prosacco DVM + // Noemy Vandervort V + // Lexi O'Conner + // Gracie Weber + // Roscoe Johns + // Emmett Lebsack + // Keegan Thiel + // Wellington Koelpin II + // Ms. Karley Kiehn V +``` + +## Formatters + +Each of the generator properties (like `name`, `address`, and `lorem`) are called "formatters". A faker generator has many of them, packaged in "providers". Here is a list of the bundled formatters in the default locale. + +### `Faker\Provider\en_US\Person` + + prefix // 'Ms.' + suffix // 'Jr.' + name // 'Dr. Zane Stroman' + firstName // 'Maynard' + lastName // 'Zulauf' + +### `Faker\Provider\en_US\Address` + + cityPrefix // 'Lake' + secondaryAddress // 'Suite 961' + state // 'NewMexico' + stateAbbr // 'OH' + citySuffix // 'borough' + streetSuffix // 'Keys' + buildingNumber // '484' + city // 'West Judge' + streetName // 'Keegan Trail' + streetAddress // '439 Karley Loaf Suite 897' + postcode // '17916' + address // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473' + country // 'Falkland Islands (Malvinas)' + latitude // '77.147489' + longitude // '86.211205' + +### `Faker\Provider\en_US\PhoneNumber` + + phoneNumber // '132-149-0269x3767' + +### `Faker\Provider\en_US\Company` + + catchPhrase // 'Monitored regional contingency' + bs // 'e-enable robust architectures' + company // 'Bogan-Treutel' + companySuffix // 'and Sons' + +### `Faker\Provider\Payment` + + creditCardType // 'MasterCard' + creditCardNumber // '4485480221084675' + creditCardExpirationDate // 04/13 + creditCardExpirationDateString // '04/13' + creditCardDetails // array('MasterCard', '4485480221084675', 'Aleksander Nowak', '04/13') + +### `Faker\Provider\Lorem` + + word // 'aut' + words($nb = 3) // array('porro', 'sed', 'magni') + sentence($nbWords = 6) // 'Sit vitae voluptas sint non voluptates.' + sentences($nb = 3) // array('Optio quos qui illo error.', 'Laborum vero a officia id corporis.', 'Saepe provident esse hic eligendi.') + paragraph($nbSentences = 3) // 'Ut ab voluptas sed a nam. Sint autem inventore aut officia aut aut blanditiis. Ducimus eos odit amet et est ut eum.' + paragraphs($nb = 3) // array('Quidem ut sunt et quidem est accusamus aut. Fuga est placeat rerum ut. Enim ex eveniet facere sunt.', 'Aut nam et eum architecto fugit repellendus illo. Qui ex esse veritatis.', 'Possimus omnis aut incidunt sunt. Asperiores incidunt iure sequi cum culpa rem. Rerum exercitationem est rem.') + text($maxNbChars = 200) // 'Fuga totam reiciendis qui architecto fugiat nemo. Consequatur recusandae qui cupiditate eos quod.' + +### `Faker\Provider\Internet` + + email // 'tkshlerin@collins.com' + safeEmail // 'king.alford@example.org' + freeEmail // 'bradley72@gmail.com' + companyEmail // 'russel.durward@mcdermott.org' + freeEmailDomain // 'yahoo.com' + safeEmailDomain // 'example.org' + userName // 'wade55' + domainName // 'wolffdeckow.net' + domainWord // 'feeney' + tld // 'biz' + url // 'http://www.strackeframi.com/' + ipv4 // '109.133.32.252' + ipv6 // '8e65:933d:22ee:a232:f1c1:2741:1f10:117c' + +### `Faker\Provider\DateTime` + + unixTime // 58781813 + dateTime // DateTime('2008-04-25 08:37:17') + dateTimeAD // DateTime('1800-04-29 20:38:49') + iso8601 // '1978-12-09T10:10:29+0000' + date($format = 'Y-m-d') // '1979-06-09' + time($format = 'H:i:s') // '20:49:42' + dateTimeBetween($startDate = '-30 years', $endDate = 'now') // DateTime('2003-03-15 02:00:49') + dateTimeThisCentury // DateTime('1915-05-30 19:28:21') + dateTimeThisDecade // DateTime('2007-05-29 22:30:48') + dateTimeThisYear // DateTime('2011-02-27 20:52:14') + dateTimeThisMonth // DateTime('2011-10-23 13:46:23') + amPm // 'pm' + dayOfMonth // '04' + dayOfWeek // 'Friday' + month // '06' + monthName // 'January' + year // '1993' + century // 'VI' + timezone // 'Europe/Paris' + +### `Faker\Provider\Miscellaneous` + + boolean($chanceOfGettingTrue = 50) // true + md5 // 'de99a620c50f2990e87144735cd357e7' + sha1 // 'f08e7f04ca1a413807ebc47551a40a20a0b4de5c' + sha256 // '0061e4c60dac5c1d82db0135a42e00c89ae3a333e7c26485321f24348c7e98a5' + locale // en_UK + countryCode // UK + languageCode // en + +### `Faker\Provider\Base` + + randomDigit // 7 + randomDigitNotNull // 5 + randomNumber($nbDigits = NULL) // 79907610 + randomNumber($from, $to) // 39049 + randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932 + randomLetter // 'b' + randomElement($array = array ('a','b','c')) // 'b' + numerify($string = '###') // '609' + lexify($string = '????') // 'wgts' + bothify($string = '## ??') // '42 jz' + +### `Faker\Provider\UserAgent` + + userAgent // 'Mozilla/5.0 (Windows CE) AppleWebKit/5350 (KHTML, like Gecko) Chrome/13.0.888.0 Safari/5350' + chrome // 'Mozilla/5.0 (Macintosh; PPC Mac OS X 10_6_5) AppleWebKit/5312 (KHTML, like Gecko) Chrome/14.0.894.0 Safari/5312' + firefox // 'Mozilla/5.0 (X11; Linuxi686; rv:7.0) Gecko/20101231 Firefox/3.6' + safari // 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_7_1 rv:3.0; en-US) AppleWebKit/534.11.3 (KHTML, like Gecko) Version/4.0 Safari/534.11.3' + opera // 'Opera/8.25 (Windows NT 5.1; en-US) Presto/2.9.188 Version/10.00' + internetExplorer // 'Mozilla/5.0 (compatible; MSIE 7.0; Windows 98; Win 9x 4.90; Trident/3.0)' + +### `Faker\Provider\Uuid` + + uuid // '7e57d004-2b97-0e7a-b45f-5387367791cd' + +### `Faker\Provider\File` + + fileExtension // 'avi' + mimeType // 'video/x-msvideo' + +### `Faker\Provider\Color` + + hexcolor // '#fa3cc2' + rgbcolor // '0,255,122' + rgbColorAsArray // array(0,255,122) + rgbCssColor // 'rgb(0,255,122)' + safeColorName // 'fuchsia' + colorName // 'Gainsbor' + +### `Faker\Provider\Image` + + /** + * Image generation provided by LoremPixel (http://lorempixel.com/) + * + * @param $dir An absolute path to a local directory + * @param $width/$height Size (in pixel) of the generated image (defaults to 640x480) + * @param $category One of 'abstract','animals','business','cats','city','food','nightlife','fashion','people','nature','sports','technics', and 'transport' + */ + image($dir) // '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg' + image($dir, $width, $height) // '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg' + image($dir, $width, $height, $category) // '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg' + imageUrl // 'http://lorempixel.com/640/480/' + imageUrl($width, $height) // 'http://lorempixel.com/800/600/' + imageUrl($width, $height, $category) // 'http://lorempixel.com/800/600/person/' + +### `Faker\Provider\Payment` + + creditCardType // 'MasterCard' + creditCardNumber($type = null) // '4485480221084675' + creditCardExpirationDate($valid = true) // DateTime('2014-10-23 13:46:23') + creditCardExpirationDateString($valid = true) // '10/14' + +## Unique and Optional modifiers + +Faker provides two special providers, `unique()` and `optional()`, to be called before any provider. `optional()` can be useful for seeding non-required fields, like a mobile telephone number ; `unique()` is required to populate fields that cannot accept twice the same value, like primary identifiers. + +```php +// unique() forces providers to return unique values +$values = array(); +for ($i=0; $i < 10; $i++) { + // get a random digit, but always a new one, to avoid duplicates + $values []= $faker->unique()->randomDigit; +} +print_r($values); // [4, 1, 8, 5, 0, 2, 6, 9, 7, 3] + +// providers with a limited range will throw an exception when no new unique value can be generated +$values = array(); +try { + for ($i=0; $i < 10; $i++) { + $values []= $faker->unique()->randomDigitNotNull; + } +} catch (\OverflowException $e) { + echo "There are only 9 unique digits not null, Faker can't generate 10 of them!"; +} + +// you can reset the unique modifier for all providers by passing true as first argument +$faker->unique($reset = true)->randomDigitNotNull; // will not throw OverflowException since unique() was reset +// tip: unique() keeps one array of values per provider + +// optional() sometimes bypasses the provider to return null instead +$values = array(); +for ($i=0; $i < 10; $i++) { + // get a random digit, but also null sometimes + $values []= $faker->optional()->randomDigit; +} +print_r($values); // [1, 4, null, 9, 5, null, null, 4, 6, null] + +// optional takes a weight argument to make the null occurrence impossible (value 0) or systematic (value 1) +$faker->optional($weight = 0.1)->randomDigit; // 10% chance to get null +$faker->optional($weight = 0.9)->randomDigit; // 90% chance to get null +// the default $weight value is 0.5 +``` + +## Localization + +`Faker\Factory` can take a locale as an argument, to return localized data. If no localized provider is found, the factory fallbacks to the default locale (en_EN). + +```php +name, "\n"; +} + // Luce du Coulon + // Auguste Dupont + // Roger Le Voisin + // Alexandre Lacroix + // Jacques Humbert-Roy + // Thérèse Guillet-Andre + // Gilles Gros-Bodin + // Amélie Pires + // Marcel Laporte + // Geneviève Marchal +``` + +You can check available Faker locales in the source code, [under the `Provider` directory](https://github.com/fzaninotto/Faker/tree/master/src/Faker/Provider). The localization of Faker is an ongoing process, for which we need your help. Don't hesitate to create localized providers to your own locale and submit a PR! + +## Populating Entities Using an ORM or an ODM + +Faker provides adapters for Object-Relational and Object-Document Mappers (currently, [Propel](http://www.propelorm.org), [Doctrine2](http://www.doctrine-project.org/projects/orm/2.0/docs/en), and [Mandango](https://github.com/mandango/mandango) are supported). These adapters ease the population of databases through the Entity classes provided by an ORM library (or the population of document stores using Document classes provided by an ODM library). + +To populate entities, create a new populator class (using a generator instance as parameter), then list the class and number of all the entities that must be generated. To launch the actual data population, call the `execute()` method. + +Here is an example showing how to populate 5 `Author` and 10 `Book` objects: + +```php +addEntity('Author', 5); +$populator->addEntity('Book', 10); +$insertedPKs = $populator->execute(); +``` + +The populator uses name and column type guessers to populate each column with relevant data. For instance, Faker populates a column named `first_name` using the `firstName` formatter, and a column with a `TIMESTAMP` type using the `dateTime` formatter. The resulting entities are therefore coherent. If Faker misinterprets a column name, you can still specify a custom closure to be used for populating a particular column, using the third argument to `addEntity()`: + +```php +addEntity('Book', 5, array( + 'ISBN' => function() use ($generator) { return $generator->randomNumber(13); } +)); +``` + +In this example, Faker will guess a formatter for all columns except `ISBN`, for which the given anonymous function will be used. + +**Tip**: To ignore some columns, specify `null` for the column names in the third argument of `addEntity()`. This is usually necessary for columns added by a behavior: + +```php +addEntity('Book', 5, array( + 'CreatedAt' => null, + 'UpdatedAt' => null, +)); +``` + +Of course, Faker does not populate autoincremented primary keys. In addition, `Faker\ORM\Propel\Populator::execute()` returns the list of inserted PKs, indexed by class: + +```php + (34, 35, 36, 37, 38), +// 'Book' => (456, 457, 458, 459, 470, 471, 472, 473, 474, 475) +// ) +``` + +In the previous example, the `Book` and `Author` models share a relationship. Since `Author` entities are populated first, Faker is smart enough to relate the populated `Book` entities to one of the populated `Author` entities. + +Lastly, if you want to execute an arbitrary function on an entity before insertion, use the fourth argument of the `addEntity()` method: + +```php +addEntity('Book', 5, array(), array( + function($book) { $book->publish(); }, +)); +``` + +## Seeding the Generator + +You may want to get always the same generated data - for instance when using Faker for unit testing purposes. The generator offers a `seed()` method, which seeds the random number generator. Calling the same script twice with the same seed produces the same results. + +```php +seed(1234); + +echo $faker->name; // 'Jess Mraz I'; +``` + +## Faker Internals: Understanding Providers + +A `Faker\Generator` alone can't do much generation. It needs `Faker\Provider` objects to delegate the data generation to them. `Faker\Factory::create()` actually creates a `Faker\Generator` bundled with the default providers. Here is what happens under the hood: + +```php +addProvider(new Faker\Provider\en_US\Person($faker)); +$faker->addProvider(new Faker\Provider\en_US\Address($faker)); +$faker->addProvider(new Faker\Provider\en_US\PhoneNumber($faker)); +$faker->addProvider(new Faker\Provider\en_US\Company($faker)); +$faker->addProvider(new Faker\Provider\Lorem($faker)); +$faker->addProvider(new Faker\Provider\Internet($faker)); +```` + +Whenever you try to access a property on the `$faker` object, the generator looks for a method with the same name in all the providers attached to it. For instance, calling `$faker->name` triggers a call to `Faker\Provider\Person::name()`. And since Faker starts with the last provider, you can easily override existing formatters: just add a provider containing methods named after the formatters you want to override. + +That means that you can easily add your own providers to a `Faker\Generator` instance. A provider is usually a class extending `\Faker\Provider\Base`. This parent class allows you to use methods like `lexify()` or `randomNumber()`; it also gives you access to formatters of other providers, through the protected `$generator` property. The new formatters are the public methods of the provider class. + +Here is an example provider for populating Book data: + +```php +generator->sentence($nbWords); + return substr($sentence, 0, strlen($sentence) - 1); + } + + public function ISBN() + { + return $this->generator->randomNumber(13); + } +} +``` + +To register this provider, just add a new instance of `\Faker\Provider\Book` to an existing generator: + +```php +addProvider(new \Faker\Provider\Book($faker)); +``` + +Now you can use the two new formatters like any other Faker formatter: + +```php +setTitle($faker->title); +$book->setISBN($faker->ISBN); +$book->setSummary($faker->text); +$book->setPrice($faker->randomNumber(2)); +``` + +**Tip**: A provider can also be a Plain Old PHP Object. In that case, all the public methods of the provider become available to the generator. + +## Real Life Usage + +The following script generates a valid XML document: + +```php + + + + + + +boolean(25)): ?> + + +
+ streetAddress ?> + city ?> + postcode ?> + state ?> +
+ +boolean(33)): ?> + bs ?> + +boolean(33)): ?> + + + +boolean(15)): ?> +
+text(400) ?> +]]> +
+ +
+ +
+``` + +Running this script produces a document looking like: + +```xml + + + + +
+ 182 Harrison Cove + North Lloyd + 45577 + Alabama +
+ + orchestrate compelling web-readiness + +
+ +
+
+ + +
+ 90111 Hegmann Inlet + South Geovanymouth + 69961-9311 + Colorado +
+ + +
+ + +
+ 9791 Nona Corner + Harberhaven + 74062-8191 + RhodeIsland +
+ + +
+ + +
+ 11161 Schultz Via + Feilstad + 98019 + NewJersey +
+ + + +
+ +
+
+ + +
+ 6106 Nader Village Suite 753 + McLaughlinstad + 43189-8621 + Missouri +
+ + expedite viral synergies + + +
+ + +
+ 7546 Kuvalis Plaza + South Wilfrid + 77069 + Georgia +
+ + +
+ + + +
+ 478 Daisha Landing Apt. 510 + West Lizethhaven + 30566-5362 + WestVirginia +
+ + orchestrate dynamic networks + + +
+ +
+
+ + +
+ 1251 Koelpin Mission + North Revastad + 81620 + Maryland +
+ + +
+ + +
+ 6396 Langworth Hills Apt. 446 + New Carlos + 89399-0268 + Wyoming +
+ + + +
+ + + +
+ 2246 Kreiger Station Apt. 291 + Kaydenmouth + 11397-1072 + Wyoming +
+ + grow sticky portals + +
+ +
+
+
+``` + +## Language specific formatters + + +### `Faker\Provider\fr_FR\Company` + +```php +siren; // 082 250 104 + +// Generates a random SIRET number +echo $faker->siret; // 347 355 708 00224 + +// Generates a random SIRET number (controlling the number of sequential digits) +echo $faker->siret(3); // 438 472 611 01513 + +``` + +### `Faker\Provider\fr_FR\Address` + +```php +departmentName; // "Haut-Rhin" + +// Generates a random department number +echo $faker->departmentNumber; // "2B" + +// Generates a random department info (department number => department name) +$faker->department; // array('18' => 'Cher'); + +// Generates a random region +echo $faker->region; // "Saint-Pierre-et-Miquelon" + +``` + +### `Faker\Provider\da_DK\Person` + +```php +cpr; // "051280-2387" + +``` + +### `Faker\Provider\da_DK\Address` + +```php +kommune; // "Frederiksberg" + +// Generates a random region name +echo $faker->region; // "Region Sjælland" + +``` + +### `Faker\Provider\da_DK\Company` + +```php +cvr; // "32458723" + +// Generates a random P number +echo $faker->p; // "5398237590" + +``` + +### `Faker\Provider\pl_PL\Person` + +```php +pesel; // "40061451555" +// Generates a random personal identity card number +echo $faker->personalIdentityNumber; // "AKX383360" +// Generates a random taxpayer identification number (NIP) +echo $faker->taxpayerIdentificationNumber; // '8211575109' + +``` + +### `Faker\Provider\pl_PL\Company` + +```php +regon; // "714676680" +// Generates a random local REGON number +echo $faker->regonLocal; // "15346111382836" + +``` + +### `Faker\Provider\pl_PL\Payment` + +```php +bank; // "Narodowy Bank Polski" +// Generates a random bank account number +echo $faker->bankAccountNumber; // "PL14968907563953822118075816" + +``` + +### `Faker\Provider\ja_JP\Person` + +```php +kanaName; // "アオタ ナオコ" + +// Generates a 'kana' first name +echo $faker->firstKanaName; // "トモミ" + +// Generates a 'kana' last name +echo $faker->lastKanaName; // "ナギサ" +``` + +### `Faker\Provider\ro_RO\Person` + +```php +name; // "Ion Ionescu" +// Generates a random male name prefix/title +echo $faker->prefixMale; // "ing." +// Generates a random female name prefix/title +echo $faker->prefixFemale; // "d-na." +// Generates a random male fist name +echo $faker->firstNameMale; // "Adrian" +// Generates a random female fist name +echo $faker->firstNameFemale; // "Miruna" +// Generates a random last name +echo $faker->firstNameFemale; // "Cojocaru" + +// Generates a random Personal Numerical Code (CNP) +echo $faker->cnp; // "2800523081231" +echo $faker->cnp($gender = NULL, $century = NULL, $county = NULL); + +// Valid option values: +// $gender: m, f, 1, 2 +// $century: 1800, 1900, 2000, 1, 2, 3, 4, 5, 6 +// $county: 2 letter ISO 3166-2:RO county codes and B1-B6 for Bucharest's 6 sectors +``` + +### `Faker\Provider\ro_RO\PhoneNumber` + +```php +phoneNumber; // "0211234567" +// Generates a random toll-free phone number +echo $faker->tollFreePhoneNumber; // "0800123456" +// Generates a random premium-rate phone number +echo $faker->premiumRatePhoneNumber; // "0900123456" +``` + +## License + +Faker is released under the MIT Licence. See the bundled LICENSE file for details. From 5aaa2c00254c2c68dbeeaa15eee7e2acd89b00d3 Mon Sep 17 00:00:00 2001 From: Mihai Zaharie Date: Mon, 6 Jan 2014 11:43:38 +0200 Subject: [PATCH 6/7] Fix line endings (CRLF -> LF) --- readme.md | 1592 ++++++++++++++++++++++++++--------------------------- 1 file changed, 796 insertions(+), 796 deletions(-) diff --git a/readme.md b/readme.md index 725991fe..3efcf560 100644 --- a/readme.md +++ b/readme.md @@ -1,796 +1,796 @@ -# Faker # - -Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you. - -Faker is heavily inspired by Perl's [Data::Faker](http://search.cpan.org/~jasonk/Data-Faker-0.07/), and by ruby's [Faker](http://faker.rubyforge.org/). - -Faker requires PHP >= 5.3.3. - -[![Build Status](https://secure.travis-ci.org/fzaninotto/Faker.png)](http://travis-ci.org/fzaninotto/Faker) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/eceb78a9-38d4-4ad5-8b6b-b52f323e3549/mini.png)](https://insight.sensiolabs.com/projects/eceb78a9-38d4-4ad5-8b6b-b52f323e3549) - -## Basic Usage - -Use `Faker\Factory::create()` to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want. - -```php -name; - // 'Lucy Cechtelar'; -echo $faker->address; - // "426 Jordy Lodge - // Cartwrightshire, SC 88120-6700" -echo $faker->text; - // Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi - // beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt - // amet quidem. Iusto deleniti cum autem ad quia aperiam. - // A consectetur quos aliquam. In iste aliquid et aut similique suscipit. Consequatur qui - // quaerat iste minus hic expedita. Consequuntur error magni et laboriosam. Aut aspernatur - // voluptatem sit aliquam. Dolores voluptatum est. - // Aut molestias et maxime. Fugit autem facilis quos vero. Eius quibusdam possimus est. - // Ea quaerat et quisquam. Deleniti sunt quam. Adipisci consequatur id in occaecati. - // Et sint et. Ut ducimus quod nemo ab voluptatum. -``` - -Even if this example shows a property access, each call to `$faker->name` yields a different (random) result. This is because Faker uses `__get()` magic, and forwards `Faker\Generator->$property` calls to `Faker\Generator->format($property)`. - -```php -name, "\n"; -} - // Adaline Reichel - // Dr. Santa Prosacco DVM - // Noemy Vandervort V - // Lexi O'Conner - // Gracie Weber - // Roscoe Johns - // Emmett Lebsack - // Keegan Thiel - // Wellington Koelpin II - // Ms. Karley Kiehn V -``` - -## Formatters - -Each of the generator properties (like `name`, `address`, and `lorem`) are called "formatters". A faker generator has many of them, packaged in "providers". Here is a list of the bundled formatters in the default locale. - -### `Faker\Provider\en_US\Person` - - prefix // 'Ms.' - suffix // 'Jr.' - name // 'Dr. Zane Stroman' - firstName // 'Maynard' - lastName // 'Zulauf' - -### `Faker\Provider\en_US\Address` - - cityPrefix // 'Lake' - secondaryAddress // 'Suite 961' - state // 'NewMexico' - stateAbbr // 'OH' - citySuffix // 'borough' - streetSuffix // 'Keys' - buildingNumber // '484' - city // 'West Judge' - streetName // 'Keegan Trail' - streetAddress // '439 Karley Loaf Suite 897' - postcode // '17916' - address // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473' - country // 'Falkland Islands (Malvinas)' - latitude // '77.147489' - longitude // '86.211205' - -### `Faker\Provider\en_US\PhoneNumber` - - phoneNumber // '132-149-0269x3767' - -### `Faker\Provider\en_US\Company` - - catchPhrase // 'Monitored regional contingency' - bs // 'e-enable robust architectures' - company // 'Bogan-Treutel' - companySuffix // 'and Sons' - -### `Faker\Provider\Payment` - - creditCardType // 'MasterCard' - creditCardNumber // '4485480221084675' - creditCardExpirationDate // 04/13 - creditCardExpirationDateString // '04/13' - creditCardDetails // array('MasterCard', '4485480221084675', 'Aleksander Nowak', '04/13') - -### `Faker\Provider\Lorem` - - word // 'aut' - words($nb = 3) // array('porro', 'sed', 'magni') - sentence($nbWords = 6) // 'Sit vitae voluptas sint non voluptates.' - sentences($nb = 3) // array('Optio quos qui illo error.', 'Laborum vero a officia id corporis.', 'Saepe provident esse hic eligendi.') - paragraph($nbSentences = 3) // 'Ut ab voluptas sed a nam. Sint autem inventore aut officia aut aut blanditiis. Ducimus eos odit amet et est ut eum.' - paragraphs($nb = 3) // array('Quidem ut sunt et quidem est accusamus aut. Fuga est placeat rerum ut. Enim ex eveniet facere sunt.', 'Aut nam et eum architecto fugit repellendus illo. Qui ex esse veritatis.', 'Possimus omnis aut incidunt sunt. Asperiores incidunt iure sequi cum culpa rem. Rerum exercitationem est rem.') - text($maxNbChars = 200) // 'Fuga totam reiciendis qui architecto fugiat nemo. Consequatur recusandae qui cupiditate eos quod.' - -### `Faker\Provider\Internet` - - email // 'tkshlerin@collins.com' - safeEmail // 'king.alford@example.org' - freeEmail // 'bradley72@gmail.com' - companyEmail // 'russel.durward@mcdermott.org' - freeEmailDomain // 'yahoo.com' - safeEmailDomain // 'example.org' - userName // 'wade55' - domainName // 'wolffdeckow.net' - domainWord // 'feeney' - tld // 'biz' - url // 'http://www.strackeframi.com/' - ipv4 // '109.133.32.252' - ipv6 // '8e65:933d:22ee:a232:f1c1:2741:1f10:117c' - -### `Faker\Provider\DateTime` - - unixTime // 58781813 - dateTime // DateTime('2008-04-25 08:37:17') - dateTimeAD // DateTime('1800-04-29 20:38:49') - iso8601 // '1978-12-09T10:10:29+0000' - date($format = 'Y-m-d') // '1979-06-09' - time($format = 'H:i:s') // '20:49:42' - dateTimeBetween($startDate = '-30 years', $endDate = 'now') // DateTime('2003-03-15 02:00:49') - dateTimeThisCentury // DateTime('1915-05-30 19:28:21') - dateTimeThisDecade // DateTime('2007-05-29 22:30:48') - dateTimeThisYear // DateTime('2011-02-27 20:52:14') - dateTimeThisMonth // DateTime('2011-10-23 13:46:23') - amPm // 'pm' - dayOfMonth // '04' - dayOfWeek // 'Friday' - month // '06' - monthName // 'January' - year // '1993' - century // 'VI' - timezone // 'Europe/Paris' - -### `Faker\Provider\Miscellaneous` - - boolean($chanceOfGettingTrue = 50) // true - md5 // 'de99a620c50f2990e87144735cd357e7' - sha1 // 'f08e7f04ca1a413807ebc47551a40a20a0b4de5c' - sha256 // '0061e4c60dac5c1d82db0135a42e00c89ae3a333e7c26485321f24348c7e98a5' - locale // en_UK - countryCode // UK - languageCode // en - -### `Faker\Provider\Base` - - randomDigit // 7 - randomDigitNotNull // 5 - randomNumber($nbDigits = NULL) // 79907610 - randomNumber($from, $to) // 39049 - randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932 - randomLetter // 'b' - randomElement($array = array ('a','b','c')) // 'b' - numerify($string = '###') // '609' - lexify($string = '????') // 'wgts' - bothify($string = '## ??') // '42 jz' - -### `Faker\Provider\UserAgent` - - userAgent // 'Mozilla/5.0 (Windows CE) AppleWebKit/5350 (KHTML, like Gecko) Chrome/13.0.888.0 Safari/5350' - chrome // 'Mozilla/5.0 (Macintosh; PPC Mac OS X 10_6_5) AppleWebKit/5312 (KHTML, like Gecko) Chrome/14.0.894.0 Safari/5312' - firefox // 'Mozilla/5.0 (X11; Linuxi686; rv:7.0) Gecko/20101231 Firefox/3.6' - safari // 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_7_1 rv:3.0; en-US) AppleWebKit/534.11.3 (KHTML, like Gecko) Version/4.0 Safari/534.11.3' - opera // 'Opera/8.25 (Windows NT 5.1; en-US) Presto/2.9.188 Version/10.00' - internetExplorer // 'Mozilla/5.0 (compatible; MSIE 7.0; Windows 98; Win 9x 4.90; Trident/3.0)' - -### `Faker\Provider\Uuid` - - uuid // '7e57d004-2b97-0e7a-b45f-5387367791cd' - -### `Faker\Provider\File` - - fileExtension // 'avi' - mimeType // 'video/x-msvideo' - -### `Faker\Provider\Color` - - hexcolor // '#fa3cc2' - rgbcolor // '0,255,122' - rgbColorAsArray // array(0,255,122) - rgbCssColor // 'rgb(0,255,122)' - safeColorName // 'fuchsia' - colorName // 'Gainsbor' - -### `Faker\Provider\Image` - - /** - * Image generation provided by LoremPixel (http://lorempixel.com/) - * - * @param $dir An absolute path to a local directory - * @param $width/$height Size (in pixel) of the generated image (defaults to 640x480) - * @param $category One of 'abstract','animals','business','cats','city','food','nightlife','fashion','people','nature','sports','technics', and 'transport' - */ - image($dir) // '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg' - image($dir, $width, $height) // '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg' - image($dir, $width, $height, $category) // '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg' - imageUrl // 'http://lorempixel.com/640/480/' - imageUrl($width, $height) // 'http://lorempixel.com/800/600/' - imageUrl($width, $height, $category) // 'http://lorempixel.com/800/600/person/' - -### `Faker\Provider\Payment` - - creditCardType // 'MasterCard' - creditCardNumber($type = null) // '4485480221084675' - creditCardExpirationDate($valid = true) // DateTime('2014-10-23 13:46:23') - creditCardExpirationDateString($valid = true) // '10/14' - -## Unique and Optional modifiers - -Faker provides two special providers, `unique()` and `optional()`, to be called before any provider. `optional()` can be useful for seeding non-required fields, like a mobile telephone number ; `unique()` is required to populate fields that cannot accept twice the same value, like primary identifiers. - -```php -// unique() forces providers to return unique values -$values = array(); -for ($i=0; $i < 10; $i++) { - // get a random digit, but always a new one, to avoid duplicates - $values []= $faker->unique()->randomDigit; -} -print_r($values); // [4, 1, 8, 5, 0, 2, 6, 9, 7, 3] - -// providers with a limited range will throw an exception when no new unique value can be generated -$values = array(); -try { - for ($i=0; $i < 10; $i++) { - $values []= $faker->unique()->randomDigitNotNull; - } -} catch (\OverflowException $e) { - echo "There are only 9 unique digits not null, Faker can't generate 10 of them!"; -} - -// you can reset the unique modifier for all providers by passing true as first argument -$faker->unique($reset = true)->randomDigitNotNull; // will not throw OverflowException since unique() was reset -// tip: unique() keeps one array of values per provider - -// optional() sometimes bypasses the provider to return null instead -$values = array(); -for ($i=0; $i < 10; $i++) { - // get a random digit, but also null sometimes - $values []= $faker->optional()->randomDigit; -} -print_r($values); // [1, 4, null, 9, 5, null, null, 4, 6, null] - -// optional takes a weight argument to make the null occurrence impossible (value 0) or systematic (value 1) -$faker->optional($weight = 0.1)->randomDigit; // 10% chance to get null -$faker->optional($weight = 0.9)->randomDigit; // 90% chance to get null -// the default $weight value is 0.5 -``` - -## Localization - -`Faker\Factory` can take a locale as an argument, to return localized data. If no localized provider is found, the factory fallbacks to the default locale (en_EN). - -```php -name, "\n"; -} - // Luce du Coulon - // Auguste Dupont - // Roger Le Voisin - // Alexandre Lacroix - // Jacques Humbert-Roy - // Thérèse Guillet-Andre - // Gilles Gros-Bodin - // Amélie Pires - // Marcel Laporte - // Geneviève Marchal -``` - -You can check available Faker locales in the source code, [under the `Provider` directory](https://github.com/fzaninotto/Faker/tree/master/src/Faker/Provider). The localization of Faker is an ongoing process, for which we need your help. Don't hesitate to create localized providers to your own locale and submit a PR! - -## Populating Entities Using an ORM or an ODM - -Faker provides adapters for Object-Relational and Object-Document Mappers (currently, [Propel](http://www.propelorm.org), [Doctrine2](http://www.doctrine-project.org/projects/orm/2.0/docs/en), and [Mandango](https://github.com/mandango/mandango) are supported). These adapters ease the population of databases through the Entity classes provided by an ORM library (or the population of document stores using Document classes provided by an ODM library). - -To populate entities, create a new populator class (using a generator instance as parameter), then list the class and number of all the entities that must be generated. To launch the actual data population, call the `execute()` method. - -Here is an example showing how to populate 5 `Author` and 10 `Book` objects: - -```php -addEntity('Author', 5); -$populator->addEntity('Book', 10); -$insertedPKs = $populator->execute(); -``` - -The populator uses name and column type guessers to populate each column with relevant data. For instance, Faker populates a column named `first_name` using the `firstName` formatter, and a column with a `TIMESTAMP` type using the `dateTime` formatter. The resulting entities are therefore coherent. If Faker misinterprets a column name, you can still specify a custom closure to be used for populating a particular column, using the third argument to `addEntity()`: - -```php -addEntity('Book', 5, array( - 'ISBN' => function() use ($generator) { return $generator->randomNumber(13); } -)); -``` - -In this example, Faker will guess a formatter for all columns except `ISBN`, for which the given anonymous function will be used. - -**Tip**: To ignore some columns, specify `null` for the column names in the third argument of `addEntity()`. This is usually necessary for columns added by a behavior: - -```php -addEntity('Book', 5, array( - 'CreatedAt' => null, - 'UpdatedAt' => null, -)); -``` - -Of course, Faker does not populate autoincremented primary keys. In addition, `Faker\ORM\Propel\Populator::execute()` returns the list of inserted PKs, indexed by class: - -```php - (34, 35, 36, 37, 38), -// 'Book' => (456, 457, 458, 459, 470, 471, 472, 473, 474, 475) -// ) -``` - -In the previous example, the `Book` and `Author` models share a relationship. Since `Author` entities are populated first, Faker is smart enough to relate the populated `Book` entities to one of the populated `Author` entities. - -Lastly, if you want to execute an arbitrary function on an entity before insertion, use the fourth argument of the `addEntity()` method: - -```php -addEntity('Book', 5, array(), array( - function($book) { $book->publish(); }, -)); -``` - -## Seeding the Generator - -You may want to get always the same generated data - for instance when using Faker for unit testing purposes. The generator offers a `seed()` method, which seeds the random number generator. Calling the same script twice with the same seed produces the same results. - -```php -seed(1234); - -echo $faker->name; // 'Jess Mraz I'; -``` - -## Faker Internals: Understanding Providers - -A `Faker\Generator` alone can't do much generation. It needs `Faker\Provider` objects to delegate the data generation to them. `Faker\Factory::create()` actually creates a `Faker\Generator` bundled with the default providers. Here is what happens under the hood: - -```php -addProvider(new Faker\Provider\en_US\Person($faker)); -$faker->addProvider(new Faker\Provider\en_US\Address($faker)); -$faker->addProvider(new Faker\Provider\en_US\PhoneNumber($faker)); -$faker->addProvider(new Faker\Provider\en_US\Company($faker)); -$faker->addProvider(new Faker\Provider\Lorem($faker)); -$faker->addProvider(new Faker\Provider\Internet($faker)); -```` - -Whenever you try to access a property on the `$faker` object, the generator looks for a method with the same name in all the providers attached to it. For instance, calling `$faker->name` triggers a call to `Faker\Provider\Person::name()`. And since Faker starts with the last provider, you can easily override existing formatters: just add a provider containing methods named after the formatters you want to override. - -That means that you can easily add your own providers to a `Faker\Generator` instance. A provider is usually a class extending `\Faker\Provider\Base`. This parent class allows you to use methods like `lexify()` or `randomNumber()`; it also gives you access to formatters of other providers, through the protected `$generator` property. The new formatters are the public methods of the provider class. - -Here is an example provider for populating Book data: - -```php -generator->sentence($nbWords); - return substr($sentence, 0, strlen($sentence) - 1); - } - - public function ISBN() - { - return $this->generator->randomNumber(13); - } -} -``` - -To register this provider, just add a new instance of `\Faker\Provider\Book` to an existing generator: - -```php -addProvider(new \Faker\Provider\Book($faker)); -``` - -Now you can use the two new formatters like any other Faker formatter: - -```php -setTitle($faker->title); -$book->setISBN($faker->ISBN); -$book->setSummary($faker->text); -$book->setPrice($faker->randomNumber(2)); -``` - -**Tip**: A provider can also be a Plain Old PHP Object. In that case, all the public methods of the provider become available to the generator. - -## Real Life Usage - -The following script generates a valid XML document: - -```php - - - - - - -boolean(25)): ?> - - -
- streetAddress ?> - city ?> - postcode ?> - state ?> -
- -boolean(33)): ?> - bs ?> - -boolean(33)): ?> - - - -boolean(15)): ?> -
-text(400) ?> -]]> -
- -
- -
-``` - -Running this script produces a document looking like: - -```xml - - - - -
- 182 Harrison Cove - North Lloyd - 45577 - Alabama -
- - orchestrate compelling web-readiness - -
- -
-
- - -
- 90111 Hegmann Inlet - South Geovanymouth - 69961-9311 - Colorado -
- - -
- - -
- 9791 Nona Corner - Harberhaven - 74062-8191 - RhodeIsland -
- - -
- - -
- 11161 Schultz Via - Feilstad - 98019 - NewJersey -
- - - -
- -
-
- - -
- 6106 Nader Village Suite 753 - McLaughlinstad - 43189-8621 - Missouri -
- - expedite viral synergies - - -
- - -
- 7546 Kuvalis Plaza - South Wilfrid - 77069 - Georgia -
- - -
- - - -
- 478 Daisha Landing Apt. 510 - West Lizethhaven - 30566-5362 - WestVirginia -
- - orchestrate dynamic networks - - -
- -
-
- - -
- 1251 Koelpin Mission - North Revastad - 81620 - Maryland -
- - -
- - -
- 6396 Langworth Hills Apt. 446 - New Carlos - 89399-0268 - Wyoming -
- - - -
- - - -
- 2246 Kreiger Station Apt. 291 - Kaydenmouth - 11397-1072 - Wyoming -
- - grow sticky portals - -
- -
-
-
-``` - -## Language specific formatters - - -### `Faker\Provider\fr_FR\Company` - -```php -siren; // 082 250 104 - -// Generates a random SIRET number -echo $faker->siret; // 347 355 708 00224 - -// Generates a random SIRET number (controlling the number of sequential digits) -echo $faker->siret(3); // 438 472 611 01513 - -``` - -### `Faker\Provider\fr_FR\Address` - -```php -departmentName; // "Haut-Rhin" - -// Generates a random department number -echo $faker->departmentNumber; // "2B" - -// Generates a random department info (department number => department name) -$faker->department; // array('18' => 'Cher'); - -// Generates a random region -echo $faker->region; // "Saint-Pierre-et-Miquelon" - -``` - -### `Faker\Provider\da_DK\Person` - -```php -cpr; // "051280-2387" - -``` - -### `Faker\Provider\da_DK\Address` - -```php -kommune; // "Frederiksberg" - -// Generates a random region name -echo $faker->region; // "Region Sjælland" - -``` - -### `Faker\Provider\da_DK\Company` - -```php -cvr; // "32458723" - -// Generates a random P number -echo $faker->p; // "5398237590" - -``` - -### `Faker\Provider\pl_PL\Person` - -```php -pesel; // "40061451555" -// Generates a random personal identity card number -echo $faker->personalIdentityNumber; // "AKX383360" -// Generates a random taxpayer identification number (NIP) -echo $faker->taxpayerIdentificationNumber; // '8211575109' - -``` - -### `Faker\Provider\pl_PL\Company` - -```php -regon; // "714676680" -// Generates a random local REGON number -echo $faker->regonLocal; // "15346111382836" - -``` - -### `Faker\Provider\pl_PL\Payment` - -```php -bank; // "Narodowy Bank Polski" -// Generates a random bank account number -echo $faker->bankAccountNumber; // "PL14968907563953822118075816" - -``` - -### `Faker\Provider\ja_JP\Person` - -```php -kanaName; // "アオタ ナオコ" - -// Generates a 'kana' first name -echo $faker->firstKanaName; // "トモミ" - -// Generates a 'kana' last name -echo $faker->lastKanaName; // "ナギサ" -``` - -### `Faker\Provider\ro_RO\Person` - -```php -name; // "Ion Ionescu" -// Generates a random male name prefix/title -echo $faker->prefixMale; // "ing." -// Generates a random female name prefix/title -echo $faker->prefixFemale; // "d-na." -// Generates a random male fist name -echo $faker->firstNameMale; // "Adrian" -// Generates a random female fist name -echo $faker->firstNameFemale; // "Miruna" -// Generates a random last name -echo $faker->firstNameFemale; // "Cojocaru" - -// Generates a random Personal Numerical Code (CNP) -echo $faker->cnp; // "2800523081231" -echo $faker->cnp($gender = NULL, $century = NULL, $county = NULL); - -// Valid option values: -// $gender: m, f, 1, 2 -// $century: 1800, 1900, 2000, 1, 2, 3, 4, 5, 6 -// $county: 2 letter ISO 3166-2:RO county codes and B1-B6 for Bucharest's 6 sectors -``` - -### `Faker\Provider\ro_RO\PhoneNumber` - -```php -phoneNumber; // "0211234567" -// Generates a random toll-free phone number -echo $faker->tollFreePhoneNumber; // "0800123456" -// Generates a random premium-rate phone number -echo $faker->premiumRatePhoneNumber; // "0900123456" -``` - -## License - -Faker is released under the MIT Licence. See the bundled LICENSE file for details. +# Faker # + +Faker is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you. + +Faker is heavily inspired by Perl's [Data::Faker](http://search.cpan.org/~jasonk/Data-Faker-0.07/), and by ruby's [Faker](http://faker.rubyforge.org/). + +Faker requires PHP >= 5.3.3. + +[![Build Status](https://secure.travis-ci.org/fzaninotto/Faker.png)](http://travis-ci.org/fzaninotto/Faker) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/eceb78a9-38d4-4ad5-8b6b-b52f323e3549/mini.png)](https://insight.sensiolabs.com/projects/eceb78a9-38d4-4ad5-8b6b-b52f323e3549) + +## Basic Usage + +Use `Faker\Factory::create()` to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want. + +```php +name; + // 'Lucy Cechtelar'; +echo $faker->address; + // "426 Jordy Lodge + // Cartwrightshire, SC 88120-6700" +echo $faker->text; + // Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi + // beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt + // amet quidem. Iusto deleniti cum autem ad quia aperiam. + // A consectetur quos aliquam. In iste aliquid et aut similique suscipit. Consequatur qui + // quaerat iste minus hic expedita. Consequuntur error magni et laboriosam. Aut aspernatur + // voluptatem sit aliquam. Dolores voluptatum est. + // Aut molestias et maxime. Fugit autem facilis quos vero. Eius quibusdam possimus est. + // Ea quaerat et quisquam. Deleniti sunt quam. Adipisci consequatur id in occaecati. + // Et sint et. Ut ducimus quod nemo ab voluptatum. +``` + +Even if this example shows a property access, each call to `$faker->name` yields a different (random) result. This is because Faker uses `__get()` magic, and forwards `Faker\Generator->$property` calls to `Faker\Generator->format($property)`. + +```php +name, "\n"; +} + // Adaline Reichel + // Dr. Santa Prosacco DVM + // Noemy Vandervort V + // Lexi O'Conner + // Gracie Weber + // Roscoe Johns + // Emmett Lebsack + // Keegan Thiel + // Wellington Koelpin II + // Ms. Karley Kiehn V +``` + +## Formatters + +Each of the generator properties (like `name`, `address`, and `lorem`) are called "formatters". A faker generator has many of them, packaged in "providers". Here is a list of the bundled formatters in the default locale. + +### `Faker\Provider\en_US\Person` + + prefix // 'Ms.' + suffix // 'Jr.' + name // 'Dr. Zane Stroman' + firstName // 'Maynard' + lastName // 'Zulauf' + +### `Faker\Provider\en_US\Address` + + cityPrefix // 'Lake' + secondaryAddress // 'Suite 961' + state // 'NewMexico' + stateAbbr // 'OH' + citySuffix // 'borough' + streetSuffix // 'Keys' + buildingNumber // '484' + city // 'West Judge' + streetName // 'Keegan Trail' + streetAddress // '439 Karley Loaf Suite 897' + postcode // '17916' + address // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473' + country // 'Falkland Islands (Malvinas)' + latitude // '77.147489' + longitude // '86.211205' + +### `Faker\Provider\en_US\PhoneNumber` + + phoneNumber // '132-149-0269x3767' + +### `Faker\Provider\en_US\Company` + + catchPhrase // 'Monitored regional contingency' + bs // 'e-enable robust architectures' + company // 'Bogan-Treutel' + companySuffix // 'and Sons' + +### `Faker\Provider\Payment` + + creditCardType // 'MasterCard' + creditCardNumber // '4485480221084675' + creditCardExpirationDate // 04/13 + creditCardExpirationDateString // '04/13' + creditCardDetails // array('MasterCard', '4485480221084675', 'Aleksander Nowak', '04/13') + +### `Faker\Provider\Lorem` + + word // 'aut' + words($nb = 3) // array('porro', 'sed', 'magni') + sentence($nbWords = 6) // 'Sit vitae voluptas sint non voluptates.' + sentences($nb = 3) // array('Optio quos qui illo error.', 'Laborum vero a officia id corporis.', 'Saepe provident esse hic eligendi.') + paragraph($nbSentences = 3) // 'Ut ab voluptas sed a nam. Sint autem inventore aut officia aut aut blanditiis. Ducimus eos odit amet et est ut eum.' + paragraphs($nb = 3) // array('Quidem ut sunt et quidem est accusamus aut. Fuga est placeat rerum ut. Enim ex eveniet facere sunt.', 'Aut nam et eum architecto fugit repellendus illo. Qui ex esse veritatis.', 'Possimus omnis aut incidunt sunt. Asperiores incidunt iure sequi cum culpa rem. Rerum exercitationem est rem.') + text($maxNbChars = 200) // 'Fuga totam reiciendis qui architecto fugiat nemo. Consequatur recusandae qui cupiditate eos quod.' + +### `Faker\Provider\Internet` + + email // 'tkshlerin@collins.com' + safeEmail // 'king.alford@example.org' + freeEmail // 'bradley72@gmail.com' + companyEmail // 'russel.durward@mcdermott.org' + freeEmailDomain // 'yahoo.com' + safeEmailDomain // 'example.org' + userName // 'wade55' + domainName // 'wolffdeckow.net' + domainWord // 'feeney' + tld // 'biz' + url // 'http://www.strackeframi.com/' + ipv4 // '109.133.32.252' + ipv6 // '8e65:933d:22ee:a232:f1c1:2741:1f10:117c' + +### `Faker\Provider\DateTime` + + unixTime // 58781813 + dateTime // DateTime('2008-04-25 08:37:17') + dateTimeAD // DateTime('1800-04-29 20:38:49') + iso8601 // '1978-12-09T10:10:29+0000' + date($format = 'Y-m-d') // '1979-06-09' + time($format = 'H:i:s') // '20:49:42' + dateTimeBetween($startDate = '-30 years', $endDate = 'now') // DateTime('2003-03-15 02:00:49') + dateTimeThisCentury // DateTime('1915-05-30 19:28:21') + dateTimeThisDecade // DateTime('2007-05-29 22:30:48') + dateTimeThisYear // DateTime('2011-02-27 20:52:14') + dateTimeThisMonth // DateTime('2011-10-23 13:46:23') + amPm // 'pm' + dayOfMonth // '04' + dayOfWeek // 'Friday' + month // '06' + monthName // 'January' + year // '1993' + century // 'VI' + timezone // 'Europe/Paris' + +### `Faker\Provider\Miscellaneous` + + boolean($chanceOfGettingTrue = 50) // true + md5 // 'de99a620c50f2990e87144735cd357e7' + sha1 // 'f08e7f04ca1a413807ebc47551a40a20a0b4de5c' + sha256 // '0061e4c60dac5c1d82db0135a42e00c89ae3a333e7c26485321f24348c7e98a5' + locale // en_UK + countryCode // UK + languageCode // en + +### `Faker\Provider\Base` + + randomDigit // 7 + randomDigitNotNull // 5 + randomNumber($nbDigits = NULL) // 79907610 + randomNumber($from, $to) // 39049 + randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932 + randomLetter // 'b' + randomElement($array = array ('a','b','c')) // 'b' + numerify($string = '###') // '609' + lexify($string = '????') // 'wgts' + bothify($string = '## ??') // '42 jz' + +### `Faker\Provider\UserAgent` + + userAgent // 'Mozilla/5.0 (Windows CE) AppleWebKit/5350 (KHTML, like Gecko) Chrome/13.0.888.0 Safari/5350' + chrome // 'Mozilla/5.0 (Macintosh; PPC Mac OS X 10_6_5) AppleWebKit/5312 (KHTML, like Gecko) Chrome/14.0.894.0 Safari/5312' + firefox // 'Mozilla/5.0 (X11; Linuxi686; rv:7.0) Gecko/20101231 Firefox/3.6' + safari // 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_7_1 rv:3.0; en-US) AppleWebKit/534.11.3 (KHTML, like Gecko) Version/4.0 Safari/534.11.3' + opera // 'Opera/8.25 (Windows NT 5.1; en-US) Presto/2.9.188 Version/10.00' + internetExplorer // 'Mozilla/5.0 (compatible; MSIE 7.0; Windows 98; Win 9x 4.90; Trident/3.0)' + +### `Faker\Provider\Uuid` + + uuid // '7e57d004-2b97-0e7a-b45f-5387367791cd' + +### `Faker\Provider\File` + + fileExtension // 'avi' + mimeType // 'video/x-msvideo' + +### `Faker\Provider\Color` + + hexcolor // '#fa3cc2' + rgbcolor // '0,255,122' + rgbColorAsArray // array(0,255,122) + rgbCssColor // 'rgb(0,255,122)' + safeColorName // 'fuchsia' + colorName // 'Gainsbor' + +### `Faker\Provider\Image` + + /** + * Image generation provided by LoremPixel (http://lorempixel.com/) + * + * @param $dir An absolute path to a local directory + * @param $width/$height Size (in pixel) of the generated image (defaults to 640x480) + * @param $category One of 'abstract','animals','business','cats','city','food','nightlife','fashion','people','nature','sports','technics', and 'transport' + */ + image($dir) // '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg' + image($dir, $width, $height) // '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg' + image($dir, $width, $height, $category) // '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.jpg' + imageUrl // 'http://lorempixel.com/640/480/' + imageUrl($width, $height) // 'http://lorempixel.com/800/600/' + imageUrl($width, $height, $category) // 'http://lorempixel.com/800/600/person/' + +### `Faker\Provider\Payment` + + creditCardType // 'MasterCard' + creditCardNumber($type = null) // '4485480221084675' + creditCardExpirationDate($valid = true) // DateTime('2014-10-23 13:46:23') + creditCardExpirationDateString($valid = true) // '10/14' + +## Unique and Optional modifiers + +Faker provides two special providers, `unique()` and `optional()`, to be called before any provider. `optional()` can be useful for seeding non-required fields, like a mobile telephone number ; `unique()` is required to populate fields that cannot accept twice the same value, like primary identifiers. + +```php +// unique() forces providers to return unique values +$values = array(); +for ($i=0; $i < 10; $i++) { + // get a random digit, but always a new one, to avoid duplicates + $values []= $faker->unique()->randomDigit; +} +print_r($values); // [4, 1, 8, 5, 0, 2, 6, 9, 7, 3] + +// providers with a limited range will throw an exception when no new unique value can be generated +$values = array(); +try { + for ($i=0; $i < 10; $i++) { + $values []= $faker->unique()->randomDigitNotNull; + } +} catch (\OverflowException $e) { + echo "There are only 9 unique digits not null, Faker can't generate 10 of them!"; +} + +// you can reset the unique modifier for all providers by passing true as first argument +$faker->unique($reset = true)->randomDigitNotNull; // will not throw OverflowException since unique() was reset +// tip: unique() keeps one array of values per provider + +// optional() sometimes bypasses the provider to return null instead +$values = array(); +for ($i=0; $i < 10; $i++) { + // get a random digit, but also null sometimes + $values []= $faker->optional()->randomDigit; +} +print_r($values); // [1, 4, null, 9, 5, null, null, 4, 6, null] + +// optional takes a weight argument to make the null occurrence impossible (value 0) or systematic (value 1) +$faker->optional($weight = 0.1)->randomDigit; // 10% chance to get null +$faker->optional($weight = 0.9)->randomDigit; // 90% chance to get null +// the default $weight value is 0.5 +``` + +## Localization + +`Faker\Factory` can take a locale as an argument, to return localized data. If no localized provider is found, the factory fallbacks to the default locale (en_EN). + +```php +name, "\n"; +} + // Luce du Coulon + // Auguste Dupont + // Roger Le Voisin + // Alexandre Lacroix + // Jacques Humbert-Roy + // Thérèse Guillet-Andre + // Gilles Gros-Bodin + // Amélie Pires + // Marcel Laporte + // Geneviève Marchal +``` + +You can check available Faker locales in the source code, [under the `Provider` directory](https://github.com/fzaninotto/Faker/tree/master/src/Faker/Provider). The localization of Faker is an ongoing process, for which we need your help. Don't hesitate to create localized providers to your own locale and submit a PR! + +## Populating Entities Using an ORM or an ODM + +Faker provides adapters for Object-Relational and Object-Document Mappers (currently, [Propel](http://www.propelorm.org), [Doctrine2](http://www.doctrine-project.org/projects/orm/2.0/docs/en), and [Mandango](https://github.com/mandango/mandango) are supported). These adapters ease the population of databases through the Entity classes provided by an ORM library (or the population of document stores using Document classes provided by an ODM library). + +To populate entities, create a new populator class (using a generator instance as parameter), then list the class and number of all the entities that must be generated. To launch the actual data population, call the `execute()` method. + +Here is an example showing how to populate 5 `Author` and 10 `Book` objects: + +```php +addEntity('Author', 5); +$populator->addEntity('Book', 10); +$insertedPKs = $populator->execute(); +``` + +The populator uses name and column type guessers to populate each column with relevant data. For instance, Faker populates a column named `first_name` using the `firstName` formatter, and a column with a `TIMESTAMP` type using the `dateTime` formatter. The resulting entities are therefore coherent. If Faker misinterprets a column name, you can still specify a custom closure to be used for populating a particular column, using the third argument to `addEntity()`: + +```php +addEntity('Book', 5, array( + 'ISBN' => function() use ($generator) { return $generator->randomNumber(13); } +)); +``` + +In this example, Faker will guess a formatter for all columns except `ISBN`, for which the given anonymous function will be used. + +**Tip**: To ignore some columns, specify `null` for the column names in the third argument of `addEntity()`. This is usually necessary for columns added by a behavior: + +```php +addEntity('Book', 5, array( + 'CreatedAt' => null, + 'UpdatedAt' => null, +)); +``` + +Of course, Faker does not populate autoincremented primary keys. In addition, `Faker\ORM\Propel\Populator::execute()` returns the list of inserted PKs, indexed by class: + +```php + (34, 35, 36, 37, 38), +// 'Book' => (456, 457, 458, 459, 470, 471, 472, 473, 474, 475) +// ) +``` + +In the previous example, the `Book` and `Author` models share a relationship. Since `Author` entities are populated first, Faker is smart enough to relate the populated `Book` entities to one of the populated `Author` entities. + +Lastly, if you want to execute an arbitrary function on an entity before insertion, use the fourth argument of the `addEntity()` method: + +```php +addEntity('Book', 5, array(), array( + function($book) { $book->publish(); }, +)); +``` + +## Seeding the Generator + +You may want to get always the same generated data - for instance when using Faker for unit testing purposes. The generator offers a `seed()` method, which seeds the random number generator. Calling the same script twice with the same seed produces the same results. + +```php +seed(1234); + +echo $faker->name; // 'Jess Mraz I'; +``` + +## Faker Internals: Understanding Providers + +A `Faker\Generator` alone can't do much generation. It needs `Faker\Provider` objects to delegate the data generation to them. `Faker\Factory::create()` actually creates a `Faker\Generator` bundled with the default providers. Here is what happens under the hood: + +```php +addProvider(new Faker\Provider\en_US\Person($faker)); +$faker->addProvider(new Faker\Provider\en_US\Address($faker)); +$faker->addProvider(new Faker\Provider\en_US\PhoneNumber($faker)); +$faker->addProvider(new Faker\Provider\en_US\Company($faker)); +$faker->addProvider(new Faker\Provider\Lorem($faker)); +$faker->addProvider(new Faker\Provider\Internet($faker)); +```` + +Whenever you try to access a property on the `$faker` object, the generator looks for a method with the same name in all the providers attached to it. For instance, calling `$faker->name` triggers a call to `Faker\Provider\Person::name()`. And since Faker starts with the last provider, you can easily override existing formatters: just add a provider containing methods named after the formatters you want to override. + +That means that you can easily add your own providers to a `Faker\Generator` instance. A provider is usually a class extending `\Faker\Provider\Base`. This parent class allows you to use methods like `lexify()` or `randomNumber()`; it also gives you access to formatters of other providers, through the protected `$generator` property. The new formatters are the public methods of the provider class. + +Here is an example provider for populating Book data: + +```php +generator->sentence($nbWords); + return substr($sentence, 0, strlen($sentence) - 1); + } + + public function ISBN() + { + return $this->generator->randomNumber(13); + } +} +``` + +To register this provider, just add a new instance of `\Faker\Provider\Book` to an existing generator: + +```php +addProvider(new \Faker\Provider\Book($faker)); +``` + +Now you can use the two new formatters like any other Faker formatter: + +```php +setTitle($faker->title); +$book->setISBN($faker->ISBN); +$book->setSummary($faker->text); +$book->setPrice($faker->randomNumber(2)); +``` + +**Tip**: A provider can also be a Plain Old PHP Object. In that case, all the public methods of the provider become available to the generator. + +## Real Life Usage + +The following script generates a valid XML document: + +```php + + + + + + +boolean(25)): ?> + + +
+ streetAddress ?> + city ?> + postcode ?> + state ?> +
+ +boolean(33)): ?> + bs ?> + +boolean(33)): ?> + + + +boolean(15)): ?> +
+text(400) ?> +]]> +
+ +
+ +
+``` + +Running this script produces a document looking like: + +```xml + + + + +
+ 182 Harrison Cove + North Lloyd + 45577 + Alabama +
+ + orchestrate compelling web-readiness + +
+ +
+
+ + +
+ 90111 Hegmann Inlet + South Geovanymouth + 69961-9311 + Colorado +
+ + +
+ + +
+ 9791 Nona Corner + Harberhaven + 74062-8191 + RhodeIsland +
+ + +
+ + +
+ 11161 Schultz Via + Feilstad + 98019 + NewJersey +
+ + + +
+ +
+
+ + +
+ 6106 Nader Village Suite 753 + McLaughlinstad + 43189-8621 + Missouri +
+ + expedite viral synergies + + +
+ + +
+ 7546 Kuvalis Plaza + South Wilfrid + 77069 + Georgia +
+ + +
+ + + +
+ 478 Daisha Landing Apt. 510 + West Lizethhaven + 30566-5362 + WestVirginia +
+ + orchestrate dynamic networks + + +
+ +
+
+ + +
+ 1251 Koelpin Mission + North Revastad + 81620 + Maryland +
+ + +
+ + +
+ 6396 Langworth Hills Apt. 446 + New Carlos + 89399-0268 + Wyoming +
+ + + +
+ + + +
+ 2246 Kreiger Station Apt. 291 + Kaydenmouth + 11397-1072 + Wyoming +
+ + grow sticky portals + +
+ +
+
+
+``` + +## Language specific formatters + + +### `Faker\Provider\fr_FR\Company` + +```php +siren; // 082 250 104 + +// Generates a random SIRET number +echo $faker->siret; // 347 355 708 00224 + +// Generates a random SIRET number (controlling the number of sequential digits) +echo $faker->siret(3); // 438 472 611 01513 + +``` + +### `Faker\Provider\fr_FR\Address` + +```php +departmentName; // "Haut-Rhin" + +// Generates a random department number +echo $faker->departmentNumber; // "2B" + +// Generates a random department info (department number => department name) +$faker->department; // array('18' => 'Cher'); + +// Generates a random region +echo $faker->region; // "Saint-Pierre-et-Miquelon" + +``` + +### `Faker\Provider\da_DK\Person` + +```php +cpr; // "051280-2387" + +``` + +### `Faker\Provider\da_DK\Address` + +```php +kommune; // "Frederiksberg" + +// Generates a random region name +echo $faker->region; // "Region Sjælland" + +``` + +### `Faker\Provider\da_DK\Company` + +```php +cvr; // "32458723" + +// Generates a random P number +echo $faker->p; // "5398237590" + +``` + +### `Faker\Provider\pl_PL\Person` + +```php +pesel; // "40061451555" +// Generates a random personal identity card number +echo $faker->personalIdentityNumber; // "AKX383360" +// Generates a random taxpayer identification number (NIP) +echo $faker->taxpayerIdentificationNumber; // '8211575109' + +``` + +### `Faker\Provider\pl_PL\Company` + +```php +regon; // "714676680" +// Generates a random local REGON number +echo $faker->regonLocal; // "15346111382836" + +``` + +### `Faker\Provider\pl_PL\Payment` + +```php +bank; // "Narodowy Bank Polski" +// Generates a random bank account number +echo $faker->bankAccountNumber; // "PL14968907563953822118075816" + +``` + +### `Faker\Provider\ja_JP\Person` + +```php +kanaName; // "アオタ ナオコ" + +// Generates a 'kana' first name +echo $faker->firstKanaName; // "トモミ" + +// Generates a 'kana' last name +echo $faker->lastKanaName; // "ナギサ" +``` + +### `Faker\Provider\ro_RO\Person` + +```php +name; // "Ion Ionescu" +// Generates a random male name prefix/title +echo $faker->prefixMale; // "ing." +// Generates a random female name prefix/title +echo $faker->prefixFemale; // "d-na." +// Generates a random male fist name +echo $faker->firstNameMale; // "Adrian" +// Generates a random female fist name +echo $faker->firstNameFemale; // "Miruna" +// Generates a random last name +echo $faker->firstNameFemale; // "Cojocaru" + +// Generates a random Personal Numerical Code (CNP) +echo $faker->cnp; // "2800523081231" +echo $faker->cnp($gender = NULL, $century = NULL, $county = NULL); + +// Valid option values: +// $gender: m, f, 1, 2 +// $century: 1800, 1900, 2000, 1, 2, 3, 4, 5, 6 +// $county: 2 letter ISO 3166-2:RO county codes and B1-B6 for Bucharest's 6 sectors +``` + +### `Faker\Provider\ro_RO\PhoneNumber` + +```php +phoneNumber; // "0211234567" +// Generates a random toll-free phone number +echo $faker->tollFreePhoneNumber; // "0800123456" +// Generates a random premium-rate phone number +echo $faker->premiumRatePhoneNumber; // "0900123456" +``` + +## License + +Faker is released under the MIT Licence. See the bundled LICENSE file for details. From 80257b79336840a984d53794b3421d6f192586fb Mon Sep 17 00:00:00 2001 From: Mihai Zaharie Date: Mon, 6 Jan 2014 13:38:03 +0200 Subject: [PATCH 7/7] Remove general formatters (not locale specific) --- readme.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/readme.md b/readme.md index 3efcf560..e666e6af 100644 --- a/readme.md +++ b/readme.md @@ -755,8 +755,6 @@ echo $faker->lastKanaName; // "ナギサ" ```php name; // "Ion Ionescu" // Generates a random male name prefix/title echo $faker->prefixMale; // "ing." // Generates a random female name prefix/title @@ -765,8 +763,6 @@ echo $faker->prefixFemale; // "d-na." echo $faker->firstNameMale; // "Adrian" // Generates a random female fist name echo $faker->firstNameFemale; // "Miruna" -// Generates a random last name -echo $faker->firstNameFemale; // "Cojocaru" // Generates a random Personal Numerical Code (CNP) echo $faker->cnp; // "2800523081231" @@ -783,8 +779,6 @@ echo $faker->cnp($gender = NULL, $century = NULL, $county = NULL); ```php phoneNumber; // "0211234567" // Generates a random toll-free phone number echo $faker->tollFreePhoneNumber; // "0800123456" // Generates a random premium-rate phone number