Included vendor/ to the project

This commit is contained in:
2017-09-13 09:35:32 +07:00
parent e72205ff09
commit 17f1643875
2483 changed files with 179073 additions and 0 deletions

View File

@@ -0,0 +1,133 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
/**
* Implements the basic functionality of data sets.
*/
abstract class AbstractDataSet implements IDataSet
{
/**
* Creates an iterator over the tables in the data set. If $reverse is
* true a reverse iterator will be returned.
*
* @param bool $reverse
*
* @return ITableIterator
*/
abstract protected function createIterator($reverse = false);
/**
* Returns an array of table names contained in the dataset.
*
* @return array
*/
public function getTableNames()
{
$tableNames = [];
foreach ($this->getIterator() as $table) {
/* @var $table ITable */
$tableNames[] = $table->getTableMetaData()->getTableName();
}
return $tableNames;
}
/**
* Returns a table meta data object for the given table.
*
* @param string $tableName
*
* @return ITableMetadata
*/
public function getTableMetaData($tableName)
{
return $this->getTable($tableName)->getTableMetaData();
}
/**
* Returns a table object for the given table.
*
* @param string $tableName
*
* @return ITable
*/
public function getTable($tableName)
{
foreach ($this->getIterator() as $table) {
/* @var $table ITable */
if ($table->getTableMetaData()->getTableName() == $tableName) {
return $table;
}
}
}
/**
* Returns an iterator for all table objects in the given dataset.
*
* @return ITableIterator
*/
public function getIterator()
{
return $this->createIterator();
}
/**
* Returns a reverse iterator for all table objects in the given dataset.
*
* @return ITableIterator
*/
public function getReverseIterator()
{
return $this->createIterator(true);
}
/**
* Asserts that the given data set matches this data set.
*
* @param IDataSet $other
*/
public function matches(IDataSet $other)
{
$thisTableNames = $this->getTableNames();
$otherTableNames = $other->getTableNames();
sort($thisTableNames);
sort($otherTableNames);
if ($thisTableNames != $otherTableNames) {
return false;
}
foreach ($thisTableNames as $tableName) {
$table = $this->getTable($tableName);
if (!$table->matches($other->getTable($tableName))) {
return false;
}
}
return true;
}
public function __toString()
{
$iterator = $this->getIterator();
$dataSetString = '';
foreach ($iterator as $table) {
$dataSetString .= $table->__toString();
}
return $dataSetString;
}
}

View File

@@ -0,0 +1,222 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PHPUnit\DbUnit\InvalidArgumentException;
use SimpleXMLElement;
/**
* Provides a basic functionality for dbunit tables
*/
class AbstractTable implements ITable
{
/**
* @var ITableMetadata
*/
protected $tableMetaData;
/**
* A 2-dimensional array containing the data for this table.
*
* @var array
*/
protected $data;
/**
* @var ITable|null
*/
private $other;
/**
* Sets the metadata for this table.
*
* @param ITableMetadata $tableMetaData
*
* @deprecated
*/
protected function setTableMetaData(ITableMetadata $tableMetaData)
{
$this->tableMetaData = $tableMetaData;
}
/**
* Returns the table's meta data.
*
* @return ITableMetadata
*/
public function getTableMetaData()
{
return $this->tableMetaData;
}
/**
* Returns the number of rows in this table.
*
* @return int
*/
public function getRowCount()
{
return count($this->data);
}
/**
* Returns the value for the given column on the given row.
*
* @param int $row
* @param int $column
*
* @todo reorganize this function to throw the exception first.
*/
public function getValue($row, $column)
{
if (isset($this->data[$row][$column])) {
$value = $this->data[$row][$column];
return ($value instanceof SimpleXMLElement) ? (string) $value : $value;
} else {
if (!in_array($column, $this->getTableMetaData()->getColumns()) || $this->getRowCount() <= $row) {
throw new InvalidArgumentException("The given row ({$row}) and column ({$column}) do not exist in table {$this->getTableMetaData()->getTableName()}");
} else {
return;
}
}
}
/**
* Returns the an associative array keyed by columns for the given row.
*
* @param int $row
*
* @return array
*/
public function getRow($row)
{
if (isset($this->data[$row])) {
return $this->data[$row];
} else {
if ($this->getRowCount() <= $row) {
throw new InvalidArgumentException("The given row ({$row}) does not exist in table {$this->getTableMetaData()->getTableName()}");
} else {
return;
}
}
}
/**
* Asserts that the given table matches this table.
*
* @param ITable $other
*/
public function matches(ITable $other)
{
$thisMetaData = $this->getTableMetaData();
$otherMetaData = $other->getTableMetaData();
if (!$thisMetaData->matches($otherMetaData) ||
$this->getRowCount() != $other->getRowCount()
) {
return false;
}
$columns = $thisMetaData->getColumns();
$rowCount = $this->getRowCount();
for ($i = 0; $i < $rowCount; $i++) {
foreach ($columns as $columnName) {
$thisValue = $this->getValue($i, $columnName);
$otherValue = $other->getValue($i, $columnName);
if (is_numeric($thisValue) && is_numeric($otherValue)) {
if ($thisValue != $otherValue) {
$this->other = $other;
return false;
}
} elseif ($thisValue !== $otherValue) {
$this->other = $other;
return false;
}
}
}
return true;
}
/**
* Checks if a given row is in the table
*
* @param array $row
*
* @return bool
*/
public function assertContainsRow(array $row)
{
return in_array($row, $this->data);
}
public function __toString()
{
$columns = $this->getTableMetaData()->getColumns();
$lineSeperator = str_repeat('+----------------------', count($columns)) . "+\n";
$lineLength = strlen($lineSeperator) - 1;
$tableString = $lineSeperator;
$tableString .= '| ' . str_pad($this->getTableMetaData()->getTableName(), $lineLength - 4, ' ', STR_PAD_RIGHT) . " |\n";
$tableString .= $lineSeperator;
$tableString .= $this->rowToString($columns);
$tableString .= $lineSeperator;
$rowCount = $this->getRowCount();
for ($i = 0; $i < $rowCount; $i++) {
$values = [];
foreach ($columns as $columnName) {
if ($this->other) {
try {
if ($this->getValue($i, $columnName) != $this->other->getValue($i, $columnName)) {
$values[] = sprintf(
'%s != actual %s',
var_export($this->getValue($i, $columnName), true),
var_export($this->other->getValue($i, $columnName), true)
);
} else {
$values[] = $this->getValue($i, $columnName);
}
} catch (\InvalidArgumentException $ex) {
$values[] = $this->getValue($i, $columnName) . ': no row';
}
} else {
$values[] = $this->getValue($i, $columnName);
}
}
$tableString .= $this->rowToString($values) . $lineSeperator;
}
return ($this->other ? '(table diff enabled)' : '') . "\n" . $tableString . "\n";
}
protected function rowToString(array $row)
{
$rowString = '';
foreach ($row as $value) {
if (is_null($value)) {
$value = 'NULL';
}
$rowString .= '| ' . str_pad(substr($value, 0, 20), 20, ' ', STR_PAD_BOTH) . ' ';
}
return $rowString . "|\n";
}
}

View File

@@ -0,0 +1,82 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
/**
* Provides basic functionality for table meta data.
*/
abstract class AbstractTableMetadata implements ITableMetadata
{
/**
* The names of all columns in the table.
*
* @var array
*/
protected $columns;
/**
* The names of all the primary keys in the table.
*
* @var array
*/
protected $primaryKeys;
/**
* @var string
*/
protected $tableName;
/**
* Returns the names of the columns in the table.
*
* @return array
*/
public function getColumns()
{
return $this->columns;
}
/**
* Returns the names of the primary key columns in the table.
*
* @return array
*/
public function getPrimaryKeys()
{
return $this->primaryKeys;
}
/**
* Returns the name of the table.
*
* @return string
*/
public function getTableName()
{
return $this->tableName;
}
/**
* Asserts that the given tableMetaData matches this tableMetaData.
*
* @param ITableMetadata $other
*/
public function matches(ITableMetadata $other)
{
if ($this->getTableName() != $other->getTableName() ||
$this->getColumns() != $other->getColumns()
) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,114 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PHPUnit\DbUnit\InvalidArgumentException;
use RuntimeException;
use SimpleXmlElement;
/**
* The default implementation of a data set.
*/
abstract class AbstractXmlDataSet extends AbstractDataSet
{
/**
* @var array
*/
protected $tables;
/**
* @var SimpleXmlElement
*/
protected $xmlFileContents;
/**
* Creates a new dataset using the given tables.
*
* @param array $tables
*/
public function __construct($xmlFile)
{
if (!is_file($xmlFile)) {
throw new InvalidArgumentException(
"Could not find xml file: {$xmlFile}"
);
}
$libxmlErrorReporting = libxml_use_internal_errors(true);
$this->xmlFileContents = simplexml_load_file($xmlFile, 'SimpleXMLElement', LIBXML_COMPACT | LIBXML_PARSEHUGE);
if (!$this->xmlFileContents) {
$message = '';
foreach (libxml_get_errors() as $error) {
$message .= print_r($error, true);
}
throw new RuntimeException($message);
}
libxml_clear_errors();
libxml_use_internal_errors($libxmlErrorReporting);
$tableColumns = [];
$tableValues = [];
$this->getTableInfo($tableColumns, $tableValues);
$this->createTables($tableColumns, $tableValues);
}
/**
* Reads the simple xml object and creates the appropriate tables and meta
* data for this dataset.
*/
abstract protected function getTableInfo(array &$tableColumns, array &$tableValues);
protected function createTables(array &$tableColumns, array &$tableValues)
{
foreach ($tableValues as $tableName => $values) {
$table = $this->getOrCreateTable($tableName, $tableColumns[$tableName]);
foreach ($values as $value) {
$table->addRow($value);
}
}
}
/**
* Returns the table with the matching name. If the table does not exist
* an empty one is created.
*
* @param string $tableName
*
* @return ITable
*/
protected function getOrCreateTable($tableName, $tableColumns)
{
if (empty($this->tables[$tableName])) {
$tableMetaData = new DefaultTableMetadata($tableName, $tableColumns);
$this->tables[$tableName] = new DefaultTable($tableMetaData);
}
return $this->tables[$tableName];
}
/**
* Creates an iterator over the tables in the data set. If $reverse is
* true a reverse iterator will be returned.
*
* @param bool $reverse
*
* @return ITableIterator
*/
protected function createIterator($reverse = false)
{
return new DefaultTableIterator($this->tables, $reverse);
}
}

View File

@@ -0,0 +1,72 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PHPUnit\DbUnit\InvalidArgumentException;
/**
* Implements the basic functionality of data sets using a PHP array.
*/
class ArrayDataSet extends AbstractDataSet
{
/**
* @var array
*/
protected $tables = [];
/**
* Constructor to build a new ArrayDataSet with the given array.
* The array parameter is an associative array of tables where the key is
* the table name and the value an array of rows. Each row is an associative
* array by itself with keys representing the field names and the values the
* actual data.
* For example:
* array(
* "addressbook" => array(
* array("id" => 1, "name" => "...", "address" => "..."),
* array("id" => 2, "name" => "...", "address" => "...")
* )
* )
*
* @param array $data
*/
public function __construct(array $data)
{
foreach ($data as $tableName => $rows) {
$columns = [];
if (isset($rows[0])) {
$columns = array_keys($rows[0]);
}
$metaData = new DefaultTableMetadata($tableName, $columns);
$table = new DefaultTable($metaData);
foreach ($rows as $row) {
$table->addRow($row);
}
$this->tables[$tableName] = $table;
}
}
protected function createIterator($reverse = false)
{
return new DefaultTableIterator($this->tables, $reverse);
}
public function getTable($tableName)
{
if (!isset($this->tables[$tableName])) {
throw new InvalidArgumentException("$tableName is not a table in the current database.");
}
return $this->tables[$tableName];
}
}

View File

@@ -0,0 +1,83 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PHPUnit\DbUnit\InvalidArgumentException;
/**
* Creates Composite Datasets
*
* Allows for creating datasets from multiple sources (csv, query, xml, etc.)
*/
class CompositeDataSet extends AbstractDataSet
{
protected $motherDataSet;
/**
* Creates a new Composite dataset
*
* You can pass in any data set that implements PHPUnit_Extensions_Database_DataSet_IDataSet
*
* @param string $delimiter
* @param string $enclosure
* @param string $escape
*/
public function __construct(array $dataSets = [])
{
$this->motherDataSet = new DefaultDataSet();
foreach ($dataSets as $dataSet) {
$this->addDataSet($dataSet);
}
}
/**
* Adds a new data set to the composite.
*
* The dataset may not define tables that already exist in the composite.
*
* @param IDataSet $dataSet
*/
public function addDataSet(IDataSet $dataSet)
{
foreach ($dataSet->getTableNames() as $tableName) {
if (!in_array($tableName, $this->getTableNames())) {
$this->motherDataSet->addTable($dataSet->getTable($tableName));
} else {
$other = $dataSet->getTable($tableName);
$table = $this->getTable($tableName);
if (!$table->getTableMetaData()->matches($other->getTableMetaData())) {
throw new InvalidArgumentException("There is already a table named $tableName with different table definition");
}
$table->addTableRows($dataSet->getTable($tableName));
}
}
}
/**
* Creates an iterator over the tables in the data set. If $reverse is
* true a reverse iterator will be returned.
*
* @param bool $reverse
*
* @return ITableIterator
*/
protected function createIterator($reverse = false)
{
if ($reverse) {
return $this->motherDataSet->getReverseIterator();
} else {
return $this->motherDataSet->getIterator();
}
}
}

View File

@@ -0,0 +1,122 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PHPUnit\DbUnit\InvalidArgumentException;
/**
* Creates CsvDataSets.
*
* You can incrementally add CSV files as tables to your datasets
*/
class CsvDataSet extends AbstractDataSet
{
/**
* @var array
*/
protected $tables = [];
/**
* @var string
*/
protected $delimiter = ',';
/**
* @var string
*/
protected $enclosure = '"';
/**
* @var string
*/
protected $escape = '"';
/**
* Creates a new CSV dataset
*
* You can pass in the parameters for how csv files will be read.
*
* @param string $delimiter
* @param string $enclosure
* @param string $escape
*/
public function __construct($delimiter = ',', $enclosure = '"', $escape = '"')
{
$this->delimiter = $delimiter;
$this->enclosure = $enclosure;
$this->escape = $escape;
}
/**
* Adds a table to the dataset
*
* The table will be given the passed name. $csvFile should be a path to
* a valid csv file (based on the arguments passed to the constructor.)
*
* @param string $tableName
* @param string $csvFile
*/
public function addTable($tableName, $csvFile)
{
if (!is_file($csvFile)) {
throw new InvalidArgumentException("Could not find csv file: {$csvFile}");
}
if (!is_readable($csvFile)) {
throw new InvalidArgumentException("Could not read csv file: {$csvFile}");
}
$fh = fopen($csvFile, 'r');
$columns = $this->getCsvRow($fh);
if ($columns === false) {
throw new InvalidArgumentException("Could not determine the headers from the given file {$csvFile}");
}
$metaData = new DefaultTableMetadata($tableName, $columns);
$table = new DefaultTable($metaData);
while (($row = $this->getCsvRow($fh)) !== false) {
$table->addRow(array_combine($columns, $row));
}
$this->tables[$tableName] = $table;
}
/**
* Creates an iterator over the tables in the data set. If $reverse is
* true a reverse iterator will be returned.
*
* @param bool $reverse
*
* @return ITableIterator
*/
protected function createIterator($reverse = false)
{
return new DefaultTableIterator($this->tables, $reverse);
}
/**
* Returns a row from the csv file in an indexed array.
*
* @param resource $fh
*
* @return array
*/
protected function getCsvRow($fh)
{
if (version_compare(PHP_VERSION, '5.3.0', '>')) {
return fgetcsv($fh, null, $this->delimiter, $this->enclosure, $this->escape);
} else {
return fgetcsv($fh, null, $this->delimiter, $this->enclosure);
}
}
}

View File

@@ -0,0 +1,57 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
/**
* The default implementation of a data set.
*/
class DefaultDataSet extends AbstractDataSet
{
/**
* An array of ITable objects.
*
* @var array
*/
protected $tables;
/**
* Creates a new dataset using the given tables.
*
* @param array $tables
*/
public function __construct(array $tables = [])
{
$this->tables = $tables;
}
/**
* Adds a table to the dataset.
*
* @param ITable $table
*/
public function addTable(ITable $table)
{
$this->tables[] = $table;
}
/**
* Creates an iterator over the tables in the data set. If $reverse is
* true a reverse iterator will be returned.
*
* @param bool $reverse
*
* @return ITableIterator
*/
protected function createIterator($reverse = false)
{
return new DefaultTableIterator($this->tables, $reverse);
}
}

View File

@@ -0,0 +1,78 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PHPUnit\DbUnit\InvalidArgumentException;
/**
* Provides default table functionality.
*/
class DefaultTable extends AbstractTable
{
/**
* Creates a new table object using the given $tableMetaData
*
* @param ITableMetadata $tableMetaData
*/
public function __construct(ITableMetadata $tableMetaData)
{
$this->setTableMetaData($tableMetaData);
$this->data = [];
}
/**
* Adds a row to the table with optional values.
*
* @param array $values
*/
public function addRow($values = [])
{
$this->data[] = array_replace(
array_fill_keys($this->getTableMetaData()->getColumns(), null),
$values
);
}
/**
* Adds the rows in the passed table to the current table.
*
* @param ITable $table
*/
public function addTableRows(ITable $table)
{
$tableColumns = $this->getTableMetaData()->getColumns();
$rowCount = $table->getRowCount();
for ($i = 0; $i < $rowCount; $i++) {
$newRow = [];
foreach ($tableColumns as $columnName) {
$newRow[$columnName] = $table->getValue($i, $columnName);
}
$this->addRow($newRow);
}
}
/**
* Sets the specified column of the specied row to the specified value.
*
* @param int $row
* @param string $column
* @param mixed $value
*/
public function setValue($row, $column, $value)
{
if (isset($this->data[$row])) {
$this->data[$row][$column] = $value;
} else {
throw new InvalidArgumentException('The row given does not exist.');
}
}
}

View File

@@ -0,0 +1,120 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
/**
* The default table iterator
*/
class DefaultTableIterator implements ITableIterator
{
/**
* An array of tables in the iterator.
*
* @var array
*/
protected $tables;
/**
* If this property is true then the tables will be iterated in reverse
* order.
*
* @var bool
*/
protected $reverse;
/**
* Creates a new default table iterator object.
*
* @param array $tables
* @param bool $reverse
*/
public function __construct(array $tables, $reverse = false)
{
$this->tables = $tables;
$this->reverse = $reverse;
$this->rewind();
}
/**
* Returns the current table.
*
* @return ITable
*/
public function getTable()
{
return $this->current();
}
/**
* Returns the current table's meta data.
*
* @return ITableMetadata
*/
public function getTableMetaData()
{
return $this->current()->getTableMetaData();
}
/**
* Returns the current table.
*
* @return ITable
*/
public function current()
{
return current($this->tables);
}
/**
* Returns the name of the current table.
*
* @return string
*/
public function key()
{
return $this->current()->getTableMetaData()->getTableName();
}
/**
* advances to the next element.
*/
public function next()
{
if ($this->reverse) {
prev($this->tables);
} else {
next($this->tables);
}
}
/**
* Rewinds to the first element
*/
public function rewind()
{
if ($this->reverse) {
end($this->tables);
} else {
reset($this->tables);
}
}
/**
* Returns true if the current index is valid
*
* @return bool
*/
public function valid()
{
return ($this->current() !== false);
}
}

View File

@@ -0,0 +1,41 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PHPUnit\DbUnit\InvalidArgumentException;
/**
* The default implementation of table meta data
*/
class DefaultTableMetadata extends AbstractTableMetadata
{
/**
* Creates a new default table meta data object.
*
* @param string $tableName
* @param array $columns
* @param array $primaryKeys
*/
public function __construct($tableName, array $columns, array $primaryKeys = [])
{
$this->tableName = $tableName;
$this->columns = $columns;
$this->primaryKeys = [];
foreach ($primaryKeys as $columnName) {
if (!in_array($columnName, $this->columns)) {
throw new InvalidArgumentException('Primary key column passed that is not in the column list.');
} else {
$this->primaryKeys[] = $columnName;
}
}
}
}

View File

@@ -0,0 +1,165 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
/**
* A dataset decorator that allows filtering out tables and table columns from
* results.
*/
class Filter extends AbstractDataSet
{
/**
* The dataset being decorated.
*
* @var IDataSet
*/
protected $originalDataSet;
/**
* The tables to exclude from the data set.
*
* @var array
*/
protected $excludeTables = [];
/**
* The tables to exclude from the data set.
*
* @var array
*/
protected $includeTables = [];
/**
* The columns to exclude from the data set.
*
* @var array
*/
protected $excludeColumns = [];
/**
* The columns to exclude from the data set.
*
* @var array
*/
protected $includeColumns = [];
/**
* Creates a new filtered data set.
*
* The $exclude tables should be an associative array using table names as
* the key and an array of column names to exclude for the value. If you
* would like to exclude a full table set the value of the table's entry
* to the special string '*'.
*
* @param IDataSet $originalDataSet
* @param array $excludeTables @deprecated use set* methods instead.
*/
public function __construct(IDataSet $originalDataSet, array $excludeTables = [])
{
$this->originalDataSet = $originalDataSet;
$tables = [];
foreach ($excludeTables as $tableName => $values) {
if (is_array($values)) {
$this->setExcludeColumnsForTable($tableName, $values);
} elseif ($values == '*') {
$tables[] = $tableName;
} else {
$this->setExcludeColumnsForTable($tableName, (array) $values);
}
}
$this->addExcludeTables($tables);
}
/**
* Creates an iterator over the tables in the data set. If $reverse is
* true a reverse iterator will be returned.
*
* @param bool $reverse
*
* @return ITableIterator
*/
protected function createIterator($reverse = false)
{
$original_tables = $this->originalDataSet->getIterator($reverse);
$new_tables = [];
foreach ($original_tables as $table) {
/* @var $table ITable */
$tableName = $table->getTableMetaData()->getTableName();
if ((!in_array($tableName, $this->includeTables) && !empty($this->includeTables)) ||
in_array($tableName, $this->excludeTables)
) {
continue;
} elseif (!empty($this->excludeColumns[$tableName]) || !empty($this->includeColumns[$tableName])) {
$new_table = new TableFilter($table);
if (!empty($this->includeColumns[$tableName])) {
$new_table->addIncludeColumns($this->includeColumns[$tableName]);
}
if (!empty($this->excludeColumns[$tableName])) {
$new_table->addExcludeColumns($this->excludeColumns[$tableName]);
}
$new_tables[] = $new_table;
} else {
$new_tables[] = $table;
}
}
return new DefaultTableIterator($new_tables);
}
/**
* Adds tables to be included in the data set.
*
* @param array $tables
*/
public function addIncludeTables(array $tables)
{
$this->includeTables = array_unique(array_merge($this->includeTables, $tables));
}
/**
* Adds tables to be included in the data set.
*
* @param array $tables
*/
public function addExcludeTables(array $tables)
{
$this->excludeTables = array_unique(array_merge($this->excludeTables, $tables));
}
/**
* Adds columns to include in the data set for the given table.
*
* @param string $table
* @param array $columns
*/
public function setIncludeColumnsForTable($table, array $columns)
{
$this->includeColumns[$table] = $columns;
}
/**
* Adds columns to include in the data set for the given table.
*
* @param string $table
* @param array $columns
*/
public function setExcludeColumnsForTable($table, array $columns)
{
$this->excludeColumns[$table] = $columns;
}
}

View File

@@ -0,0 +1,48 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PHPUnit\DbUnit\RuntimeException;
/**
* The default implementation of a data set.
*/
class FlatXmlDataSet extends AbstractXmlDataSet
{
protected function getTableInfo(array &$tableColumns, array &$tableValues)
{
if ($this->xmlFileContents->getName() != 'dataset') {
throw new RuntimeException('The root element of a flat xml data set file must be called <dataset>');
}
foreach ($this->xmlFileContents->children() as $row) {
$tableName = $row->getName();
if (!isset($tableColumns[$tableName])) {
$tableColumns[$tableName] = [];
$tableValues[$tableName] = [];
}
$values = [];
foreach ($row->attributes() as $name => $value) {
if (!in_array($name, $tableColumns[$tableName])) {
$tableColumns[$tableName][] = $name;
}
$values[$name] = $value;
}
if (count($values)) {
$tableValues[$tableName][] = $values;
}
}
}
}

View File

@@ -0,0 +1,58 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use IteratorAggregate;
/**
* Provides a basic interface for creating and reading data from data sets.
*/
interface IDataSet extends IteratorAggregate
{
/**
* Returns an array of table names contained in the dataset.
*
* @return array
*/
public function getTableNames();
/**
* Returns a table meta data object for the given table.
*
* @param string $tableName
*
* @return ITableMetadata
*/
public function getTableMetaData($tableName);
/**
* Returns a table object for the given table.
*
* @param string $tableName
*
* @return ITable
*/
public function getTable($tableName);
/**
* Returns a reverse iterator for all table objects in the given dataset.
*
* @return ITableIterator
*/
public function getReverseIterator();
/**
* Asserts that the given data set matches this data set.
*
* @param IDataSet $other
*/
public function matches(IDataSet $other);
}

View File

@@ -0,0 +1,55 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
/**
* Provides a basic interface for creating and reading data from data sets.
*/
interface ITable
{
/**
* Returns the table's meta data.
*
* @return ITableMetadata
*/
public function getTableMetaData();
/**
* Returns the number of rows in this table.
*
* @return int
*/
public function getRowCount();
/**
* Returns the value for the given column on the given row.
*
* @param int $row
* @param int $column
*/
public function getValue($row, $column);
/**
* Returns the an associative array keyed by columns for the given row.
*
* @param int $row
*
* @return array
*/
public function getRow($row);
/**
* Asserts that the given table matches this table.
*
* @param ITable $other
*/
public function matches(ITable $other);
}

View File

@@ -0,0 +1,33 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use Iterator;
/**
* Provides a basic interface for creating and reading data from data sets.
*/
interface ITableIterator extends Iterator
{
/**
* Returns the current table.
*
* @return ITable
*/
public function getTable();
/**
* Returns the current table's meta data.
*
* @return ITableMetadata
*/
public function getTableMetaData();
}

View File

@@ -0,0 +1,45 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
/**
* Provides a basic interface for returning table meta data.
*/
interface ITableMetadata
{
/**
* Returns the names of the columns in the table.
*
* @return array
*/
public function getColumns();
/**
* Returns the names of the primary key columns in the table.
*
* @return array
*/
public function getPrimaryKeys();
/**
* Returns the name of the table.
*
* @return string
*/
public function getTableName();
/**
* Asserts that the given tableMetaData matches this tableMetaData.
*
* @param ITableMetadata $other
*/
public function matches(ITableMetadata $other);
}

View File

@@ -0,0 +1,24 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
/**
* An interface for parsing YAML files.
*/
interface IYamlParser
{
/**
* @param string $yamlFile
*
* @return array parsed YAML
*/
public function parseYaml($yamlFile);
}

View File

@@ -0,0 +1,95 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PHPUnit\DbUnit\RuntimeException;
/**
* Data set implementation for the output of mysqldump --xml.
*/
class MysqlXmlDataSet extends AbstractXmlDataSet
{
protected function getTableInfo(array &$tableColumns, array &$tableValues)
{
if ($this->xmlFileContents->getName() != 'mysqldump') {
throw new RuntimeException('The root element of a MySQL XML data set file must be called <mysqldump>');
}
foreach ($this->xmlFileContents->xpath('./database/table_data') as $tableElement) {
if (empty($tableElement['name'])) {
throw new RuntimeException('<table_data> elements must include a name attribute');
}
$tableName = (string) $tableElement['name'];
if (!isset($tableColumns[$tableName])) {
$tableColumns[$tableName] = [];
}
if (!isset($tableValues[$tableName])) {
$tableValues[$tableName] = [];
}
foreach ($tableElement->xpath('./row') as $rowElement) {
$rowValues = [];
foreach ($rowElement->xpath('./field') as $columnElement) {
if (empty($columnElement['name'])) {
throw new RuntimeException('<field> element name attributes cannot be empty');
}
$columnName = (string) $columnElement['name'];
if (!in_array($columnName, $tableColumns[$tableName])) {
$tableColumns[$tableName][] = $columnName;
}
}
foreach ($tableColumns[$tableName] as $columnName) {
$fields = $rowElement->xpath('./field[@name="' . $columnName . '"]');
$column = $fields[0];
$attr = $column->attributes('http://www.w3.org/2001/XMLSchema-instance');
if (isset($attr['type']) && (string) $attr['type'] === 'xs:hexBinary') {
$columnValue = pack('H*', (string) $column);
} else {
$null = isset($column['nil']) || isset($attr[0]);
$columnValue = $null ? null : (string) $column;
}
$rowValues[$columnName] = $columnValue;
}
$tableValues[$tableName][] = $rowValues;
}
}
foreach ($this->xmlFileContents->xpath('./database/table_structure') as $tableElement) {
if (empty($tableElement['name'])) {
throw new RuntimeException('<table_structure> elements must include a name attribute');
}
$tableName = (string) $tableElement['name'];
foreach ($tableElement->xpath('./field') as $fieldElement) {
if (empty($fieldElement['Field']) && empty($fieldElement['field'])) {
throw new RuntimeException('<field> elements must include a Field attribute');
}
$columnName = (string) (empty($fieldElement['Field']) ? $fieldElement['field'] : $fieldElement['Field']);
if (!in_array($columnName, $tableColumns[$tableName])) {
$tableColumns[$tableName][] = $columnName;
}
}
}
}
}

View File

@@ -0,0 +1,94 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PHPUnit\DbUnit\Database\Connection;
use PHPUnit\DbUnit\Database\Table;
use PHPUnit\DbUnit\Database\TableIterator;
use PHPUnit\DbUnit\InvalidArgumentException;
/**
* Provides access to a database instance as a data set.
*/
class QueryDataSet extends AbstractDataSet
{
/**
* An array of ITable objects.
*
* @var array
*/
protected $tables = [];
/**
* The database connection this dataset is using.
*
* @var Connection
*/
protected $databaseConnection;
/**
* Creates a new dataset using the given database connection.
*
* @param Connection $databaseConnection
*/
public function __construct(Connection $databaseConnection)
{
$this->databaseConnection = $databaseConnection;
}
public function addTable($tableName, $query = null)
{
if ($query === null) {
$query = 'SELECT * FROM ' . $tableName;
}
$this->tables[$tableName] = new QueryTable($tableName, $query, $this->databaseConnection);
}
/**
* Creates an iterator over the tables in the data set. If $reverse is
* true a reverse iterator will be returned.
*
* @param bool $reverse
*
* @return TableIterator
*/
protected function createIterator($reverse = false)
{
return new DefaultTableIterator($this->tables, $reverse);
}
/**
* Returns a table object for the given table.
*
* @param string $tableName
*
* @return Table
*/
public function getTable($tableName)
{
if (!isset($this->tables[$tableName])) {
throw new InvalidArgumentException("$tableName is not a table in the current database.");
}
return $this->tables[$tableName];
}
/**
* Returns a list of table names for the database
*
* @return array
*/
public function getTableNames()
{
return array_keys($this->tables);
}
}

View File

@@ -0,0 +1,159 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PDO;
use PHPUnit\DbUnit\Database\Connection;
/**
* Provides the functionality to represent a database table.
*/
class QueryTable extends AbstractTable
{
/**
* @var string
*/
protected $query;
/**
* @var Connection
*/
protected $databaseConnection;
/**
* @var string
*/
protected $tableName;
/**
* Creates a new database query table object.
*
* @param string $table_name
* @param string $query
* @param Connection $databaseConnection
*/
public function __construct($tableName, $query, Connection $databaseConnection)
{
$this->query = $query;
$this->databaseConnection = $databaseConnection;
$this->tableName = $tableName;
}
/**
* Returns the table's meta data.
*
* @return ITableMetadata
*/
public function getTableMetaData()
{
$this->createTableMetaData();
return parent::getTableMetaData();
}
/**
* Checks if a given row is in the table
*
* @param array $row
*
* @return bool
*/
public function assertContainsRow(array $row)
{
$this->loadData();
return parent::assertContainsRow($row);
}
/**
* Returns the number of rows in this table.
*
* @return int
*/
public function getRowCount()
{
$this->loadData();
return parent::getRowCount();
}
/**
* Returns the value for the given column on the given row.
*
* @param int $row
* @param int $column
*/
public function getValue($row, $column)
{
$this->loadData();
return parent::getValue($row, $column);
}
/**
* Returns the an associative array keyed by columns for the given row.
*
* @param int $row
*
* @return array
*/
public function getRow($row)
{
$this->loadData();
return parent::getRow($row);
}
/**
* Asserts that the given table matches this table.
*
* @param ITable $other
*/
public function matches(ITable $other)
{
$this->loadData();
return parent::matches($other);
}
protected function loadData()
{
if ($this->data === null) {
$pdoStatement = $this->databaseConnection->getConnection()->query($this->query);
$this->data = $pdoStatement->fetchAll(PDO::FETCH_ASSOC);
}
}
protected function createTableMetaData()
{
if ($this->tableMetaData === null) {
$this->loadData();
// if some rows are in the table
$columns = [];
if (isset($this->data[0])) {
// get column names from data
$columns = array_keys($this->data[0]);
} else {
// if no rows found, get column names from database
$pdoStatement = $this->databaseConnection->getConnection()->prepare('SELECT column_name FROM information_schema.COLUMNS WHERE table_schema=:schema AND table_name=:table');
$pdoStatement->execute([
'table' => $this->tableName,
'schema' => $this->databaseConnection->getSchema()
]);
$columns = $pdoStatement->fetchAll(PDO::FETCH_COLUMN, 0);
}
// create metadata
$this->tableMetaData = new DefaultTableMetadata($this->tableName, $columns);
}
}
}

View File

@@ -0,0 +1,91 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
/**
* Allows for replacing arbitrary values or portions of values with new data.
*
* A usage for this is replacing all values == '[NULL'] with a true NULL value
*/
class ReplacementDataSet extends AbstractDataSet
{
/**
* @var IDataSet
*/
protected $dataSet;
/**
* @var array
*/
protected $fullReplacements;
/**
* @var array
*/
protected $subStrReplacements;
/**
* Creates a new replacement dataset
*
* You can pass in any data set that implements PHPUnit_Extensions_Database_DataSet_IDataSet
*
* @param string $delimiter
* @param string $enclosure
* @param string $escape
*/
public function __construct(IDataSet $dataSet, array $fullReplacements = [], array $subStrReplacements = [])
{
$this->dataSet = $dataSet;
$this->fullReplacements = $fullReplacements;
$this->subStrReplacements = $subStrReplacements;
}
/**
* Adds a new full replacement
*
* Full replacements will only replace values if the FULL value is a match
*
* @param string $value
* @param string $replacement
*/
public function addFullReplacement($value, $replacement)
{
$this->fullReplacements[$value] = $replacement;
}
/**
* Adds a new substr replacement
*
* Substr replacements will replace all occurances of the substr in every column
*
* @param string $value
* @param string $replacement
*/
public function addSubStrReplacement($value, $replacement)
{
$this->subStrReplacements[$value] = $replacement;
}
/**
* Creates an iterator over the tables in the data set. If $reverse is
* true a reverse iterator will be returned.
*
* @param bool $reverse
*
* @return ITableIterator
*/
protected function createIterator($reverse = false)
{
$innerIterator = $reverse ? $this->dataSet->getReverseIterator() : $this->dataSet->getIterator();
return new ReplacementTableIterator($innerIterator, $this->fullReplacements, $this->subStrReplacements);
}
}

View File

@@ -0,0 +1,210 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
/**
* Allows for replacing arbitrary strings in your data sets with other values.
*
* @todo When setTableMetaData() is taken out of the AbstractTable this class should extend AbstractTable.
*/
class ReplacementTable implements ITable
{
/**
* @var ITable
*/
protected $table;
/**
* @var array
*/
protected $fullReplacements;
/**
* @var array
*/
protected $subStrReplacements;
/**
* Creates a new replacement table
*
* @param ITable $table
* @param array $fullReplacements
* @param array $subStrReplacements
*/
public function __construct(ITable $table, array $fullReplacements = [], array $subStrReplacements = [])
{
$this->table = $table;
$this->fullReplacements = $fullReplacements;
$this->subStrReplacements = $subStrReplacements;
}
/**
* Adds a new full replacement
*
* Full replacements will only replace values if the FULL value is a match
*
* @param string $value
* @param string $replacement
*/
public function addFullReplacement($value, $replacement)
{
$this->fullReplacements[$value] = $replacement;
}
/**
* Adds a new substr replacement
*
* Substr replacements will replace all occurances of the substr in every column
*
* @param string $value
* @param string $replacement
*/
public function addSubStrReplacement($value, $replacement)
{
$this->subStrReplacements[$value] = $replacement;
}
/**
* Returns the table's meta data.
*
* @return ITableMetadata
*/
public function getTableMetaData()
{
return $this->table->getTableMetaData();
}
/**
* Returns the number of rows in this table.
*
* @return int
*/
public function getRowCount()
{
return $this->table->getRowCount();
}
/**
* Returns the value for the given column on the given row.
*
* @param int $row
* @param int $column
*/
public function getValue($row, $column)
{
return $this->getReplacedValue($this->table->getValue($row, $column));
}
/**
* Returns the an associative array keyed by columns for the given row.
*
* @param int $row
*
* @return array
*/
public function getRow($row)
{
$row = $this->table->getRow($row);
return array_map([$this, 'getReplacedValue'], $row);
}
/**
* Asserts that the given table matches this table.
*
* @param ITable $other
*/
public function matches(ITable $other)
{
$thisMetaData = $this->getTableMetaData();
$otherMetaData = $other->getTableMetaData();
if (!$thisMetaData->matches($otherMetaData) ||
$this->getRowCount() != $other->getRowCount()
) {
return false;
}
$columns = $thisMetaData->getColumns();
$rowCount = $this->getRowCount();
for ($i = 0; $i < $rowCount; $i++) {
foreach ($columns as $columnName) {
$thisValue = $this->getValue($i, $columnName);
$otherValue = $other->getValue($i, $columnName);
if (is_numeric($thisValue) && is_numeric($otherValue)) {
if ($thisValue != $otherValue) {
return false;
}
} elseif ($thisValue !== $otherValue) {
return false;
}
}
}
return true;
}
public function __toString()
{
$columns = $this->getTableMetaData()->getColumns();
$lineSeperator = str_repeat('+----------------------', count($columns)) . "+\n";
$lineLength = strlen($lineSeperator) - 1;
$tableString = $lineSeperator;
$tableString .= '| ' . str_pad($this->getTableMetaData()->getTableName(), $lineLength - 4, ' ', STR_PAD_RIGHT) . " |\n";
$tableString .= $lineSeperator;
$tableString .= $this->rowToString($columns);
$tableString .= $lineSeperator;
$rowCount = $this->getRowCount();
for ($i = 0; $i < $rowCount; $i++) {
$values = [];
foreach ($columns as $columnName) {
$values[] = $this->getValue($i, $columnName);
}
$tableString .= $this->rowToString($values);
$tableString .= $lineSeperator;
}
return "\n" . $tableString . "\n";
}
protected function rowToString(array $row)
{
$rowString = '';
foreach ($row as $value) {
if (is_null($value)) {
$value = 'NULL';
}
$rowString .= '| ' . str_pad(substr($value, 0, 20), 20, ' ', STR_PAD_BOTH) . ' ';
}
return $rowString . "|\n";
}
protected function getReplacedValue($value)
{
if (is_scalar($value) && array_key_exists((string) $value, $this->fullReplacements)) {
return $this->fullReplacements[$value];
} elseif (count($this->subStrReplacements) && isset($value)) {
return str_replace(array_keys($this->subStrReplacements), array_values($this->subStrReplacements), $value);
} else {
return $value;
}
}
}

View File

@@ -0,0 +1,145 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use OuterIterator;
/**
* The default table iterator
*/
class ReplacementTableIterator implements OuterIterator, ITableIterator
{
/**
* @var ITableIterator
*/
protected $innerIterator;
/**
* @var array
*/
protected $fullReplacements;
/**
* @var array
*/
protected $subStrReplacements;
/**
* Creates a new replacement table iterator object.
*
* @param ITableIterator $innerIterator
* @param array $fullReplacements
* @param array $subStrReplacements
*/
public function __construct(ITableIterator $innerIterator, array $fullReplacements = [], array $subStrReplacements = [])
{
$this->innerIterator = $innerIterator;
$this->fullReplacements = $fullReplacements;
$this->subStrReplacements = $subStrReplacements;
}
/**
* Adds a new full replacement
*
* Full replacements will only replace values if the FULL value is a match
*
* @param string $value
* @param string $replacement
*/
public function addFullReplacement($value, $replacement)
{
$this->fullReplacements[$value] = $replacement;
}
/**
* Adds a new substr replacement
*
* Substr replacements will replace all occurances of the substr in every column
*
* @param string $value
* @param string $replacement
*/
public function addSubStrReplacement($value, $replacement)
{
$this->subStrReplacements[$value] = $replacement;
}
/**
* Returns the current table.
*
* @return ITable
*/
public function getTable()
{
return $this->current();
}
/**
* Returns the current table's meta data.
*
* @return ITableMetadata
*/
public function getTableMetaData()
{
$this->current()->getTableMetaData();
}
/**
* Returns the current table.
*
* @return ITable
*/
public function current()
{
return new ReplacementTable($this->innerIterator->current(), $this->fullReplacements, $this->subStrReplacements);
}
/**
* Returns the name of the current table.
*
* @return string
*/
public function key()
{
return $this->current()->getTableMetaData()->getTableName();
}
/**
* advances to the next element.
*/
public function next()
{
$this->innerIterator->next();
}
/**
* Rewinds to the first element
*/
public function rewind()
{
$this->innerIterator->rewind();
}
/**
* Returns true if the current index is valid
*
* @return bool
*/
public function valid()
{
return $this->innerIterator->valid();
}
public function getInnerIterator()
{
return $this->innerIterator;
}
}

View File

@@ -0,0 +1,92 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet\Specification;
use PHPUnit\DbUnit\DataSet\CsvDataSet;
use ReflectionClass;
/**
* Creates CsvDataSets based off of a spec string.
*
* The format of the spec string is as follows:
*
* <csv options>|table1:filename.csv,table2:filename2.csv
*
* The first portion of the spec including the pipe symbol '|' is optional.
* If the pipe option is included than it may be preceded by up to four
* characters specifying values for the following arguments in order:
* delimiter (defaults to ',',) enclosure (defaults to '"',) escape (defaults to '"',).
*
* Any additional characters in the csv options will be discarded.
*/
class Csv implements Specification
{
/**
* Creates CSV Data Set from a data set spec.
*
* @param string $dataSetSpec
*
* @return CsvDataSet
*/
public function getDataSet($dataSetSpec)
{
$csvDataSetArgs = $this->getCsvOptions($dataSetSpec);
$csvDataSetRfl = new ReflectionClass(CsvDataSet::class);
$csvDataSet = $csvDataSetRfl->newInstanceArgs($csvDataSetArgs);
foreach ($this->getTableFileMap($dataSetSpec) as $tableName => $file) {
$csvDataSet->addTable($tableName, $file);
}
return $csvDataSet;
}
/**
* Returns CSV options.
*
* Returns an array containing the options that will be passed to the
* PHPUnit_Extensions_Database_DataSet_CsvDataSet constructor. The options
* are determined by the given $dataSetSpec.
*
* @param string $dataSetSpec
*
* @return array
*/
protected function getCsvOptions($dataSetSpec)
{
list($csvOptStr) = explode('|', $dataSetSpec, 2);
return str_split($csvOptStr);
}
/**
* Returns map of tables to files.
*
* Returns an associative array containing a mapping of tables (the key)
* to files (the values.) The tables and files are determined by the given
* $dataSetSpec
*
* @param string $dataSetSpec
*
* @return array
*/
protected function getTableFileMap($dataSetSpec)
{
$tables = [];
foreach (explode(',', $dataSetSpec) as $csvfile) {
list($tableName, $file) = explode(':', $csvfile, 2);
$tables[$tableName] = $file;
}
return $tables;
}
}

View File

@@ -0,0 +1,52 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet\Specification;
use PHPUnit\DbUnit\RuntimeException;
/**
* Creates the appropriate DataSet Spec based on a given type.
*/
class Factory implements IFactory
{
/**
* Returns the data set
*
* @param string $type
*
* @return Specification
*/
public function getDataSetSpecByType($type)
{
switch ($type) {
case 'xml':
return new Xml();
case 'flatxml':
return new FlatXml();
case 'csv':
return new Csv();
case 'yaml':
return new Yaml();
case 'dbtable':
return new Table();
case 'dbquery':
return new Query();
default:
throw new RuntimeException("I don't know what you want from me.");
}
}
}

View File

@@ -0,0 +1,38 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet\Specification;
use PHPUnit\DbUnit\DataSet\FlatXmlDataSet;
/**
* Creates a FlatXML dataset based off of a spec string.
*
* The format of the spec string is as follows:
*
* <filename>
*
* The filename should be the location of a flat xml file relative to the
* current working directory.
*/
class FlatXml implements Specification
{
/**
* Creates Flat XML Data Set from a data set spec.
*
* @param string $dataSetSpec
*
* @return FlatXmlDataSet
*/
public function getDataSet($dataSetSpec)
{
return new FlatXmlDataSet($dataSetSpec);
}
}

View File

@@ -0,0 +1,26 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet\Specification;
/**
* An interface for data set spec factories.
*/
interface IFactory
{
/**
* Returns the data set
*
* @param string $type
*
* @return Specification
*/
public function getDataSetSpecByType($type);
}

View File

@@ -0,0 +1,77 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet\Specification;
use PHPUnit\DbUnit\Database\DefaultConnection;
use PHPUnit\DbUnit\DatabaseListConsumer;
use PHPUnit\DbUnit\DataSet\DefaultDataSet;
use ReflectionClass;
/**
* Creates DefaultDataSets based off of a spec string.
*
* This spec class requires a list of databases to be set to the object before
* it can return a list of databases.
*
* The format of the spec string is as follows:
*
* <db label>:<schema>:<table name>:<sql>
*
* The db label should be equal to one of the keys in the array of databases
* passed to setDatabases().
*
* The schema should be the primary schema you will be running the sql query
* against.
*
* The table name should be set to what you would like the table name in the
* dataset to be.
*
* The sql is the query you want to use to generate the table columns and data.
* The column names in the table will be identical to the column aliases in the
* query.
*/
class Query implements Specification, DatabaseListConsumer
{
/**
* @var array
*/
protected $databases = [];
/**
* Sets the database for the spec
*
* @param array $databases
*/
public function setDatabases(array $databases)
{
$this->databases = $databases;
}
/**
* Creates a Default Data Set with a query table from a data set spec.
*
* @param string $dataSetSpec
*
* @return DefaultDataSet
*/
public function getDataSet($dataSetSpec)
{
list($dbLabel, $schema, $table, $sql) = explode(':', $dataSetSpec, 4);
$databaseInfo = $this->databases[$dbLabel];
$pdoRflc = new ReflectionClass('PDO');
$pdo = $pdoRflc->newInstanceArgs(explode('|', $databaseInfo));
$dbConnection = new DefaultConnection($pdo, $schema);
$table = $dbConnection->createQueryTable($table, $sql);
return new DefaultDataSet([$table]);
}
}

View File

@@ -0,0 +1,28 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet\Specification;
use PHPUnit\DbUnit\DataSet\IDataSet;
/**
* Provides an interface for creating data sets from data set spec strings.
*/
interface Specification
{
/**
* Creates a data set from a data set spec string.
*
* @param string $dataSetSpec
*
* @return IDataSet
*/
public function getDataSet($dataSetSpec);
}

View File

@@ -0,0 +1,75 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet\Specification;
use PHPUnit\DbUnit\Database\DefaultConnection;
use PHPUnit\DbUnit\DatabaseListConsumer;
use PHPUnit\DbUnit\DataSet\IDataSet;
use ReflectionClass;
/**
* Creates a database dataset based off of a spec string.
*
* This spec class requires a list of databases to be set to the object before
* it can return a list of databases.
*
* The format of the spec string is as follows:
*
* <db label>:<schema>:<tables>
*
* The db label should be equal to one of the keys in the array of databases
* passed to setDatabases().
*
* The schema should be the primary schema you will be choosing tables from.
*
* The tables should be a comma delimited list of all tables you would like to
* pull data from.
*
* The sql is the query you want to use to generate the table columns and data.
* The column names in the table will be identical to the column aliases in the
* query.
*/
class Table implements Specification, DatabaseListConsumer
{
/**
* @var array
*/
protected $databases = [];
/**
* Sets the database for the spec
*
* @param array $databases
*/
public function setDatabases(array $databases)
{
$this->databases = $databases;
}
/**
* Creates a DB Data Set from a data set spec.
*
* @param string $dataSetSpec
*
* @return IDataSet
*/
public function getDataSet($dataSetSpec)
{
list($dbLabel, $schema, $tables) = explode(':', $dataSetSpec, 3);
$databaseInfo = $this->databases[$dbLabel];
$pdoRflc = new ReflectionClass('PDO');
$pdo = $pdoRflc->newInstanceArgs(explode('|', $databaseInfo));
$dbConnection = new DefaultConnection($pdo, $schema);
return !empty($tables) ? $dbConnection->createDataSet(explode(',', $tables)) : $dbConnection->createDataSet();
}
}

View File

@@ -0,0 +1,38 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet\Specification;
use PHPUnit\DbUnit\DataSet\XmlDataSet;
/**
* Creates a XML dataset based off of a spec string.
*
* The format of the spec string is as follows:
*
* <filename>
*
* The filename should be the location of a xml file relative to the
* current working directory.
*/
class Xml implements Specification
{
/**
* Creates XML Data Set from a data set spec.
*
* @param string $dataSetSpec
*
* @return XmlDataSet
*/
public function getDataSet($dataSetSpec)
{
return new XmlDataSet($dataSetSpec);
}
}

View File

@@ -0,0 +1,38 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet\Specification;
use PHPUnit\DbUnit\DataSet\YamlDataSet;
/**
* Creates a YAML dataset based off of a spec string.
*
* The format of the spec string is as follows:
*
* <filename>
*
* The filename should be the location of a yaml file relative to the
* current working directory.
*/
class Yaml implements Specification
{
/**
* Creates YAML Data Set from a data set spec.
*
* @param string $dataSetSpec
*
* @return YamlDataSet
*/
public function getDataSet($dataSetSpec)
{
return new YamlDataSet($dataSetSpec);
}
}

View File

@@ -0,0 +1,24 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use Symfony;
/**
* The default YAML parser, using Symfony/Yaml.
*/
class SymfonyYamlParser implements IYamlParser
{
public function parseYaml($yamlFile)
{
return Symfony\Component\Yaml\Yaml::parse(file_get_contents($yamlFile));
}
}

View File

@@ -0,0 +1,132 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PHPUnit\DbUnit\InvalidArgumentException;
/**
* A table decorator that allows filtering out table columns from results.
*/
class TableFilter extends AbstractTable
{
/**
* The table meta data being decorated.
*
* @var ITable
*/
protected $originalTable;
/**
* Creates a new table filter using the original table
*
* @param $originalTable ITable
* @param $excludeColumns Array @deprecated, use the set* methods instead.
*/
public function __construct(ITable $originalTable, array $excludeColumns = [])
{
$this->originalTable = $originalTable;
$this->setTableMetaData(new TableMetadataFilter($originalTable->getTableMetaData()));
$this->addExcludeColumns($excludeColumns);
}
/**
* Returns the number of rows in this table.
*
* @return int
*/
public function getRowCount()
{
return $this->originalTable->getRowCount();
}
/**
* Returns the value for the given column on the given row.
*
* @param int $row
* @param int $column
*/
public function getValue($row, $column)
{
if (in_array($column, $this->getTableMetaData()->getColumns())) {
return $this->originalTable->getValue($row, $column);
} else {
throw new InvalidArgumentException("The given row ({$row}) and column ({$column}) do not exist in table {$this->getTableMetaData()->getTableName()}");
}
}
/**
* Sets the columns to include in the table.
*
* @param array $includeColumns
*/
public function addIncludeColumns(array $includeColumns)
{
$this->tableMetaData->addIncludeColumns($includeColumns);
}
/**
* Clears the included columns.
*/
public function clearIncludeColumns()
{
$this->tableMetaData->clearIncludeColumns();
}
/**
* Sets the columns to exclude from the table.
*
* @param array $excludeColumns
*/
public function addExcludeColumns(array $excludeColumns)
{
$this->tableMetaData->addExcludeColumns($excludeColumns);
}
/**
* Clears the included columns.
*/
public function clearExcludeColumns()
{
$this->tableMetaData->clearExcludeColumns();
}
/**
* Checks if a given row is in the table
*
* @param array $row
*
* @return bool
*/
public function assertContainsRow(array $row)
{
$this->loadData();
return parent::assertContainsRow($row);
}
/**
* Loads data into local data table if it's not already loaded
*/
protected function loadData()
{
if ($this->data === null) {
$data = [];
for ($row = 0; $row < $this->originalTable->getRowCount(); $row++) {
$tRow = [];
foreach ($this->getTableMetaData()->getColumns() as $col) {
$tRow[$col] = $this->getValue($row, $col);
}
$data[$row] = $tRow;
}
$this->data = $data;
}
}
}

View File

@@ -0,0 +1,127 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
/**
* A TableMetaData decorator that allows filtering columns from another
* metaData object.
*
* The if a whitelist (include) filter is specified, then only those columns
* will be included.
*/
class TableMetadataFilter extends AbstractTableMetadata
{
/**
* The table meta data being decorated.
*
* @var ITableMetadata
*/
protected $originalMetaData;
/**
* The columns to exclude from the meta data.
*
* @var array
*/
protected $excludeColumns = [];
/**
* The columns to include from the meta data.
*
* @var array
*/
protected $includeColumns = [];
/**
* Creates a new filtered table meta data object filtering out
* $excludeColumns.
*
* @param ITableMetadata $originalMetaData
* @param array $excludeColumns - Deprecated. Use the set* methods instead.
*/
public function __construct(ITableMetadata $originalMetaData, array $excludeColumns = [])
{
$this->originalMetaData = $originalMetaData;
$this->addExcludeColumns($excludeColumns);
}
/**
* Returns the names of the columns in the table.
*
* @return array
*/
public function getColumns()
{
if (!empty($this->includeColumns)) {
return array_values(array_intersect($this->originalMetaData->getColumns(), $this->includeColumns));
} elseif (!empty($this->excludeColumns)) {
return array_values(array_diff($this->originalMetaData->getColumns(), $this->excludeColumns));
} else {
return $this->originalMetaData->getColumns();
}
}
/**
* Returns the names of the primary key columns in the table.
*
* @return array
*/
public function getPrimaryKeys()
{
return $this->originalMetaData->getPrimaryKeys();
}
/**
* Returns the name of the table.
*
* @return string
*/
public function getTableName()
{
return $this->originalMetaData->getTableName();
}
/**
* Sets the columns to include in the table.
*
* @param array $includeColumns
*/
public function addIncludeColumns(array $includeColumns)
{
$this->includeColumns = array_unique(array_merge($this->includeColumns, $includeColumns));
}
/**
* Clears the included columns.
*/
public function clearIncludeColumns()
{
$this->includeColumns = [];
}
/**
* Sets the columns to exclude from the table.
*
* @param array $excludeColumns
*/
public function addExcludeColumns(array $excludeColumns)
{
$this->excludeColumns = array_unique(array_merge($this->excludeColumns, $excludeColumns));
}
/**
* Clears the excluded columns.
*/
public function clearExcludeColumns()
{
$this->excludeColumns = [];
}
}

View File

@@ -0,0 +1,83 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
use PHPUnit\DbUnit\RuntimeException;
/**
* The default implementation of a data set.
*/
class XmlDataSet extends AbstractXmlDataSet
{
protected function getTableInfo(array &$tableColumns, array &$tableValues)
{
if ($this->xmlFileContents->getName() != 'dataset') {
throw new RuntimeException('The root element of an xml data set file must be called <dataset>');
}
foreach ($this->xmlFileContents->xpath('/dataset/table') as $tableElement) {
if (empty($tableElement['name'])) {
throw new RuntimeException('Table elements must include a name attribute specifying the table name.');
}
$tableName = (string) $tableElement['name'];
if (!isset($tableColumns[$tableName])) {
$tableColumns[$tableName] = [];
}
if (!isset($tableValues[$tableName])) {
$tableValues[$tableName] = [];
}
$tableInstanceColumns = [];
foreach ($tableElement->xpath('./column') as $columnElement) {
$columnName = (string) $columnElement;
if (empty($columnName)) {
throw new RuntimeException("Missing <column> elements for table $tableName. Add one or more <column> elements to the <table> element.");
}
if (!in_array($columnName, $tableColumns[$tableName])) {
$tableColumns[$tableName][] = $columnName;
}
$tableInstanceColumns[] = $columnName;
}
foreach ($tableElement->xpath('./row') as $rowElement) {
$rowValues = [];
$index = 0;
$numOfTableInstanceColumns = count($tableInstanceColumns);
foreach ($rowElement->children() as $columnValue) {
if ($index >= $numOfTableInstanceColumns) {
throw new RuntimeException("Row contains more values than the number of columns defined for table $tableName.");
}
switch ($columnValue->getName()) {
case 'value':
$rowValues[$tableInstanceColumns[$index]] = (string) $columnValue;
$index++;
break;
case 'null':
$rowValues[$tableInstanceColumns[$index]] = null;
$index++;
break;
default:
throw new RuntimeException('Unknown element ' . $columnValue->getName() . ' in a row element.');
}
}
$tableValues[$tableName][] = $rowValues;
}
}
}
}

View File

@@ -0,0 +1,116 @@
<?php
/*
* This file is part of DbUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\DbUnit\DataSet;
/**
* Creates YamlDataSets.
*
* You can incrementally add YAML files as tables to your datasets
*/
class YamlDataSet extends AbstractDataSet
{
/**
* @var array
*/
protected $tables = [];
/**
* @var IYamlParser
*/
protected $parser;
/**
* Creates a new YAML dataset
*
* @param string $yamlFile
* @param IYamlParser $parser
*/
public function __construct($yamlFile, $parser = null)
{
if ($parser == null) {
$parser = new SymfonyYamlParser();
}
$this->parser = $parser;
$this->addYamlFile($yamlFile);
}
/**
* Adds a new yaml file to the dataset.
*
* @param string $yamlFile
*/
public function addYamlFile($yamlFile)
{
$data = $this->parser->parseYaml($yamlFile);
foreach ($data as $tableName => $rows) {
if (!isset($rows)) {
$rows = [];
}
if (!is_array($rows)) {
continue;
}
if (!array_key_exists($tableName, $this->tables)) {
$columns = $this->getColumns($rows);
$tableMetaData = new DefaultTableMetadata(
$tableName, $columns
);
$this->tables[$tableName] = new DefaultTable(
$tableMetaData
);
}
foreach ($rows as $row) {
$this->tables[$tableName]->addRow($row);
}
}
}
/**
* Creates a unique list of columns from all the rows in a table.
* If the table is defined another time in the Yaml, and if the Yaml
* parser could return the multiple occerrences, then this would be
* insufficient unless we grouped all the occurences of the table
* into onwe row set. sfYaml, however, does not provide multiple tables
* with the same name, it only supplies the last table.
*
* @params all the rows in a table.
*/
private function getColumns($rows)
{
$columns = [];
foreach ($rows as $row) {
$columns = array_merge($columns, array_keys($row));
}
return array_values(array_unique($columns));
}
/**
* Creates an iterator over the tables in the data set. If $reverse is
* true a reverse iterator will be returned.
*
* @param bool $reverse
*
* @return ITableIterator
*/
protected function createIterator($reverse = false)
{
return new DefaultTableIterator(
$this->tables, $reverse
);
}
}