fzaninotto / faker Goto Github PK
View Code? Open in Web Editor NEWFaker is a PHP library that generates fake data for you
License: MIT License
Faker is a PHP library that generates fake data for you
License: MIT License
If I have OneToOne relationship in Doctrine2, I get error below, because Faker try to assign more entities.
Integrity constraint violation: 1062 Duplicate entry '221' for key
With the support of existing API such as Placehold.it or LoremPixel, Faker could easily provide fake pictures/avatars etc which is more and more present in layouts.
<?php
$faker = Faker\Factory::create();
$faker->seed(1);
echo $faker->dateTime;
This piece of code generates new value for every new day. Is it normal?
I think you forgot to extend the Faker\Provider\Base class.
Hi,
I generate a bunch of data with as many providers as possible, to generate a realistic international set. However whenever I use the Bulgarian provider I keep getting invalid utf-8 sequences, like: Йоан-Александър92@���к��е������������.bg
The problem seems to lie with domain generation. This becomes even more clear in the second example.
In hex:
\xd0\x99\xd0\xbe\xd0\xb0\xd0\xbd\x2d\xd0\x90\xd0\xbb\xd0\xb5\xd0\xba\xd1\x81\xd0\xb0\xd0\xbd\xd0\xb4\xd1\x8a\xd1\x80\x39\x32\x40\xd0\xd1\xd1\xd0\xba\xd1\xd0\xd0\xb5\xd0\xd0\xd0\xd0\xd0\xd0\xd0\xd0\xd1\xd0\xd0\xd0\x2e\x62\x67
(\x40 == @)
The definition:
Foo\Entity\EmailAddress:
mail_bg{1...500}:
__construct: [ <bg_BG:safeEmail()> ]
Second example:
Foo\Entity\Network
network_bg{1...5}:
__construct: [ <bg_BG:company()>, <bg_BG:domainWord()> ]
subdomain (unique): <bg_BG:domainWord()>
The error
[Doctrine\DBAL\DBALException]
An exception occurred while executing 'INSERT INTO network (name, subdomain, ...) VALUES (?, ?, ...)' with params ["\u0413\u0430\u0431\u0440\u043e\u0432\u043b\u0438\u0435\u0432\u0430-\u041f\u0435\u043d\u0434\u0436\u0430\u043a\u043e\u0432\u0430", "\xd0\xd0\xd1\xd1\xd0\xd0\xba\xd0\xd0\xd0\xd0", ...]:
SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xD0\xD0\xD1\xD1\xD0\xD0...' for column 'subdomain' at row 1
The first is the name, a valid sequence. The second is the subdomain name, an invalid sequence.
I have downloaded the .zip file and given path later i run the file using the browser to check the data is displaying randomly or not. Till now am clear but can any one tell me how to insert the data into my database table.
Is it possible to populate join tables (ManyToMany relation in doctrine)?
I am going to create a Dutch Provider. If you want to help or have some great resources, feel free to contact me or add a comment below!
This issue will close when a Dutch Provider pull request is posted.
Create a localized provider, and modify the factory to take a locale argument
Hi,
The library may bug when you generate sentences inferior or equal to 2 words ("Undefined offset 0" ).
It comes from the sentence function from the Lorem provider:
<?php
public static function sentence($nbWords = 6) // if $nbWords <= 2
{
$words = static::words($nbWords + mt_rand(-2, 2)); // may return empty array
$words[0] = ucwords($words[0]); // so this line causes the application to crash
return join($words, ' ') . '.';
}
I suspect there is a similar problem with the paragraph function.
There are a couple of ways to deal with these 'problems', that's why I didn't attached any code.
What do you propose? Is it the normal behaviour, should it throws exceptions or should it returns an empty string?
Currently you have url method that returns something like this:
http://randomsite.com/
Can you add method like urlWithParams (not the best title) that will return something like:
http://anothersite.com/?id=2&aff_id=20&source=banner
or
http://thirdsite.com/forum.php?topic_id=20
I think its gonna be great tool for testing purpose.
Hi there,
the current implementation of safeEmail is not really safe, because of the localized TLDs. The domain example.de
in case of Germany is registered to a private artist. As RFC 2606 states the following TLDs are regarded safe for testing and documentation purposes:
*.test
*.example
*.invalid
*.localhost
Additionally the following second level domains are reserved as well and therefore are safe:
example.com
example.net
example.org
example.<any other TLD>
is not safe!
I can provide a Pull Request if you want. It may take some time, depending how busy I am in the next days, though.
Hi,
What about adding an autoloader for this lib ? And to set a "standard" directory structure as below:
Faker
|_ src/
| |_ Faker/
| |_ Provider/
| |_ Factory.php
| |_ Generator.php
|_ tests/
|_ Faker/
|_ Provider/
|_ FactoryTest.php
|_ GeneratorTest.php
That will follow the PSR-0 standard and will ease integration in other projects. You won't have to provide a dependency with ClassLoader except for unit test or standalone usage (which is more or less the same thing).
See: https://github.com/knplabs/Gaufrette
Note: Propel2 will follow the same standard.
Be exhaustive to let the user ignore the provider classes if she doesn't want to understand how they work.
Hi I have a Doctrine Entity like this:
...
name: {type: string, length: 255}
address: {type: string, length: 255}
phone_number: {type: string, length: 255}
company: {type: string, length: 255}
email: {type: string, length: 255}
url: {type: string, length: 255}
...
When I try to fake on entry with this code
...
$em = $this->getEntityManager();
$generator = \Faker\Factory::create($locale);
$populator = new \Faker\ORM\Doctrine\Populator($generator, $em);
$populator->addEntity($this->getEntityName(), 1);
$results = $populator->execute();
...
What I get is something like this:
I have debug to EntityPopulator fillColumns Method on
https://github.com/fzaninotto/Faker/blob/master/src/Faker/ORM/Doctrine/EntityPopulator.php
And I suppose something is missing/wrong with this line
$value = is_callable($format) ? $format($insertedEntities, $obj) : $format;
But I really cannot follow up. Any ideas?? Thank you in advance.
Hi,
I LOVE PHP FAKER! It is unbelievably awesome and integrates flawlessly with anything!
Anyways, I really like the bs and catchphrase feature in Faker, especially because they make a lot of sense. Lipsum texts are cool but you just cannot beat human readable texts.
It will be nice if Faker automatically grabbed random contents from public domain ebooks.
Sites like http://www.gutenberg.org/ are great for public domain contents.
So, you shouldn't get in any kind of trouble for using those contents on a script like this.
I would like to contribute provider for Serbian locale. But I'm not sure which locale ID I should use.
We have two locales sr_Latn and sr_Cyrl since we use both latin and cyrillic script, so we should have separated providers for this two.
Should it be sr_Latn_RS and sr_Cyrl_RS, or I can go with sr_Latn and sr_Cyrl? Or some other ID, I'm not sure, I usually work with sr_Latn and sr_Cyrl, but I see the format here is language_COUNTRY.
Thoughts?
Since a couple of days, Faker is throwing exceptions.
[InvalidArgumentException] Unknown formatter "catchPhrase"
When using faker as follows :
$faker = Factory::create('fr_FR');
echo $faker->catchPhrase;
Am I missing something?
I need the ability to pick a random image from a local directory.
I am currently playing around with the following idea where you can either pass in a filename pattern as needed by glob() or by passing in a directory and a list of extensions. This will pick a random filename given those parameters.
class FileLocal
{
public static function fileLocalPattern($pattern)
{
$files = glob($pattern, GLOB_BRACE);
if (count($files) == 0) {
return false;
}
$file = array_rand($files);
return $files[$file];
}
public static function fileLocal($dir, $types = array())
{
$pattern = $dir . DIRECTORY_SEPARATOR . '*.{' . implode(',', $types) . '}';
return static::fileLocalPattern($pattern);
}
}
It needs tests and this is currently only a local implementation (not as part of a forked Faker, I'm still a little new to GitHub) Would something like this be a useful provider to add?
There is an issue with the code used to generate an ipv4 address. On a 32-bit platform it frequently returns '0.0.0.0' due to the code used in the random number generator.
The code used in Fakers\Provider\Internet.php line 122 is:
return long2ip(mt_rand(-2147483648, 2147483647));
http://php.net/manual/en/function.mt-rand.php#96022 describes the issue: "mt_getrandmax() is NOT the max INTEGER size. It is limited to positive numbers from ZERO to your integers largest value. Thus, it is HALF the size of an INTEGER, since integers are SIGNED, but mt_rand can only correctly randomize from ZERO to mt_getrandmax()."
Therefore using mt_rand(0, 2147483647) works consistently, but only produces half the range. Using mt_rand(-2147483648, 2147483647) produces a large number of '0' values.
One solution might be to use an additional call to generate either a 0 or 1 and use this as a basis for whether to produce a positive or negative number. The following works perfectly every time:
return long2ip(mt_rand(0, 1) == 0 ? mt_rand(-2147483648, 0) : mt_rand(1, 2147483647));
Here are code examples and their outputs:
$faker = \Faker\Factory::create();
var_dump($faker->text(20)); // string(0) "" (expected some text)
$faker = \Faker\Factory::create();
var_dump($faker->sentence(2)); // string(22) "Quos vel odit dolorum." (expected 2 words sentence)
$faker = \Faker\Factory::create();
var_dump($faker->paragraph(2)); // string(136) "Quasi et qui quos ut veniam sunt. Soluta harum minima aut mollitia libero quae cum. Sapiente dolor ullam eaque voluptatibus aperiam quo." (expected 2 sentence paragraph)
Has anyone created a provider for html or markov chains ?
Html would be handy for wysiwyg editor content for blogs, cms's and comment systems.
A markov generator would be much better for approximation of actual logical content than the random lorem one. Especially for word count statistics and keyword analysis, tagging, search systems etc.
Currently a design is chosen that follows the following design principle:
$faker = new Faker\Generator();
$faker->addProvider(new Faker\Provider\en_US\Name($faker));
// ...
This seems like an unnecessary dependency and makes extending Faker more difficult. I would vote to change the design and allow for optional injection and add some logic to test if an alternate provider has been defined:
$faker = new Faker\Generator();
$faker->addProvider(new Faker\Provider\en_US\Name()); // $faker is not passed as argument
// ...
Faker\Generator should be refactored to embrace this change:
class Generator
{
public function addProvider(\Faker\Provider $provider)
{
if ( ! $provider->hasGenerator()) {
$provider->setGenerator($this);
}
// ..
}
// ..
}
When you run Faker in PHP 5.3.2 you'll get this error:
Fatal error: Call to a member function parse() on a non-object in /www/symfony/vendor/faker/src/Faker/Provider/Name.php on line 23
This is because of the following:
As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.
http://php.net/manual/en/language.oop5.decon.php
The Name provider has a name() method which is the same as the name of the class.
It seems that Faker could be an exceptional candidate for Fixture Factory support. This was originally made popular by Martin Fowler's Object Mother Pattern and has since been adopted in popular ruby packages like Factory Girl and Object Daddy. Here's a great Blog Post on the benefits of Factories over Fixtures.
There appears to be one such attempt in PHP land, namely in the Xi Project. https://github.com/xi-project/xi-doctrine. See FixtureFactory. Faker already has the ability to create fixtures and has ORM/ODM providers. With a little work, we could provide a very solid Object Mother that makes testing incredibly succinct.
Hi,
I have a question about Faker and the Propel ORM adapter. How to disable a field of an entity to avoid populate it.
The main problem is to deal with Propel behaviors: specific columns shouldn't be populated by the adapter but by the behavior itself. It doesn't work at the moment..
Regards,
William
Hi,
I have wrote a simple product provider to populate my virtual store. Is it good enough for a provider? I would like to contribute. Here is the code: https://gist.github.com/dextervip/5655263
I'm using Faker with BazingaFakerBundle to populate a database. Some entities have UNIQUE
constraints on their fields, for example
table MyCountry
id
name (unique = true)
I'm using the Address
provider to insert e.g. 10 countries, but most of the time some country will be inserted twice and the insert fails.
Is there already an easy way to get only unique values from the provider methods?
Last tag is 7 months old. Some useful features have been added to the project (like randomFloat in Base Provider). Time for another tag?
it return an array of entities.
I have not test if propel behaves the same.
Anyway the readme should be adapted...
Thanks for this useful lib.
Today I've updated Faker to it's most recent version using Composer. For some reason, the $faker->optional()
method does not work anymore. I have also tried to use it as an object $faker->optional
, but that didn't work either.
The error message I get is:
[InvalidArgumentException]
Unkown argument "optional"
I am using Faker in a Laravel 4 application, but that doesn't seem to have anything to do with it. I've tested on both Windows and Mac machines.
Usually I update dependencies once a week, so I expect this problem has been introduced in one of the recent commits.
I discovered it today and I can´t stop playing with it, ;). Just lo let you know that phaker could be a cool name. Anyway, don´t pay too much attention to this.
Thank you so much for such a great project.
dates within intervals, years, months, weekdays, etc.
Source: http://cpansearch.perl.org/src/JASONK/Data-Faker-0.07/lib/Data/Faker/DateTime.pm
Email generation in spanish language use some non valid email chars that are availables in spanish names (ñ, á, é, í, ó, ú).
Emails show be free of this chars because most software apps return as a not valid email.
Regards,
Lito.
It would be great if I could just install it via pear and Faker is always in my include path.
I know that I can archive this right now by hand, still… this is what pear is for – at least the installer.
it seems this is supported just by Propel populator...
<?php
$populator->addEntity('Book', 5, array(), array(
function($book) { $book->publish(); },
));
Would it be bad idea to also provide API for faking images? This could easily be done with gd library and would also help when styling webpage with random data in it. What do you think?
Not really an issue and maybe it's a little overkill.
I would just like to share my own library.
When I was using this, there wasn't any ja_JP before so I actually rolled up my own.
Hi,
The alias "dev-master": "1.2.x-dev" in your composer.json still points on the tag 1.2.0 which has no Color provider.
Could you do something about this ?
Thank you in advance,
Regards.
This code is not valid with doctrine. Throws errors.
<?php
$populator->addEntity('Book', 5, array(), array(
function($book) { $book->publish(); },
));
What about an arrayPopulator or a stcClassPopulator ? I'm using faker for testing purpose and often I need to generate some fake data and the store it in a variable for later use.
Right now I need to manually copy these values from the faker object. Wouldn't be nice to have some kind of populator to solve this problem ?
Am I missing something? Is that already possible with faker ?
Hi,
If I populate emails in Spanish (the same problem will happen in other langs with written accents) y get emails with accents like:
álvaro@...... which is not correct.
I suggest adding something like [^a-zA-Z0-9.-_@] to the email functions in
Faker\Provider\Internet
I am not very good at reg_exp that is why I have not do it by myself.
Sorry and thanks for the help.
After the recent version bump and a composer update, 1.2.*
is currently mapping to the tagged release instead of dev master. The first thing I ran into was that unique()
was no longer an option.
Not a bug per se, but it was a bit of a surprise when composer update
downgraded Faker. Fixing to 1.3.*
gets everything back to normal.
I noticed Documentor
throws a warning with french locale
Warning: Missing argument 1 for Faker\Provider\fr_FR\Company::isCatchPhraseValid()
The problem is that Documentor
parses all the public methods, and isCatchPhraseValid
is public static, to make it testable. The warning can be easily removed by adding a default value to the parameter (should I send a pull request for that ??)
public static function isCatchPhraseValid($catchPhrase = '')
BUT isCatchPhraseValid
is still returned as an API method by Documentor
I didn't really understand why there is a mix of instance & static public method inside Providers, what is the difference ?
Maybe isCatchPhraseValid
shouldn't be exposed as public or moved to another class ?
Is exist a way to have a cycleElement() function, which seems to be better for testes than randomElement() ?
I'm working with Faker to populate fixtures and I have an entity with sexe and first name. As firstname provider mixes male and female, I obtain uncoherents datas and I don't know if it would be an interresting add... I'm not very familiar with pull so I'd rather prefer asking.
Anyway, I'm forking your project to work on some more personnal issues.
Hi
I'm currently working on using Faker for a project using PHP 5.3.2 and I'm running into an issue.
According to this documentation on PHP's constructor, PHP versions < 5.3.3 will use a method named the same as a class if it can not find a __construct
method in that class.
This is an issue with Faker as some of the providers have a method in them with the same name as the class, which will cause these versions of PHP to call the method. e.g. the Faker\Provider\Address
class has an address()
method. It leads to errors such as:
PHP Fatal error: Call to a member function parse() on a non-object in faker/src/Faker/Provider/Address.php on line 91
Defining a __construct
method that just calls the parent constructor works, but throws a PHP strict standards notice:
PHP Strict Standards: Redefining already defined constructor for class Faker\Provider\Address in faker/src/Faker/Provider/Address.php on line 93
Is there a solution that allows you to keep your architecture but ignores this php backwards compatibility shim?
Cheers,
Chris.
emails, ip addresses, domain names, etc.
Source: https://github.com/stympy/faker/blob/master/lib/faker/internet.rb
The Laravel framework has been gaining a lot of weight this past year and with the close release of Laravel 4 which will be Composer-ready, it has already imposed itself as one of the top PHP frameworks available. Is there a plan to support its ORM in the roadmap ?
Details on the Eloquent ORM can be found here. I'd gladly work on a PR myself but I would need more details on how Faker handles ORM, I tried peeking into the code but couldn't quite grasp how it's all managed.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.