Commit bef3862b by 叶明星

去除过滤目录

parent ed7f4c14
Showing with 5025 additions and 2 deletions

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit12da169cd7a4ae1278d12b87df158790::getLoader();
#!/usr/bin/env sh
dir=$(cd "${0%[/\\]*}" > /dev/null; cd "../phpunit/phpunit" && pwd)
if [ -d /proc/cygdrive ]; then
case $(which php) in
$(readlink -n /proc/cygdrive)/*)
# We are in Cygwin using Windows php, so the path must be translated
dir=$(cygpath -m "$dir");
;;
esac
fi
"${dir}/phpunit" "$@"
@ECHO OFF
setlocal DISABLEDELAYEDEXPANSION
SET BIN_TARGET=%~dp0/../phpunit/phpunit/phpunit
php "%BIN_TARGET%" %*
#!/usr/bin/env sh
dir=$(cd "${0%[/\\]*}" > /dev/null; cd "../nesbot/carbon/bin" && pwd)
if [ -d /proc/cygdrive ]; then
case $(which php) in
$(readlink -n /proc/cygdrive)/*)
# We are in Cygwin using Windows php, so the path must be translated
dir=$(cygpath -m "$dir");
;;
esac
fi
"${dir}/upgrade-carbon" "$@"
@ECHO OFF
setlocal DISABLEDELAYEDEXPANSION
SET BIN_TARGET=%~dp0/../nesbot/carbon/bin/upgrade-carbon
php "%BIN_TARGET%" %*
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'5255c38a0faeba867671b61dfda6d864' => $vendorDir . '/paragonie/random_compat/lib/random.php',
'72579e7bd17821bb1321b87411366eae' => $vendorDir . '/illuminate/support/helpers.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'253c157292f75eb38082b5acb06f3f01' => $vendorDir . '/nikic/fast-route/src/functions.php',
'bd9634f2d41831496de0d3dfe4c94881' => $vendorDir . '/symfony/polyfill-php56/bootstrap.php',
'bee9632da3ca00a99623b9c35d0c4f8b' => $vendorDir . '/laravel/lumen-framework/src/helpers.php',
'7039eb1b48735a2a2905d88c22d84a48' => $baseDir . '/common/function.php',
'c71e5a39a1f58c05a11e8537318d6d3d' => $baseDir . '/common/LogReport.php',
);
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'UpdateHelper\\' => array($vendorDir . '/kylekatarnls/update-helper/src'),
);
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'phpDocumentor\\Reflection\\' => array($vendorDir . '/phpdocumentor/reflection-common/src', $vendorDir . '/phpdocumentor/reflection-docblock/src', $vendorDir . '/phpdocumentor/type-resolver/src'),
'Webmozart\\Assert\\' => array($vendorDir . '/webmozart/assert/src'),
'Symfony\\Polyfill\\Util\\' => array($vendorDir . '/symfony/polyfill-util'),
'Symfony\\Polyfill\\Php56\\' => array($vendorDir . '/symfony/polyfill-php56'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
'Symfony\\Component\\Yaml\\' => array($vendorDir . '/symfony/yaml'),
'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'),
'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'),
'Symfony\\Component\\HttpKernel\\' => array($vendorDir . '/symfony/http-kernel'),
'Symfony\\Component\\HttpFoundation\\' => array($vendorDir . '/symfony/http-foundation'),
'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'),
'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'),
'Symfony\\Component\\Debug\\' => array($vendorDir . '/symfony/debug'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'ScmWmsCommon\\' => array($baseDir . '/scm_wms_common'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Prophecy\\' => array($vendorDir . '/phpspec/prophecy/src/Prophecy'),
'Predis\\' => array($vendorDir . '/predis/predis/src'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'Laravel\\Lumen\\' => array($vendorDir . '/laravel/lumen-framework/src'),
'Illuminate\\View\\' => array($vendorDir . '/illuminate/view'),
'Illuminate\\Validation\\' => array($vendorDir . '/illuminate/validation'),
'Illuminate\\Translation\\' => array($vendorDir . '/illuminate/translation'),
'Illuminate\\Support\\' => array($vendorDir . '/illuminate/support'),
'Illuminate\\Session\\' => array($vendorDir . '/illuminate/session'),
'Illuminate\\Redis\\' => array($vendorDir . '/illuminate/redis'),
'Illuminate\\Queue\\' => array($vendorDir . '/illuminate/queue'),
'Illuminate\\Pipeline\\' => array($vendorDir . '/illuminate/pipeline'),
'Illuminate\\Pagination\\' => array($vendorDir . '/illuminate/pagination'),
'Illuminate\\Http\\' => array($vendorDir . '/illuminate/http'),
'Illuminate\\Hashing\\' => array($vendorDir . '/illuminate/hashing'),
'Illuminate\\Filesystem\\' => array($vendorDir . '/illuminate/filesystem'),
'Illuminate\\Events\\' => array($vendorDir . '/illuminate/events'),
'Illuminate\\Encryption\\' => array($vendorDir . '/illuminate/encryption'),
'Illuminate\\Database\\' => array($vendorDir . '/illuminate/database'),
'Illuminate\\Contracts\\' => array($vendorDir . '/illuminate/contracts'),
'Illuminate\\Container\\' => array($vendorDir . '/illuminate/container'),
'Illuminate\\Console\\' => array($vendorDir . '/illuminate/console'),
'Illuminate\\Config\\' => array($vendorDir . '/illuminate/config'),
'Illuminate\\Cache\\' => array($vendorDir . '/illuminate/cache'),
'Illuminate\\Bus\\' => array($vendorDir . '/illuminate/bus'),
'Illuminate\\Broadcasting\\' => array($vendorDir . '/illuminate/broadcasting'),
'Illuminate\\Auth\\' => array($vendorDir . '/illuminate/auth'),
'FastRoute\\' => array($vendorDir . '/nikic/fast-route/src'),
'Faker\\' => array($vendorDir . '/fzaninotto/faker/src/Faker'),
'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'),
'Doctrine\\Instantiator\\' => array($vendorDir . '/doctrine/instantiator/src/Doctrine/Instantiator'),
'Doctrine\\Common\\Inflector\\' => array($vendorDir . '/doctrine/inflector/lib/Doctrine/Common/Inflector'),
'Cron\\' => array($vendorDir . '/mtdowling/cron-expression/src/Cron'),
'Common\\' => array($baseDir . '/common'),
'App\\' => array($baseDir . '/app'),
'' => array($vendorDir . '/nesbot/carbon/src'),
);
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit12da169cd7a4ae1278d12b87df158790
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit12da169cd7a4ae1278d12b87df158790', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit12da169cd7a4ae1278d12b87df158790', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit12da169cd7a4ae1278d12b87df158790::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit12da169cd7a4ae1278d12b87df158790::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire12da169cd7a4ae1278d12b87df158790($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequire12da169cd7a4ae1278d12b87df158790($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}
This diff could not be displayed because it is too large.
Copyright (c) 2006-2015 Doctrine Project
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Doctrine Inflector
Doctrine Inflector is a small library that can perform string manipulations
with regard to upper-/lowercase and singular/plural forms of words.
[![Build Status](https://travis-ci.org/doctrine/inflector.svg?branch=master)](https://travis-ci.org/doctrine/inflector)
{
"name": "doctrine/inflector",
"type": "library",
"description": "Common String Manipulations with regard to casing and singular/plural rules.",
"keywords": ["string", "inflection", "singularize", "pluralize"],
"homepage": "http://www.doctrine-project.org",
"license": "MIT",
"authors": [
{"name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com"},
{"name": "Roman Borschel", "email": "roman@code-factory.org"},
{"name": "Benjamin Eberlei", "email": "kontakt@beberlei.de"},
{"name": "Jonathan Wage", "email": "jonwage@gmail.com"},
{"name": "Johannes Schmitt", "email": "schmittjoh@gmail.com"}
],
"require": {
"php": "^7.1"
},
"require-dev": {
"phpunit/phpunit": "^6.2"
},
"autoload": {
"psr-4": { "Doctrine\\Common\\Inflector\\": "lib/Doctrine/Common/Inflector" }
},
"autoload-dev": {
"psr-4": { "Doctrine\\Tests\\Common\\Inflector\\": "tests/Doctrine/Tests/Common/Inflector" }
},
"extra": {
"branch-alias": {
"dev-master": "1.3.x-dev"
}
}
}
Introduction
============
The Doctrine Inflector has static methods for inflecting text.
The features include pluralization, singularization,
converting between camelCase and under_score and capitalizing
words.
All you need to use the Inflector is the ``Doctrine\Common\Inflector\Inflector``
class.
Installation
============
You can install the Inflector with composer:
.. code-block::
$ composer require doctrine/inflector
Here are the available methods that you can use:
Tableize
========
Converts ``ModelName`` to ``model_name``:
.. code-block:: php
echo Inflector::tableize('ModelName'); // model_name
Classify
========
Converts ``model_name`` to ``ModelName``:
.. code-block:: php
echo Inflector::classify('model_name'); // ModelName
Camelize
========
This method uses `Classify`_ and then converts the first character to lowercase:
.. code-block:: php
echo Inflector::camelize('model_name'); // modelName
ucwords
=======
Takes a string and capitalizes all of the words, like PHP's built-in
ucwords function. This extends that behavior, however, by allowing the
word delimiters to be configured, rather than only separating on
whitespace.
Here is an example:
.. code-block:: php
$string = 'top-o-the-morning to all_of_you!';
echo Inflector::ucwords($string); // Top-O-The-Morning To All_of_you!
echo Inflector::ucwords($string, '-_ '); // Top-O-The-Morning To All_Of_You!
Pluralize
=========
Returns a word in plural form.
.. code-block:: php
echo Inflector::pluralize('browser'); // browsers
Singularize
===========
.. code-block:: php
echo Inflector::singularize('browsers'); // browser
Rules
=====
Customize the rules for pluralization and singularization:
.. code-block:: php
Inflector::rules('plural', ['/^(inflect)or$/i' => '\1ables']);
Inflector::rules('plural', [
'rules' => ['/^(inflect)ors$/i' => '\1ables'],
'uninflected' => ['dontinflectme'],
'irregular' => ['red' => 'redlings']
]);
The arguments for the ``rules`` method are:
- ``$type`` - The type of inflection, either ``plural`` or ``singular``
- ``$rules`` - An array of rules to be added.
- ``$reset`` - If true, will unset default inflections for all new rules that are being defined in $rules.
Reset
=====
Clears Inflectors inflected value caches, and resets the inflection
rules to the initial values.
.. code-block:: php
Inflector::reset();
Slugify
=======
You can easily use the Inflector to create a slug from a string of text
by using the `tableize`_ method and replacing underscores with hyphens:
.. code-block:: php
public static function slugify(string $text) : string
{
return str_replace('_', '-', Inflector::tableize($text));
}
{
"active": true,
"name": "Instantiator",
"slug": "instantiator",
"docsSlug": "doctrine-instantiator",
"codePath": "/src",
"versions": [
{
"name": "1.1",
"branchName": "master",
"slug": "latest",
"aliases": [
"current",
"stable"
],
"maintained": true,
"current": true
},
{
"name": "1.0",
"branchName": "1.0.x",
"slug": "1.0"
}
]
}
patreon: phpdoctrine
tidelift: packagist/doctrine%2Finstantiator
custom: https://www.doctrine-project.org/sponsorship.html
# Contributing
* Follow the [Doctrine Coding Standard](https://github.com/doctrine/coding-standard)
* The project will follow strict [object calisthenics](http://www.slideshare.net/guilhermeblanco/object-calisthenics-applied-to-php)
* Any contribution must provide tests for additional introduced conditions
* Any un-confirmed issue needs a failing test case before being accepted
* Pull requests must be sent from a new hotfix/feature branch, not from `master`.
## Installation
To install the project and run the tests, you need to clone it first:
```sh
$ git clone git://github.com/doctrine/instantiator.git
```
You will then need to run a composer installation:
```sh
$ cd Instantiator
$ curl -s https://getcomposer.org/installer | php
$ php composer.phar update
```
## Testing
The PHPUnit version to be used is the one installed as a dev- dependency via composer:
```sh
$ ./vendor/bin/phpunit
```
Accepted coverage for new contributions is 80%. Any contribution not satisfying this requirement
won't be merged.
Copyright (c) 2014 Doctrine Project
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Instantiator
This library provides a way of avoiding usage of constructors when instantiating PHP classes.
[![Build Status](https://travis-ci.org/doctrine/instantiator.svg?branch=master)](https://travis-ci.org/doctrine/instantiator)
[![Code Coverage](https://scrutinizer-ci.com/g/doctrine/instantiator/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/doctrine/instantiator/?branch=master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/doctrine/instantiator/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/doctrine/instantiator/?branch=master)
[![Dependency Status](https://www.versioneye.com/package/php--doctrine--instantiator/badge.svg)](https://www.versioneye.com/package/php--doctrine--instantiator)
[![Latest Stable Version](https://poser.pugx.org/doctrine/instantiator/v/stable.png)](https://packagist.org/packages/doctrine/instantiator)
[![Latest Unstable Version](https://poser.pugx.org/doctrine/instantiator/v/unstable.png)](https://packagist.org/packages/doctrine/instantiator)
## Installation
The suggested installation method is via [composer](https://getcomposer.org/):
```sh
php composer.phar require "doctrine/instantiator:~1.0.3"
```
## Usage
The instantiator is able to create new instances of any class without using the constructor or any API of the class
itself:
```php
$instantiator = new \Doctrine\Instantiator\Instantiator();
$instance = $instantiator->instantiate(\My\ClassName\Here::class);
```
## Contributing
Please read the [CONTRIBUTING.md](CONTRIBUTING.md) contents if you wish to help out!
## Credits
This library was migrated from [ocramius/instantiator](https://github.com/Ocramius/Instantiator), which
has been donated to the doctrine organization, and which is now deprecated in favour of this package.
{
"name": "doctrine/instantiator",
"description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors",
"type": "library",
"license": "MIT",
"homepage": "https://www.doctrine-project.org/projects/instantiator.html",
"keywords": [
"instantiate",
"constructor"
],
"authors": [
{
"name": "Marco Pivetta",
"email": "ocramius@gmail.com",
"homepage": "http://ocramius.github.com/"
}
],
"require": {
"php": "^7.1"
},
"require-dev": {
"ext-phar": "*",
"ext-pdo": "*",
"doctrine/coding-standard": "^6.0",
"phpbench/phpbench": "^0.13",
"phpstan/phpstan-phpunit": "^0.11",
"phpstan/phpstan-shim": "^0.11",
"phpunit/phpunit": "^7.0"
},
"autoload": {
"psr-4": {
"Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/"
}
},
"autoload-dev": {
"psr-0": {
"DoctrineTest\\InstantiatorPerformance\\": "tests",
"DoctrineTest\\InstantiatorTest\\": "tests",
"DoctrineTest\\InstantiatorTestAsset\\": "tests"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.2.x-dev"
}
}
}
Introduction
============
This library provides a way of avoiding usage of constructors when instantiating PHP classes.
Installation
============
The suggested installation method is via `composer`_:
.. code-block:: console
$ composer require doctrine/instantiator
Usage
=====
The instantiator is able to create new instances of any class without
using the constructor or any API of the class itself:
.. code-block:: php
<?php
use Doctrine\Instantiator\Instantiator;
use App\Entities\User;
$instantiator = new Instantiator();
$user = $instantiator->instantiate(User::class);
Contributing
============
- Follow the `Doctrine Coding Standard`_
- The project will follow strict `object calisthenics`_
- Any contribution must provide tests for additional introduced
conditions
- Any un-confirmed issue needs a failing test case before being
accepted
- Pull requests must be sent from a new hotfix/feature branch, not from
``master``.
Testing
=======
The PHPUnit version to be used is the one installed as a dev- dependency
via composer:
.. code-block:: console
$ ./vendor/bin/phpunit
Accepted coverage for new contributions is 80%. Any contribution not
satisfying this requirement won’t be merged.
Credits
=======
This library was migrated from `ocramius/instantiator`_, which has been
donated to the doctrine organization, and which is now deprecated in
favour of this package.
.. _composer: https://getcomposer.org/
.. _CONTRIBUTING.md: CONTRIBUTING.md
.. _ocramius/instantiator: https://github.com/Ocramius/Instantiator
.. _Doctrine Coding Standard: https://github.com/doctrine/coding-standard
.. _object calisthenics: http://www.slideshare.net/guilhermeblanco/object-calisthenics-applied-to-php
{
"bootstrap": "vendor/autoload.php",
"path": "tests/DoctrineTest/InstantiatorPerformance"
}
<?xml version="1.0"?>
<ruleset>
<arg name="basepath" value="."/>
<arg name="extensions" value="php"/>
<arg name="parallel" value="80"/>
<arg name="cache" value=".phpcs-cache"/>
<arg name="colors"/>
<!-- Ignore warnings, show progress of the run and show sniff names -->
<arg value="nps"/>
<file>src</file>
<file>tests</file>
<rule ref="Doctrine">
<exclude name="SlevomatCodingStandard.TypeHints.DeclareStrictTypes"/>
<exclude name="SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint"/>
<exclude name="SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingReturnTypeHint"/>
<exclude name="SlevomatCodingStandard.Exceptions.ReferenceThrowableOnly.ReferencedGeneralException"/>
</rule>
<rule ref="SlevomatCodingStandard.Classes.SuperfluousAbstractClassNaming">
<exclude-pattern>tests/DoctrineTest/InstantiatorTestAsset/AbstractClassAsset.php</exclude-pattern>
</rule>
<rule ref="SlevomatCodingStandard.Classes.SuperfluousExceptionNaming">
<exclude-pattern>src/Doctrine/Instantiator/Exception/UnexpectedValueException.php</exclude-pattern>
<exclude-pattern>src/Doctrine/Instantiator/Exception/InvalidArgumentException.php</exclude-pattern>
</rule>
<rule ref="SlevomatCodingStandard.Classes.SuperfluousInterfaceNaming">
<exclude-pattern>src/Doctrine/Instantiator/Exception/ExceptionInterface.php</exclude-pattern>
<exclude-pattern>src/Doctrine/Instantiator/InstantiatorInterface.php</exclude-pattern>
</rule>
</ruleset>
includes:
- vendor/phpstan/phpstan-phpunit/extension.neon
- vendor/phpstan/phpstan-phpunit/rules.neon
parameters:
level: max
paths:
- src
- tests
ignoreErrors:
-
message: '#::__construct\(\) does not call parent constructor from#'
path: '*/tests/DoctrineTest/InstantiatorTestAsset/*.php'
# dynamic properties confuse static analysis
-
message: '#Access to an undefined property object::\$foo\.#'
path: '*/tests/DoctrineTest/InstantiatorTest/InstantiatorTest.php'
<?php
namespace Doctrine\Instantiator\Exception;
use Throwable;
/**
* Base exception marker interface for the instantiator component
*/
interface ExceptionInterface extends Throwable
{
}
<?php
namespace Doctrine\Instantiator\Exception;
use InvalidArgumentException as BaseInvalidArgumentException;
use ReflectionClass;
use const PHP_VERSION_ID;
use function interface_exists;
use function sprintf;
use function trait_exists;
/**
* Exception for invalid arguments provided to the instantiator
*/
class InvalidArgumentException extends BaseInvalidArgumentException implements ExceptionInterface
{
public static function fromNonExistingClass(string $className) : self
{
if (interface_exists($className)) {
return new self(sprintf('The provided type "%s" is an interface, and can not be instantiated', $className));
}
if (PHP_VERSION_ID >= 50400 && trait_exists($className)) {
return new self(sprintf('The provided type "%s" is a trait, and can not be instantiated', $className));
}
return new self(sprintf('The provided class "%s" does not exist', $className));
}
public static function fromAbstractClass(ReflectionClass $reflectionClass) : self
{
return new self(sprintf(
'The provided class "%s" is abstract, and can not be instantiated',
$reflectionClass->getName()
));
}
}
<?php
namespace Doctrine\Instantiator\Exception;
use Exception;
use ReflectionClass;
use UnexpectedValueException as BaseUnexpectedValueException;
use function sprintf;
/**
* Exception for given parameters causing invalid/unexpected state on instantiation
*/
class UnexpectedValueException extends BaseUnexpectedValueException implements ExceptionInterface
{
public static function fromSerializationTriggeredException(
ReflectionClass $reflectionClass,
Exception $exception
) : self {
return new self(
sprintf(
'An exception was raised while trying to instantiate an instance of "%s" via un-serialization',
$reflectionClass->getName()
),
0,
$exception
);
}
public static function fromUncleanUnSerialization(
ReflectionClass $reflectionClass,
string $errorString,
int $errorCode,
string $errorFile,
int $errorLine
) : self {
return new self(
sprintf(
'Could not produce an instance of "%s" via un-serialization, since an error was triggered '
. 'in file "%s" at line "%d"',
$reflectionClass->getName(),
$errorFile,
$errorLine
),
0,
new Exception($errorString, $errorCode)
);
}
}
<?php
namespace Doctrine\Instantiator;
use ArrayIterator;
use Doctrine\Instantiator\Exception\InvalidArgumentException;
use Doctrine\Instantiator\Exception\UnexpectedValueException;
use Exception;
use ReflectionClass;
use ReflectionException;
use Serializable;
use function class_exists;
use function is_subclass_of;
use function restore_error_handler;
use function set_error_handler;
use function sprintf;
use function strlen;
use function unserialize;
/**
* {@inheritDoc}
*/
final class Instantiator implements InstantiatorInterface
{
/**
* Markers used internally by PHP to define whether {@see \unserialize} should invoke
* the method {@see \Serializable::unserialize()} when dealing with classes implementing
* the {@see \Serializable} interface.
*/
public const SERIALIZATION_FORMAT_USE_UNSERIALIZER = 'C';
public const SERIALIZATION_FORMAT_AVOID_UNSERIALIZER = 'O';
/**
* Used to instantiate specific classes, indexed by class name.
*
* @var callable[]
*/
private static $cachedInstantiators = [];
/**
* Array of objects that can directly be cloned, indexed by class name.
*
* @var object[]
*/
private static $cachedCloneables = [];
/**
* {@inheritDoc}
*/
public function instantiate($className)
{
if (isset(self::$cachedCloneables[$className])) {
return clone self::$cachedCloneables[$className];
}
if (isset(self::$cachedInstantiators[$className])) {
$factory = self::$cachedInstantiators[$className];
return $factory();
}
return $this->buildAndCacheFromFactory($className);
}
/**
* Builds the requested object and caches it in static properties for performance
*
* @return object
*/
private function buildAndCacheFromFactory(string $className)
{
$factory = self::$cachedInstantiators[$className] = $this->buildFactory($className);
$instance = $factory();
if ($this->isSafeToClone(new ReflectionClass($instance))) {
self::$cachedCloneables[$className] = clone $instance;
}
return $instance;
}
/**
* Builds a callable capable of instantiating the given $className without
* invoking its constructor.
*
* @throws InvalidArgumentException
* @throws UnexpectedValueException
* @throws ReflectionException
*/
private function buildFactory(string $className) : callable
{
$reflectionClass = $this->getReflectionClass($className);
if ($this->isInstantiableViaReflection($reflectionClass)) {
return [$reflectionClass, 'newInstanceWithoutConstructor'];
}
$serializedString = sprintf(
'%s:%d:"%s":0:{}',
is_subclass_of($className, Serializable::class) ? self::SERIALIZATION_FORMAT_USE_UNSERIALIZER : self::SERIALIZATION_FORMAT_AVOID_UNSERIALIZER,
strlen($className),
$className
);
$this->checkIfUnSerializationIsSupported($reflectionClass, $serializedString);
return static function () use ($serializedString) {
return unserialize($serializedString);
};
}
/**
* @throws InvalidArgumentException
* @throws ReflectionException
*/
private function getReflectionClass(string $className) : ReflectionClass
{
if (! class_exists($className)) {
throw InvalidArgumentException::fromNonExistingClass($className);
}
$reflection = new ReflectionClass($className);
if ($reflection->isAbstract()) {
throw InvalidArgumentException::fromAbstractClass($reflection);
}
return $reflection;
}
/**
* @throws UnexpectedValueException
*/
private function checkIfUnSerializationIsSupported(ReflectionClass $reflectionClass, string $serializedString) : void
{
set_error_handler(static function (int $code, string $message, string $file, int $line) use ($reflectionClass, &$error) : bool {
$error = UnexpectedValueException::fromUncleanUnSerialization(
$reflectionClass,
$message,
$code,
$file,
$line
);
return true;
});
try {
$this->attemptInstantiationViaUnSerialization($reflectionClass, $serializedString);
} finally {
restore_error_handler();
}
if ($error) {
throw $error;
}
}
/**
* @throws UnexpectedValueException
*/
private function attemptInstantiationViaUnSerialization(ReflectionClass $reflectionClass, string $serializedString) : void
{
try {
unserialize($serializedString);
} catch (Exception $exception) {
throw UnexpectedValueException::fromSerializationTriggeredException($reflectionClass, $exception);
}
}
private function isInstantiableViaReflection(ReflectionClass $reflectionClass) : bool
{
return ! ($this->hasInternalAncestors($reflectionClass) && $reflectionClass->isFinal());
}
/**
* Verifies whether the given class is to be considered internal
*/
private function hasInternalAncestors(ReflectionClass $reflectionClass) : bool
{
do {
if ($reflectionClass->isInternal()) {
return true;
}
$reflectionClass = $reflectionClass->getParentClass();
} while ($reflectionClass);
return false;
}
/**
* Checks if a class is cloneable
*
* Classes implementing `__clone` cannot be safely cloned, as that may cause side-effects.
*/
private function isSafeToClone(ReflectionClass $reflection) : bool
{
return $reflection->isCloneable()
&& ! $reflection->hasMethod('__clone')
&& ! $reflection->isSubclassOf(ArrayIterator::class);
}
}
<?php
namespace Doctrine\Instantiator;
use Doctrine\Instantiator\Exception\ExceptionInterface;
/**
* Instantiator provides utility methods to build objects without invoking their constructors
*/
interface InstantiatorInterface
{
/**
* @param string $className
*
* @return object
*
* @throws ExceptionInterface
*/
public function instantiate($className);
}
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
### Summary
<!-- provide a summary here -->
### Versions
<!-- Please provide the versions of PHP as well as `fzaninotto/faker` on which the issue has been observed -->
| | Version |
|:--------------------|:--------|
| PHP | x.y.z |
| `fzaninotto/faker` | x.y.z |
### Self-enclosed code snippet for reproduction
```php
<!-- please replace this with a self-enclosed usage example -->
```
### Expected output
```txt
<!-- please replace this with the expected output of your self-enclosed example -->
```
### Actual output
```txt
<!-- please replace this with the actual output of your self-enclosed example -->
```
#!/usr/bin/env bash
# The problem is that we do not want to remove the configuration file, just disable it for a few tasks, then enable it
#
# For reference, see
#
# - https://docs.travis-ci.com/user/languages/php#Disabling-preinstalled-PHP-extensions
# - https://docs.travis-ci.com/user/languages/php#Custom-PHP-configuration
config="/home/travis/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini"
function xdebug-disable() {
if [[ -f $config ]]; then
mv $config "$config.bak"
fi
}
function xdebug-enable() {
if [[ -f "$config.bak" ]]; then
mv "$config.bak" $config
fi
}
Copyright (c) 2011 François Zaninotto
Portions Copyright (c) 2008 Caius Durling
Portions Copyright (c) 2008 Adam Royle
Portions Copyright (c) 2008 Fiona Burrows
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
{
"name": "fzaninotto/faker",
"type": "library",
"description": "Faker is a PHP library that generates fake data for you.",
"keywords": [
"faker",
"fixtures",
"data"
],
"license": "MIT",
"authors": [
{
"name": "François Zaninotto"
}
],
"require": {
"php": "^5.3.3 || ^7.0"
},
"require-dev": {
"ext-intl": "*",
"phpunit/phpunit": "^4.8.35 || ^5.7",
"squizlabs/php_codesniffer": "^2.9.2"
},
"autoload": {
"psr-4": {
"Faker\\": "src/Faker/"
}
},
"autoload-dev": {
"psr-4": {
"Faker\\Test\\": "test/Faker/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.9-dev"
}
},
"config": {
"sort-packages": true
}
}
<?php
namespace Faker\Calculator;
/**
* Utility class for validating EAN-8 and EAN-13 numbers
*
* @package Faker\Calculator
*/
class Ean
{
/** @var string EAN validation pattern */
const PATTERN = '/^(?:\d{8}|\d{13})$/';
/**
* Computes the checksum of an EAN number.
*
* @see https://en.wikipedia.org/wiki/International_Article_Number
*
* @param string $digits
* @return int
*/
public static function checksum($digits)
{
$length = strlen($digits);
$even = 0;
for ($i = $length - 1; $i >= 0; $i -= 2) {
$even += $digits[$i];
}
$odd = 0;
for ($i = $length - 2; $i >= 0; $i -= 2) {
$odd += $digits[$i];
}
return (10 - ((3 * $even + $odd) % 10)) % 10;
}
/**
* Checks whether the provided number is an EAN compliant number and that
* the checksum is correct.
*
* @param string $ean An EAN number
* @return boolean
*/
public static function isValid($ean)
{
if (!preg_match(self::PATTERN, $ean)) {
return false;
}
return self::checksum(substr($ean, 0, -1)) === intval(substr($ean, -1));
}
}
<?php
namespace Faker\Calculator;
class Iban
{
/**
* Generates IBAN Checksum
*
* @param string $iban
* @return string Checksum (numeric string)
*/
public static function checksum($iban)
{
// Move first four digits to end and set checksum to '00'
$checkString = substr($iban, 4) . substr($iban, 0, 2) . '00';
// Replace all letters with their number equivalents
$checkString = preg_replace_callback('/[A-Z]/', array('self','alphaToNumberCallback'), $checkString);
// Perform mod 97 and subtract from 98
$checksum = 98 - self::mod97($checkString);
return str_pad($checksum, 2, '0', STR_PAD_LEFT);
}
/**
* @param string $match
*
* @return int
*/
private static function alphaToNumberCallback($match)
{
return self::alphaToNumber($match[0]);
}
/**
* Converts letter to number
*
* @param string $char
* @return int
*/
public static function alphaToNumber($char)
{
return ord($char) - 55;
}
/**
* Calculates mod97 on a numeric string
*
* @param string $number Numeric string
* @return int
*/
public static function mod97($number)
{
$checksum = (int)$number[0];
for ($i = 1, $size = strlen($number); $i < $size; $i++) {
$checksum = (10 * $checksum + (int) $number[$i]) % 97;
}
return $checksum;
}
/**
* Checks whether an IBAN has a valid checksum
*
* @param string $iban
* @return boolean
*/
public static function isValid($iban)
{
return self::checksum($iban) === substr($iban, 2, 2);
}
}
<?php
namespace Faker\Calculator;
class Inn
{
/**
* Generates INN Checksum
*
* https://ru.wikipedia.org/wiki/%D0%98%D0%B4%D0%B5%D0%BD%D1%82%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D0%BE%D0%BD%D0%BD%D1%8B%D0%B9_%D0%BD%D0%BE%D0%BC%D0%B5%D1%80_%D0%BD%D0%B0%D0%BB%D0%BE%D0%B3%D0%BE%D0%BF%D0%BB%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D1%89%D0%B8%D0%BA%D0%B0
*
* @param string $inn
* @return string Checksum (one digit)
*/
public static function checksum($inn)
{
$multipliers = array(1 => 2, 2 => 4, 3 => 10, 4 => 3, 5 => 5, 6 => 9, 7 => 4, 8 => 6, 9 => 8);
$sum = 0;
for ($i = 1; $i <= 9; $i++) {
$sum += intval(substr($inn, $i-1, 1)) * $multipliers[$i];
}
return strval(($sum % 11) % 10);
}
/**
* Checks whether an INN has a valid checksum
*
* @param string $inn
* @return boolean
*/
public static function isValid($inn)
{
return self::checksum(substr($inn, 0, -1)) === substr($inn, -1, 1);
}
}
<?php
namespace Faker\Calculator;
use InvalidArgumentException;
/**
* Utility class for generating and validating Luhn numbers.
*
* Luhn algorithm is used to validate credit card numbers, IMEI numbers, and
* National Provider Identifier numbers.
*
* @see http://en.wikipedia.org/wiki/Luhn_algorithm
*/
class Luhn
{
/**
* @param string $number
* @return int
*/
private static function checksum($number)
{
$number = (string) $number;
$length = strlen($number);
$sum = 0;
for ($i = $length - 1; $i >= 0; $i -= 2) {
$sum += $number[$i];
}
for ($i = $length - 2; $i >= 0; $i -= 2) {
$sum += array_sum(str_split($number[$i] * 2));
}
return $sum % 10;
}
/**
* @param $partialNumber
* @return string
*/
public static function computeCheckDigit($partialNumber)
{
$checkDigit = self::checksum($partialNumber . '0');
if ($checkDigit === 0) {
return 0;
}
return (string) (10 - $checkDigit);
}
/**
* Checks whether a number (partial number + check digit) is Luhn compliant
*
* @param string $number
* @return bool
*/
public static function isValid($number)
{
return self::checksum($number) === 0;
}
/**
* Generate a Luhn compliant number.
*
* @param string $partialValue
*
* @return string
*/
public static function generateLuhnNumber($partialValue)
{
if (!preg_match('/^\d+$/', $partialValue)) {
throw new InvalidArgumentException('Argument should be an integer.');
}
return $partialValue . Luhn::computeCheckDigit($partialValue);
}
}
<?php
namespace Faker\Calculator;
use InvalidArgumentException;
class TCNo
{
/**
* Generates Turkish Identity Number Checksum
* Gets first 9 digit as prefix and calcuates checksums
*
* https://en.wikipedia.org/wiki/Turkish_Identification_Number
*
* @param string $identityPrefix
* @return string Checksum (two digit)
*/
public static function checksum($identityPrefix)
{
if (strlen((string)$identityPrefix) !== 9) {
throw new InvalidArgumentException('Argument should be an integer and should be 9 digits.');
}
$oddSum = 0;
$evenSum = 0;
$identityArray = array_map('intval', str_split($identityPrefix)); // Creates array from int
foreach ($identityArray as $index => $digit) {
if ($index % 2 == 0) {
$evenSum += $digit;
} else {
$oddSum += $digit;
}
}
$tenthDigit = (7 * $evenSum - $oddSum) % 10;
$eleventhDigit = ($evenSum + $oddSum + $tenthDigit) % 10;
return $tenthDigit . $eleventhDigit;
}
/**
* Checks whether an TCNo has a valid checksum
*
* @param string $tcNo
* @return boolean
*/
public static function isValid($tcNo)
{
return self::checksum(substr($tcNo, 0, -2)) === substr($tcNo, -2, 2);
}
}
<?php
namespace Faker;
/**
* This generator returns a default value for all called properties
* and methods. It works with Faker\Generator\Base->optional().
*/
class DefaultGenerator
{
protected $default;
public function __construct($default = null)
{
$this->default = $default;
}
/**
* @param string $attribute
*
* @return mixed
*/
public function __get($attribute)
{
return $this->default;
}
/**
* @param string $method
* @param array $attributes
*
* @return mixed
*/
public function __call($method, $attributes)
{
return $this->default;
}
}
<?php
namespace Faker;
class Documentor
{
protected $generator;
/**
* @param Generator $generator
*/
public function __construct(Generator $generator)
{
$this->generator = $generator;
}
/**
* @return array
*/
public function getFormatters()
{
$formatters = array();
$providers = array_reverse($this->generator->getProviders());
$providers[]= new Provider\Base($this->generator);
foreach ($providers as $provider) {
$providerClass = get_class($provider);
$formatters[$providerClass] = array();
$refl = new \ReflectionObject($provider);
foreach ($refl->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflmethod) {
if ($reflmethod->getDeclaringClass()->getName() == 'Faker\Provider\Base' && $providerClass != 'Faker\Provider\Base') {
continue;
}
$methodName = $reflmethod->name;
if ($reflmethod->isConstructor()) {
continue;
}
$parameters = array();
foreach ($reflmethod->getParameters() as $reflparameter) {
$parameter = '$'. $reflparameter->getName();
if ($reflparameter->isDefaultValueAvailable()) {
$parameter .= ' = ' . var_export($reflparameter->getDefaultValue(), true);
}
$parameters []= $parameter;
}
$parameters = $parameters ? '('. join(', ', $parameters) . ')' : '';
try {
$example = $this->generator->format($methodName);
} catch (\InvalidArgumentException $e) {
$example = '';
}
if (is_array($example)) {
$example = "array('". join("', '", $example) . "')";
} elseif ($example instanceof \DateTime) {
$example = "DateTime('" . $example->format('Y-m-d H:i:s') . "')";
} elseif ($example instanceof Generator || $example instanceof UniqueGenerator) { // modifier
$example = '';
} else {
$example = var_export($example, true);
}
$formatters[$providerClass][$methodName . $parameters] = $example;
}
}
return $formatters;
}
}
<?php
namespace Faker;
class Factory
{
const DEFAULT_LOCALE = 'en_US';
protected static $defaultProviders = array('Address', 'Barcode', 'Biased', 'Color', 'Company', 'DateTime', 'File', 'HtmlLorem', 'Image', 'Internet', 'Lorem', 'Miscellaneous', 'Payment', 'Person', 'PhoneNumber', 'Text', 'UserAgent', 'Uuid');
/**
* Create a new generator
*
* @param string $locale
* @return Generator
*/
public static function create($locale = self::DEFAULT_LOCALE)
{
$generator = new Generator();
foreach (static::$defaultProviders as $provider) {
$providerClassName = self::getProviderClassname($provider, $locale);
$generator->addProvider(new $providerClassName($generator));
}
return $generator;
}
/**
* @param string $provider
* @param string $locale
* @return string
*/
protected static function getProviderClassname($provider, $locale = '')
{
if ($providerClass = self::findProviderClassname($provider, $locale)) {
return $providerClass;
}
// fallback to default locale
if ($providerClass = self::findProviderClassname($provider, static::DEFAULT_LOCALE)) {
return $providerClass;
}
// fallback to no locale
if ($providerClass = self::findProviderClassname($provider)) {
return $providerClass;
}
throw new \InvalidArgumentException(sprintf('Unable to find provider "%s" with locale "%s"', $provider, $locale));
}
/**
* @param string $provider
* @param string $locale
* @return string
*/
protected static function findProviderClassname($provider, $locale = '')
{
$providerClass = 'Faker\\' . ($locale ? sprintf('Provider\%s\%s', $locale, $provider) : sprintf('Provider\%s', $provider));
if (class_exists($providerClass, true)) {
return $providerClass;
}
}
}
<?php
namespace Faker;
/**
* @property string $name
* @method string name(string $gender = null)
* @property string $firstName
* @method string firstName(string $gender = null)
* @property string $firstNameMale
* @property string $firstNameFemale
* @property string $lastName
* @property string $title
* @method string title(string $gender = null)
* @property string $titleMale
* @property string $titleFemale
*
* @property string $citySuffix
* @property string $streetSuffix
* @property string $buildingNumber
* @property string $city
* @property string $streetName
* @property string $streetAddress
* @property string $secondaryAddress
* @property string $postcode
* @property string $address
* @property string $state
* @property string $country
* @property float $latitude
* @property float $longitude
*
* @property string $ean13
* @property string $ean8
* @property string $isbn13
* @property string $isbn10
*
* @property string $phoneNumber
* @property string $e164PhoneNumber
*
* @property string $company
* @property string $companySuffix
* @property string $jobTitle
*
* @property string $creditCardType
* @property string $creditCardNumber
* @method string creditCardNumber($type = null, $formatted = false, $separator = '-')
* @property \DateTime $creditCardExpirationDate
* @property string $creditCardExpirationDateString
* @property array $creditCardDetails
* @property string $bankAccountNumber
* @method string iban($countryCode = null, $prefix = '', $length = null)
* @property string $swiftBicNumber
* @property string $vat
*
* @property string $word
* @property string|array $words
* @method string|array words($nb = 3, $asText = false)
* @method string word()
* @property string $sentence
* @method string sentence($nbWords = 6, $variableNbWords = true)
* @property string|array $sentences
* @method string|array sentences($nb = 3, $asText = false)
* @property string $paragraph
* @method string paragraph($nbSentences = 3, $variableNbSentences = true)
* @property string|array $paragraphs
* @method string|array paragraphs($nb = 3, $asText = false)
* @property string $text
* @method string text($maxNbChars = 200)
*
* @method string realText($maxNbChars = 200, $indexSize = 2)
*
* @property string $email
* @property string $safeEmail
* @property string $freeEmail
* @property string $companyEmail
* @property string $freeEmailDomain
* @property string $safeEmailDomain
* @property string $userName
* @property string $password
* @method string password($minLength = 6, $maxLength = 20)
* @property string $domainName
* @property string $domainWord
* @property string $tld
* @property string $url
* @property string $slug
* @method string slug($nbWords = 6, $variableNbWords = true)
* @property string $ipv4
* @property string $ipv6
* @property string $localIpv4
* @property string $macAddress
*
* @property int $unixTime
* @property \DateTime $dateTime
* @property \DateTime $dateTimeAD
* @property string $iso8601
* @property \DateTime $dateTimeThisCentury
* @property \DateTime $dateTimeThisDecade
* @property \DateTime $dateTimeThisYear
* @property \DateTime $dateTimeThisMonth
* @property string $amPm
* @property string $dayOfMonth
* @property string $dayOfWeek
* @property string $month
* @property string $monthName
* @property string $year
* @property string $century
* @property string $timezone
* @method string amPm($max = 'now')
* @method string date($format = 'Y-m-d', $max = 'now')
* @method string dayOfMonth($max = 'now')
* @method string dayOfWeek($max = 'now')
* @method string iso8601($max = 'now')
* @method string month($max = 'now')
* @method string monthName($max = 'now')
* @method string time($format = 'H:i:s', $max = 'now')
* @method int unixTime($max = 'now')
* @method string year($max = 'now')
* @method \DateTime dateTime($max = 'now', $timezone = null)
* @method \DateTime dateTimeAd($max = 'now', $timezone = null)
* @method \DateTime dateTimeBetween($startDate = '-30 years', $endDate = 'now', $timezone = null)
* @method \DateTime dateTimeInInterval($date = '-30 years', $interval = '+5 days', $timezone = null)
* @method \DateTime dateTimeThisCentury($max = 'now', $timezone = null)
* @method \DateTime dateTimeThisDecade($max = 'now', $timezone = null)
* @method \DateTime dateTimeThisYear($max = 'now', $timezone = null)
* @method \DateTime dateTimeThisMonth($max = 'now', $timezone = null)
*
* @property string $md5
* @property string $sha1
* @property string $sha256
* @property string $locale
* @property string $countryCode
* @property string $countryISOAlpha3
* @property string $languageCode
* @property string $currencyCode
* @property boolean $boolean
* @method boolean boolean($chanceOfGettingTrue = 50)
*
* @property int $randomDigit
* @property int $randomDigitNot
* @property int $randomDigitNotNull
* @property string $randomLetter
* @property string $randomAscii
* @method int randomNumber($nbDigits = null, $strict = false)
* @method int|string|null randomKey(array $array = array())
* @method int numberBetween($min = 0, $max = 2147483647)
* @method float randomFloat($nbMaxDecimals = null, $min = 0, $max = null)
* @method mixed randomElement(array $array = array('a', 'b', 'c'))
* @method array randomElements(array $array = array('a', 'b', 'c'), $count = 1, $allowDuplicates = false)
* @method array|string shuffle($arg = '')
* @method array shuffleArray(array $array = array())
* @method string shuffleString($string = '', $encoding = 'UTF-8')
* @method string numerify($string = '###')
* @method string lexify($string = '????')
* @method string bothify($string = '## ??')
* @method string asciify($string = '****')
* @method string regexify($regex = '')
* @method string toLower($string = '')
* @method string toUpper($string = '')
* @method Generator optional($weight = 0.5, $default = null)
* @method Generator unique($reset = false, $maxRetries = 10000)
* @method Generator valid($validator = null, $maxRetries = 10000)
* @method mixed passthrough($passthrough)
*
* @method integer biasedNumberBetween($min = 0, $max = 100, $function = 'sqrt')
*
* @property string $macProcessor
* @property string $linuxProcessor
* @property string $userAgent
* @property string $chrome
* @property string $firefox
* @property string $safari
* @property string $opera
* @property string $internetExplorer
* @property string $windowsPlatformToken
* @property string $macPlatformToken
* @property string $linuxPlatformToken
*
* @property string $uuid
*
* @property string $mimeType
* @property string $fileExtension
* @method string file($sourceDirectory = '/tmp', $targetDirectory = '/tmp', $fullPath = true)
*
* @method string imageUrl($width = 640, $height = 480, $category = null, $randomize = true, $word = null, $gray = false)
* @method string image($dir = null, $width = 640, $height = 480, $category = null, $fullPath = true, $randomize = true, $word = null)
*
* @property string $hexColor
* @property string $safeHexColor
* @property string $rgbColor
* @property array $rgbColorAsArray
* @property string $rgbCssColor
* @property string $safeColorName
* @property string $colorName
*
* @method string randomHtml($maxDepth = 4, $maxWidth = 4)
*
*/
class Generator
{
protected $providers = array();
protected $formatters = array();
public function addProvider($provider)
{
array_unshift($this->providers, $provider);
}
public function getProviders()
{
return $this->providers;
}
public function seed($seed = null)
{
if ($seed === null) {
mt_srand();
} else {
if (PHP_VERSION_ID < 70100) {
mt_srand((int) $seed);
} else {
mt_srand((int) $seed, MT_RAND_PHP);
}
}
}
public function format($formatter, $arguments = array())
{
return call_user_func_array($this->getFormatter($formatter), $arguments);
}
/**
* @param string $formatter
*
* @return Callable
*/
public function getFormatter($formatter)
{
if (isset($this->formatters[$formatter])) {
return $this->formatters[$formatter];
}
foreach ($this->providers as $provider) {
if (method_exists($provider, $formatter)) {
$this->formatters[$formatter] = array($provider, $formatter);
return $this->formatters[$formatter];
}
}
throw new \InvalidArgumentException(sprintf('Unknown formatter "%s"', $formatter));
}
/**
* Replaces tokens ('{{ tokenName }}') with the result from the token method call
*
* @param string $string String that needs to bet parsed
* @return string
*/
public function parse($string)
{
return preg_replace_callback('/\{\{\s?(\w+)\s?\}\}/u', array($this, 'callFormatWithMatches'), $string);
}
protected function callFormatWithMatches($matches)
{
return $this->format($matches[1]);
}
/**
* @param string $attribute
*
* @return mixed
*/
public function __get($attribute)
{
return $this->format($attribute);
}
/**
* @param string $method
* @param array $attributes
*
* @return mixed
*/
public function __call($method, $attributes)
{
return $this->format($method, $attributes);
}
public function __destruct()
{
$this->seed();
}
}
<?php
namespace Faker\Guesser;
use \Faker\Provider\Base;
class Name
{
protected $generator;
/**
* @param \Faker\Generator $generator
*/
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* @param string $name
* @param int|null $size Length of field, if known
* @return callable
*/
public function guessFormat($name, $size = null)
{
$name = Base::toLower($name);
$generator = $this->generator;
if (preg_match('/^is[_A-Z]/', $name)) {
return function () use ($generator) {
return $generator->boolean;
};
}
if (preg_match('/(_a|A)t$/', $name)) {
return function () use ($generator) {
return $generator->dateTime;
};
}
switch (str_replace('_', '', $name)) {
case 'firstname':
return function () use ($generator) {
return $generator->firstName;
};
case 'lastname':
return function () use ($generator) {
return $generator->lastName;
};
case 'username':
case 'login':
return function () use ($generator) {
return $generator->userName;
};
case 'email':
case 'emailaddress':
return function () use ($generator) {
return $generator->email;
};
case 'phonenumber':
case 'phone':
case 'telephone':
case 'telnumber':
return function () use ($generator) {
return $generator->phoneNumber;
};
case 'address':
return function () use ($generator) {
return $generator->address;
};
case 'city':
case 'town':
return function () use ($generator) {
return $generator->city;
};
case 'streetaddress':
return function () use ($generator) {
return $generator->streetAddress;
};
case 'postcode':
case 'zipcode':
return function () use ($generator) {
return $generator->postcode;
};
case 'state':
return function () use ($generator) {
return $generator->state;
};
case 'county':
if ($this->generator->locale == 'en_US') {
return function () use ($generator) {
return sprintf('%s County', $generator->city);
};
}
return function () use ($generator) {
return $generator->state;
};
case 'country':
switch ($size) {
case 2:
return function () use ($generator) {
return $generator->countryCode;
};
case 3:
return function () use ($generator) {
return $generator->countryISOAlpha3;
};
case 5:
case 6:
return function () use ($generator) {
return $generator->locale;
};
default:
return function () use ($generator) {
return $generator->country;
};
}
break;
case 'locale':
return function () use ($generator) {
return $generator->locale;
};
case 'currency':
case 'currencycode':
return function () use ($generator) {
return $generator->currencyCode;
};
case 'url':
case 'website':
return function () use ($generator) {
return $generator->url;
};
case 'company':
case 'companyname':
case 'employer':
return function () use ($generator) {
return $generator->company;
};
case 'title':
if ($size !== null && $size <= 10) {
return function () use ($generator) {
return $generator->title;
};
}
return function () use ($generator) {
return $generator->sentence;
};
case 'body':
case 'summary':
case 'article':
case 'description':
return function () use ($generator) {
return $generator->text;
};
}
}
}
<?php
namespace Faker\ORM\CakePHP;
class ColumnTypeGuesser
{
protected $generator;
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* @return \Closure|null
*/
public function guessFormat($column, $table)
{
$generator = $this->generator;
$schema = $table->schema();
switch ($schema->columnType($column)) {
case 'boolean':
return function () use ($generator) {
return $generator->boolean;
};
case 'integer':
return function () {
return mt_rand(0, intval('2147483647'));
};
case 'biginteger':
return function () {
return mt_rand(0, intval('9223372036854775807'));
};
case 'decimal':
case 'float':
return function () use ($generator) {
return $generator->randomFloat();
};
case 'uuid':
return function () use ($generator) {
return $generator->uuid();
};
case 'string':
if (method_exists($schema, 'getColumn')) {
$columnData = $schema->getColumn($column);
} else {
$columnData = $schema->column($column);
}
$length = $columnData['length'];
return function () use ($generator, $length) {
return $generator->text($length);
};
case 'text':
return function () use ($generator) {
return $generator->text();
};
case 'date':
case 'datetime':
case 'timestamp':
case 'time':
return function () use ($generator) {
return $generator->datetime();
};
case 'binary':
default:
return null;
}
}
}
<?php
namespace Faker\ORM\CakePHP;
use Cake\ORM\TableRegistry;
class EntityPopulator
{
protected $class;
protected $connectionName;
protected $columnFormatters = [];
protected $modifiers = [];
public function __construct($class)
{
$this->class = $class;
}
/**
* @param string $name
*/
public function __get($name)
{
return $this->{$name};
}
/**
* @param string $name
*/
public function __set($name, $value)
{
$this->{$name} = $value;
}
public function mergeColumnFormattersWith($columnFormatters)
{
$this->columnFormatters = array_merge($this->columnFormatters, $columnFormatters);
}
public function mergeModifiersWith($modifiers)
{
$this->modifiers = array_merge($this->modifiers, $modifiers);
}
/**
* @return array
*/
public function guessColumnFormatters($populator)
{
$formatters = [];
$class = $this->class;
$table = $this->getTable($class);
$schema = $table->schema();
$pk = $schema->primaryKey();
$guessers = $populator->getGuessers() + ['ColumnTypeGuesser' => new ColumnTypeGuesser($populator->getGenerator())];
$isForeignKey = function ($column) use ($table) {
foreach ($table->associations()->type('BelongsTo') as $assoc) {
if ($column == $assoc->foreignKey()) {
return true;
}
}
return false;
};
foreach ($schema->columns() as $column) {
if ($column == $pk[0] || $isForeignKey($column)) {
continue;
}
foreach ($guessers as $guesser) {
if ($formatter = $guesser->guessFormat($column, $table)) {
$formatters[$column] = $formatter;
break;
}
}
}
return $formatters;
}
/**
* @return array
*/
public function guessModifiers()
{
$modifiers = [];
$table = $this->getTable($this->class);
$belongsTo = $table->associations()->type('BelongsTo');
foreach ($belongsTo as $assoc) {
$modifiers['belongsTo' . $assoc->name()] = function ($data, $insertedEntities) use ($assoc) {
$table = $assoc->target();
$foreignModel = $table->alias();
$foreignKeys = [];
if (!empty($insertedEntities[$foreignModel])) {
$foreignKeys = $insertedEntities[$foreignModel];
} else {
$foreignKeys = $table->find('all')
->select(['id'])
->map(function ($row) {
return $row->id;
})
->toArray();
}
if (empty($foreignKeys)) {
throw new \Exception(sprintf('%s belongsTo %s, which seems empty at this point.', $this->getTable($this->class)->table(), $assoc->table()));
}
$foreignKey = $foreignKeys[array_rand($foreignKeys)];
$data[$assoc->foreignKey()] = $foreignKey;
return $data;
};
}
// TODO check if TreeBehavior attached to modify lft/rgt cols
return $modifiers;
}
/**
* @param array $options
*/
public function execute($class, $insertedEntities, $options = [])
{
$table = $this->getTable($class);
$entity = $table->newEntity();
foreach ($this->columnFormatters as $column => $format) {
if (!is_null($format)) {
$entity->{$column} = is_callable($format) ? $format($insertedEntities, $table) : $format;
}
}
foreach ($this->modifiers as $modifier) {
$entity = $modifier($entity, $insertedEntities);
}
if (!$entity = $table->save($entity, $options)) {
throw new \RuntimeException("Failed saving $class record");
}
$pk = $table->primaryKey();
if (is_string($pk)) {
return $entity->{$pk};
}
return $entity->{$pk[0]};
}
public function setConnection($name)
{
$this->connectionName = $name;
}
protected function getTable($class)
{
$options = [];
if (!empty($this->connectionName)) {
$options['connection'] = $this->connectionName;
}
return TableRegistry::get($class, $options);
}
}
<?php
namespace Faker\ORM\CakePHP;
class Populator
{
protected $generator;
protected $entities = [];
protected $quantities = [];
protected $guessers = [];
/**
* @param \Faker\Generator $generator
*/
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* @return \Faker\Generator
*/
public function getGenerator()
{
return $this->generator;
}
/**
* @return array
*/
public function getGuessers()
{
return $this->guessers;
}
/**
* @return $this
*/
public function removeGuesser($name)
{
if ($this->guessers[$name]) {
unset($this->guessers[$name]);
}
return $this;
}
/**
* @return $this
* @throws \Exception
*/
public function addGuesser($class)
{
if (!is_object($class)) {
$class = new $class($this->generator);
}
if (!method_exists($class, 'guessFormat')) {
throw new \Exception('Missing required custom guesser method: ' . get_class($class) . '::guessFormat()');
}
$this->guessers[get_class($class)] = $class;
return $this;
}
/**
* @param array $customColumnFormatters
* @param array $customModifiers
* @return $this
*/
public function addEntity($entity, $number, $customColumnFormatters = [], $customModifiers = [])
{
if (!$entity instanceof EntityPopulator) {
$entity = new EntityPopulator($entity);
}
$entity->columnFormatters = $entity->guessColumnFormatters($this);
if ($customColumnFormatters) {
$entity->mergeColumnFormattersWith($customColumnFormatters);
}
$entity->modifiers = $entity->guessModifiers($this);
if ($customModifiers) {
$entity->mergeModifiersWith($customModifiers);
}
$class = $entity->class;
$this->entities[$class] = $entity;
$this->quantities[$class] = $number;
return $this;
}
/**
* @param array $options
* @return array
*/
public function execute($options = [])
{
$insertedEntities = [];
foreach ($this->quantities as $class => $number) {
for ($i = 0; $i < $number; $i++) {
$insertedEntities[$class][] = $this->entities[$class]->execute($class, $insertedEntities, $options);
}
}
return $insertedEntities;
}
}
<?php
namespace Faker\ORM\Doctrine;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
class ColumnTypeGuesser
{
protected $generator;
/**
* @param \Faker\Generator $generator
*/
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* @param ClassMetadata $class
* @return \Closure|null
*/
public function guessFormat($fieldName, ClassMetadata $class)
{
$generator = $this->generator;
$type = $class->getTypeOfField($fieldName);
switch ($type) {
case 'boolean':
return function () use ($generator) {
return $generator->boolean;
};
case 'decimal':
$size = isset($class->fieldMappings[$fieldName]['precision']) ? $class->fieldMappings[$fieldName]['precision'] : 2;
return function () use ($generator, $size) {
return $generator->randomNumber($size + 2) / 100;
};
case 'smallint':
return function () {
return mt_rand(0, 65535);
};
case 'integer':
return function () {
return mt_rand(0, intval('2147483647'));
};
case 'bigint':
return function () {
return mt_rand(0, intval('18446744073709551615'));
};
case 'float':
return function () {
return mt_rand(0, intval('4294967295'))/mt_rand(1, intval('4294967295'));
};
case 'string':
$size = isset($class->fieldMappings[$fieldName]['length']) ? $class->fieldMappings[$fieldName]['length'] : 255;
return function () use ($generator, $size) {
return $generator->text($size);
};
case 'text':
return function () use ($generator) {
return $generator->text;
};
case 'datetime':
case 'date':
case 'time':
return function () use ($generator) {
return $generator->datetime;
};
case 'datetime_immutable':
case 'date_immutable':
case 'time_immutable':
return function () use ($generator) {
return \DateTimeImmutable::createFromMutable($generator->datetime);
};
default:
// no smart way to guess what the user expects here
return null;
}
}
}
<?php
namespace Faker\ORM\Doctrine;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
/**
* Service class for populating a table through a Doctrine Entity class.
*/
class EntityPopulator
{
/**
* @var ClassMetadata
*/
protected $class;
/**
* @var array
*/
protected $columnFormatters = array();
/**
* @var array
*/
protected $modifiers = array();
/**
* Class constructor.
*
* @param ClassMetadata $class
*/
public function __construct(ClassMetadata $class)
{
$this->class = $class;
}
/**
* @return string
*/
public function getClass()
{
return $this->class->getName();
}
/**
* @param $columnFormatters
*/
public function setColumnFormatters($columnFormatters)
{
$this->columnFormatters = $columnFormatters;
}
/**
* @return array
*/
public function getColumnFormatters()
{
return $this->columnFormatters;
}
public function mergeColumnFormattersWith($columnFormatters)
{
$this->columnFormatters = array_merge($this->columnFormatters, $columnFormatters);
}
/**
* @param array $modifiers
*/
public function setModifiers(array $modifiers)
{
$this->modifiers = $modifiers;
}
/**
* @return array
*/
public function getModifiers()
{
return $this->modifiers;
}
/**
* @param array $modifiers
*/
public function mergeModifiersWith(array $modifiers)
{
$this->modifiers = array_merge($this->modifiers, $modifiers);
}
/**
* @param \Faker\Generator $generator
* @return array
*/
public function guessColumnFormatters(\Faker\Generator $generator)
{
$formatters = array();
$nameGuesser = new \Faker\Guesser\Name($generator);
$columnTypeGuesser = new ColumnTypeGuesser($generator);
foreach ($this->class->getFieldNames() as $fieldName) {
if ($this->class->isIdentifier($fieldName) || !$this->class->hasField($fieldName)) {
continue;
}
$size = isset($this->class->fieldMappings[$fieldName]['length']) ? $this->class->fieldMappings[$fieldName]['length'] : null;
if ($formatter = $nameGuesser->guessFormat($fieldName, $size)) {
$formatters[$fieldName] = $formatter;
continue;
}
if ($formatter = $columnTypeGuesser->guessFormat($fieldName, $this->class)) {
$formatters[$fieldName] = $formatter;
continue;
}
}
foreach ($this->class->getAssociationNames() as $assocName) {
if ($this->class->isCollectionValuedAssociation($assocName)) {
continue;
}
$relatedClass = $this->class->getAssociationTargetClass($assocName);
$unique = $optional = false;
if ($this->class instanceof \Doctrine\ORM\Mapping\ClassMetadata) {
$mappings = $this->class->getAssociationMappings();
foreach ($mappings as $mapping) {
if ($mapping['targetEntity'] == $relatedClass) {
if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadata::ONE_TO_ONE) {
$unique = true;
$optional = isset($mapping['joinColumns'][0]['nullable']) ? $mapping['joinColumns'][0]['nullable'] : false;
break;
}
}
}
} elseif ($this->class instanceof \Doctrine\ODM\MongoDB\Mapping\ClassMetadata) {
$mappings = $this->class->associationMappings;
foreach ($mappings as $mapping) {
if ($mapping['targetDocument'] == $relatedClass) {
if ($mapping['type'] == \Doctrine\ODM\MongoDB\Mapping\ClassMetadata::ONE && $mapping['association'] == \Doctrine\ODM\MongoDB\Mapping\ClassMetadata::REFERENCE_ONE) {
$unique = true;
$optional = isset($mapping['nullable']) ? $mapping['nullable'] : false;
break;
}
}
}
}
$index = 0;
$formatters[$assocName] = function ($inserted) use ($relatedClass, &$index, $unique, $optional) {
if (isset($inserted[$relatedClass])) {
if ($unique) {
$related = null;
if (isset($inserted[$relatedClass][$index]) || !$optional) {
$related = $inserted[$relatedClass][$index];
}
$index++;
return $related;
}
return $inserted[$relatedClass][mt_rand(0, count($inserted[$relatedClass]) - 1)];
}
return null;
};
}
return $formatters;
}
/**
* Insert one new record using the Entity class.
* @param ObjectManager $manager
* @param bool $generateId
* @return EntityPopulator
*/
public function execute(ObjectManager $manager, $insertedEntities, $generateId = false)
{
$obj = $this->class->newInstance();
$this->fillColumns($obj, $insertedEntities);
$this->callMethods($obj, $insertedEntities);
if ($generateId) {
$idsName = $this->class->getIdentifier();
foreach ($idsName as $idName) {
$id = $this->generateId($obj, $idName, $manager);
$this->class->reflFields[$idName]->setValue($obj, $id);
}
}
$manager->persist($obj);
return $obj;
}
private function fillColumns($obj, $insertedEntities)
{
foreach ($this->columnFormatters as $field => $format) {
if (null !== $format) {
// Add some extended debugging information to any errors thrown by the formatter
try {
$value = is_callable($format) ? $format($insertedEntities, $obj) : $format;
} catch (\InvalidArgumentException $ex) {
throw new \InvalidArgumentException(sprintf(
"Failed to generate a value for %s::%s: %s",
get_class($obj),
$field,
$ex->getMessage()
));
}
// Try a standard setter if it's available, otherwise fall back on reflection
$setter = sprintf("set%s", ucfirst($field));
if (is_callable(array($obj, $setter))) {
$obj->$setter($value);
} else {
$this->class->reflFields[$field]->setValue($obj, $value);
}
}
}
}
private function callMethods($obj, $insertedEntities)
{
foreach ($this->getModifiers() as $modifier) {
$modifier($obj, $insertedEntities);
}
}
/**
* @param ObjectManager $manager
* @return int|null
*/
private function generateId($obj, $column, ObjectManager $manager)
{
/* @var $repository \Doctrine\Common\Persistence\ObjectRepository */
$repository = $manager->getRepository(get_class($obj));
$result = $repository->createQueryBuilder('e')
->select(sprintf('e.%s', $column))
->getQuery()
->execute();
$ids = array_map('current', $result->toArray());
$id = null;
do {
$id = mt_rand();
} while (in_array($id, $ids));
return $id;
}
}
<?php
namespace Faker\ORM\Doctrine;
use Doctrine\Common\Persistence\ObjectManager;
use Faker\Generator;
/**
* Service class for populating a database using the Doctrine ORM or ODM.
* A Populator can populate several tables using ActiveRecord classes.
*/
class Populator
{
/** @var int */
protected $batchSize;
/** @var Generator */
protected $generator;
/** @var ObjectManager|null */
protected $manager;
/** @var array */
protected $entities = array();
/** @var array */
protected $quantities = array();
/** @var array */
protected $generateId = array();
/**
* Populator constructor.
* @param Generator $generator
* @param ObjectManager|null $manager
* @param int $batchSize
*/
public function __construct(Generator $generator, ObjectManager $manager = null, $batchSize = 1000)
{
$this->generator = $generator;
$this->manager = $manager;
$this->batchSize = $batchSize;
}
/**
* Add an order for the generation of $number records for $entity.
*
* @param mixed $entity A Doctrine classname, or a \Faker\ORM\Doctrine\EntityPopulator instance
* @param int $number The number of entities to populate
*/
public function addEntity($entity, $number, $customColumnFormatters = array(), $customModifiers = array(), $generateId = false)
{
if (!$entity instanceof \Faker\ORM\Doctrine\EntityPopulator) {
if (null === $this->manager) {
throw new \InvalidArgumentException("No entity manager passed to Doctrine Populator.");
}
$entity = new \Faker\ORM\Doctrine\EntityPopulator($this->manager->getClassMetadata($entity));
}
$entity->setColumnFormatters($entity->guessColumnFormatters($this->generator));
if ($customColumnFormatters) {
$entity->mergeColumnFormattersWith($customColumnFormatters);
}
$entity->mergeModifiersWith($customModifiers);
$this->generateId[$entity->getClass()] = $generateId;
$class = $entity->getClass();
$this->entities[$class] = $entity;
$this->quantities[$class] = $number;
}
/**
* Populate the database using all the Entity classes previously added.
*
* Please note that large amounts of data will result in more memory usage since the the Populator will return
* all newly created primary keys after executing.
*
* @param null|EntityManager $entityManager A Doctrine connection object
*
* @return array A list of the inserted PKs
*/
public function execute($entityManager = null)
{
if (null === $entityManager) {
$entityManager = $this->manager;
}
if (null === $entityManager) {
throw new \InvalidArgumentException("No entity manager passed to Doctrine Populator.");
}
$insertedEntities = array();
foreach ($this->quantities as $class => $number) {
$generateId = $this->generateId[$class];
for ($i=0; $i < $number; $i++) {
$insertedEntities[$class][]= $this->entities[$class]->execute(
$entityManager,
$insertedEntities,
$generateId
);
if (count($insertedEntities) % $this->batchSize === 0) {
$entityManager->flush();
$entityManager->clear($class);
}
}
$entityManager->flush();
$entityManager->clear($class);
}
return $insertedEntities;
}
}
<?php
namespace Faker\ORM\Mandango;
class ColumnTypeGuesser
{
protected $generator;
/**
* @param \Faker\Generator $generator
*/
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* @return \Closure|null
*/
public function guessFormat($field)
{
$generator = $this->generator;
switch ($field['type']) {
case 'boolean':
return function () use ($generator) {
return $generator->boolean;
};
case 'integer':
return function () {
return mt_rand(0, intval('4294967295'));
};
case 'float':
return function () {
return mt_rand(0, intval('4294967295'))/mt_rand(1, intval('4294967295'));
};
case 'string':
return function () use ($generator) {
return $generator->text(255);
};
case 'date':
return function () use ($generator) {
return $generator->datetime;
};
default:
// no smart way to guess what the user expects here
return null;
}
}
}
<?php
namespace Faker\ORM\Mandango;
use Mandango\Mandango;
use Faker\Provider\Base;
/**
* Service class for populating a table through a Mandango ActiveRecord class.
*/
class EntityPopulator
{
protected $class;
protected $columnFormatters = array();
/**
* Class constructor.
*
* @param string $class A Mandango ActiveRecord classname
*/
public function __construct($class)
{
$this->class = $class;
}
/**
* @return string
*/
public function getClass()
{
return $this->class;
}
public function setColumnFormatters($columnFormatters)
{
$this->columnFormatters = $columnFormatters;
}
/**
* @return array
*/
public function getColumnFormatters()
{
return $this->columnFormatters;
}
public function mergeColumnFormattersWith($columnFormatters)
{
$this->columnFormatters = array_merge($this->columnFormatters, $columnFormatters);
}
/**
* @param \Faker\Generator $generator
* @param Mandango $mandango
* @return array
*/
public function guessColumnFormatters(\Faker\Generator $generator, Mandango $mandango)
{
$formatters = array();
$nameGuesser = new \Faker\Guesser\Name($generator);
$columnTypeGuesser = new \Faker\ORM\Mandango\ColumnTypeGuesser($generator);
$metadata = $mandango->getMetadata($this->class);
// fields
foreach ($metadata['fields'] as $fieldName => $field) {
if ($formatter = $nameGuesser->guessFormat($fieldName)) {
$formatters[$fieldName] = $formatter;
continue;
}
if ($formatter = $columnTypeGuesser->guessFormat($field)) {
$formatters[$fieldName] = $formatter;
continue;
}
}
// references
foreach (array_merge($metadata['referencesOne'], $metadata['referencesMany']) as $referenceName => $reference) {
if (!isset($reference['class'])) {
continue;
}
$referenceClass = $reference['class'];
$formatters[$referenceName] = function ($insertedEntities) use ($referenceClass) {
if (isset($insertedEntities[$referenceClass])) {
return Base::randomElement($insertedEntities[$referenceClass]);
}
};
}
return $formatters;
}
/**
* Insert one new record using the Entity class.
* @param Mandango $mandango
*/
public function execute(Mandango $mandango, $insertedEntities)
{
$metadata = $mandango->getMetadata($this->class);
$obj = $mandango->create($this->class);
foreach ($this->columnFormatters as $column => $format) {
if (null !== $format) {
$value = is_callable($format) ? $format($insertedEntities, $obj) : $format;
if (isset($metadata['fields'][$column]) ||
isset($metadata['referencesOne'][$column])) {
$obj->set($column, $value);
}
if (isset($metadata['referencesMany'][$column])) {
$adder = 'add'.ucfirst($column);
$obj->$adder($value);
}
}
}
$mandango->persist($obj);
return $obj;
}
}
<?php
namespace Faker\ORM\Mandango;
use Mandango\Mandango;
/**
* Service class for populating a database using Mandango.
* A Populator can populate several tables using ActiveRecord classes.
*/
class Populator
{
protected $generator;
protected $mandango;
protected $entities = array();
protected $quantities = array();
/**
* @param \Faker\Generator $generator
* @param Mandango $mandango
*/
public function __construct(\Faker\Generator $generator, Mandango $mandango)
{
$this->generator = $generator;
$this->mandango = $mandango;
}
/**
* Add an order for the generation of $number records for $entity.
*
* @param mixed $entity A Propel ActiveRecord classname, or a \Faker\ORM\Propel\EntityPopulator instance
* @param int $number The number of entities to populate
*/
public function addEntity($entity, $number, $customColumnFormatters = array())
{
if (!$entity instanceof \Faker\ORM\Mandango\EntityPopulator) {
$entity = new \Faker\ORM\Mandango\EntityPopulator($entity);
}
$entity->setColumnFormatters($entity->guessColumnFormatters($this->generator, $this->mandango));
if ($customColumnFormatters) {
$entity->mergeColumnFormattersWith($customColumnFormatters);
}
$class = $entity->getClass();
$this->entities[$class] = $entity;
$this->quantities[$class] = $number;
}
/**
* Populate the database using all the Entity classes previously added.
*
* @return array A list of the inserted entities.
*/
public function execute()
{
$insertedEntities = array();
foreach ($this->quantities as $class => $number) {
for ($i=0; $i < $number; $i++) {
$insertedEntities[$class][]= $this->entities[$class]->execute($this->mandango, $insertedEntities);
}
}
$this->mandango->flush();
return $insertedEntities;
}
}
<?php
namespace Faker\ORM\Propel;
use \PropelColumnTypes;
use \ColumnMap;
class ColumnTypeGuesser
{
protected $generator;
/**
* @param \Faker\Generator $generator
*/
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* @param ColumnMap $column
* @return \Closure|null
*/
public function guessFormat(ColumnMap $column)
{
$generator = $this->generator;
if ($column->isTemporal()) {
if ($column->isEpochTemporal()) {
return function () use ($generator) {
return $generator->dateTime;
};
}
return function () use ($generator) {
return $generator->dateTimeAD;
};
}
$type = $column->getType();
switch ($type) {
case PropelColumnTypes::BOOLEAN:
case PropelColumnTypes::BOOLEAN_EMU:
return function () use ($generator) {
return $generator->boolean;
};
case PropelColumnTypes::NUMERIC:
case PropelColumnTypes::DECIMAL:
$size = $column->getSize();
return function () use ($generator, $size) {
return $generator->randomNumber($size + 2) / 100;
};
case PropelColumnTypes::TINYINT:
return function () {
return mt_rand(0, 127);
};
case PropelColumnTypes::SMALLINT:
return function () {
return mt_rand(0, 32767);
};
case PropelColumnTypes::INTEGER:
return function () {
return mt_rand(0, intval('2147483647'));
};
case PropelColumnTypes::BIGINT:
return function () {
return mt_rand(0, intval('9223372036854775807'));
};
case PropelColumnTypes::FLOAT:
return function () {
return mt_rand(0, intval('2147483647'))/mt_rand(1, intval('2147483647'));
};
case PropelColumnTypes::DOUBLE:
case PropelColumnTypes::REAL:
return function () {
return mt_rand(0, intval('9223372036854775807'))/mt_rand(1, intval('9223372036854775807'));
};
case PropelColumnTypes::CHAR:
case PropelColumnTypes::VARCHAR:
case PropelColumnTypes::BINARY:
case PropelColumnTypes::VARBINARY:
$size = $column->getSize();
return function () use ($generator, $size) {
return $generator->text($size);
};
case PropelColumnTypes::LONGVARCHAR:
case PropelColumnTypes::LONGVARBINARY:
case PropelColumnTypes::CLOB:
case PropelColumnTypes::CLOB_EMU:
case PropelColumnTypes::BLOB:
return function () use ($generator) {
return $generator->text;
};
case PropelColumnTypes::ENUM:
$valueSet = $column->getValueSet();
return function () use ($generator, $valueSet) {
return $generator->randomElement($valueSet);
};
case PropelColumnTypes::OBJECT:
case PropelColumnTypes::PHP_ARRAY:
default:
// no smart way to guess what the user expects here
return null;
}
}
}
<?php
namespace Faker\ORM\Propel;
use \Faker\Provider\Base;
use \ColumnMap;
/**
* Service class for populating a table through a Propel ActiveRecord class.
*/
class EntityPopulator
{
protected $class;
protected $columnFormatters = array();
protected $modifiers = array();
/**
* Class constructor.
*
* @param string $class A Propel ActiveRecord classname
*/
public function __construct($class)
{
$this->class = $class;
}
/**
* @return string
*/
public function getClass()
{
return $this->class;
}
public function setColumnFormatters($columnFormatters)
{
$this->columnFormatters = $columnFormatters;
}
/**
* @return array
*/
public function getColumnFormatters()
{
return $this->columnFormatters;
}
public function mergeColumnFormattersWith($columnFormatters)
{
$this->columnFormatters = array_merge($this->columnFormatters, $columnFormatters);
}
/**
* @param \Faker\Generator $generator
* @return array
*/
public function guessColumnFormatters(\Faker\Generator $generator)
{
$formatters = array();
$class = $this->class;
$peerClass = $class::PEER;
$tableMap = $peerClass::getTableMap();
$nameGuesser = new \Faker\Guesser\Name($generator);
$columnTypeGuesser = new \Faker\ORM\Propel\ColumnTypeGuesser($generator);
foreach ($tableMap->getColumns() as $columnMap) {
// skip behavior columns, handled by modifiers
if ($this->isColumnBehavior($columnMap)) {
continue;
}
if ($columnMap->isForeignKey()) {
$relatedClass = $columnMap->getRelation()->getForeignTable()->getClassname();
$formatters[$columnMap->getPhpName()] = function ($inserted) use ($relatedClass) {
return isset($inserted[$relatedClass]) ? $inserted[$relatedClass][mt_rand(0, count($inserted[$relatedClass]) - 1)] : null;
};
continue;
}
if ($columnMap->isPrimaryKey()) {
continue;
}
if ($formatter = $nameGuesser->guessFormat($columnMap->getPhpName(), $columnMap->getSize())) {
$formatters[$columnMap->getPhpName()] = $formatter;
continue;
}
if ($formatter = $columnTypeGuesser->guessFormat($columnMap)) {
$formatters[$columnMap->getPhpName()] = $formatter;
continue;
}
}
return $formatters;
}
/**
* @param ColumnMap $columnMap
* @return bool
*/
protected function isColumnBehavior(ColumnMap $columnMap)
{
foreach ($columnMap->getTable()->getBehaviors() as $name => $params) {
$columnName = Base::toLower($columnMap->getName());
switch ($name) {
case 'nested_set':
$columnNames = array($params['left_column'], $params['right_column'], $params['level_column']);
if (in_array($columnName, $columnNames)) {
return true;
}
break;
case 'timestampable':
$columnNames = array($params['create_column'], $params['update_column']);
if (in_array($columnName, $columnNames)) {
return true;
}
break;
}
}
return false;
}
public function setModifiers($modifiers)
{
$this->modifiers = $modifiers;
}
/**
* @return array
*/
public function getModifiers()
{
return $this->modifiers;
}
public function mergeModifiersWith($modifiers)
{
$this->modifiers = array_merge($this->modifiers, $modifiers);
}
/**
* @param \Faker\Generator $generator
* @return array
*/
public function guessModifiers(\Faker\Generator $generator)
{
$modifiers = array();
$class = $this->class;
$peerClass = $class::PEER;
$tableMap = $peerClass::getTableMap();
foreach ($tableMap->getBehaviors() as $name => $params) {
switch ($name) {
case 'nested_set':
$modifiers['nested_set'] = function ($obj, $inserted) use ($class, $generator) {
if (isset($inserted[$class])) {
$queryClass = $class . 'Query';
$parent = $queryClass::create()->findPk($generator->randomElement($inserted[$class]));
$obj->insertAsLastChildOf($parent);
} else {
$obj->makeRoot();
}
};
break;
case 'sortable':
$modifiers['sortable'] = function ($obj, $inserted) use ($class) {
$maxRank = isset($inserted[$class]) ? count($inserted[$class]) : 0;
$obj->insertAtRank(mt_rand(1, $maxRank + 1));
};
break;
}
}
return $modifiers;
}
/**
* Insert one new record using the Entity class.
*/
public function execute($con, $insertedEntities)
{
$obj = new $this->class();
foreach ($this->getColumnFormatters() as $column => $format) {
if (null !== $format) {
$obj->setByName($column, is_callable($format) ? $format($insertedEntities, $obj) : $format);
}
}
foreach ($this->getModifiers() as $modifier) {
$modifier($obj, $insertedEntities);
}
$obj->save($con);
return $obj->getPrimaryKey();
}
}
<?php
namespace Faker\ORM\Propel;
/**
* Service class for populating a database using the Propel ORM.
* A Populator can populate several tables using ActiveRecord classes.
*/
class Populator
{
protected $generator;
protected $entities = array();
protected $quantities = array();
/**
* @param \Faker\Generator $generator
*/
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* Add an order for the generation of $number records for $entity.
*
* @param mixed $entity A Propel ActiveRecord classname, or a \Faker\ORM\Propel\EntityPopulator instance
* @param int $number The number of entities to populate
*/
public function addEntity($entity, $number, $customColumnFormatters = array(), $customModifiers = array())
{
if (!$entity instanceof \Faker\ORM\Propel\EntityPopulator) {
$entity = new \Faker\ORM\Propel\EntityPopulator($entity);
}
$entity->setColumnFormatters($entity->guessColumnFormatters($this->generator));
if ($customColumnFormatters) {
$entity->mergeColumnFormattersWith($customColumnFormatters);
}
$entity->setModifiers($entity->guessModifiers($this->generator));
if ($customModifiers) {
$entity->mergeModifiersWith($customModifiers);
}
$class = $entity->getClass();
$this->entities[$class] = $entity;
$this->quantities[$class] = $number;
}
/**
* Populate the database using all the Entity classes previously added.
*
* @param PropelPDO $con A Propel connection object
*
* @return array A list of the inserted PKs
*/
public function execute($con = null)
{
if (null === $con) {
$con = $this->getConnection();
}
$isInstancePoolingEnabled = \Propel::isInstancePoolingEnabled();
\Propel::disableInstancePooling();
$insertedEntities = array();
$con->beginTransaction();
foreach ($this->quantities as $class => $number) {
for ($i=0; $i < $number; $i++) {
$insertedEntities[$class][]= $this->entities[$class]->execute($con, $insertedEntities);
}
}
$con->commit();
if ($isInstancePoolingEnabled) {
\Propel::enableInstancePooling();
}
return $insertedEntities;
}
protected function getConnection()
{
// use the first connection available
$class = key($this->entities);
if (!$class) {
throw new \RuntimeException('No class found from entities. Did you add entities to the Populator ?');
}
$peer = $class::PEER;
return \Propel::getConnection($peer::DATABASE_NAME, \Propel::CONNECTION_WRITE);
}
}
<?php
namespace Faker\ORM\Propel2;
use \Propel\Generator\Model\PropelTypes;
use \Propel\Runtime\Map\ColumnMap;
class ColumnTypeGuesser
{
protected $generator;
/**
* @param \Faker\Generator $generator
*/
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* @param ColumnMap $column
* @return \Closure|null
*/
public function guessFormat(ColumnMap $column)
{
$generator = $this->generator;
if ($column->isTemporal()) {
if ($column->getType() == PropelTypes::BU_DATE || $column->getType() == PropelTypes::BU_TIMESTAMP) {
return function () use ($generator) {
return $generator->dateTime;
};
}
return function () use ($generator) {
return $generator->dateTimeAD;
};
}
$type = $column->getType();
switch ($type) {
case PropelTypes::BOOLEAN:
case PropelTypes::BOOLEAN_EMU:
return function () use ($generator) {
return $generator->boolean;
};
case PropelTypes::NUMERIC:
case PropelTypes::DECIMAL:
$size = $column->getSize();
return function () use ($generator, $size) {
return $generator->randomNumber($size + 2) / 100;
};
case PropelTypes::TINYINT:
return function () {
return mt_rand(0, 127);
};
case PropelTypes::SMALLINT:
return function () {
return mt_rand(0, 32767);
};
case PropelTypes::INTEGER:
return function () {
return mt_rand(0, intval('2147483647'));
};
case PropelTypes::BIGINT:
return function () {
return mt_rand(0, intval('9223372036854775807'));
};
case PropelTypes::FLOAT:
return function () {
return mt_rand(0, intval('2147483647'))/mt_rand(1, intval('2147483647'));
};
case PropelTypes::DOUBLE:
case PropelTypes::REAL:
return function () {
return mt_rand(0, intval('9223372036854775807'))/mt_rand(1, intval('9223372036854775807'));
};
case PropelTypes::CHAR:
case PropelTypes::VARCHAR:
case PropelTypes::BINARY:
case PropelTypes::VARBINARY:
$size = $column->getSize();
return function () use ($generator, $size) {
return $generator->text($size);
};
case PropelTypes::LONGVARCHAR:
case PropelTypes::LONGVARBINARY:
case PropelTypes::CLOB:
case PropelTypes::CLOB_EMU:
case PropelTypes::BLOB:
return function () use ($generator) {
return $generator->text;
};
case PropelTypes::ENUM:
$valueSet = $column->getValueSet();
return function () use ($generator, $valueSet) {
return $generator->randomElement($valueSet);
};
case PropelTypes::OBJECT:
case PropelTypes::PHP_ARRAY:
default:
// no smart way to guess what the user expects here
return null;
}
}
}
<?php
namespace Faker\ORM\Propel2;
use \Faker\Provider\Base;
use \Propel\Runtime\Map\ColumnMap;
/**
* Service class for populating a table through a Propel ActiveRecord class.
*/
class EntityPopulator
{
protected $class;
protected $columnFormatters = array();
protected $modifiers = array();
/**
* Class constructor.
*
* @param string $class A Propel ActiveRecord classname
*/
public function __construct($class)
{
$this->class = $class;
}
/**
* @return string
*/
public function getClass()
{
return $this->class;
}
public function setColumnFormatters($columnFormatters)
{
$this->columnFormatters = $columnFormatters;
}
/**
* @return array
*/
public function getColumnFormatters()
{
return $this->columnFormatters;
}
public function mergeColumnFormattersWith($columnFormatters)
{
$this->columnFormatters = array_merge($this->columnFormatters, $columnFormatters);
}
/**
* @param \Faker\Generator $generator
* @return array
*/
public function guessColumnFormatters(\Faker\Generator $generator)
{
$formatters = array();
$class = $this->class;
$peerClass = $class::TABLE_MAP;
$tableMap = $peerClass::getTableMap();
$nameGuesser = new \Faker\Guesser\Name($generator);
$columnTypeGuesser = new \Faker\ORM\Propel2\ColumnTypeGuesser($generator);
foreach ($tableMap->getColumns() as $columnMap) {
// skip behavior columns, handled by modifiers
if ($this->isColumnBehavior($columnMap)) {
continue;
}
if ($columnMap->isForeignKey()) {
$relatedClass = $columnMap->getRelation()->getForeignTable()->getClassname();
$formatters[$columnMap->getPhpName()] = function ($inserted) use ($relatedClass) {
$relatedClass = trim($relatedClass, "\\");
return isset($inserted[$relatedClass]) ? $inserted[$relatedClass][mt_rand(0, count($inserted[$relatedClass]) - 1)] : null;
};
continue;
}
if ($columnMap->isPrimaryKey()) {
continue;
}
if ($formatter = $nameGuesser->guessFormat($columnMap->getPhpName(), $columnMap->getSize())) {
$formatters[$columnMap->getPhpName()] = $formatter;
continue;
}
if ($formatter = $columnTypeGuesser->guessFormat($columnMap)) {
$formatters[$columnMap->getPhpName()] = $formatter;
continue;
}
}
return $formatters;
}
/**
* @param ColumnMap $columnMap
* @return bool
*/
protected function isColumnBehavior(ColumnMap $columnMap)
{
foreach ($columnMap->getTable()->getBehaviors() as $name => $params) {
$columnName = Base::toLower($columnMap->getName());
switch ($name) {
case 'nested_set':
$columnNames = array($params['left_column'], $params['right_column'], $params['level_column']);
if (in_array($columnName, $columnNames)) {
return true;
}
break;
case 'timestampable':
$columnNames = array($params['create_column'], $params['update_column']);
if (in_array($columnName, $columnNames)) {
return true;
}
break;
}
}
return false;
}
public function setModifiers($modifiers)
{
$this->modifiers = $modifiers;
}
/**
* @return array
*/
public function getModifiers()
{
return $this->modifiers;
}
public function mergeModifiersWith($modifiers)
{
$this->modifiers = array_merge($this->modifiers, $modifiers);
}
/**
* @param \Faker\Generator $generator
* @return array
*/
public function guessModifiers(\Faker\Generator $generator)
{
$modifiers = array();
$class = $this->class;
$peerClass = $class::TABLE_MAP;
$tableMap = $peerClass::getTableMap();
foreach ($tableMap->getBehaviors() as $name => $params) {
switch ($name) {
case 'nested_set':
$modifiers['nested_set'] = function ($obj, $inserted) use ($class, $generator) {
if (isset($inserted[$class])) {
$queryClass = $class . 'Query';
$parent = $queryClass::create()->findPk($generator->randomElement($inserted[$class]));
$obj->insertAsLastChildOf($parent);
} else {
$obj->makeRoot();
}
};
break;
case 'sortable':
$modifiers['sortable'] = function ($obj, $inserted) use ($class) {
$maxRank = isset($inserted[$class]) ? count($inserted[$class]) : 0;
$obj->insertAtRank(mt_rand(1, $maxRank + 1));
};
break;
}
}
return $modifiers;
}
/**
* Insert one new record using the Entity class.
*/
public function execute($con, $insertedEntities)
{
$obj = new $this->class();
foreach ($this->getColumnFormatters() as $column => $format) {
if (null !== $format) {
$obj->setByName($column, is_callable($format) ? $format($insertedEntities, $obj) : $format);
}
}
foreach ($this->getModifiers() as $modifier) {
$modifier($obj, $insertedEntities);
}
$obj->save($con);
return $obj->getPrimaryKey();
}
}
<?php
namespace Faker\ORM\Propel2;
use Propel\Runtime\Propel;
use Propel\Runtime\ServiceContainer\ServiceContainerInterface;
/**
* Service class for populating a database using the Propel ORM.
* A Populator can populate several tables using ActiveRecord classes.
*/
class Populator
{
protected $generator;
protected $entities = array();
protected $quantities = array();
/**
* @param \Faker\Generator $generator
*/
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* Add an order for the generation of $number records for $entity.
*
* @param mixed $entity A Propel ActiveRecord classname, or a \Faker\ORM\Propel2\EntityPopulator instance
* @param int $number The number of entities to populate
*/
public function addEntity($entity, $number, $customColumnFormatters = array(), $customModifiers = array())
{
if (!$entity instanceof \Faker\ORM\Propel2\EntityPopulator) {
$entity = new \Faker\ORM\Propel2\EntityPopulator($entity);
}
$entity->setColumnFormatters($entity->guessColumnFormatters($this->generator));
if ($customColumnFormatters) {
$entity->mergeColumnFormattersWith($customColumnFormatters);
}
$entity->setModifiers($entity->guessModifiers($this->generator));
if ($customModifiers) {
$entity->mergeModifiersWith($customModifiers);
}
$class = $entity->getClass();
$this->entities[$class] = $entity;
$this->quantities[$class] = $number;
}
/**
* Populate the database using all the Entity classes previously added.
*
* @param PropelPDO $con A Propel connection object
*
* @return array A list of the inserted PKs
*/
public function execute($con = null)
{
if (null === $con) {
$con = $this->getConnection();
}
$isInstancePoolingEnabled = Propel::isInstancePoolingEnabled();
Propel::disableInstancePooling();
$insertedEntities = array();
$con->beginTransaction();
foreach ($this->quantities as $class => $number) {
for ($i=0; $i < $number; $i++) {
$insertedEntities[$class][]= $this->entities[$class]->execute($con, $insertedEntities);
}
}
$con->commit();
if ($isInstancePoolingEnabled) {
Propel::enableInstancePooling();
}
return $insertedEntities;
}
protected function getConnection()
{
// use the first connection available
$class = key($this->entities);
if (!$class) {
throw new \RuntimeException('No class found from entities. Did you add entities to the Populator ?');
}
$peer = $class::TABLE_MAP;
return Propel::getConnection($peer::DATABASE_NAME, ServiceContainerInterface::CONNECTION_WRITE);
}
}
<?php
namespace Faker\ORM\Spot;
use Faker\Generator;
class ColumnTypeGuesser
{
protected $generator;
/**
* ColumnTypeGuesser constructor.
* @param Generator $generator
*/
public function __construct(Generator $generator)
{
$this->generator = $generator;
}
/**
* @param array $field
* @return \Closure|null
*/
public function guessFormat(array $field)
{
$generator = $this->generator;
$type = $field['type'];
switch ($type) {
case 'boolean':
return function () use ($generator) {
return $generator->boolean;
};
case 'decimal':
$size = isset($field['precision']) ? $field['precision'] : 2;
return function () use ($generator, $size) {
return $generator->randomNumber($size + 2) / 100;
};
case 'smallint':
return function () use ($generator) {
return $generator->numberBetween(0, 65535);
};
case 'integer':
return function () use ($generator) {
return $generator->numberBetween(0, intval('2147483647'));
};
case 'bigint':
return function () use ($generator) {
return $generator->numberBetween(0, intval('18446744073709551615'));
};
case 'float':
return function () use ($generator) {
return $generator->randomFloat(null, 0, intval('4294967295'));
};
case 'string':
$size = isset($field['length']) ? $field['length'] : 255;
return function () use ($generator, $size) {
return $generator->text($size);
};
case 'text':
return function () use ($generator) {
return $generator->text;
};
case 'datetime':
case 'date':
case 'time':
return function () use ($generator) {
return $generator->datetime;
};
default:
// no smart way to guess what the user expects here
return null;
}
}
}
<?php
namespace Faker\ORM\Spot;
use Faker\Generator;
use Faker\Guesser\Name;
use Spot\Locator;
use Spot\Mapper;
use Spot\Relation\BelongsTo;
/**
* Service class for populating a table through a Spot Entity class.
*/
class EntityPopulator
{
/**
* When fetching existing data - fetch only few first rows.
*/
const RELATED_FETCH_COUNT = 10;
/**
* @var Mapper
*/
protected $mapper;
/**
* @var Locator
*/
protected $locator;
/**
* @var array
*/
protected $columnFormatters = array();
/**
* @var array
*/
protected $modifiers = array();
/**
* @var bool
*/
protected $useExistingData = false;
/**
* Class constructor.
*
* @param Mapper $mapper
* @param Locator $locator
* @param $useExistingData
*/
public function __construct(Mapper $mapper, Locator $locator, $useExistingData = false)
{
$this->mapper = $mapper;
$this->locator = $locator;
$this->useExistingData = $useExistingData;
}
/**
* @return string
*/
public function getMapper()
{
return $this->mapper;
}
/**
* @param $columnFormatters
*/
public function setColumnFormatters($columnFormatters)
{
$this->columnFormatters = $columnFormatters;
}
/**
* @return array
*/
public function getColumnFormatters()
{
return $this->columnFormatters;
}
/**
* @param $columnFormatters
*/
public function mergeColumnFormattersWith($columnFormatters)
{
$this->columnFormatters = array_merge($this->columnFormatters, $columnFormatters);
}
/**
* @param array $modifiers
*/
public function setModifiers(array $modifiers)
{
$this->modifiers = $modifiers;
}
/**
* @return array
*/
public function getModifiers()
{
return $this->modifiers;
}
/**
* @param array $modifiers
*/
public function mergeModifiersWith(array $modifiers)
{
$this->modifiers = array_merge($this->modifiers, $modifiers);
}
/**
* @param Generator $generator
* @return array
*/
public function guessColumnFormatters(Generator $generator)
{
$formatters = array();
$nameGuesser = new Name($generator);
$columnTypeGuesser = new ColumnTypeGuesser($generator);
$fields = $this->mapper->fields();
foreach ($fields as $fieldName => $field) {
if ($field['primary'] === true) {
continue;
}
if ($formatter = $nameGuesser->guessFormat($fieldName)) {
$formatters[$fieldName] = $formatter;
continue;
}
if ($formatter = $columnTypeGuesser->guessFormat($field)) {
$formatters[$fieldName] = $formatter;
continue;
}
}
$entityName = $this->mapper->entity();
$entity = $this->mapper->build([]);
$relations = $entityName::relations($this->mapper, $entity);
foreach ($relations as $relation) {
// We don't need any other relation here.
if ($relation instanceof BelongsTo) {
$fieldName = $relation->localKey();
$entityName = $relation->entityName();
$field = $fields[$fieldName];
$required = $field['required'];
$locator = $this->locator;
$formatters[$fieldName] = function ($inserted) use ($required, $entityName, $locator) {
if (!empty($inserted[$entityName])) {
return $inserted[$entityName][mt_rand(0, count($inserted[$entityName]) - 1)]->get('id');
}
if ($required && $this->useExistingData) {
// We did not add anything like this, but it's required,
// So let's find something existing in DB.
$mapper = $locator->mapper($entityName);
$records = $mapper->all()->limit(self::RELATED_FETCH_COUNT)->toArray();
if (empty($records)) {
return null;
}
return $records[mt_rand(0, count($records) - 1)]['id'];
}
return null;
};
}
}
return $formatters;
}
/**
* Insert one new record using the Entity class.
*
* @param $insertedEntities
* @return string
*/
public function execute($insertedEntities)
{
$obj = $this->mapper->build([]);
$this->fillColumns($obj, $insertedEntities);
$this->callMethods($obj, $insertedEntities);
$this->mapper->insert($obj);
return $obj;
}
/**
* @param $obj
* @param $insertedEntities
*/
private function fillColumns($obj, $insertedEntities)
{
foreach ($this->columnFormatters as $field => $format) {
if (null !== $format) {
$value = is_callable($format) ? $format($insertedEntities, $obj) : $format;
$obj->set($field, $value);
}
}
}
/**
* @param $obj
* @param $insertedEntities
*/
private function callMethods($obj, $insertedEntities)
{
foreach ($this->getModifiers() as $modifier) {
$modifier($obj, $insertedEntities);
}
}
}
<?php
namespace Faker\ORM\Spot;
use Spot\Locator;
/**
* Service class for populating a database using the Spot ORM.
*/
class Populator
{
protected $generator;
protected $locator;
protected $entities = array();
protected $quantities = array();
/**
* Populator constructor.
* @param \Faker\Generator $generator
* @param Locator|null $locator
*/
public function __construct(\Faker\Generator $generator, Locator $locator = null)
{
$this->generator = $generator;
$this->locator = $locator;
}
/**
* Add an order for the generation of $number records for $entity.
*
* @param $entityName string Name of Entity object to generate
* @param $number int The number of entities to populate
* @param $customColumnFormatters array
* @param $customModifiers array
* @param $useExistingData bool Should we use existing rows (e.g. roles) to populate relations?
*/
public function addEntity(
$entityName,
$number,
$customColumnFormatters = array(),
$customModifiers = array(),
$useExistingData = false
) {
$mapper = $this->locator->mapper($entityName);
if (null === $mapper) {
throw new \InvalidArgumentException("No mapper can be found for entity " . $entityName);
}
$entity = new EntityPopulator($mapper, $this->locator, $useExistingData);
$entity->setColumnFormatters($entity->guessColumnFormatters($this->generator));
if ($customColumnFormatters) {
$entity->mergeColumnFormattersWith($customColumnFormatters);
}
$entity->mergeModifiersWith($customModifiers);
$this->entities[$entityName] = $entity;
$this->quantities[$entityName] = $number;
}
/**
* Populate the database using all the Entity classes previously added.
*
* @param Locator $locator A Spot locator
*
* @return array A list of the inserted PKs
*/
public function execute($locator = null)
{
if (null === $locator) {
$locator = $this->locator;
}
if (null === $locator) {
throw new \InvalidArgumentException("No entity manager passed to Spot Populator.");
}
$insertedEntities = array();
foreach ($this->quantities as $entityName => $number) {
for ($i = 0; $i < $number; $i++) {
$insertedEntities[$entityName][] = $this->entities[$entityName]->execute(
$insertedEntities
);
}
}
return $insertedEntities;
}
}
<?php
namespace Faker\Provider;
class Address extends Base
{
protected static $citySuffix = array('Ville');
protected static $streetSuffix = array('Street');
protected static $cityFormats = array(
'{{firstName}}{{citySuffix}}',
);
protected static $streetNameFormats = array(
'{{lastName}} {{streetSuffix}}'
);
protected static $streetAddressFormats = array(
'{{buildingNumber}} {{streetName}}'
);
protected static $addressFormats = array(
'{{streetAddress}} {{postcode}} {{city}}',
);
protected static $buildingNumber = array('%#');
protected static $postcode = array('#####');
protected static $country = array();
/**
* @example 'town'
*/
public static function citySuffix()
{
return static::randomElement(static::$citySuffix);
}
/**
* @example 'Avenue'
*/
public static function streetSuffix()
{
return static::randomElement(static::$streetSuffix);
}
/**
* @example '791'
*/
public static function buildingNumber()
{
return static::numerify(static::randomElement(static::$buildingNumber));
}
/**
* @example 'Sashabury'
*/
public function city()
{
$format = static::randomElement(static::$cityFormats);
return $this->generator->parse($format);
}
/**
* @example 'Crist Parks'
*/
public function streetName()
{
$format = static::randomElement(static::$streetNameFormats);
return $this->generator->parse($format);
}
/**
* @example '791 Crist Parks'
*/
public function streetAddress()
{
$format = static::randomElement(static::$streetAddressFormats);
return $this->generator->parse($format);
}
/**
* @example 86039-9874
*/
public static function postcode()
{
return static::toUpper(static::bothify(static::randomElement(static::$postcode)));
}
/**
* @example '791 Crist Parks, Sashabury, IL 86039-9874'
*/
public function address()
{
$format = static::randomElement(static::$addressFormats);
return $this->generator->parse($format);
}
/**
* @example 'Japan'
*/
public static function country()
{
return static::randomElement(static::$country);
}
/**
* @example '77.147489'
* @param float|int $min
* @param float|int $max
* @return float Uses signed degrees format (returns a float number between -90 and 90)
*/
public static function latitude($min = -90, $max = 90)
{
return static::randomFloat(6, $min, $max);
}
/**
* @example '86.211205'
* @param float|int $min
* @param float|int $max
* @return float Uses signed degrees format (returns a float number between -180 and 180)
*/
public static function longitude($min = -180, $max = 180)
{
return static::randomFloat(6, $min, $max);
}
/**
* @example array('77.147489', '86.211205')
* @return array | latitude, longitude
*/
public static function localCoordinates()
{
return array(
'latitude' => static::latitude(),
'longitude' => static::longitude()
);
}
}
<?php
namespace Faker\Provider;
/**
* @see http://en.wikipedia.org/wiki/EAN-13
* @see http://en.wikipedia.org/wiki/ISBN
*/
class Barcode extends Base
{
private function ean($length = 13)
{
$code = static::numerify(str_repeat('#', $length - 1));
return $code . static::eanChecksum($code);
}
/**
* Utility function for computing EAN checksums
*
* @param string $input
*
* @return integer
*/
protected static function eanChecksum($input)
{
$sequence = (strlen($input) + 1) === 8 ? array(3, 1) : array(1, 3);
$sums = 0;
foreach (str_split($input) as $n => $digit) {
$sums += $digit * $sequence[$n % 2];
}
return (10 - $sums % 10) % 10;
}
/**
* ISBN-10 check digit
* @link http://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digits
*
* @param string $input ISBN without check-digit
* @throws \LengthException When wrong input length passed
*
* @return integer Check digit
*/
protected static function isbnChecksum($input)
{
// We're calculating check digit for ISBN-10
// so, the length of the input should be 9
$length = 9;
if (strlen($input) !== $length) {
throw new \LengthException(sprintf('Input length should be equal to %d', $length));
}
$digits = str_split($input);
array_walk(
$digits,
function (&$digit, $position) {
$digit = (10 - $position) * $digit;
}
);
$result = (11 - array_sum($digits) % 11) % 11;
// 10 is replaced by X
return ($result < 10)?$result:'X';
}
/**
* Get a random EAN13 barcode.
* @return string
* @example '4006381333931'
*/
public function ean13()
{
return $this->ean(13);
}
/**
* Get a random EAN8 barcode.
* @return string
* @example '73513537'
*/
public function ean8()
{
return $this->ean(8);
}
/**
* Get a random ISBN-10 code
* @link http://en.wikipedia.org/wiki/International_Standard_Book_Number
*
* @return string
* @example '4881416324'
*/
public function isbn10()
{
$code = static::numerify(str_repeat('#', 9));
return $code . static::isbnChecksum($code);
}
/**
* Get a random ISBN-13 code
* @link http://en.wikipedia.org/wiki/International_Standard_Book_Number
*
* @return string
* @example '9790404436093'
*/
public function isbn13()
{
$code = '97' . static::numberBetween(8, 9) . static::numerify(str_repeat('#', 9));
return $code . static::eanChecksum($code);
}
}
<?php
namespace Faker\Provider;
class Biased extends Base
{
/**
* Returns a biased integer between $min and $max (both inclusive).
* The distribution depends on $function.
*
* The algorithm creates two doubles, x ∈ [0, 1], y ∈ [0, 1) and checks whether the
* return value of $function for x is greater than or equal to y. If this is
* the case the number is accepted and x is mapped to the appropriate integer
* between $min and $max. Otherwise two new doubles are created until the pair
* is accepted.
*
* @param integer $min Minimum value of the generated integers.
* @param integer $max Maximum value of the generated integers.
* @param callable $function A function mapping x ∈ [0, 1] onto a double ∈ [0, 1]
* @return integer An integer between $min and $max.
*/
public function biasedNumberBetween($min = 0, $max = 100, $function = 'sqrt')
{
do {
$x = mt_rand() / mt_getrandmax();
$y = mt_rand() / (mt_getrandmax() + 1);
} while (call_user_func($function, $x) < $y);
return (int) floor($x * ($max - $min + 1) + $min);
}
/**
* 'unbiased' creates an unbiased distribution by giving
* each value the same value of one.
*
* @return integer
*/
protected static function unbiased()
{
return 1;
}
/**
* 'linearLow' favors lower numbers. The probability decreases
* in a linear fashion.
*
* @return integer
*/
protected static function linearLow($x)
{
return 1 - $x;
}
/**
* 'linearHigh' favors higher numbers. The probability increases
* in a linear fashion.
*
* @return integer
*/
protected static function linearHigh($x)
{
return $x;
}
}
<?php
namespace Faker\Provider;
/**
* @author lsv
*/
class Color extends Base
{
protected static $safeColorNames = array(
'black', 'maroon', 'green', 'navy', 'olive',
'purple', 'teal', 'lime', 'blue', 'silver',
'gray', 'yellow', 'fuchsia', 'aqua', 'white'
);
protected static $allColorNames = array(
'AliceBlue', 'AntiqueWhite', 'Aqua', 'Aquamarine',
'Azure', 'Beige', 'Bisque', 'Black', 'BlanchedAlmond',
'Blue', 'BlueViolet', 'Brown', 'BurlyWood', 'CadetBlue',
'Chartreuse', 'Chocolate', 'Coral', 'CornflowerBlue',
'Cornsilk', 'Crimson', 'Cyan', 'DarkBlue', 'DarkCyan',
'DarkGoldenRod', 'DarkGray', 'DarkGreen', 'DarkKhaki',
'DarkMagenta', 'DarkOliveGreen', 'Darkorange', 'DarkOrchid',
'DarkRed', 'DarkSalmon', 'DarkSeaGreen', 'DarkSlateBlue',
'DarkSlateGray', 'DarkTurquoise', 'DarkViolet', 'DeepPink',
'DeepSkyBlue', 'DimGray', 'DimGrey', 'DodgerBlue', 'FireBrick',
'FloralWhite', 'ForestGreen', 'Fuchsia', 'Gainsboro', 'GhostWhite',
'Gold', 'GoldenRod', 'Gray', 'Green', 'GreenYellow', 'HoneyDew',
'HotPink', 'IndianRed', 'Indigo', 'Ivory', 'Khaki', 'Lavender',
'LavenderBlush', 'LawnGreen', 'LemonChiffon', 'LightBlue', 'LightCoral',
'LightCyan', 'LightGoldenRodYellow', 'LightGray', 'LightGreen', 'LightPink',
'LightSalmon', 'LightSeaGreen', 'LightSkyBlue', 'LightSlateGray', 'LightSteelBlue',
'LightYellow', 'Lime', 'LimeGreen', 'Linen', 'Magenta', 'Maroon', 'MediumAquaMarine',
'MediumBlue', 'MediumOrchid', 'MediumPurple', 'MediumSeaGreen', 'MediumSlateBlue',
'MediumSpringGreen', 'MediumTurquoise', 'MediumVioletRed', 'MidnightBlue',
'MintCream', 'MistyRose', 'Moccasin', 'NavajoWhite', 'Navy', 'OldLace', 'Olive',
'OliveDrab', 'Orange', 'OrangeRed', 'Orchid', 'PaleGoldenRod', 'PaleGreen',
'PaleTurquoise', 'PaleVioletRed', 'PapayaWhip', 'PeachPuff', 'Peru', 'Pink', 'Plum',
'PowderBlue', 'Purple', 'Red', 'RosyBrown', 'RoyalBlue', 'SaddleBrown', 'Salmon',
'SandyBrown', 'SeaGreen', 'SeaShell', 'Sienna', 'Silver', 'SkyBlue', 'SlateBlue',
'SlateGray', 'Snow', 'SpringGreen', 'SteelBlue', 'Tan', 'Teal', 'Thistle', 'Tomato',
'Turquoise', 'Violet', 'Wheat', 'White', 'WhiteSmoke', 'Yellow', 'YellowGreen'
);
/**
* @example '#fa3cc2'
*/
public static function hexColor()
{
return '#' . str_pad(dechex(mt_rand(1, 16777215)), 6, '0', STR_PAD_LEFT);
}
/**
* @example '#ff0044'
*/
public static function safeHexColor()
{
$color = str_pad(dechex(mt_rand(0, 255)), 3, '0', STR_PAD_LEFT);
return '#' . $color[0] . $color[0] . $color[1] . $color[1] . $color[2] . $color[2];
}
/**
* @example 'array(0,255,122)'
*/
public static function rgbColorAsArray()
{
$color = static::hexColor();
return array(
hexdec(substr($color, 1, 2)),
hexdec(substr($color, 3, 2)),
hexdec(substr($color, 5, 2))
);
}
/**
* @example '0,255,122'
*/
public static function rgbColor()
{
return implode(',', static::rgbColorAsArray());
}
/**
* @example 'rgb(0,255,122)'
*/
public static function rgbCssColor()
{
return 'rgb(' . static::rgbColor() . ')';
}
/**
* @example 'rgba(0,255,122,0.8)'
*/
public static function rgbaCssColor()
{
return 'rgba(' . static::rgbColor() . ',' . static::randomFloat(1, 0, 1) . ')';
}
/**
* @example 'blue'
*/
public static function safeColorName()
{
return static::randomElement(static::$safeColorNames);
}
/**
* @example 'NavajoWhite'
*/
public static function colorName()
{
return static::randomElement(static::$allColorNames);
}
/**
* @example '340,50,20'
* @return string
*/
public static function hslColor()
{
return sprintf(
'%s,%s,%s',
static::numberBetween(0, 360),
static::numberBetween(0, 100),
static::numberBetween(0, 100)
);
}
/**
* @example array(340, 50, 20)
* @return array
*/
public static function hslColorAsArray()
{
return array(
static::numberBetween(0, 360),
static::numberBetween(0, 100),
static::numberBetween(0, 100)
);
}
}
<?php
namespace Faker\Provider;
class Company extends Base
{
protected static $formats = array(
'{{lastName}} {{companySuffix}}',
);
protected static $companySuffix = array('Ltd');
protected static $jobTitleFormat = array(
'{{word}}',
);
/**
* @example 'Acme Ltd'
*
* @return string
*/
public function company()
{
$format = static::randomElement(static::$formats);
return $this->generator->parse($format);
}
/**
* @example 'Ltd'
*
* @return string
*/
public static function companySuffix()
{
return static::randomElement(static::$companySuffix);
}
/**
* @example 'Job'
*
* @return string
*/
public function jobTitle()
{
$format = static::randomElement(static::$jobTitleFormat);
return $this->generator->parse($format);
}
}
<?php
namespace Faker\Provider;
use Faker\Generator;
use Faker\UniqueGenerator;
class HtmlLorem extends Base
{
const HTML_TAG = "html";
const HEAD_TAG = "head";
const BODY_TAG = "body";
const DIV_TAG = "div";
const P_TAG = "p";
const A_TAG = "a";
const SPAN_TAG = "span";
const TABLE_TAG = "table";
const THEAD_TAG = "thead";
const TBODY_TAG = "tbody";
const TR_TAG = "tr";
const TD_TAG = "td";
const TH_TAG = "th";
const UL_TAG = "ul";
const LI_TAG = "li";
const H_TAG = "h";
const B_TAG = "b";
const I_TAG = "i";
const TITLE_TAG = "title";
const FORM_TAG = "form";
const INPUT_TAG = "input";
const LABEL_TAG = "label";
private $idGenerator;
public function __construct(Generator $generator)
{
parent::__construct($generator);
$generator->addProvider(new Lorem($generator));
$generator->addProvider(new Internet($generator));
}
/**
* @param integer $maxDepth
* @param integer $maxWidth
*
* @return string
*/
public function randomHtml($maxDepth = 4, $maxWidth = 4)
{
$document = new \DOMDocument();
$this->idGenerator = new UniqueGenerator($this->generator);
$head = $document->createElement("head");
$this->addRandomTitle($head);
$body = $document->createElement("body");
$this->addLoginForm($body);
$this->addRandomSubTree($body, $maxDepth, $maxWidth);
$html = $document->createElement("html");
$html->appendChild($head);
$html->appendChild($body);
$document->appendChild($html);
return $document->saveHTML();
}
private function addRandomSubTree(\DOMElement $root, $maxDepth, $maxWidth)
{
$maxDepth--;
if ($maxDepth <= 0) {
return $root;
}
$siblings = mt_rand(1, $maxWidth);
for ($i = 0; $i < $siblings; $i++) {
if ($maxDepth == 1) {
$this->addRandomLeaf($root);
} else {
$sibling = $root->ownerDocument->createElement("div");
$root->appendChild($sibling);
$this->addRandomAttribute($sibling);
$this->addRandomSubTree($sibling, mt_rand(0, $maxDepth), $maxWidth);
}
}
return $root;
}
private function addRandomLeaf(\DOMElement $node)
{
$rand = mt_rand(1, 10);
switch ($rand) {
case 1:
$this->addRandomP($node);
break;
case 2:
$this->addRandomA($node);
break;
case 3:
$this->addRandomSpan($node);
break;
case 4:
$this->addRandomUL($node);
break;
case 5:
$this->addRandomH($node);
break;
case 6:
$this->addRandomB($node);
break;
case 7:
$this->addRandomI($node);
break;
case 8:
$this->addRandomTable($node);
break;
default:
$this->addRandomText($node);
break;
}
}
private function addRandomAttribute(\DOMElement $node)
{
$rand = mt_rand(1, 2);
switch ($rand) {
case 1:
$node->setAttribute("class", $this->generator->word);
break;
case 2:
$node->setAttribute("id", (string)$this->idGenerator->randomNumber(5));
break;
}
}
private function addRandomP(\DOMElement $element, $maxLength = 10)
{
$node = $element->ownerDocument->createElement(static::P_TAG);
$node->textContent = $this->generator->sentence(mt_rand(1, $maxLength));
$element->appendChild($node);
}
private function addRandomText(\DOMElement $element, $maxLength = 10)
{
$text = $element->ownerDocument->createTextNode($this->generator->sentence(mt_rand(1, $maxLength)));
$element->appendChild($text);
}
private function addRandomA(\DOMElement $element, $maxLength = 10)
{
$text = $element->ownerDocument->createTextNode($this->generator->sentence(mt_rand(1, $maxLength)));
$node = $element->ownerDocument->createElement(static::A_TAG);
$node->setAttribute("href", $this->generator->safeEmailDomain);
$node->appendChild($text);
$element->appendChild($node);
}
private function addRandomTitle(\DOMElement $element, $maxLength = 10)
{
$text = $element->ownerDocument->createTextNode($this->generator->sentence(mt_rand(1, $maxLength)));
$node = $element->ownerDocument->createElement(static::TITLE_TAG);
$node->appendChild($text);
$element->appendChild($node);
}
private function addRandomH(\DOMElement $element, $maxLength = 10)
{
$h = static::H_TAG . (string)mt_rand(1, 3);
$text = $element->ownerDocument->createTextNode($this->generator->sentence(mt_rand(1, $maxLength)));
$node = $element->ownerDocument->createElement($h);
$node->appendChild($text);
$element->appendChild($node);
}
private function addRandomB(\DOMElement $element, $maxLength = 10)
{
$text = $element->ownerDocument->createTextNode($this->generator->sentence(mt_rand(1, $maxLength)));
$node = $element->ownerDocument->createElement(static::B_TAG);
$node->appendChild($text);
$element->appendChild($node);
}
private function addRandomI(\DOMElement $element, $maxLength = 10)
{
$text = $element->ownerDocument->createTextNode($this->generator->sentence(mt_rand(1, $maxLength)));
$node = $element->ownerDocument->createElement(static::I_TAG);
$node->appendChild($text);
$element->appendChild($node);
}
private function addRandomSpan(\DOMElement $element, $maxLength = 10)
{
$text = $element->ownerDocument->createTextNode($this->generator->sentence(mt_rand(1, $maxLength)));
$node = $element->ownerDocument->createElement(static::SPAN_TAG);
$node->appendChild($text);
$element->appendChild($node);
}
private function addLoginForm(\DOMElement $element)
{
$textInput = $element->ownerDocument->createElement(static::INPUT_TAG);
$textInput->setAttribute("type", "text");
$textInput->setAttribute("id", "username");
$textLabel = $element->ownerDocument->createElement(static::LABEL_TAG);
$textLabel->setAttribute("for", "username");
$textLabel->textContent = $this->generator->word;
$passwordInput = $element->ownerDocument->createElement(static::INPUT_TAG);
$passwordInput->setAttribute("type", "password");
$passwordInput->setAttribute("id", "password");
$passwordLabel = $element->ownerDocument->createElement(static::LABEL_TAG);
$passwordLabel->setAttribute("for", "password");
$passwordLabel->textContent = $this->generator->word;
$submit = $element->ownerDocument->createElement(static::INPUT_TAG);
$submit->setAttribute("type", "submit");
$submit->setAttribute("value", $this->generator->word);
$submit = $element->ownerDocument->createElement(static::FORM_TAG);
$submit->setAttribute("action", $this->generator->safeEmailDomain);
$submit->setAttribute("method", "POST");
$submit->appendChild($textLabel);
$submit->appendChild($textInput);
$submit->appendChild($passwordLabel);
$submit->appendChild($passwordInput);
$element->appendChild($submit);
}
private function addRandomTable(\DOMElement $element, $maxRows = 10, $maxCols = 6, $maxTitle = 4, $maxLength = 10)
{
$rows = mt_rand(1, $maxRows);
$cols = mt_rand(1, $maxCols);
$table = $element->ownerDocument->createElement(static::TABLE_TAG);
$thead = $element->ownerDocument->createElement(static::THEAD_TAG);
$tbody = $element->ownerDocument->createElement(static::TBODY_TAG);
$table->appendChild($thead);
$table->appendChild($tbody);
$tr = $element->ownerDocument->createElement(static::TR_TAG);
$thead->appendChild($tr);
for ($i = 0; $i < $cols; $i++) {
$th = $element->ownerDocument->createElement(static::TH_TAG);
$th->textContent = $this->generator->sentence(mt_rand(1, $maxTitle));
$tr->appendChild($th);
}
for ($i = 0; $i < $rows; $i++) {
$tr = $element->ownerDocument->createElement(static::TR_TAG);
$tbody->appendChild($tr);
for ($j = 0; $j < $cols; $j++) {
$th = $element->ownerDocument->createElement(static::TD_TAG);
$th->textContent = $this->generator->sentence(mt_rand(1, $maxLength));
$tr->appendChild($th);
}
}
$element->appendChild($table);
}
private function addRandomUL(\DOMElement $element, $maxItems = 11, $maxLength = 4)
{
$num = mt_rand(1, $maxItems);
$ul = $element->ownerDocument->createElement(static::UL_TAG);
for ($i = 0; $i < $num; $i++) {
$li = $element->ownerDocument->createElement(static::LI_TAG);
$li->textContent = $this->generator->sentence(mt_rand(1, $maxLength));
$ul->appendChild($li);
}
$element->appendChild($ul);
}
}
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment