text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: DbTableDataSet.php 23775 2011-03-01 17:25:24Z ralph $
 */

require_once "PHPUnit/Extensions/Database/DataSet/QueryDataSet.php";

require_once "PHPUnit/Extensions/Database/DB/IDatabaseConnection.php";

/**
 * @see Zend_Test_PHPUnit_Db_DataSet_DbTable
 */
require_once "Zend/Test/PHPUnit/Db/DataSet/DbTable.php";

/**
 * Aggregate several Zend_Db_Table instances into a dataset.
 *
 * @uses       Zend_Db_Table
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Test_PHPUnit_Db_DataSet_DbTableDataSet extends PHPUnit_Extensions_Database_DataSet_AbstractDataSet
{
    /**
     * @var array
     */
    protected $tables = array();

    /**
     * Add a Table dataset representation by specifiying an arbitrary select query.
     *
     * By default a select * will be done on the given tablename.
     *
     * @param Zend_Db_Table_Abstract $table
     * @param string|Zend_Db_Select $query
     * @param string $where
     * @param string $order
     * @param string $count
     * @param string $offset
     */
    public function addTable(Zend_Db_Table_Abstract $table, $where = null, $order = null, $count = null, $offset = null)
    {
        $tableName = $table->info('name');
        $this->tables[$tableName] = new Zend_Test_PHPUnit_Db_DataSet_DbTable($table, $where, $order, $count, $offset);
    }

    /**
     * Creates an iterator over the tables in the data set. If $reverse is
     * true a reverse iterator will be returned.
     *
     * @param bool $reverse
     * @return PHPUnit_Extensions_Database_DB_TableIterator
     */
    protected function createIterator($reverse = FALSE)
    {
        return new PHPUnit_Extensions_Database_DataSet_DefaultTableIterator($this->tables, $reverse);
    }

    /**
     * Returns a table object for the given table.
     *
     * @param string $tableName
     * @return PHPUnit_Extensions_Database_DB_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);
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: DbTable.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see PHPUnit_Extensions_Database_DataSet_QueryTable
 */
require_once "PHPUnit/Extensions/Database/DataSet/QueryTable.php";

/**
 * @see Zend_Db_Table_Abstract
 */
require_once "Zend/Db/Table/Abstract.php";

/**
 * Use a Zend_Db_Table for assertions with other PHPUnit Database Extension table types.
 *
 * @uses       PHPUnit_Extensions_Database_DataSet_QueryTable
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Test_PHPUnit_Db_DataSet_DbTable extends PHPUnit_Extensions_Database_DataSet_QueryTable
{
    /**
     * Zend_Db_Table object
     *
     * @var Zend_Db_Table_Abstract
     */
    protected $_table = null;

    /**
     * @var array
     */
    protected $_columns = array();

    /**
     * @var string
     */
    protected $_where = null;

    /**
     * @var string
     */
    protected $_orderBy = null;

    /**
     * @var string
     */
    protected $_count = null;

    /**
     * @var int
     */
    protected $_offset = null;

    /**
     * Construct Dataset Table from Zend_Db_Table object
     *
     * @param Zend_Db_Table_Abstract        $table
     * @param string|Zend_Db_Select|null    $where
     * @param string|null                   $order
     * @param int                           $count
     * @param int                           $offset
     */
    public function __construct(Zend_Db_Table_Abstract $table, $where=null, $order=null, $count=null, $offset=null)
    {
        $this->tableName = $table->info('name');
        $this->_columns = $table->info('cols');

        $this->_table = $table;
        $this->_where = $where;
        $this->_order = $order;
        $this->_count = $count;
        $this->_offset = $offset;
    }

    /**
     * Lazy load data via table fetchAll() method.
     *
     * @return void
     */
    protected function loadData()
    {
        if ($this->data === null) {
            $this->data = $this->_table->fetchAll(
                $this->_where, $this->_order, $this->_count, $this->_offset
            );
            if($this->data instanceof Zend_Db_Table_Rowset_Abstract) {
                $this->data = $this->data->toArray();
            }
        }
    }

    /**
     * Create Table Metadata object
     */
    protected function createTableMetaData()
    {
        if ($this->tableMetaData === NULL) {
            $this->loadData();
            $this->tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($this->tableName, $this->_columns);
        }
    }
}

repo_name: michael-romer/zf-boilerplate

repo_language: PHP

mime_type: text/html


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: QueryDataSet.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see PHPUnit_Extensions_Database_DataSet_QueryDataSet
 */
require_once "PHPUnit/Extensions/Database/DataSet/QueryDataSet.php";

/**
 * @see PHPUnit_Extensions_Database_DB_IDatabaseConnection
 */
require_once "PHPUnit/Extensions/Database/DB/IDatabaseConnection.php";

/**
 * @see Zend_Test_PHPUnit_Db_DataSet_QueryTable
 */
require_once "Zend/Test/PHPUnit/Db/DataSet/QueryTable.php";

/**
 * @see Zend_Db_Select
 */
require_once "Zend/Db/Select.php";

/**
 * Uses several query strings or Zend_Db_Select objects to form a dataset of tables for assertion with other datasets.
 *
 * @uses       PHPUnit_Extensions_Database_DataSet_QueryDataSet
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Test_PHPUnit_Db_DataSet_QueryDataSet extends PHPUnit_Extensions_Database_DataSet_QueryDataSet
{
    /**
     * Creates a new dataset using the given database connection.
     *
     * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection
     */
    public function __construct(PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection)
    {
        if( !($databaseConnection instanceof Zend_Test_PHPUnit_Db_Connection) ) {
            require_once "Zend/Test/PHPUnit/Db/Exception.php";
            throw new Zend_Test_PHPUnit_Db_Exception("Zend_Test_PHPUnit_Db_DataSet_QueryDataSet only works with Zend_Test_PHPUnit_Db_Connection connections-");
        }
        $this->databaseConnection = $databaseConnection;
    }

    /**
     * Add a Table dataset representation by specifiying an arbitrary select query.
     *
     * By default a select * will be done on the given tablename.
     *
     * @param string                $tableName
     * @param string|Zend_Db_Select $query
     */
    public function addTable($tableName, $query = NULL)
    {
        if ($query === NULL) {
            $query = $this->databaseConnection->getConnection()->select();
            $query->from($tableName, Zend_Db_Select::SQL_WILDCARD);
        }

        if($query instanceof Zend_Db_Select) {
            $query = $query->__toString();
        }

        $this->tables[$tableName] = new Zend_Test_PHPUnit_Db_DataSet_QueryTable($tableName, $query, $this->databaseConnection);
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: DbRowset.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Db_Table_Rowset_Abstract
 */
require_once "Zend/Db/Table/Rowset/Abstract.php";

/**
 * @see PHPUnit_Extensions_Database_DataSet_AbstractTable
 */
require_once "PHPUnit/Extensions/Database/DataSet/AbstractTable.php";

/**
 * Use a Zend_Db Rowset as a datatable for assertions with other PHPUnit Database extension tables.
 *
 * @uses       PHPUnit_Extensions_Database_DataSet_AbstractTable
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Test_PHPUnit_Db_DataSet_DbRowset extends PHPUnit_Extensions_Database_DataSet_AbstractTable
{
    /**
     * Construct Table object from a Zend_Db_Table_Rowset
     *
     * @param Zend_Db_Table_Rowset_Abstract $rowset
     * @param string $tableName
     */
    public function __construct(Zend_Db_Table_Rowset_Abstract $rowset, $tableName = null)
    {
        if($tableName == null) {
            $table = $rowset->getTable();
            if($table !== null) {
                $tableName = $table->info('name');
            } else {
                require_once "Zend/Test/PHPUnit/Db/Exception.php";
                throw new Zend_Test_PHPUnit_Db_Exception(
                    'No table name was given to Rowset Table and table name cannot be infered from the table, '.
                    'because the rowset is disconnected from database.'
                );
            }
        }

        $this->data = $rowset->toArray();

        $columns = array();
        if(isset($this->data[0]) > 0) {
            $columns = array_keys($this->data[0]);
        } else if($rowset->getTable() != null) {
            $columns = $rowset->getTable()->info('cols');
        }

        $this->tableName = $tableName;
        $this->tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($this->tableName, $columns);
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Insert.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see PHPUnit_Extensions_Database_Operation_IDatabaseOperation
 */
require_once "PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php";

/**
 * @see PHPUnit_Extensions_Database_DB_IDatabaseConnection
 */
require_once "PHPUnit/Extensions/Database/DB/IDatabaseConnection.php";

/**
 * @see PHPUnit_Extensions_Database_DataSet_IDataSet
 */
require_once "PHPUnit/Extensions/Database/DataSet/IDataSet.php";

/**
 * @see PHPUnit_Extensions_Database_Operation_Exception
 */
require_once "PHPUnit/Extensions/Database/Operation/Exception.php";

/**
 * @see Zend_Test_PHPUnit_Db_Connection
 */
require_once "Zend/Test/PHPUnit/Db/Connection.php";

/**
 * Operation for Inserting on setup or teardown of a database tester.
 *
 * @uses       PHPUnit_Extensions_Database_Operation_IDatabaseOperation
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Test_PHPUnit_Db_Operation_Insert implements PHPUnit_Extensions_Database_Operation_IDatabaseOperation
{
    /**
     * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection
     * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet
     */
    public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet)
    {
        if(!($connection instanceof Zend_Test_PHPUnit_Db_Connection)) {
            require_once "Zend/Test/PHPUnit/Db/Exception.php";
            throw new Zend_Test_PHPUnit_Db_Exception("Not a valid Zend_Test_PHPUnit_Db_Connection instance, ".get_class($connection)." given!");
        }

        $databaseDataSet = $connection->createDataSet();

        $dsIterator = $dataSet->getIterator();

        foreach($dsIterator as $table) {
            $tableName = $table->getTableMetaData()->getTableName();

            $db = $connection->getConnection();
            for($i = 0; $i < $table->getRowCount(); $i++) {
                $values = $this->buildInsertValues($table, $i);
                try {
                    $db->insert($tableName, $values);
                } catch (Exception $e) {
                    throw new PHPUnit_Extensions_Database_Operation_Exception("INSERT", "INSERT INTO ".$tableName." [..]", $values, $table, $e->getMessage());
                }
            }
        }
    }

    /**
     *
     * @param PHPUnit_Extensions_Database_DataSet_ITable $table
     * @param int $rowNum
     * @return array
     */
    protected function buildInsertValues(PHPUnit_Extensions_Database_DataSet_ITable $table, $rowNum)
    {
        $values = array();
        foreach($table->getTableMetaData()->getColumns() as $columnName) {
            $values[$columnName] = $table->getValue($rowNum, $columnName);
        }
        return $values;
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: DeleteAll.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see PHPUnit_Extensions_Database_Operation_IDatabaseOperation
 */
require_once "PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php";

/**
 * @see PHPUnit_Extensions_Database_DB_IDatabaseConnection
 */
require_once "PHPUnit/Extensions/Database/DB/IDatabaseConnection.php";

/**
 * @see PHPUnit_Extensions_Database_DataSet_IDataSet
 */
require_once "PHPUnit/Extensions/Database/DataSet/IDataSet.php";

/**
 * @see PHPUnit_Extensions_Database_Operation_Exception
 */
require_once "PHPUnit/Extensions/Database/Operation/Exception.php";

/**
 * @see Zend_Test_PHPUnit_Db_Connection
 */
require_once "Zend/Test/PHPUnit/Db/Connection.php";

/**
 * Delete All Operation that can be executed on set up or tear down of a database tester.
 *
 * @uses       PHPUnit_Extensions_Database_Operation_IDatabaseOperation
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Test_PHPUnit_Db_Operation_DeleteAll implements PHPUnit_Extensions_Database_Operation_IDatabaseOperation
{
    /**
     * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection
     * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet
     */
    public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet)
    {
        if(!($connection instanceof Zend_Test_PHPUnit_Db_Connection)) {
            require_once "Zend/Test/PHPUnit/Db/Exception.php";
            throw new Zend_Test_PHPUnit_Db_Exception("Not a valid Zend_Test_PHPUnit_Db_Connection instance, ".get_class($connection)." given!");
        }

        foreach ($dataSet as $table) {
            try {
                $tableName = $table->getTableMetaData()->getTableName();
                $connection->getConnection()->delete($tableName);
            } catch (Exception $e) {
                require_once "PHPUnit/Extensions/Database/Operation/Exception.php";
                throw new PHPUnit_Extensions_Database_Operation_Exception('DELETEALL', 'DELETE FROM '.$tableName.'', array(), $table, $e->getMessage());
            }
        }
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Truncate.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see PHPUnit_Extensions_Database_Operation_IDatabaseOperation
 */
require_once "PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php";

/**
 * @see PHPUnit_Extensions_Database_DB_IDatabaseConnection
 */
require_once "PHPUnit/Extensions/Database/DB/IDatabaseConnection.php";

/**
 * @see PHPUnit_Extensions_Database_DataSet_IDataSet
 */
require_once "PHPUnit/Extensions/Database/DataSet/IDataSet.php";

/**
 * @see PHPUnit_Extensions_Database_Operation_Exception
 */
require_once "PHPUnit/Extensions/Database/Operation/Exception.php";

/**
 * @see Zend_Test_PHPUnit_Db_Connection
 */
require_once "Zend/Test/PHPUnit/Db/Connection.php";

/**
 * Operation for Truncating on setup or teardown of a database tester.
 *
 * @uses       PHPUnit_Extensions_Database_Operation_IDatabaseOperation
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Test_PHPUnit_Db_Operation_Truncate implements PHPUnit_Extensions_Database_Operation_IDatabaseOperation
{
    /**
     *
     * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection
     * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet
     * @return void
     */
    public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet)
    {
        if(!($connection instanceof Zend_Test_PHPUnit_Db_Connection)) {
            require_once "Zend/Test/PHPUnit/Db/Exception.php";
            throw new Zend_Test_PHPUnit_Db_Exception("Not a valid Zend_Test_PHPUnit_Db_Connection instance, ".get_class($connection)." given!");
        }

        foreach ($dataSet->getReverseIterator() AS $table) {
            try {
                $tableName = $table->getTableMetaData()->getTableName();
                $this->_truncate($connection->getConnection(), $tableName);
            } catch (Exception $e) {
                throw new PHPUnit_Extensions_Database_Operation_Exception('TRUNCATE', 'TRUNCATE '.$tableName.'', array(), $table, $e->getMessage());
            }
        }
    }

    /**
     * Truncate a given table.
     *
     * @param Zend_Db_Adapter_Abstract $db
     * @param string $tableName
     * @return void
     */
    protected function _truncate(Zend_Db_Adapter_Abstract $db, $tableName)
    {
        $tableName = $db->quoteIdentifier($tableName, true);
        if($db instanceof Zend_Db_Adapter_Pdo_Sqlite) {
            $db->query('DELETE FROM '.$tableName);
        } else if($db instanceof Zend_Db_Adapter_Db2) {
            /*if(strstr(PHP_OS, "WIN")) {
                $file = tempnam(sys_get_temp_dir(), "zendtestdbibm_");
                file_put_contents($file, "");
                $db->query('IMPORT FROM '.$file.' OF DEL REPLACE INTO '.$tableName);
                unlink($file);
            } else {
                $db->query('IMPORT FROM /dev/null OF DEL REPLACE INTO '.$tableName);
            }*/
            require_once "Zend/Exception.php";
            throw Zend_Exception("IBM Db2 TRUNCATE not supported.");
        } else if($this->_isMssqlOrOracle($db)) {
            $db->query('TRUNCATE TABLE '.$tableName);
        } else if($db instanceof Zend_Db_Adapter_Pdo_Pgsql) {
            $db->query('TRUNCATE '.$tableName.' CASCADE');
        } else {
            $db->query('TRUNCATE '.$tableName);
        }
    }

    /**
     * Detect if an adapter is for Mssql or Oracle Databases.
     *
     * @param  Zend_Db_Adapter_Abstract $db
     * @return bool
     */
    private function _isMssqlOrOracle($db)
    {
        return (
            $db instanceof Zend_Db_Adapter_Pdo_Mssql ||
            $db instanceof Zend_Db_Adapter_Sqlsrv ||
            $db instanceof Zend_Db_Adapter_Pdo_Oci ||
            $db instanceof Zend_Db_Adapter_Oracle
        );
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Generic.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Db_Adapter_Abstract
 */
require_once "Zend/Db/Adapter/Abstract.php";

/**
 * @see PHPUnit_Extensions_Database_DB_IMetaData
 */
require_once "PHPUnit/Extensions/Database/DB/IMetaData.php";

/**
 * Generic Metadata accessor for the Zend_Db adapters
 *
 * @uses       PHPUnit_Extensions_Database_DB_IMetaData
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Test_PHPUnit_Db_Metadata_Generic implements PHPUnit_Extensions_Database_DB_IMetaData
{
    /**
     * Zend_Db Connection
     *
     * @var Zend_Db_Adapter_Abstract
     */
    protected $_connection;

    /**
     * Schemaname
     *
     * @var string
     */
    protected $_schema;

    /**
     * Cached Table metadata
     *
     * @var array
     */
    protected $_tableMetadata = array();

    /**
     * Creates a new database meta data object using the given pdo connection
     * and schema name.
     *
     * @param PDO $pdo
     * @param string $schema
     */
    public final function __construct(Zend_Db_Adapter_Abstract $db, $schema)
    {
        $this->_connection = $db;
        $this->_schema     = $schema;
    }

    /**
     * List Tables
     *
     * @return array
     */
    public function getTableNames()
    {
        return $this->_connection->listTables();
    }

    /**
     * Get Table information
     *
     * @param  string $tableName
     * @return array
     */
    protected function getTableDescription($tableName)
    {
        if(!isset($this->_tableMetadata[$tableName])) {
            $this->_tableMetadata[$tableName] = $this->_connection->describeTable($tableName);
        }
        return $this->_tableMetadata[$tableName];
    }

    /**
     * Returns an array containing the names of all the columns in the
     * $tableName table,
     *
     * @param string $tableName
     * @return array
     */
    public function getTableColumns($tableName)
    {
        $tableMeta = $this->getTableDescription($tableName);
        $columns = array_keys($tableMeta);
        return $columns;
    }

    /**
     * Returns an array containing the names of all the primary key columns in
     * the $tableName table.
     *
     * @param string $tableName
     * @return array
     */
    public function getTablePrimaryKeys($tableName)
    {
        $tableMeta = $this->getTableDescription($tableName);

        $primaryColumnNames = array();
        foreach($tableMeta AS $column) {
            if($column['PRIMARY'] == true) {
                $primaryColumnNames[] = $column['COLUMN_NAME'];
            }
        }
        return $primaryColumnNames;
    }

    /**
     * Returns the name of the default schema.
     *
     * @return string
     */
    public function getSchema()
    {
        return $this->_schema;
    }

    /**
     * Returns a quoted schema object. (table name, column name, etc)
     *
     * @param string $object
     * @return string
     */
    public function quoteSchemaObject($object)
    {
        return $this->_connection->quoteIdentifier($object);
    }

    /**
     * Returns true if the rdbms allows cascading
     *
     * @return bool
     */
    public function allowsCascading()
    {
        return false;
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
 */

/** @see PHPUnit_Framework_ExpectationFailedException */
require_once 'PHPUnit/Framework/ExpectationFailedException.php';

/**
 * Zend_Test_PHPUnit_Constraint_Exception
 *
 * @uses       PHPUnit_Framework_ExpectationFailedException
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Test_PHPUnit_Constraint_Exception extends PHPUnit_Framework_ExpectationFailedException
{
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Redirect.php 23775 2011-03-01 17:25:24Z ralph $
 */

/** @see PHPUnit_Framework_Constraint */
require_once 'PHPUnit/Framework/Constraint.php';

/**
 * Redirection constraints
 *
 * @uses       PHPUnit_Framework_Constraint
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Test_PHPUnit_Constraint_Redirect extends PHPUnit_Framework_Constraint
{
    /**#@+
     * Assertion type constants
     */
    const ASSERT_REDIRECT       = 'assertRedirect';
    const ASSERT_REDIRECT_TO    = 'assertRedirectTo';
    const ASSERT_REDIRECT_REGEX = 'assertRedirectRegex';
    /**#@-*/

    /**
     * Current assertion type
     * @var string
     */
    protected $_assertType      = null;

    /**
     * Available assertion types
     * @var array
     */
    protected $_assertTypes     = array(
        self::ASSERT_REDIRECT,
        self::ASSERT_REDIRECT_TO,
        self::ASSERT_REDIRECT_REGEX,
    );

    /**
     * Pattern to match against
     * @var string
     */
    protected $_match             = null;

    /**
     * Whether or not assertion is negated
     * @var bool
     */
    protected $_negate            = false;

    /**
     * Constructor; setup constraint state
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Indicate negative match
     *
     * @param  bool $flag
     * @return void
     */
    public function setNegate($flag = true)
    {
        $this->_negate = $flag;
    }

    /**
     * Evaluate an object to see if it fits the constraints
     *
     * @param  string $other String to examine
     * @param  null|string Assertion type
     * @return bool
     */
    public function evaluate($other, $assertType = null)
    {
        if (!$other instanceof Zend_Controller_Response_Abstract) {
            require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
            throw new Zend_Test_PHPUnit_Constraint_Exception('Redirect constraint assertions require a response object');
        }

        if (strstr($assertType, 'Not')) {
            $this->setNegate(true);
            $assertType = str_replace('Not', '', $assertType);
        }

        if (!in_array($assertType, $this->_assertTypes)) {
            require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
            throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__));
        }

        $this->_assertType = $assertType;

        $response = $other;
        $argv     = func_get_args();
        $argc     = func_num_args();

        switch ($assertType) {
            case self::ASSERT_REDIRECT_TO:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No redirect URL provided against which to match');
                }
                $this->_match = $match = $argv[2];
                return ($this->_negate)
                    ? $this->_notMatch($response, $match)
                    : $this->_match($response, $match);
            case self::ASSERT_REDIRECT_REGEX:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No pattern provided against which to match redirect');
                }
                $this->_match = $match = $argv[2];
                return ($this->_negate)
                    ? $this->_notRegex($response, $match)
                    : $this->_regex($response, $match);
            case self::ASSERT_REDIRECT:
            default:
                return ($this->_negate) ? !$response->isRedirect() : $response->isRedirect();
        }
    }

    /**
     * Report Failure
     *
     * @see    PHPUnit_Framework_Constraint for implementation details
     * @param  mixed $other
     * @param  string $description Additional message to display
     * @param  bool $not
     * @return void
     * @throws PHPUnit_Framework_ExpectationFailedException
     */
    public function fail($other, $description, $not = false)
    {
        require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
        switch ($this->_assertType) {
            case self::ASSERT_REDIRECT_TO:
                $failure = 'Failed asserting response redirects to "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting response DOES NOT redirect to "%s"';
                }
                $failure = sprintf($failure, $this->_match);
                break;
            case self::ASSERT_REDIRECT_REGEX:
                $failure = 'Failed asserting response redirects to URL MATCHING "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting response DOES NOT redirect to URL MATCHING "%s"';
                }
                $failure = sprintf($failure, $this->_match);
                break;
            case self::ASSERT_REDIRECT:
            default:
                $failure = 'Failed asserting response is a redirect';
                if ($this->_negate) {
                    $failure = 'Failed asserting response is NOT a redirect';
                }
                break;
        }

        if (!empty($description)) {
            $failure = $description . "\n" . $failure;
        }

        throw new Zend_Test_PHPUnit_Constraint_Exception($failure);
    }

    /**
     * Complete implementation
     *
     * @return string
     */
    public function toString()
    {
        return '';
    }

    /**
     * Check to see if content is matched in selected nodes
     *
     * @param  Zend_Controller_Response_HttpTestCase $response
     * @param  string $match Content to match
     * @return bool
     */
    protected function _match($response, $match)
    {
        if (!$response->isRedirect()) {
            return false;
        }

        $headers  = $response->sendHeaders();
        $redirect = $headers['location'];
        $redirect = str_replace('Location: ', '', $redirect);

        return ($redirect == $match);
    }

    /**
     * Check to see if content is NOT matched in selected nodes
     *
     * @param  Zend_Controller_Response_HttpTestCase $response
     * @param  string $match
     * @return bool
     */
    protected function _notMatch($response, $match)
    {
        if (!$response->isRedirect()) {
            return true;
        }

        $headers  = $response->sendHeaders();
        $redirect = $headers['location'];
        $redirect = str_replace('Location: ', '', $redirect);

        return ($redirect != $match);
    }

    /**
     * Check to see if content is matched by regex in selected nodes
     *
     * @param  Zend_Controller_Response_HttpTestCase $response
     * @param  string $pattern
     * @return bool
     */
    protected function _regex($response, $pattern)
    {
        if (!$response->isRedirect()) {
            return false;
        }

        $headers  = $response->sendHeaders();
        $redirect = $headers['location'];
        $redirect = str_replace('Location: ', '', $redirect);

        return preg_match($pattern, $redirect);
    }

    /**
     * Check to see if content is NOT matched by regex in selected nodes
     *
     * @param  Zend_Controller_Response_HttpTestCase $response
     * @param  string $pattern
     * @return bool
     */
    protected function _notRegex($response, $pattern)
    {
        if (!$response->isRedirect()) {
            return true;
        }

        $headers  = $response->sendHeaders();
        $redirect = $headers['location'];
        $redirect = str_replace('Location: ', '', $redirect);

        return !preg_match($pattern, $redirect);
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ResponseHeader.php 23775 2011-03-01 17:25:24Z ralph $
 */

/** @see PHPUnit_Framework_Constraint */
require_once 'PHPUnit/Framework/Constraint.php';

/**
 * Response header PHPUnit Constraint
 *
 * @uses       PHPUnit_Framework_Constraint
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Test_PHPUnit_Constraint_ResponseHeader extends PHPUnit_Framework_Constraint
{
    /**#@+
     * Assertion type constants
     */
    const ASSERT_RESPONSE_CODE   = 'assertResponseCode';
    const ASSERT_HEADER          = 'assertHeader';
    const ASSERT_HEADER_CONTAINS = 'assertHeaderContains';
    const ASSERT_HEADER_REGEX    = 'assertHeaderRegex';
    /**#@-*/

    /**
     * Current assertion type
     * @var string
     */
    protected $_assertType      = null;

    /**
     * Available assertion types
     * @var array
     */
    protected $_assertTypes     = array(
        self::ASSERT_RESPONSE_CODE,
        self::ASSERT_HEADER,
        self::ASSERT_HEADER_CONTAINS,
        self::ASSERT_HEADER_REGEX,
    );

    /**
     * @var int Response code
     */
    protected $_code              = 200;

    /**
     * @var string Header
     */
    protected $_header            = null;

    /**
     * @var string pattern against which to compare header content
     */
    protected $_match             = null;

    /**
     * Whether or not assertion is negated
     * @var bool
     */
    protected $_negate            = false;

    /**
     * Constructor; setup constraint state
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Indicate negative match
     *
     * @param  bool $flag
     * @return void
     */
    public function setNegate($flag = true)
    {
        $this->_negate = $flag;
    }

    /**
     * Evaluate an object to see if it fits the constraints
     *
     * @param  Zend_Controller_Response_Abstract $other String to examine
     * @param  null|string Assertion type
     * @return bool
     */
    public function evaluate($other, $assertType = null)
    {
        if (!$other instanceof Zend_Controller_Response_Abstract) {
            require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
            throw new Zend_Test_PHPUnit_Constraint_Exception('Header constraint assertions require a response object');
        }

        if (strstr($assertType, 'Not')) {
            $this->setNegate(true);
            $assertType = str_replace('Not', '', $assertType);
        }

        if (!in_array($assertType, $this->_assertTypes)) {
            require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
            throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__));
        }

        $this->_assertType = $assertType;

        $response = $other;
        $argv     = func_get_args();
        $argc     = func_num_args();

        switch ($assertType) {
            case self::ASSERT_RESPONSE_CODE:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No response code provided against which to match');
                }
                $this->_code = $code = $argv[2];
                return ($this->_negate)
                    ? $this->_notCode($response, $code)
                    : $this->_code($response, $code);
            case self::ASSERT_HEADER:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No header provided against which to match');
                }
                $this->_header = $header = $argv[2];
                return ($this->_negate)
                    ? $this->_notHeader($response, $header)
                    : $this->_header($response, $header);
            case self::ASSERT_HEADER_CONTAINS:
                if (4 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('Both a header name and content to match are required for ' . __FUNCTION__);
                }
                $this->_header = $header = $argv[2];
                $this->_match  = $match  = $argv[3];
                return ($this->_negate)
                    ? $this->_notHeaderContains($response, $header, $match)
                    : $this->_headerContains($response, $header, $match);
            case self::ASSERT_HEADER_REGEX:
                if (4 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('Both a header name and content to match are required for ' . __FUNCTION__);
                }
                $this->_header = $header = $argv[2];
                $this->_match  = $match  = $argv[3];
                return ($this->_negate)
                    ? $this->_notHeaderRegex($response, $header, $match)
                    : $this->_headerRegex($response, $header, $match);
            default:
                require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                throw new Zend_Test_PHPUnit_Constraint_Exception('Invalid assertion type ' . __FUNCTION__);
        }
    }

    /**
     * Report Failure
     *
     * @see    PHPUnit_Framework_Constraint for implementation details
     * @param  mixed $other
     * @param  string $description Additional message to display
     * @param  bool $not
     * @return void
     * @throws PHPUnit_Framework_ExpectationFailedException
     */
    public function fail($other, $description, $not = false)
    {
        require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
        switch ($this->_assertType) {
            case self::ASSERT_RESPONSE_CODE:
                $failure = 'Failed asserting response code "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting response code IS NOT "%s"';
                }
                $failure = sprintf($failure, $this->_code);
                break;
            case self::ASSERT_HEADER:
                $failure = 'Failed asserting response header "%s" found';
                if ($this->_negate) {
                    $failure = 'Failed asserting response response header "%s" WAS NOT found';
                }
                $failure = sprintf($failure, $this->_header);
                break;
            case self::ASSERT_HEADER_CONTAINS:
                $failure = 'Failed asserting response header "%s" exists and contains "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting response header "%s" DOES NOT CONTAIN "%s"';
                }
                $failure = sprintf($failure, $this->_header, $this->_match);
                break;
            case self::ASSERT_HEADER_REGEX:
                $failure = 'Failed asserting response header "%s" exists and matches regex "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting response header "%s" DOES NOT MATCH regex "%s"';
                }
                $failure = sprintf($failure, $this->_header, $this->_match);
                break;
            default:
                throw new Zend_Test_PHPUnit_Constraint_Exception('Invalid assertion type ' . __FUNCTION__);
        }

        if (!empty($description)) {
            $failure = $description . "\n" . $failure;
        }

        throw new Zend_Test_PHPUnit_Constraint_Exception($failure);
    }

    /**
     * Complete implementation
     *
     * @return string
     */
    public function toString()
    {
        return '';
    }

    /**
     * Compare response code for positive match
     *
     * @param  Zend_Controller_Response_Abstract $response
     * @param  int $code
     * @return bool
     */
    protected function _code(Zend_Controller_Response_Abstract $response, $code)
    {
        $test = $this->_getCode($response);
        return ($test == $code);
    }

    /**
     * Compare response code for negative match
     *
     * @param  Zend_Controller_Response_Abstract $response
     * @param  int $code
     * @return bool
     */
    protected function _notCode(Zend_Controller_Response_Abstract $response, $code)
    {
        $test = $this->_getCode($response);
        return ($test != $code);
    }

    /**
     * Retrieve response code
     *
     * @param  Zend_Controller_Response_Abstract $response
     * @return int
     */
    protected function _getCode(Zend_Controller_Response_Abstract $response)
    {
        $test = $response->getHttpResponseCode();
        if (null === $test) {
            $test = 200;
        }
        return $test;
    }

    /**
     * Positive check for response header presence
     *
     * @param  Zend_Controller_Response_Abstract $response
     * @param  string $header
     * @return bool
     */
    protected function _header(Zend_Controller_Response_Abstract $response, $header)
    {
        return (null !== $this->_getHeader($response, $header));
    }

    /**
     * Negative check for response header presence
     *
     * @param  Zend_Controller_Response_Abstract $response
     * @param  string $header
     * @return bool
     */
    protected function _notHeader(Zend_Controller_Response_Abstract $response, $header)
    {
        return (null === $this->_getHeader($response, $header));
    }

    /**
     * Retrieve response header
     *
     * @param  Zend_Controller_Response_Abstract $response
     * @param  string $header
     * @return string|null
     */
    protected function _getHeader(Zend_Controller_Response_Abstract $response, $header)
    {
        $headers = $response->sendHeaders();
        $header  = strtolower($header);
        if (array_key_exists($header, $headers)) {
            return $headers[$header];
        }
        return null;
    }

    /**
     * Positive check for header contents matching pattern
     *
     * @param  Zend_Controller_Response_Abstract $response
     * @param  string $header
     * @param  string $match
     * @return bool
     */
    protected function _headerContains(Zend_Controller_Response_Abstract $response, $header, $match)
    {
        if (null === ($fullHeader = $this->_getHeader($response, $header))) {
            return false;
        }

        $contents = str_replace($header . ': ', '', $fullHeader);

        return (strstr($contents, $match));
    }

    /**
     * Negative check for header contents matching pattern
     *
     * @param  Zend_Controller_Response_Abstract $response
     * @param  string $header
     * @param  string $match
     * @return bool
     */
    protected function _notHeaderContains(Zend_Controller_Response_Abstract $response, $header, $match)
    {
        if (null === ($fullHeader = $this->_getHeader($response, $header))) {
            return true;
        }

        $contents = str_replace($header . ': ', '', $fullHeader);

        return (!strstr($contents, $match));
    }

    /**
     * Positive check for header contents matching regex
     *
     * @param  Zend_Controller_Response_Abstract $response
     * @param  string $header
     * @param  string $pattern
     * @return bool
     */
    protected function _headerRegex(Zend_Controller_Response_Abstract $response, $header, $pattern)
    {
        if (null === ($fullHeader = $this->_getHeader($response, $header))) {
            return false;
        }

        $contents = str_replace($header . ': ', '', $fullHeader);

        return preg_match($pattern, $contents);
    }

    /**
     * Negative check for header contents matching regex
     *
     * @param  Zend_Controller_Response_Abstract $response
     * @param  string $header
     * @param  string $pattern
     * @return bool
     */
    protected function _notHeaderRegex(Zend_Controller_Response_Abstract $response, $header, $pattern)
    {
        if (null === ($fullHeader = $this->_getHeader($response, $header))) {
            return true;
        }

        $contents = str_replace($header . ': ', '', $fullHeader);

        return !preg_match($pattern, $contents);
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: DomQuery.php 23775 2011-03-01 17:25:24Z ralph $
 */

/** @see PHPUnit_Framework_Constraint */
require_once 'PHPUnit/Framework/Constraint.php';

/** @see Zend_Dom_Query */
require_once 'Zend/Dom/Query.php';

/**
 * Zend_Dom_Query-based PHPUnit Constraint
 *
 * @uses       PHPUnit_Framework_Constraint
 * @category   Zend
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Test_PHPUnit_Constraint_DomQuery extends PHPUnit_Framework_Constraint
{
    /**#@+
     * Assertion type constants
     */
    const ASSERT_QUERY            = 'assertQuery';
    const ASSERT_CONTENT_CONTAINS = 'assertQueryContentContains';
    const ASSERT_CONTENT_REGEX    = 'assertQueryContentRegex';
    const ASSERT_CONTENT_COUNT    = 'assertQueryCount';
    const ASSERT_CONTENT_COUNT_MIN= 'assertQueryCountMin';
    const ASSERT_CONTENT_COUNT_MAX= 'assertQueryCountMax';
    /**#@-*/

    /**
     * Current assertion type
     * @var string
     */
    protected $_assertType        = null;

    /**
     * Available assertion types
     * @var array
     */
    protected $_assertTypes       = array(
        self::ASSERT_QUERY,
        self::ASSERT_CONTENT_CONTAINS,
        self::ASSERT_CONTENT_REGEX,
        self::ASSERT_CONTENT_COUNT,
        self::ASSERT_CONTENT_COUNT_MIN,
        self::ASSERT_CONTENT_COUNT_MAX,
    );

    /**
     * Content being matched
     * @var string
     */
    protected $_content           = null;

    /**
     * Whether or not assertion is negated
     * @var bool
     */
    protected $_negate            = false;

    /**
     * CSS selector or XPath path to select against
     * @var string
     */
    protected $_path              = null;

    /**
     * Whether or not to use XPath when querying
     * @var bool
     */
    protected $_useXpath          = false;

    /**
     * XPath namespaces
     * @var array
     */
    protected $_xpathNamespaces = array();

    /**
     * Constructor; setup constraint state
     *
     * @param  string $path CSS selector path
     * @return void
     */
    public function __construct($path)
    {
        $this->_path = $path;
    }

    /**
     * Indicate negative match
     *
     * @param  bool $flag
     * @return void
     */
    public function setNegate($flag = true)
    {
        $this->_negate = $flag;
    }

    /**
     * Whether or not path is a straight XPath expression
     *
     * @param  bool $flag
     * @return Zend_Test_PHPUnit_Constraint_DomQuery
     */
    public function setUseXpath($flag = true)
    {
        $this->_useXpath = (bool) $flag;
        return $this;
    }

    /**
     * Evaluate an object to see if it fits the constraints
     *
     * @param  string $other String to examine
     * @param  null|string Assertion type
     * @return bool
     */
    public function evaluate($other, $assertType = null)
    {
        if (strstr($assertType, 'Not')) {
            $this->setNegate(true);
            $assertType = str_replace('Not', '', $assertType);
        }

        if (strstr($assertType, 'Xpath')) {
            $this->setUseXpath(true);
            $assertType = str_replace('Xpath', 'Query', $assertType);
        }

        if (!in_array($assertType, $this->_assertTypes)) {
            require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
            throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__));
        }

        $this->_assertType = $assertType;

        $method   = $this->_useXpath ? 'queryXpath' : 'query';
        $domQuery = new Zend_Dom_Query($other);
        $domQuery->registerXpathNamespaces($this->_xpathNamespaces);
        $result   = $domQuery->$method($this->_path);
        $argv     = func_get_args();
        $argc     = func_num_args();

        switch ($assertType) {
            case self::ASSERT_CONTENT_CONTAINS:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No content provided against which to match');
                }
                $this->_content = $content = $argv[2];
                return ($this->_negate)
                    ? $this->_notMatchContent($result, $content)
                    : $this->_matchContent($result, $content);
            case self::ASSERT_CONTENT_REGEX:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No pattern provided against which to match');
                }
                $this->_content = $content = $argv[2];
                return ($this->_negate)
                    ? $this->_notRegexContent($result, $content)
                    : $this->_regexContent($result, $content);
            case self::ASSERT_CONTENT_COUNT:
            case self::ASSERT_CONTENT_COUNT_MIN:
            case self::ASSERT_CONTENT_COUNT_MAX:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No count provided against which to compare');
                }
                $this->_content = $content = $argv[2];
                return $this->_countContent($result, $content, $assertType);
            case self::ASSERT_QUERY:
            default:
                if ($this->_negate) {
                    return (0 == count($result));
                } else {
                    return (0 != count($result));
                }
        }
    }

    /**
     * Report Failure
     *
     * @see    PHPUnit_Framework_Constraint for implementation details
     * @param  mixed $other CSS selector path
     * @param  string $description
     * @param  bool $not
     * @return void
     * @throws PHPUnit_Framework_ExpectationFailedException
     */
    public function fail($other, $description, $not = false)
    {
        require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
        switch ($this->_assertType) {
            case self::ASSERT_CONTENT_CONTAINS:
                $failure = 'Failed asserting node denoted by %s CONTAINS content "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting node DENOTED BY %s DOES NOT CONTAIN content "%s"';
                }
                $failure = sprintf($failure, $other, $this->_content);
                break;
            case self::ASSERT_CONTENT_REGEX:
                $failure = 'Failed asserting node denoted by %s CONTAINS content MATCHING "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting node DENOTED BY %s DOES NOT CONTAIN content MATCHING "%s"';
                }
                $failure = sprintf($failure, $other, $this->_content);
                break;
            case self::ASSERT_CONTENT_COUNT:
                $failure = 'Failed asserting node DENOTED BY %s OCCURS EXACTLY %d times';
                if ($this->_negate) {
                    $failure = 'Failed asserting node DENOTED BY %s DOES NOT OCCUR EXACTLY %d times';
                }
                $failure = sprintf($failure, $other, $this->_content);
                break;
            case self::ASSERT_CONTENT_COUNT_MIN:
                $failure = 'Failed asserting node DENOTED BY %s OCCURS AT LEAST %d times';
                $failure = sprintf($failure, $other, $this->_content);
                break;
            case self::ASSERT_CONTENT_COUNT_MAX:
                $failure = 'Failed asserting node DENOTED BY %s OCCURS AT MOST %d times';
                $failure = sprintf($failure, $other, $this->_content);
                break;
            case self::ASSERT_QUERY:
            default:
                $failure = 'Failed asserting node DENOTED BY %s EXISTS';
                if ($this->_negate) {
                    $failure = 'Failed asserting node DENOTED BY %s DOES NOT EXIST';
                }
                $failure = sprintf($failure, $other);
                break;
        }

        if (!empty($description)) {
            $failure = $description . "\n" . $failure;
        }

        throw new Zend_Test_PHPUnit_Constraint_Exception($failure);
    }

    /**
     * Complete implementation
     *
     * @return string
     */
    public function toString()
    {
        return '';
    }

    /**
     * Register XPath namespaces
     *
     * @param   array $xpathNamespaces
     * @return  void
     */
    public function registerXpathNamespaces($xpathNamespaces)
    {
        $this->_xpathNamespaces = $xpathNamespaces;
    }

    /**
     * Check to see if content is matched in selected nodes
     *
     * @param  Zend_Dom_Query_Result $result
     * @param  string $match Content to match
     * @return bool
     */
    protected function _matchContent($result, $match)
    {
        $match = (string) $match;

        if (0 == count($result)) {
            return false;
        }

        foreach ($result as $node) {
            $content = $this->_getNodeContent($node);
            if (strstr($content, $match)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check to see if content is NOT matched in selected nodes
     *
     * @param  Zend_Dom_Query_Result $result
     * @param  string $match
     * @return bool
     */
    protected function _notMatchContent($result, $match)
    {
        if (0 == count($result)) {
            return true;
        }

        foreach ($result as $node) {
            $content = $this->_getNodeContent($node);
            if (strstr($content, $match)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Check to see if content is matched by regex in selected nodes
     *
     * @param  Zend_Dom_Query_Result $result
     * @param  string $pattern
     * @return bool
     */
    protected function _regexContent($result, $pattern)
    {
        if (0 == count($result)) {
            return false;
        }

        foreach ($result as $node) {
            $content = $this->_getNodeContent($node);
            if (preg_match($pattern, $content)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check to see if content is NOT matched by regex in selected nodes
     *
     * @param  Zend_Dom_Query_Result $result
     * @param  string $pattern
     * @return bool
     */
    protected function _notRegexContent($result, $pattern)
    {
        if (0 == count($result)) {
            return true;
        }

        foreach ($result as $node) {
            $content = $this->_getNodeContent($node);
            if (preg_match($pattern, $content)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Determine if content count matches criteria
     *
     * @param  Zend_Dom_Query_Result $result
     * @param  int $test Value against which to test
     * @param  string $type assertion type
     * @return boolean
     */
    protected function _countContent($result, $test, $type)
    {
        $count = count($result);

        switch ($type) {
            case self::ASSERT_CONTENT_COUNT:
                return ($this->_negate)
                    ? ($test != $count)
                    : ($test == $count);
            case self::ASSERT_CONTENT_COUNT_MIN:
                return ($count >= $test);
            case self::ASSERT_CONTENT_COUNT_MAX:
                return ($count <= $test);
            default:
                return false;
        }
    }

    /**
     * Get node content, minus node markup tags
     *
     * @param  DOMNode $node
     * @return string
     */
    protected function _getNodeContent(DOMNode $node)
    {
        if ($node instanceof DOMAttr) {
            return $node->value;
        } else {
            $doc     = $node->ownerDocument;
            $content = $doc->saveXML($node);
            $tag     = $node->nodeName;
            $regex   = '|</?' . $tag . '[^>]*>|';
            return preg_replace($regex, '', $content);
        }
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Oauth
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * Zend_Exception
 */
require_once 'Zend/Exception.php';

/**
 * @category   Zend
 * @package    Zend_Oauth
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Oauth_Exception extends Zend_Exception {}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Oauth
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Client.php 24415 2011-08-27 22:09:37Z adamlundrigan $
 */

/** Zend_Oauth */
require_once 'Zend/Oauth.php';

/** Zend_Http_Client */
require_once 'Zend/Http/Client.php';

/** Zend_Oauth_Http_Utility */
require_once 'Zend/Oauth/Http/Utility.php';

/** Zend_Oauth_Config */
require_once 'Zend/Oauth/Config.php';

/**
 * @category   Zend
 * @package    Zend_Oauth
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Oauth_Client extends Zend_Http_Client
{
    /**
     * Flag to indicate that the client has detected the server as supporting
     * OAuth 1.0a
     */
    public static $supportsRevisionA = false;

    /**
     * Holds the current OAuth Configuration set encapsulated in an instance
     * of Zend_Oauth_Config; it's not a Zend_Config instance since that level
     * of abstraction is unnecessary and doesn't let me escape the accessors
     * and mutators anyway!
     *
     * @var Zend_Oauth_Config
     */
    protected $_config = null;

    /**
     * True if this request is being made with data supplied by
     * a stream object instead of a raw encoded string.
     *
     * @var bool
     */
    protected $_streamingRequest = null;

    /**
     * Constructor; creates a new HTTP Client instance which itself is
     * just a typical Zend_Http_Client subclass with some OAuth icing to
     * assist in automating OAuth parameter generation, addition and
     * cryptographioc signing of requests.
     *
     * @param  array|Zend_Config $oauthOptions
     * @param  string            $uri
     * @param  array|Zend_Config $config
     * @return void
     */
    public function __construct($oauthOptions, $uri = null, $config = null)
    {
        if ($config instanceof Zend_Config && !isset($config->rfc3986_strict)) {
            $config                   = $config->toArray();
            $config['rfc3986_strict'] = true;
        } else if (null === $config ||
                   (is_array($config) && !isset($config['rfc3986_strict']))) {
            $config['rfc3986_strict'] = true;
        }
        parent::__construct($uri, $config);
        $this->_config = new Zend_Oauth_Config;
        if ($oauthOptions !== null) {
            if ($oauthOptions instanceof Zend_Config) {
                $oauthOptions = $oauthOptions->toArray();
            }
            $this->_config->setOptions($oauthOptions);
        }
    }

   /**
     * Load the connection adapter
     *
     * @param Zend_Http_Client_Adapter_Interface $adapter
     * @return void
     */
    public function setAdapter($adapter)
    {
        if ($adapter == null) {
            $this->adapter = $adapter;
        } else {
              parent::setAdapter($adapter);
        }
    }

    /**
     * Set the streamingRequest variable which controls whether we are
     * sending the raw (already encoded) POST data from a stream source.
     *
     * @param boolean $value The value to set.
     * @return void
     */
    public function setStreamingRequest($value)
    {
        $this->_streamingRequest = $value;
    }

    /**
     * Check whether the client is set to perform streaming requests.
     *
     * @return boolean True if yes, false otherwise.
     */
    public function getStreamingRequest()
    {
        if ($this->_streamingRequest) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Prepare the request body (for POST and PUT requests)
     *
     * @return string
     * @throws Zend_Http_Client_Exception
     */
    protected function _prepareBody()
    {
        if($this->_streamingRequest) {
            $this->setHeaders(self::CONTENT_LENGTH,
                $this->raw_post_data->getTotalSize());
            return $this->raw_post_data;
        }
        else {
            return parent::_prepareBody();
        }
    }

    /**
     * Clear all custom parameters we set.
     *
     * @return Zend_Http_Client
     */
    public function resetParameters($clearAll = false)
    {
        $this->_streamingRequest = false;
        return parent::resetParameters($clearAll);
    }

    /**
     * Set the raw (already encoded) POST data from a stream source.
     *
     * This is used to support POSTing from open file handles without
     * caching the entire body into memory. It is a wrapper around
     * Zend_Http_Client::setRawData().
     *
     * @param string $data The request data
     * @param string $enctype The encoding type
     * @return Zend_Http_Client
     */
    public function setRawDataStream($data, $enctype = null)
    {
        $this->_streamingRequest = true;
        return $this->setRawData($data, $enctype);
    }

    /**
     * Same as Zend_Http_Client::setMethod() except it also creates an
     * Oauth specific reference to the method type.
     * Might be defunct and removed in a later iteration.
     *
     * @param  string $method
     * @return Zend_Http_Client
     */
    public function setMethod($method = self::GET)
    {
        if ($method == self::GET) {
            $this->setRequestMethod(self::GET);
        } elseif($method == self::POST) {
            $this->setRequestMethod(self::POST);
        } elseif($method == self::PUT) {
            $this->setRequestMethod(self::PUT);
        }  elseif($method == self::DELETE) {
            $this->setRequestMethod(self::DELETE);
        }   elseif($method == self::HEAD) {
            $this->setRequestMethod(self::HEAD);
        }
        return parent::setMethod($method);
    }

    /**
     * Same as Zend_Http_Client::request() except just before the request is
     * executed, we automatically append any necessary OAuth parameters and
     * sign the request using the relevant signature method.
     *
     * @param  string $method
     * @return Zend_Http_Response
     */
    public function request($method = null)
    {
        if ($method !== null) {
            $this->setMethod($method);
        }
        $this->prepareOauth();
        return parent::request();
    }

    /**
     * Performs OAuth preparation on the request before sending.
     *
     * This primarily means taking a request, correctly encoding and signing
     * all parameters, and applying the correct OAuth scheme to the method
     * being used.
     *
     * @return void
     * @throws Zend_Oauth_Exception If POSTBODY scheme requested, but GET request method used; or if invalid request scheme provided
     */
    public function prepareOauth()
    {
        $requestScheme = $this->getRequestScheme();
        $requestMethod = $this->getRequestMethod();
        $query = null;
        if ($requestScheme == Zend_Oauth::REQUEST_SCHEME_HEADER) {
            $oauthHeaderValue = $this->getToken()->toHeader(
                $this->getUri(true),
                $this->_config,
                $this->_getSignableParametersAsQueryString(),
                $this->getRealm()
            );
            $this->setHeaders('Authorization', $oauthHeaderValue);
        } elseif ($requestScheme == Zend_Oauth::REQUEST_SCHEME_POSTBODY) {
            if ($requestMethod == self::GET) {
                require_once 'Zend/Oauth/Exception.php';
                throw new Zend_Oauth_Exception(
                    'The client is configured to'
                    . ' pass OAuth parameters through a POST body but request method'
                    . ' is set to GET'
                );
            }
            $raw = $this->getToken()->toQueryString(
                $this->getUri(true),
                $this->_config,
                $this->_getSignableParametersAsQueryString()
            );
            $this->setRawData($raw, 'application/x-www-form-urlencoded');
            $this->paramsPost = array();
        } elseif ($requestScheme == Zend_Oauth::REQUEST_SCHEME_QUERYSTRING) {
            $params = $this->paramsGet;
            $query = $this->getUri()->getQuery();
            if ($query) {
                $queryParts = explode('&', $this->getUri()->getQuery());
                foreach ($queryParts as $queryPart) {
                    $kvTuple = explode('=', $queryPart);
                    $params[urldecode($kvTuple[0])] =
                        (array_key_exists(1, $kvTuple) ? urldecode($kvTuple[1]) : null);
                }
            }
            if (!empty($this->paramsPost)) {
                $params = array_merge($params, $this->paramsPost);
                $query  = $this->getToken()->toQueryString(
                    $this->getUri(true), $this->_config, $params
                );
            }
            $query = $this->getToken()->toQueryString(
                $this->getUri(true), $this->_config, $params
            );
            $this->getUri()->setQuery($query);
            $this->paramsGet = array();
        } else {
            require_once 'Zend/Oauth/Exception.php';
            throw new Zend_Oauth_Exception('Invalid request scheme: ' . $requestScheme);
        }
    }

    /**
     * Collect all signable parameters into a single array across query string
     * and POST body. These are returned as a properly formatted single
     * query string.
     *
     * @return string
     */
    protected function _getSignableParametersAsQueryString()
    {
        $params = array();
            if (!empty($this->paramsGet)) {
                $params = array_merge($params, $this->paramsGet);
                $query  = $this->getToken()->toQueryString(
                    $this->getUri(true), $this->_config, $params
                );
            }
            if (!empty($this->paramsPost)) {
                $params = array_merge($params, $this->paramsPost);
                $query  = $this->getToken()->toQueryString(
                    $this->getUri(true), $this->_config, $params
                );
            }
            return $params;
    }

    /**
     * Simple Proxy to the current Zend_Oauth_Config method. It's that instance
     * which holds all configuration methods and values this object also presents
     * as it's API.
     *
     * @param  string $method
     * @param  array $args
     * @return mixed
     * @throws Zend_Oauth_Exception if method does not exist in config object
     */
    public function __call($method, array $args)
    {
        if (!method_exists($this->_config, $method)) {
            require_once 'Zend/Oauth/Exception.php';
            throw new Zend_Oauth_Exception('Method does not exist: ' . $method);
        }
        return call_user_func_array(array($this->_config,$method), $args);
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Oauth
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Config.php 24364 2011-08-13 14:45:17Z padraic $
 */

/** Zend_Oauth */
require_once 'Zend/Oauth.php';

/** Zend_Uri */
require_once 'Zend/Uri.php';

/** Zend_Oauth_Config_Interface */
require_once 'Zend/Oauth/Config/ConfigInterface.php';

/**
 * @category   Zend
 * @package    Zend_Oauth
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Oauth_Config implements Zend_Oauth_Config_ConfigInterface
{
    /**
     * Signature method used when signing all parameters for an HTTP request
     *
     * @var string
     */
    protected $_signatureMethod = 'HMAC-SHA1';

    /**
     * Three request schemes are defined by OAuth, of which passing
     * all OAuth parameters by Header is preferred. The other two are
     * POST Body and Query String.
     *
     * @var string
     */
    protected $_requestScheme = Zend_Oauth::REQUEST_SCHEME_HEADER;

    /**
     * Preferred request Method - one of GET or POST - which Zend_Oauth
     * will enforce as standard throughout the library. Generally a default
     * of POST works fine unless a Provider specifically requires otherwise.
     *
     * @var string
     */
    protected $_requestMethod = Zend_Oauth::POST;

    /**
     * OAuth Version; This defaults to 1.0 - Must not be changed!
     *
     * @var string
     */
    protected $_version = '1.0';

    /**
     * This optional value is used to define where the user is redirected to
     * after authorizing a Request Token from an OAuth Providers website.
     * It's optional since a Provider may ask for this to be defined in advance
     * when registering a new application for a Consumer Key.
     *
     * @var string
     */
    protected $_callbackUrl = null;

    /**
     * The URL root to append default OAuth endpoint paths.
     *
     * @var string
     */
    protected $_siteUrl = null;

    /**
     * The URL to which requests for a Request Token should be directed.
     * When absent, assumed siteUrl+'/request_token'
     *
     * @var string
     */
    protected $_requestTokenUrl = null;

    /**
     * The URL to which requests for an Access Token should be directed.
     * When absent, assumed siteUrl+'/access_token'
     *
     * @var string
     */
    protected $_accessTokenUrl = null;

    /**
     * The URL to which users should be redirected to authorize a Request Token.
     * When absent, assumed siteUrl+'/authorize'
     *
     * @var string
     */
    protected $_authorizeUrl = null;

    /**
     * An OAuth application's Consumer Key.
     *
     * @var string
     */
    protected $_consumerKey = null;

    /**
     * Every Consumer Key has a Consumer Secret unless you're in RSA-land.
     *
     * @var string
     */
    protected $_consumerSecret = null;

    /**
     * If relevant, a PEM encoded RSA private key encapsulated as a
     * Zend_Crypt_Rsa Key
     *
     * @var Zend_Crypt_Rsa_Key_Private
     */
    protected $_rsaPrivateKey = null;

    /**
     * If relevant, a PEM encoded RSA public key encapsulated as a
     * Zend_Crypt_Rsa Key
     *
     * @var Zend_Crypt_Rsa_Key_Public
     */
    protected $_rsaPublicKey = null;

    /**
     * Generally this will nearly always be an Access Token represented as a
     * Zend_Oauth_Token_Access object.
     *
     * @var Zend_Oauth_Token
     */
    protected $_token = null;

    /**
     * Define the OAuth realm
     *
     * @var string
     */
    protected $_realm = null;

    /**
     * Constructor; create a new object with an optional array|Zend_Config
     * instance containing initialising options.
     *
     * @param  array|Zend_Config $options
     * @return void
     */
    public function __construct($options = null)
    {
        if ($options !== null) {
            if ($options instanceof Zend_Config) {
                $options = $options->toArray();
            }
            $this->setOptions($options);
        }
    }

    /**
     * Parse option array or Zend_Config instance and setup options using their
     * relevant mutators.
     *
     * @param  array|Zend_Config $options
     * @return Zend_Oauth_Config
     */
    public function setOptions(array $options)
    {
        foreach ($options as $key => $value) {
            switch ($key) {
                case 'consumerKey':
                    $this->setConsumerKey($value);
                    break;
                case 'consumerSecret':
                    $this->setConsumerSecret($value);
                    break;
                case 'signatureMethod':
                    $this->setSignatureMethod($value);
                    break;
                case 'version':
                    $this->setVersion($value);
                    break;
                case 'callbackUrl':
                    $this->setCallbackUrl($value);
                    break;
                case 'siteUrl':
                    $this->setSiteUrl($value);
                    break;
                case 'requestTokenUrl':
                    $this->setRequestTokenUrl($value);
                    break;
                case 'accessTokenUrl':
                    $this->setAccessTokenUrl($value);
                    break;
                case 'userAuthorizationUrl':
                    $this->setUserAuthorizationUrl($value);
                    break;
                case 'authorizeUrl':
                    $this->setAuthorizeUrl($value);
                    break;
                case 'requestMethod':
                    $this->setRequestMethod($value);
                    break;
                case 'rsaPrivateKey':
                    $this->setRsaPrivateKey($value);
                    break;
                case 'rsaPublicKey':
                    $this->setRsaPublicKey($value);
                    break;
                case 'realm':
                    $this->setRealm($value);
                    break;
            }
        }
        if (isset($options['requestScheme'])) {
            $this->setRequestScheme($options['requestScheme']);
        }

        return $this;
    }

    /**
     * Set consumer key
     *
     * @param  string $key
     * @return Zend_Oauth_Config
     */
    public function setConsumerKey($key)
    {
        $this->_consumerKey = $key;
        return $this;
    }

    /**
     * Get consumer key
     *
     * @return string
     */
    public function getConsumerKey()
    {
        return $this->_consumerKey;
    }

    /**
     * Set consumer secret
     *
     * @param  string $secret
     * @return Zend_Oauth_Config
     */
    public function setConsumerSecret($secret)
    {
        $this->_consumerSecret = $secret;
        return $this;
    }

    /**
     * Get consumer secret
     *
     * Returns RSA private key if set; otherwise, returns any previously set
     * consumer secret.
     *
     * @return string
     */
    public function getConsumerSecret()
    {
        if ($this->_rsaPrivateKey !== null) {
            return $this->_rsaPrivateKey;
        }
        return $this->_consumerSecret;
    }

    /**
     * Set signature method
     *
     * @param  string $method
     * @return Zend_Oauth_Config
     * @throws Zend_Oauth_Exception if unsupported signature method specified
     */
    public function setSignatureMethod($method)
    {
        $method = strtoupper($method);
        if (!in_array($method, array(
                'HMAC-SHA1', 'HMAC-SHA256', 'RSA-SHA1', 'PLAINTEXT'
            ))
        ) {
            require_once 'Zend/Oauth/Exception.php';
            throw new Zend_Oauth_Exception('Unsupported signature method: '
                . $method
                . '. Supported are HMAC-SHA1, RSA-SHA1, PLAINTEXT and HMAC-SHA256');
        }
        $this->_signatureMethod = $method;;
        return $this;
    }

    /**
     * Get signature method
     *
     * @return string
     */
    public function getSignatureMethod()
    {
        return $this->_signatureMethod;
    }

    /**
     * Set request scheme
     *
     * @param  string $scheme
     * @return Zend_Oauth_Config
     * @throws Zend_Oauth_Exception if invalid scheme specified, or if POSTBODY set when request method of GET is specified
     */
    public function setRequestScheme($scheme)
    {
        $scheme = strtolower($scheme);
        if (!in_array($scheme, array(
                Zend_Oauth::REQUEST_SCHEME_HEADER,
                Zend_Oauth::REQUEST_SCHEME_POSTBODY,
                Zend_Oauth::REQUEST_SCHEME_QUERYSTRING,
            ))
        ) {
            require_once 'Zend/Oauth/Exception.php';
            throw new Zend_Oauth_Exception(
                '\'' . $scheme . '\' is an unsupported request scheme'
            );
        }
        if ($scheme == Zend_Oauth::REQUEST_SCHEME_POSTBODY
            && $this->getRequestMethod() == Zend_Oauth::GET
        ) {
            require_once 'Zend/Oauth/Exception.php';
            throw new Zend_Oauth_Exception(
                'Cannot set POSTBODY request method if HTTP method set to GET'
            );
        }
        $this->_requestScheme = $scheme;
        return $this;
    }

    /**
     * Get request scheme
     *
     * @return string
     */
    public function getRequestScheme()
    {
        return $this->_requestScheme;
    }

    /**
     * Set version
     *
     * @param  string $version
     * @return Zend_Oauth_Config
     */
    public function setVersion($version)
    {
        $this->_version = $version;
        return $this;
    }

    /**
     * Get version
     *
     * @return string
     */
    public function getVersion()
    {
        return $this->_version;
    }

    /**
     * Set callback URL
     *
     * @param  string $url
     * @return Zend_Oauth_Config
     * @throws Zend_Oauth_Exception for invalid URLs
     */
    public function setCallbackUrl($url)
    {
        if (!Zend_Uri::check($url) && $url !== 'oob') {
            require_once 'Zend/Oauth/Exception.php';
            throw new Zend_Oauth_Exception(
                '\'' . $url . '\' is not a valid URI'
            );
        }
        $this->_callbackUrl = $url;
        return $this;
    }

    /**
     * Get callback URL
     *
     * @return string
     */
    public function getCallbackUrl()
    {
        return $this->_callbackUrl;
    }

    /**
     * Set site URL
     *
     * @param  string $url
     * @return Zend_Oauth_Config
     * @throws Zend_Oauth_Exception for invalid URLs
     */
    public function setSiteUrl($url)
    {
        if (!Zend_Uri::check($url)) {
            require_once 'Zend/Oauth/Exception.php';
            throw new Zend_Oauth_Exception(
                '\'' . $url . '\' is not a valid URI'
            );
        }
        $this->_siteUrl = $url;
        return $this;
    }

    /**
     * Get site URL
     *
     * @return string
     */
    public function getSiteUrl()
    {
        return $this->_siteUrl;
    }

    /**
     * Set request token URL
     *
     * @param  string $url
     * @return Zend_Oauth_Config
     * @throws Zend_Oauth_Exception for invalid URLs
     */
    public function setRequestTokenUrl($url)
    {
        if (!Zend_Uri::check($url)) {
            require_once 'Zend/Oauth/Exception.php';
            throw new Zend_Oauth_Exception(
                '\'' . $url . '\' is not a valid URI'
            );
        }
        $this->_requestTokenUrl = rtrim($url, '/');
        return $this;
    }

    /**
     * Get request token URL
     *
     * If no request token URL has been set, but a site URL has, returns the
     * site URL with the string "/request_token" appended.
     *
     * @return string
     */
    public function getRequestTokenUrl()
    {
        if (!$this->_requestTokenUrl && $this->_siteUrl) {
            return $this->_siteUrl . '/request_token';
        }
        return $this->_requestTokenUrl;
    }

    /**
     * Set access token URL
     *
     * @param  string $url
     * @return Zend_Oauth_Config
     * @throws Zend_Oauth_Exception for invalid URLs
     */
    public function setAccessTokenUrl($url)
    {
        if (!Zend_Uri::check($url)) {
            require_once 'Zend/Oauth/Exception.php';
            throw new Zend_Oauth_Exception(
                '\'' . $url . '\' is not a valid URI'
            );
        }
        $this->_accessTokenUrl = rtrim($url, '/');
        return $this;
    }

    /**
     * Get access token URL
     *
     * If no access token URL has been set, but a site URL has, returns the
     * site URL with the string "/access_token" appended.
     *
     * @return string
     */
    public function getAccessTokenUrl()
    {
        if (!$this->_accessTokenUrl && $this->_siteUrl) {
            return $this->_siteUrl . '/access_token';
        }
        return $this->_accessTokenUrl;
    }

    /**
     * Set user authorization URL
     *
     * @param  string $url
     * @return Zend_Oauth_Config
     * @throws Zend_Oauth_Exception for invalid URLs
     */
    public function setUserAuthorizationUrl($url)
    {
        return $this->setAuthorizeUrl($url);
    }

    /**
     * Set authorization URL
     *
     * @param  string $url
     * @return Zend_Oauth_Config
     * @throws Zend_Oauth_Exception for invalid URLs
     */
    public function setAuthorizeUrl($url)
    {
        if (!Zend_Uri::check($url)) {
            require_once 'Zend/Oauth/Exception.php';
            throw new Zend_Oauth_Exception(
                '\'' . $url . '\' is not a valid URI'
            );
        }
        $this->_authorizeUrl = rtrim($url, '/');
        return $this;
    }

    /**
     * Get user authorization URL
     *
     * @return string
     */
    public function getUserAuthorizationUrl()
    {
        return $this->getAuthorizeUrl();
    }

    /**
     * Get authorization URL
     *
     * If no authorization URL has been set, but a site URL has, returns the
     * site URL with the string "/authorize" appended.
     *
     * @return string
     */
    public function getAuthorizeUrl()
    {
        if (!$this->_authorizeUrl && $this->_siteUrl) {
            return $this->_siteUrl . '/authorize';
        }
        return $this->_authorizeUrl;
    }

    /**
     * Set request method
     *
     * @param  string $method
     * @return Zend_Oauth_Config
     * @throws Zend_Oauth_Exception for invalid request methods
     */
    public function setRequestMethod($method)
    {
        $method = strtoupper($method);
        if (!in_array($method, array(
                Zend_Oauth::GET,
                Zend_Oauth::POST,
                Zend_Oauth::PUT,
                Zend_Oauth::DELETE,
            ))
        ) {
            require_once 'Zend/Oauth/Exception.php';
            throw new Zend_Oauth_Exception('Invalid method: ' . $method);
        }
        $this->_requestMethod = $method;
        return $this;
    }

    /**
     * Get request method
     *
     * @return string
     */
    public function getRequestMethod()
    {
        return $this->_requestMethod;
    }

    /**
     * Set RSA public key
     *
     * @param  Zend_Crypt_Rsa_Key_Public $key
     * @return Zend_Oauth_Config
     */
    public function setRsaPublicKey(Zend_Crypt_Rsa_Key_Public $key)
    {
        $this->_rsaPublicKey = $key;
        return $this;
    }

    /**
     * Get RSA public key
     *
     * @return Zend_Crypt_Rsa_Key_Public
     */
    public function getRsaPublicKey()
    {
        return $this->_rsaPublicKey;
    }

    /**
     * Set RSA private key
     *
     * @param  Zend_Crypt_Rsa_Key_Private $key
     * @return Zend_Oauth_Config
     */
    public function setRsaPrivateKey(Zend_Crypt_Rsa_Key_Private $key)
    {
        $this->_rsaPrivateKey = $key;
        return $this;
    }

    /**
     * Get RSA private key
     *
     * @return Zend_Crypt_Rsa_Key_Private
     */
    public function getRsaPrivateKey()
    {
        return $this->_rsaPrivateKey;
    }

    /**
     * Set OAuth token
     *
     * @param  Zend_Oauth_Token $token
     * @return Zend_Oauth_Config
     */
    public function setToken(Zend_Oauth_Token $token)
    {
        $this->_token = $token;
        return $this;
    }

    /**
     * Get OAuth token
     *
     * @return Zend_Oauth_Token
     */
    public function getToken()
    {
        return $this->_token;
    }

    /**
     * Set OAuth realm
     *
     * @param  string $realm
     * @return Zend_Oauth_Config
     */
    public function setRealm($realm)
    {
        $this->_realm = $realm;
        return $this;
    }

    /**
     * Get OAuth realm
     *
     * @return string
     */
    public function getRealm()
    {
        return $this->_realm;
    }
}