text:
<?php
/**
 * Elastica index status object
 *
 * @link http://www.elasticsearch.org/guide/reference/api/admin-indices-status.html
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Index_Status
{
	protected $_response = null;

	protected $_data = array();

	protected $_name = '';

	public function __construct(Elastica_Index $index) {
		$this->_index = $index;
		$this->refresh();
	}

	public function getData() {
		return $this->_data;
	}

	public function getName() {
		return $this->getIndex()->getName();
	}

	/**
	 * Returns the entry in the data array based on the params.
	 * Various params possible.
	 *
	 * @return mixed Data array entry or null if not found
	 */
	public function get() {

		$data = $this->getData();
		$data = $data['indices'][$this->getName()];

		foreach (func_get_args() as $arg) {
			if (isset($data[$arg])) {
				$data = $data[$arg];
			} else {
				return null;
			}
		}

		return $data;
	}

	public function getAliases() {
		// TODO Update as soon as new API is implmented
		$cluster = new Elastica_Cluster($this->_index->getClient());
		$state = $cluster->getState();
		return $state['metadata']['indices'][$this->_index->getName()]['aliases'];
	}

	public function getSettings() {
		// TODO Update as soon as new API is implmented
		$cluster = new Elastica_Cluster($this->_index->getClient());
		$state = $cluster->getState();
		return $state['metadata']['indices'][$this->_index->getName()]['settings'];
	}

	public function hasAlias($name) {
		return in_array($name, $this->getAliases());
	}

	/**
	 * Returns the index object
	 *
	 * @return Elastica_Index Index object
	 */
	public function getIndex() {
		return $this->_index;
	}

	/**
	 * Returns response object
	 *
	 * @return Elastica_Response Response object
	 */
	public function getResponse() {
		return $this->_response;
	}

	/**
	 * Reloads all status data of this object
	 */
	public function refresh() {
		$path = '_status';
		$this->_response = $this->getIndex()->request($path, Elastica_Request::GET);
		$this->_data = $this->getResponse()->getData();
	}
}


text:
<?php
/**
 * Elastica index settings object
 *
 * @link http://www.elasticsearch.org/guide/reference/api/admin-indices-update-settings.html
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Index_Settings
{
	protected $_response = null;

	protected $_data = array();

	protected $_name = '';

	public function __construct(Elastica_Index $index) {
		$this->_index = $index;
	}

	/**
	 * Returns the current settings of the index
	 *
	 * If param is set, only specified setting is return
	 *
	 * @param string $setting OPTIONAL Setting name to return
	 * @return array|string|null Settings data
	 */
	public function get($setting = '') {

		$data = $this->request()->getData();
		$settings = $data[$this->_index->getName()]['settings'];

		if (!empty($setting)) {
			if (isset($settings[$setting])) {
				return $settings[$setting];
			} else {
				return null;
			}
		}
		return $settings;
	}

	/**
	 * Sets the number of replicas
	 *
	 * @param int $replicas Number of replicas
	 * @return Elastica_Response Response object
	 */
	public function setNumberOfReplicas($replicas) {
		$replicas = (int) $replicas;

		$data = array('number_of_replicas' => $replicas);

		return $this->request($data, Elastica_Request::PUT);
	}

	/**
	 * Sets the number of shards
	 *
	 * @param int $shards Number of shards
	 * @return Elastica_Response Response object
	 */
	public function setNumberOfShards($shards) {
		$shards = (int) $shards;

		$data = array('number_of_shards' => $shards);

		return $this->request($data, Elastica_Request::PUT);
	}

	/**
	 * Sets the index refresh interval
	 *
	 * Value can be for example 3s for 3 seconds or
	 * 5m for 5 minutes. -1 refreshing is disabled.
	 *
	 * @param int $interval Number of seconds
	 * @return Elastica_Response Response object
	 */
	public function setRefreshInterval($interval) {
		$data = array('refresh_interval' => $interval);
		return $this->request($data, Elastica_Request::PUT);
	}

	/**
	 * Returns the index object
	 *
	 * @return Elastica_Index Index object
	 */
	public function getIndex() {
		return $this->_index;
	}

	/**
	 * Updates the given settings for the index
	 *
	 * With elasticsearch 0.16 the following settings are supported
	 * - index.term_index_interval
	 * - index.term_index_divisor
	 * - index.translog.flush_threshold_ops
	 * - index.translog.flush_threshold_size
	 * - index.translog.flush_threshold_period
	 * - index.refresh_interval
	 * - index.merge.policy
	 * - index.auto_expand_replicas
	 *
	 * @return Elastica_Response Response object
	 */
	public function request(array $data = array(), $method = Elastica_Request::GET) {
		$path = '_settings';

		$data = array('index' => $data);
		return $this->getIndex()->request($path, $method, $data);
	}
}

repo_name: michael-romer/zf-boilerplate

repo_language: PHP

mime_type: text/html


text:
<?php
/**
 * Implements the range facet.
 *
 * @category Xodoa
 * @package Elastica
 * @author Jasper van Wanrooy <jasper@vanwanrooy.net>
 * @link http://www.elasticsearch.org/guide/reference/api/search/facets/range-facet.html
 */
class Elastica_Facet_Range extends Elastica_Facet_Abstract
{
	/**
	 * Holds the parameters of the range facet.
	 *
	 * @var array
	 */
	protected $_params = array();

	/**
	 * Sets the field for the range.
	 *
	 * @param string $field The name of the field for range.
	 * @return Elastica_Facet_Range
	 */
	public function setField($field) {
		return $this->setParam('field', $field);
	}

	/**
	 * Sets the fields by their separate key and value fields.
	 *
	 * @param string $keyField The key_field param for the range.
	 * @param string $valueField The key_value param for the range.
	 * @return Elastica_Facet_Range
	 */
	public function setKeyValueFields($keyField, $valueField) {
		return $this->setParam('key_field', $keyField)
					->setParam('value_field', $valueField);
	}

	/**
	 * Sets the key and value for this facet by script.
	 *
	 * @param string $keyScript Script to check whether it falls into the range.
	 * @param string $valueScript Script to use for statistical calculations.
	 */
	public function setKeyValueScripts($keyScript, $valueScript) {
		return $this->setParam('key_script', $keyScript)
					->setParam('value_script', $valueScript);
	}

	/**
	 * Sets the ranges for the facet all at once. Sample ranges:
	 * array (
	 *     array('to' => 50),
	 *     array('from' => 20, 'to' 70),
	 *     array('from' => 70, 'to' => 120),
	 *     array('from' => 150)
	 * )
	 *
	 * @param array $ranges Numerical array with range definitions.
	 * @return Elastica_Facet_Range
	 */
	public function setRanges(array $ranges) {
		return $this->setParam('ranges', $ranges);
	}

	/**
	 * Adds a range to the range facet.
	 *
	 * @param mixed $from The from for the range.
	 * @param mixed $to The to for the range.
	 * @return Elastica_Facet_Range
	 */
	public function addRange($from = null, $to = null) {
		if (!isset($this->_params['ranges']) || !is_array($this->_params['ranges'])) {
			$this->_params['ranges'] = array();
		}

		$this->_params['ranges'][] = array('from' => $from, 'to' => $to);
		return $this;
	}

	/**
	 * Gets a general parameter for this facet by key.
	 *
	 * @param string $key The key of the param to fetch.
	 * @return mixed
	 */
	public function getParam($key) {
		if (isset($this->_params[$key])) {
			return $this->_params[$key];
		}
	}

	/**
	 * Sets a general parameter for this facet by key and value.
	 *
	 * @param string $key Key to set
	 * @param mixed $value Value
	 * @return Elastica_Facet_Range
	 */
	public function setParam($key, $value) {
		$this->_params[$key] = $value;
		return $this;
	}

	/**
	 * Creates the full facet definition, which includes the basic
	 * facet definition of the parent.
	 *
	 * @see Elastica_Facet_Abstract::toArray()
	 * @throws Elastica_Exception_Invalid When the right fields haven't been set.
	 * @return array
	 */
	public function toArray() {
		/**
		 * Check the facet for validity.
		 * There are three ways to set the key and value field for the range:
		 *  - a single field for both key and value; or
		 *  - separate fields for key and value; or
		 *  - separate scripts for key and value.
		 */
		$fieldTypesSet = 0;
		if (isset($this->_params['field'])) {
			$fieldTypesSet++;
		}
		if (isset($this->_params['key_field'])) {
			$fieldTypesSet++;
		}
		if (isset($this->_params['key_script'])) {
			$fieldTypesSet++;
		}

		if ($fieldTypesSet === 0) {
			throw new Elastica_Exception_Invalid('Neither field, key_field nor key_script is set.');
		}
		else if ($fieldTypesSet > 1) {
			throw new Elastica_Exception_Invalid('Either field, key_field and key_value or key_script and value_script should be set.');
		}

		/**
		 * Set the range in the abstract as param.
		 */
		parent::setParam('range', $this->_params);
		return $this->_query;
	}
}


text:
<?php
/**
 * Abstract facet object. Should be extended by all facet types
 *
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 * @author Jasper van Wanrooy <jasper@vanwanrooy.net>
 */
abstract class Elastica_Facet_Abstract
{
	/**
	 * Holds the name of the facet.
	 * @var string
	 */
	protected $_name = '';

	/**
	 * Holds all facet parameters.
	 * @var array
	 */
	protected $_query = array();

	/**
	 * Constructs a Facet object.
	 *
	 * @param string $name The name of the facet.
	 */
	public function __construct($name) {
		$this->setName($name);
	}

	/**
	 * Sets the name of the facet. It is automatically set by
	 * the constructor.
	 *
	 * @param string $name The name of the facet.
	 * @throws Elastica_Exception_Invalid
	 * @return Elastica_Facet_Abstract
	 */
	public function setName($name) {
		if (empty($name)) {
			throw new Elastica_Exception_Invalid('Facet name has to be set');
		}
		$this->_name = $name;
		return $this;
	}

	/**
	 * Gets the name of the facet.
	 *
	 * @return string
	 */
	public function getName() {
		return $this->_name;
	}

	/**
	 * Sets a filter for this facet.
	 *
	 * @param Elastica_Filter_Abstract $filter A filter to apply on the facet.
	 * @return Elastica_Facet_Abstract
	 */
	public function setFilter(Elastica_Filter_Abstract $filter) {
		return $this->setParam('facet_filter', $filter->toArray());
	}

	/**
	 * Sets a param for the facet.
	 *
	 * @param string $key The key of the param to set.
	 * @param mixed $value The value of the param.
	 * @return Elastica_Facet_Abstract
	 */
	public function setParam($key, $value) {
		$this->_query[$key] = $value;
		return $this;
	}

	/**
	 * Sets the flag to either run the facet globally or bound to the
	 * current search query. When not set, it defaults to the
	 * ElasticSearch default value.
	 *
	 * @param bool $global Flag to either run the facet globally.
	 */
	public function setGlobal($global = true) {
		$this->_query['global'] = (bool) $global;
	}

	/**
	 * Abstract definition of all specs of the facet. It needs to be
	 * overridden by the implementation in order to set the facet-type
	 * specific parameters.
	 *
	 * @return array
	 */
	abstract public function toArray();
}


text:
<?php
/**
 * Implements the terms facet.
 *
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 * @author Jasper van Wanrooy <jasper@vanwanrooy.net>
 * @link http://www.elasticsearch.org/guide/reference/api/search/facets/terms-facet.html
 */
class Elastica_Facet_Terms extends Elastica_Facet_Abstract
{
	/**
	 * Holds the parameters of the terms facet.
	 *
	 * @var array
	 */
	protected $_params = array();

	/**
	 * Holds the types of ordering which are allowed
	 * by ElasticSearch.
	 *
	 * @var array
	 */
	protected $_order_types = array('count', 'term', 'reverse_count', 'reverse_term');

	/**
	 * Sets the field for the terms.
	 *
	 * @param string $field The field name for the terms.
	 * @return Elastica_Facet_Terms
	 */
	public function setField($field) {
		return $this->setParam('field', $field);
	}

	/**
	 * Sets multiple fields for the terms.
	 *
	 * @param array $fields Numerical array with the fields for the terms.
	 * @return Elastica_Facet_Terms
	 */
	public function setFields(array $fields) {
		return $this->setParam('field', $fields);
	}

	/**
	 * Sets the flag to return all available terms. When they
	 * don't have a hit, they have a count of zero.
	 *
	 * @param bool $allTerms Flag to fetch all terms.
	 * @return Elastica_Facet_Terms
	 */
	public function setAllTerms($allTerms) {
		$allTerms = (bool) $allTerms;
		return $this->setParam('all_terms', $allTerms);
	}

	/**
	 * Sets the ordering type for this facet. ElasticSearch
	 * internal default is count.
	 *
	 * @param string $type The order type to set use for sorting of the terms.
	 * @throws Elastica_Exception_Invalid When an invalid order type was set.
	 * @return Elastica_Facet_Terms
	 */
	public function setOrder($type) {
		if (in_array($type, $this->_order_types)) {
			return $this->setParam('order', $type);
		}

		throw new Elastica_Exception_Invalid('Invalid order type: ' . $type);
	}

	/**
	 * Set an array with terms which are omitted in the search.
	 *
	 * @param array $exclude Numerical array which includes all terms which needs to be ignored.
	 * @return Elastica_Facet_Terms
	 */
	public function setExclude(array $exclude) {
		return $this->setParam('exclude', $exclude);
	}

	/**
	 * Sets a general parameter for this facet by key and value.
	 *
	 * @param string $key Key to set
	 * @param mixed $value Value
	 * @return Elastica_Facet_Terms
	 */
	public function setParam($key, $value) {
		$this->_params[$key] = $value;
		return $this;
	}

	/**
	 * Sets the amount of terms to be returned.
	 *
	 * @param int $size The amount of terms to be returned.
	 * @return Elastica_Facet_Terms
	 */
	public function setSize($size) {
		$size = (int) $size;
		return $this->setParam('size', $size);
	}

	/**
	 * Creates the full facet definition, which includes the basic
	 * facet definition of the parent.
	 *
	 * @see Elastica_Facet_Abstract::toArray()
	 * @return array
	 */
	public function toArray() {
		parent::setParam('terms', $this->_params);
		return $this->_query;
	}
}


text:
<?php
/**
 * Bool Filter
 *
 * @link http://www.elasticsearch.com/docs/elasticsearch/rest_api/query_dsl/bool_query/
 * @uses Elastica_Filter_Abstract
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Filter_Bool extends Elastica_Filter_Abstract
{
	protected $_minimumNumberShouldMatch = 1;

	protected $_must = array();
	protected $_should = array();
	protected $_mustNot = array();

	public function addShould($args) {
		$this->_addFilter('should', $args);
	}

	public function addMust($args) {
		$this->_addFilter('must', $args);
	}

	public function addMustNot($args) {
		$this->_addFilter('mustNot', $args);
	}

	public function _addFilter($type, $args) {
		if ($args instanceof Elastica_Filter_Abstract) {
			$args = $args->toArray();
		}

		if (!is_array($args)) {
			throw new Elastica_Exception_Invalid('Invalid parameter. Has to be array or instance of Elastica_Filter');
		}

		$varName = '_' . $type;
		$this->{$varName}[] = $args;
	}

	public function toArray() {
		$args = array();

		if (!empty($this->_must)) {
			$args['must'] = $this->_must;
		}

		if (!empty($this->_should)) {
			$args['should'] = $this->_should;
			$args['minimum_number_should_match'] = $this->_minimumNumberShouldMatch;
		}

		if (!empty($this->_mustNot)) {
			$args['must_not'] = $this->_mustNot;
		}

		return array('bool' => $args);
	}

	public function setBoost($boost) {
		$this->_boost = $boost;
	}

	public function setMinimumNumberShouldMatch($minimumNumberShouldMatch) {
		$this->_minimumNumberShouldMatch = intval($minimumNumberShouldMatch);
	}

}


text:
<?php
/**
 * Geo bounding box filter
 *
 * @link http://www.elasticsearch.com/docs/elasticsearch/rest_api/query_dsl/geo_bounding_box_filter/
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Filter_GoeBoundingBox extends Elastica_Filter_Abstract
{
	public function toArray()
	{
	}
}

/**
	"filter" : {
		"geo_bounding_box" : {
			"pin.location" : {
				"top_left" : {
					"lat" : 40.73,
					"lon" : -74.1
				},
				"bottom_right" : {
					"lat" : 40.717,
					"lon" : -73.99
				}
			}
		}
	}
}
*/


text:
<?php
/**
 * Range Filter
 *
 * @link http://www.elasticsearch.com/docs/elasticsearch/rest_api/query_dsl/range_query/
 * @uses Elastica_Filter_Abstract
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Filter_Range extends Elastica_Filter_Abstract
{
	protected $_fields = array();

	public function addField($fieldName, array $args) {
		$this->_fields[$fieldName] = $args;
	}

	public function toArray() {
		$args = $this->_fields;
		return array('range' => $args);
	}
}


text:
<?php
/**
 * Or Filter
 *
 * @link http://www.elasticsearch.com/docs/elasticsearch/rest_api/query_dsl/or_filter/
 * @uses Elastica_Filter_Abstract
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Filter_Or extends Elastica_Filter_Abstract
{

	protected $_filters = array();

	public function addFilter(Elastica_Filter_Abstract $filter) {
		$this->_filters[] = $filter->toArray();
	}

	public function toArray() {
		return array('or' => $this->_filters);
	}
}


text:
<?php
/**
 * Not Filter
 *
 * @link http://www.elasticsearch.org/guide/reference/query-dsl/not-filter.html
 * @uses Elastica_Filter_Abstract
 * @package Elastica
 * @author Lee Parker
 */
class Elastica_Filter_Not extends Elastica_Filter_Abstract
{

	protected $_filter = '';

	public function __construct(Elastica_Filter_Abstract $filter) {
		$this->_filter = $filter->toArray();
	}

	public function toArray() {
		return array('not' => array('filter' => $this->_filter));
	}
}


text:
<?php
/**
 * Geo distance filter
 *
 * @link http://www.elasticsearch.com/docs/elasticsearch/rest_api/query_dsl/geo_distance_filter/
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Filter_GeoDistance extends Elastica_Filter_Abstract
{
	protected $_key;
	protected $_distance;
	protected $_latitude;
	protected $_longitude;

	public function __construct($key, $latitude, $longitude, $distance) {
		$this->_key = $key;
		$this->setLatitude($latitude);
		$this->setLongitude($longitude);
		$this->setDistance($distance);
	}

	public function setDistance($distance) {
		// TODO: validate distance?
		$this->_distance = $distance;
	}

	public function setLatitude($latitude) {
		$this->_latitude = $latitude;
	}

	public function setLongitude($longitude) {
		$this->_longitude = $longitude;
	}

	public function toArray() {
		return array(
			'geo_distance' => array(
				'distance' => $this->_distance,
				$this->_key => array(
					'lat' => $this->_latitude,
					'lon' => $this->_longitude
				),
			),
		);
	}
}


text:
<?php
/**
 * Abstract filter object. Should be extended by all filter types
 *
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
abstract class Elastica_Filter_Abstract
{
	abstract public function toArray();
}


text:
<?php
/**
 * Exists query
 *
 * @link http://www.elasticsearch.org/guide/reference/query-dsl/exists-filter.html
 * @uses Elastica_Query_Abstract
 * @category Xodoa
 * @package Elastica
 * @author Oleg Cherniy <oleg.cherniy@gmail.com>
 */
class Elastica_Filter_Exists extends Elastica_Filter_Abstract
{
    /**
     * @var string
     */
	protected $_field;

    /**
     * @param string $field
     */
	public function __construct($field) {
		$this->setField($field);
	}

    /**
     * @param string $field
     */
	public function setField($field) {
		$this->_field = $field;
		return $this;
	}

	public function toArray() {
		$args = array('field' => $this->_field);

		return array('exists' => $args);
	}
}


text:
<?php
/**
 * Term query
 *
 * @link http://www.elasticsearch.com/docs/elasticsearch/rest_api/query_dsl/term_query/
 * @uses Elastica_Query_Abstract
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Filter_Term extends Elastica_Filter_Abstract
{
	protected $_term = array();

	public function __construct(array $term = array()) {
		$this->setTerm($term);
	}

	public function setTerm(array $term) {
		$this->_term = $term;
	}

	/**
	 * Adds a term to the term query
	 *
	 * @param string $key Key to query
	 * @param string|array $value Values(s) for the query. Boost can be set with array
	 */
	public function addTerm($key, $value) {
		$this->_term = array($key => $value);
	}

	public function toArray() {
		$args = $this->_term;

		return array('term' => $args);
	}
}


text:
<?php
/**
 * Terms filter
 *
 * @link http://www.elasticsearch.org/guide/reference/query-dsl/terms-filter.html
 * @uses Elastica_Query_Abstract
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Filter_Terms extends Elastica_Filter_Abstract
{
	protected $_terms = array();
	protected $_params = array();
	protected $_key = '';

	public function __construct($key = '', array $terms = array()) {
		$this->setTerms($key, $terms);
	}

	/**
	 * Sets key and terms for the filter
	 *
	 * @param string $key Terms key
	 * @param array $terms Terms for the query.
	 */
	public function setTerms($key, array $terms) {
		$this->_key = $key;
		$this->_terms = array_values($terms);
		return $this;
	}

	public function addTerm($term) {
		$this->_terms[] = $term;
		return $this;
	}

	public function setParam($key, $value) {
		$this->_params[$key] = $value;
		return $this;
	}

	public function toArray() {
		if (empty($this->_key)) {
			throw new Elastica_Exception_Invalid('Terms key has to be set');
		}
		$this->_params[$this->_key] = $this->_terms;
		return array('terms' => $this->_params);
	}
}


text:
<?php
/**
 * And Filter
 *
 * @link http://www.elasticsearch.org/guide/reference/query-dsl/and-filter.html
 * @uses Elastica_Filter_Abstract
 * @package Elastica
 * @author Lee Parker
 */
class Elastica_Filter_And extends Elastica_Filter_Abstract
{

	protected $_filters = array();

	public function addFilter(Elastica_Filter_Abstract $filter) {
		$this->_filters[] = $filter->toArray();
	}

	public function toArray() {
		return array('and' => $this->_filters);
	}
}


text:
<?php
/**
 * Abstract helper class to implement search indices based on models.
 *
 * This abstract model should help creating search index and a subtype
 * with some easy config entries that are overloaded.
 *
 * The following variables have to be set:
 *	- $_indexName
 *	- $_typeName
 *
 * The following variables can be set for additional configuration
 *	- $_mapping: Value type mapping for the given type
 *	- $_indexParams: Parameters for the index
 *
 * @todo Add some settings examples to code
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
abstract class Elastica_Type_Abstract implements Elastica_Searchable
{
	const MAX_DOCS_PER_REQUEST = 1000;

	protected $_indexName = '';
	protected $_typeName = '';
	protected $_client = null;
	protected $_index = null;
	protected $_type = null;
	protected $_mapping = array();
	protected $_indexParams = array();
	protected $_source = true;

	/**
	 * Creates index object with client connection
	 *
	 * Reads index and type name from protected vars _indexName and _typeName.
	 * Has to be set in child class
	 *
	 * @param Elastica_Client $client OPTIONAL Client object
	 */
	public function __construct(Elastica_Client $client = null) {
		if (!$client) {
			$client = new Elastica_Client();
		}

		if (empty($this->_indexName)) {
			throw new Elastica_Exception_Invalid('Index name has to be set');
		}

		if (empty($this->_typeName)) {
			throw new Elastica_Exception_Invalid('Type name has to be set');
		}

		$this->_client = $client;
		$this->_index = new Elastica_Index($this->_client, $this->_indexName);
		$this->_type = new Elastica_Type($this->_index, $this->_typeName);
	}

	/**
	 * Creates the index and sets the mapping for this type
	 *
	 * @param bool $recreate OPTIONAL Recreates the index if true (default = false)
	 */
	public function create($recreate = false) {
		$this->getIndex()->create($this->_indexParams, $recreate);
		$this->getType()->setMapping($this->_mapping, $this->_source);
	}

	/**
	 * {@inheritDoc}
	 */
	public function search($query) {
		return $this->getType()->search($query);
	}

	/**
	 * {@inheritDoc}
	 */
	public function count($query) {
		return $this->getType()->count($query);
	}

	/**
	 * Returns the search index
	 *
	 * @return Elastica_Index Index object
	 */
	public function getIndex() {
		return $this->_index;
	}

	/**
	 * Returns type object
	 *
	 * @return Elastica_Type Type object
	 */
	public function getType() {
		return $this->_type;
	}

	/**
	 * Converts given time to format: 1995-12-31T23:59:59Z
	 *
	 * This is the lucene date format
	 *
	 * @param int $date Date input (could be string etc.) -> must be supported by strtotime
	 * @return string Converted date string
	 */
	public function convertDate($date) {
		if (is_int($date)) {
			$timestamp = $date;
		} else {
			$timestamp = strtotime($date);
		}
		$string =  date('Y-m-d\TH:i:s\Z', $timestamp);
		return $string;
	}
}


text:
<?php
/**
 * Client exception
 *
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Exception_Client extends Elastica_Exception_Abstract {

	protected $_error = 0;
	protected $_request = null;
	protected $_response = null;

	public function __construct($error, Elastica_Request $request = null, Elastica_Response $response = null) {
		$this->_error = $error;
		$this->_request = $request;
		$this->_response = $response;

		$message = $this->getErrorMessage($this->getError());
		parent::__construct($message);
	}

	/**
	 * Returns the error message corresponding to the error code
	 * cUrl error code reference can be found here {@link http://curl.haxx.se/libcurl/c/libcurl-errors.html}
	 *
	 * @return string Error message
	 */
	public function getErrorMessage($error) {

		switch ($error) {
			case CURLE_UNSUPPORTED_PROTOCOL:
				$error = "Unsupported protocol";
				break;
			case CURLE_FAILED_INIT:
				$error = "Internal cUrl error?";
				break;
			case CURLE_URL_MALFORMAT:
				$error = "Malformed URL";
				break;
			case CURLE_COULDNT_RESOLVE_PROXY:
				$error = "Couldnt resolve proxy";
				break;
			case CURLE_COULDNT_RESOLVE_HOST:
				$error = "Couldnt resolve host";
				break;
			case CURLE_COULDNT_CONNECT:
				$error = "Couldnt connect to host, ElasticSearch down?";
				break;
			case 28:
				$error = "Operation timed out";
				break;
			default:
				$error = "Unknown error:" . $error;
				break;
		}

		return $error;
	}

	public function getError() {
		return $this->_error;
	}

	/**
	 * Returns request object
	 *
	 * @return Elastica_Request Request object
	 */
	public function getRequest() {
		return $this->_request;
	}

	/**
	 * Returns response object
	 *
	 * @return Elastica_Response Response object
	 */
	public function getResponse() {
		return $this->_response;
	}
}


text:
<?php
/**
 * Invalid exception
 *
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Exception_Invalid extends Elastica_Exception_Abstract {

}


text:
<?php
/**
 * Bulk Response exception
 *
 * @category Xodoa
 * @package Elastica
 */
class Elastica_Exception_BulkResponse extends Elastica_Exception_Abstract {

	protected $_response = null;

	public function __construct(Elastica_Response $response) {
		$this->_response = $response;
		parent::__construct('Error in one or more bulk request actions');
	}

	/**
	 * Returns response object
	 *
	 * @return Elastica_Response Response object
	 */
	public function getResponse() {
		return $this->_response;
	}

	/**
	 * Returns array of failed actions
	 *
	 * @return array Array of failed actions
	 */
	public function getFailures() {
		$data = $this->_response->getData();
		$errors = array();

		foreach($data['items'] as $item) {
			$meta = reset($item);
			$action = key($item);
			if(isset($meta['error'])) {
				$error = array(
					'action' => $action,
				);
				foreach($meta as $key => $value) {
					$key = ltrim($key, '_');
					$error[$key] = $value;
				}

				$errors[] = $error;
			}
		}

		return $errors;
	}
}


text:
<?php
/**
 * Not implemented exception
 *
 * Is thrown if a function or feature is not implemented yet
 *
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Exception_NotImplemented extends Elastica_Exception_Abstract {

}


text:
<?php
/**
 * Abstract general Elastica exception object
 *
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
abstract class Elastica_Exception_Abstract extends Exception {
}


text:
<?php
/**
 * Response exception
 *
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 */
class Elastica_Exception_Response extends Elastica_Exception_Abstract {

	protected $_response = null;

	public function __construct(Elastica_Response $response) {
		$this->_response = $response;
		parent::__construct($response->getError());
	}

	/**
	 * Returns reponsce object
	 *
	 * @return Elastica_Response Response object
	 */
	public function getResponse() {
		return $this->_response;
	}
}


text:
<?php

class Boilerplate_Controller_Plugin_ModuleLayout
    extends Zend_Controller_Plugin_Abstract
{
    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {
        Zend_Layout::getMvcInstance()->setLayout($request->getModuleName());

        Zend_Layout::getMvcInstance()->setLayoutPath(
            APPLICATION_PATH . "/modules/" . $request->getModuleName() .
            "/layouts/scripts"
        );

        $eh = Zend_Controller_Front::getInstance()->getPlugin(
            "Zend_Controller_Plugin_ErrorHandler"
        );

        $eh->setErrorHandlerModule($request->getModuleName());
    }
}


text:
<?php

class Boilerplate_Controller_Helper_DependencyInjector
    extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * Takes care of injecting controller dependencies
     * into the controller at runtime.
     */
    public function preDispatch()
    {
        $actionController = $this->getActionController();

        $r = new Zend_Reflection_Class($actionController);
        $properties = $r->getProperties();

        foreach ($properties as $property) {
            if ($property->getDeclaringClass()->getName() ==
               get_class($actionController)) {

                if ($property->getDocComment() &&
                   $property->getDocComment()->hasTag('InjectService')) {

                    $tag = $property->getDocComment()->getTag('InjectService');

                    if ($tag->getDescription()) {

                        $sc = Zend_Registry::get('sc');

                        $service = $sc->getService(
                            trim(lcfirst($tag->getDescription()))
                        );

                        $property->setAccessible(true);
                        $property->setValue($actionController, $service);
                    }
                    else
                        throw new Exception("No service key given");
                }
            }
        }
    }
}


text:
<?php

namespace Boilerplate\Webservice\Soap;

class AutoDiscover extends \Zend_Soap_AutoDiscover {

    private $_extra_params = array('apikey' => 'string');

    public function __construct($strategy = true, $uri=null) {
        parent::__construct($strategy,$uri);
    }

    /**
     * overload the ZF method
     *
     * @param $function Zend_Server_Reflection_Function_Abstract function to add
     * @param $wsdl Zend_Soap_Wsdl WSDL document
     * @param $port object wsdl:portType
     * @param $binding object wsdl:binding
     * @return void
     */
    protected function _addFunctionToWsdl($function, $wsdl, $port, $binding)
    {
        $uri = $this->getUri();

        $prototype = null;
        $maxNumArgumentsOfPrototype = -1;
        foreach ($function->getPrototypes() as $tmpPrototype) {
            $numParams = count($tmpPrototype->getParameters());
            if ($numParams > $maxNumArgumentsOfPrototype) {
                $maxNumArgumentsOfPrototype = $numParams;
                $prototype = $tmpPrototype;
            }
        }
        if ($prototype === null) {
            require_once "Zend/Soap/AutoDiscover/Exception.php";
            throw new \Zend_Soap_AutoDiscover_Exception("No prototypes could be found for the '" . $function->getName() . "' function");
        }

        // Add the input message (parameters)
        $args = array();
        if ($this->_bindingStyle['style'] == 'document') {
            // Document style: wrap all parameters in a sequence element
            $sequence = array();
            foreach ($this->_extra_params as $param_name => $param_type) {
                $sequenceElement = array(
                    'name' => $param_name,
                    'type' => $wsdl->getType($param_type)
                );
                if (in_array($param_name,$this->_extra_optional)) {
                    $sequenceElement['nillable'] = 'true';
                }
                $sequence[] = $sequenceElement;
            }
            foreach ($prototype->getParameters() as $param) {
                $sequenceElement = array(
                    'name' => $param->getName(),
                    'type' => $wsdl->getType($param->getType())
                );
                if ($param->isOptional()) {
                    $sequenceElement['nillable'] = 'true';
                }
                $sequence[] = $sequenceElement;
            }
            $element = array(
                'name' => $function->getName(),
                'sequence' => $sequence
            );
            // Add the wrapper element part, which must be named 'parameters'
            $args['parameters'] = array('element' => $wsdl->addElement($element));
        } else {
            // RPC style: add each parameter as a typed part
            foreach ($this->_extra_params as $param_name => $param_type) {
                $args[$param_name] = array('type' => $wsdl->getType($param_type));
            }
            foreach ($prototype->getParameters() as $param) {
                $args[$param->getName()] = array('type' => $wsdl->getType($param->getType()));
            }
        }
        $wsdl->addMessage($function->getName() . 'In', $args);

        $isOneWayMessage = false;
        if($prototype->getReturnType() == "void") {
            $isOneWayMessage = true;
        }

        if($isOneWayMessage == false) {
            // Add the output message (return value)
            $args = array();
            if ($this->_bindingStyle['style'] == 'document') {
                // Document style: wrap the return value in a sequence element
                $sequence = array();
                if ($prototype->getReturnType() != "void") {
                    $sequence[] = array(
                        'name' => $function->getName() . 'Result',
                        'type' => $wsdl->getType($prototype->getReturnType())
                    );
                }
                if (isset($this->_extra_out)) {
                    foreach ($this->_extra_out as $out_name => $out_type) {
                        $sequence[] = array(
                            'name' => $out_name . 'Result',
                            'type' => $wsdl->getType($out_type)
                        );
                    }
                }

                $element = array(
                    'name' => $function->getName() . 'Response',
                    'sequence' => $sequence
                );
                // Add the wrapper element part, which must be named 'parameters'
                $args['parameters'] = array('element' => $wsdl->addElement($element));
            } else if ($prototype->getReturnType() != "void") {
                // RPC style: add the return value as a typed part
                $args['return'] = array('type' => $wsdl->getType($prototype->getReturnType()));
            }
            $wsdl->addMessage($function->getName() . 'Out', $args);
        }

        // Add the portType operation
        if($isOneWayMessage == false) {
            $portOperation = $wsdl->addPortOperation($port, $function->getName(), 'tns:' . $function->getName() . 'In', 'tns:' . $function->getName() . 'Out');
        } else {
            $portOperation = $wsdl->addPortOperation($port, $function->getName(), 'tns:' . $function->getName() . 'In', false);
        }
        $desc = $function->getDescription();
        if (strlen($desc) > 0) {
            //$wsdl->addDocumentation($portOperation, $desc);
        }

        // When using the RPC style, make sure the operation style includes a 'namespace' attribute (WS-I Basic Profile 1.1 R2717)
        if ($this->_bindingStyle['style'] == 'rpc' && !isset($this->_operationBodyStyle['namespace'])) {
            $this->_operationBodyStyle['namespace'] = ''.$uri;
        }

        // Add the binding operation
        $operation = $wsdl->addBindingOperation($binding, $function->getName(),  $this->_operationBodyStyle, $this->_operationBodyStyle);
        $wsdl->addSoapOperation($operation, $uri . '#' .$function->getName());

        // Add the function name to the list
        $this->_functions[] = $function->getName();
    }

}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 16.09.11
 * Time: 03:59
 * To change this template use File | Settings | File Templates.
 */

namespace Boilerplate\Webservice\Soap;

class Server extends \Zend_Soap_Server {

    private $allowedKeys = array('123456');

    public function __construct($wsdl = null, array $options = null) {

        parent::__construct($wsdl,$options);

    }

        /**
     * Handle a request
     * overload the default ZF method
     *
     * @param string $request Optional request
     * @return void|string
     */
    public function handle($request = null) {

        if (null === $request) {
            $request = file_get_contents('php://input');
        }
        if (strlen($request) == 0) {
            $soap = $this->_getSoap();
            $soap->fault(401 , 'Message contains no XML');
        }

        $dom = new \DOMDocument();
        if(!$dom->loadXML($request)) {
            $soap = $this->_getSoap();
            $soap->fault(401 , 'Message contains invalid XML');
        } else {
            //strip out api_key stuff
            $xml = simplexml_load_string($request);
            $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

            $children  = (array) $xml->children('http://schemas.xmlsoap.org/soap/envelope/')
                                     ->Body
                                     ->children($url);

            $methods = array_keys($children);
            $method =  $methods[0];

            $soap = $this->_getSoap();

            $apikey = (string) $xml->children('http://schemas.xmlsoap.org/soap/envelope/')
                                    ->Body
                                    ->children($url)
                                    ->{$method}
                                    ->children()
                                    ->apikey;

            if ($this->_hasAccess($apikey, $method)) {
                //strip api info
                unset($xml->children('http://schemas.xmlsoap.org/soap/envelope/')
                                    ->Body
                                    ->children($url)
                                    ->{$method}
                                    ->children()
                                    ->apikey);

                $request = $xml->asXml();

                //remove whitespace & empty lines
                $request = trim($request);
                $request = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $request);
                return parent::handle($request);
                                } else {
                    $soap = $this->_getSoap();
                    $soap->fault(403 , 'Access forbidden');
                }
        }
    }

                /**
     * check if apikey has access to method
     *
     * @param string $apikey
     * @param string $method
     * @return bool
     */
    protected function _hasAccess($apikey, $method) {
        return in_array($apikey, $this->allowedKeys);
    }

}


text:
<?php

class Boilerplate_Resource_Depinjector
    extends Zend_Application_Resource_ResourceAbstract
{

    public function init()
    {
        return $this->getDependencyInjector();
    }

    public function getDependencyInjector()
    {
        $dependencyInjector =
                new Boilerplate_Controller_Helper_DependencyInjector();

        Zend_Controller_Action_HelperBroker::addHelper($dependencyInjector);
    }
}


text:
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL;

use PDO,
    Doctrine\DBAL\Types\Type,
    Doctrine\DBAL\Driver\Statement as DriverStatement;

/**
 * A thin wrapper around a Doctrine\DBAL\Driver\Statement that adds support
 * for logging, DBAL mapping types, etc.
 *
 * @author Roman Borschel <roman@code-factory.org>
 * @since 2.0
 */
class Statement implements DriverStatement
{
    /**
     * @var string The SQL statement.
     */
    private $_sql;
    /**
     * @var array The bound parameters.
     */
    private $_params = array();
    /**
     * @var Doctrine\DBAL\Driver\Statement The underlying driver statement.
     */
    private $_stmt;
    /**
     * @var Doctrine\DBAL\Platforms\AbstractPlatform The underlying database platform.
     */
    private $_platform;
    /**
     * @var Doctrine\DBAL\Connection The connection this statement is bound to and executed on.
     */
    private $_conn;

    /**
     * Creates a new <tt>Statement</tt> for the given SQL and <tt>Connection</tt>.
     *
     * @param string $sql The SQL of the statement.
     * @param Doctrine\DBAL\Connection The connection on which the statement should be executed.
     */
    public function __construct($sql, Connection $conn)
    {
        $this->_sql = $sql;
        $this->_stmt = $conn->getWrappedConnection()->prepare($sql);
        $this->_conn = $conn;
        $this->_platform = $conn->getDatabasePlatform();
    }

    /**
     * Binds a parameter value to the statement.
     *
     * The value can optionally be bound with a PDO binding type or a DBAL mapping type.
     * If bound with a DBAL mapping type, the binding type is derived from the mapping
     * type and the value undergoes the conversion routines of the mapping type before
     * being bound.
     *
     * @param $name The name or position of the parameter.
     * @param $value The value of the parameter.
     * @param mixed $type Either a PDO binding type or a DBAL mapping type name or instance.
     * @return boolean TRUE on success, FALSE on failure.
     */
    public function bindValue($name, $value, $type = null)
    {
        $this->_params[$name] = $value;
        if ($type !== null) {
            if (is_string($type)) {
                $type = Type::getType($type);
            }
            if ($type instanceof Type) {
                $value = $type->convertToDatabaseValue($value, $this->_platform);
                $bindingType = $type->getBindingType();
            } else {
                $bindingType = $type; // PDO::PARAM_* constants
            }
            return $this->_stmt->bindValue($name, $value, $bindingType);
        } else {
            return $this->_stmt->bindValue($name, $value);
        }
    }

    /**
     * Binds a parameter to a value by reference.
     *
     * Binding a parameter by reference does not support DBAL mapping types.
     *
     * @param string $name The name or position of the parameter.
     * @param mixed $value The reference to the variable to bind
     * @param integer $type The PDO binding type.
     * @return boolean TRUE on success, FALSE on failure.
     */
    public function bindParam($name, &$var, $type = PDO::PARAM_STR)
    {
        return $this->_stmt->bindParam($name, $var, $type);
    }

    /**
     * Executes the statement with the currently bound parameters.
     *
     * @return boolean TRUE on success, FALSE on failure.
     */
    public function execute($params = null)
    {
        $hasLogger = $this->_conn->getConfiguration()->getSQLLogger();
        if ($hasLogger) {
            $this->_conn->getConfiguration()->getSQLLogger()->startQuery($this->_sql, $this->_params);
        }

        $stmt = $this->_stmt->execute($params);

        if ($hasLogger) {
            $this->_conn->getConfiguration()->getSQLLogger()->stopQuery();
        }
        $this->_params = array();
        return $stmt;
    }

    /**
     * Closes the cursor, freeing the database resources used by this statement.
     *
     * @return boolean TRUE on success, FALSE on failure.
     */
    public function closeCursor()
    {
        return $this->_stmt->closeCursor();
    }

    /**
     * Returns the number of columns in the result set.
     *
     * @return integer
     */
    public function columnCount()
    {
        return $this->_stmt->columnCount();
    }

    /**
     * Fetches the SQLSTATE associated with the last operation on the statement.
     *
     * @return string
     */
    public function errorCode()
    {
        return $this->_stmt->errorCode();
    }

    /**
     * Fetches extended error information associated with the last operation on the statement.
     *
     * @return array
     */
    public function errorInfo()
    {
        return $this->_stmt->errorInfo();
    }

    /**
     * Fetches the next row from a result set.
     *
     * @param integer $fetchStyle
     * @return mixed The return value of this function on success depends on the fetch type.
     *               In all cases, FALSE is returned on failure.
     */
    public function fetch($fetchStyle = PDO::FETCH_BOTH)
    {
        return $this->_stmt->fetch($fetchStyle);
    }

    /**
     * Returns an array containing all of the result set rows.
     *
     * @param integer $fetchStyle
     * @param integer $columnIndex
     * @return array An array containing all of the remaining rows in the result set.
     */
    public function fetchAll($fetchStyle = PDO::FETCH_BOTH, $columnIndex = 0)
    {
        if ($columnIndex != 0) {
            return $this->_stmt->fetchAll($fetchStyle, $columnIndex);
        }
        return $this->_stmt->fetchAll($fetchStyle);
    }

    /**
     * Returns a single column from the next row of a result set.
     *
     * @param integer $columnIndex
     * @return mixed A single column from the next row of a result set or FALSE if there are no more rows.
     */
    public function fetchColumn($columnIndex = 0)
    {
        return $this->_stmt->fetchColumn($columnIndex);
    }

    /**
     * Returns the number of rows affected by the last execution of this statement.
     *
     * @return integer The number of affected rows.
     */
    public function rowCount()
    {
        return $this->_stmt->rowCount();
    }

    /**
     * Gets the wrapped driver statement.
     *
     * @return Doctrine\DBAL\Driver\Statement
     */
    public function getWrappedStatement()
    {
        return $this->_stmt;
    }
}


text:
<?php

namespace Doctrine\DBAL;

class DBALException extends \Exception
{
    public static function notSupported($method)
    {
        return new self("Operation '$method' is not supported by platform.");
    }

    public static function invalidPlatformSpecified()
    {
        return new self(
            "Invalid 'platform' option specified, need to give an instance of ".
            "\Doctrine\DBAL\Platforms\AbstractPlatform.");
    }

    public static function invalidPdoInstance()
    {
        return new self(
            "The 'pdo' option was used in DriverManager::getConnection() but no ".
            "instance of PDO was given."
        );
    }

    public static function driverRequired()
    {
        return new self("The options 'driver' or 'driverClass' are mandatory if no PDO ".
            "instance is given to DriverManager::getConnection().");
    }

    public static function unknownDriver($unknownDriverName, array $knownDrivers)
    {
        return new self("The given 'driver' ".$unknownDriverName." is unknown, ".
            "Doctrine currently supports only the following drivers: ".implode(", ", $knownDrivers));
    }

    public static function invalidWrapperClass($wrapperClass)
    {
        return new self("The given 'wrapperClass' ".$wrapperClass." has to be a ".
            "subtype of \Doctrine\DBAL\Connection.");
    }

    public static function invalidDriverClass($driverClass)
    {
        return new self("The given 'driverClass' ".$driverClass." has to implement the ".
            "\Doctrine\DBAL\Driver interface.");
    }

    /**
     * @param string $tableName
     * @return DBALException
     */
    public static function invalidTableName($tableName)
    {
        return new self("Invalid table name specified: ".$tableName);
    }

    /**
     * @param string $tableName
     * @return DBALException
     */
    public static function noColumnsSpecifiedForTable($tableName)
    {
        return new self("No columns specified for table ".$tableName);
    }

    public static function limitOffsetInvalid()
    {
        return new self("Invalid Offset in Limit Query, it has to be larger or equal to 0.");
    }

    public static function typeExists($name)
    {
        return new self('Type '.$name.' already exists.');
    }

    public static function unknownColumnType($name)
    {
        return new self('Unknown column type '.$name.' requested.');
    }

    public static function typeNotFound($name)
    {
        return new self('Type to be overwritten '.$name.' does not exist.');
    }
}


text:
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL;

/**
 * Container for all DBAL events.
 *
 * This class cannot be instantiated.
 *
 * @author Roman Borschel <roman@code-factory.org>
 * @since 2.0
 */
final class Events
{
    private function __construct() {}

    const postConnect = 'postConnect';
}


text:
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL;

use PDO, Closure, Exception,
    Doctrine\DBAL\Types\Type,
    Doctrine\DBAL\Driver\Connection as DriverConnection,
    Doctrine\Common\EventManager,
    Doctrine\DBAL\DBALException;

/**
 * A wrapper around a Doctrine\DBAL\Driver\Connection that adds features like
 * events, transaction isolation levels, configuration, emulated transaction nesting,
 * lazy connecting and more.
 *
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 * @author  Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author  Lukas Smith <smith@pooteeweet.org> (MDB2 library)
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 */
class Connection implements DriverConnection
{
    /**
     * Constant for transaction isolation level READ UNCOMMITTED.
     */
    const TRANSACTION_READ_UNCOMMITTED = 1;

    /**
     * Constant for transaction isolation level READ COMMITTED.
     */
    const TRANSACTION_READ_COMMITTED = 2;

    /**
     * Constant for transaction isolation level REPEATABLE READ.
     */
    const TRANSACTION_REPEATABLE_READ = 3;

    /**
     * Constant for transaction isolation level SERIALIZABLE.
     */
    const TRANSACTION_SERIALIZABLE = 4;

    /**
     * Represents an array of ints to be expanded by Doctrine SQL parsing.
     *
     * @var int
     */
    const PARAM_INT_ARRAY = 101;

    /**
     * Represents an array of strings to be expanded by Doctrine SQL parsing.
     *
     * @var int
     */
    const PARAM_STR_ARRAY = 102;

    /**
     * Offset by which PARAM_* constants are detected as arrays of the param type.
     *
     * @var int
     */
    const ARRAY_PARAM_OFFSET = 100;

    /**
     * The wrapped driver connection.
     *
     * @var Doctrine\DBAL\Driver\Connection
     */
    protected $_conn;

    /**
     * @var Doctrine\DBAL\Configuration
     */
    protected $_config;

    /**
     * @var Doctrine\Common\EventManager
     */
    protected $_eventManager;

    /**
     * @var Doctrine\DBAL\Query\ExpressionBuilder
     */
    protected $_expr;

    /**
     * Whether or not a connection has been established.
     *
     * @var boolean
     */
    private $_isConnected = false;

    /**
     * The transaction nesting level.
     *
     * @var integer
     */
    private $_transactionNestingLevel = 0;

    /**
     * The currently active transaction isolation level.
     *
     * @var integer
     */
    private $_transactionIsolationLevel;

    /**
     * If nested transations should use savepoints
     *
     * @var integer
     */
    private $_nestTransactionsWithSavepoints;

    /**
     * The parameters used during creation of the Connection instance.
     *
     * @var array
     */
    private $_params = array();

    /**
     * The DatabasePlatform object that provides information about the
     * database platform used by the connection.
     *
     * @var Doctrine\DBAL\Platforms\AbstractPlatform
     */
    protected $_platform;

    /**
     * The schema manager.
     *
     * @var Doctrine\DBAL\Schema\SchemaManager
     */
    protected $_schemaManager;

    /**
     * The used DBAL driver.
     *
     * @var Doctrine\DBAL\Driver
     */
    protected $_driver;

    /**
     * Flag that indicates whether the current transaction is marked for rollback only.
     *
     * @var boolean
     */
    private $_isRollbackOnly = false;

    /**
     * Initializes a new instance of the Connection class.
     *
     * @param array $params  The connection parameters.
     * @param Driver $driver
     * @param Configuration $config
     * @param EventManager $eventManager
     */
    public function __construct(array $params, Driver $driver, Configuration $config = null,
            EventManager $eventManager = null)
    {
        $this->_driver = $driver;
        $this->_params = $params;

        if (isset($params['pdo'])) {
            $this->_conn = $params['pdo'];
            $this->_isConnected = true;
        }

        // Create default config and event manager if none given
        if ( ! $config) {
            $config = new Configuration();
        }

        if ( ! $eventManager) {
            $eventManager = new EventManager();
        }

        $this->_config = $config;
        $this->_eventManager = $eventManager;

        $this->_expr = new Query\Expression\ExpressionBuilder($this);

        if ( ! isset($params['platform'])) {
            $this->_platform = $driver->getDatabasePlatform();
        } else if ($params['platform'] instanceof Platforms\AbstractPlatform) {
            $this->_platform = $params['platform'];
        } else {
            throw DBALException::invalidPlatformSpecified();
        }

        $this->_transactionIsolationLevel = $this->_platform->getDefaultTransactionIsolationLevel();
    }

    /**
     * Gets the parameters used during instantiation.
     *
     * @return array $params
     */
    public function getParams()
    {
        return $this->_params;
    }

    /**
     * Gets the name of the database this Connection is connected to.
     *
     * @return string $database
     */
    public function getDatabase()
    {
        return $this->_driver->getDatabase($this);
    }

    /**
     * Gets the hostname of the currently connected database.
     *
     * @return string
     */
    public function getHost()
    {
        return isset($this->_params['host']) ? $this->_params['host'] : null;
    }

    /**
     * Gets the port of the currently connected database.
     *
     * @return mixed
     */
    public function getPort()
    {
        return isset($this->_params['port']) ? $this->_params['port'] : null;
    }

    /**
     * Gets the username used by this connection.
     *
     * @return string
     */
    public function getUsername()
    {
        return isset($this->_params['user']) ? $this->_params['user'] : null;
    }

    /**
     * Gets the password used by this connection.
     *
     * @return string
     */
    public function getPassword()
    {
        return isset($this->_params['password']) ? $this->_params['password'] : null;
    }

    /**
     * Gets the DBAL driver instance.
     *
     * @return \Doctrine\DBAL\Driver
     */
    public function getDriver()
    {
        return $this->_driver;
    }

    /**
     * Gets the Configuration used by the Connection.
     *
     * @return \Doctrine\DBAL\Configuration
     */
    public function getConfiguration()
    {
        return $this->_config;
    }

    /**
     * Gets the EventManager used by the Connection.
     *
     * @return \Doctrine\Common\EventManager
     */
    public function getEventManager()
    {
        return $this->_eventManager;
    }

    /**
     * Gets the DatabasePlatform for the connection.
     *
     * @return \Doctrine\DBAL\Platforms\AbstractPlatform
     */
    public function getDatabasePlatform()
    {
        return $this->_platform;
    }

    /**
     * Gets the ExpressionBuilder for the connection.
     *
     * @return \Doctrine\DBAL\Query\ExpressionBuilder
     */
    public function getExpressionBuilder()
    {
        return $this->_expr;
    }

    /**
     * Establishes the connection with the database.
     *
     * @return boolean TRUE if the connection was successfully established, FALSE if
     *                 the connection is already open.
     */
    public function connect()
    {
        if ($this->_isConnected) return false;

        $driverOptions = isset($this->_params['driverOptions']) ?
                $this->_params['driverOptions'] : array();
        $user = isset($this->_params['user']) ? $this->_params['user'] : null;
        $password = isset($this->_params['password']) ?
                $this->_params['password'] : null;

        $this->_conn = $this->_driver->connect($this->_params, $user, $password, $driverOptions);
        $this->_isConnected = true;

        if ($this->_eventManager->hasListeners(Events::postConnect)) {
            $eventArgs = new Event\ConnectionEventArgs($this);
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
        }

        return true;
    }

    /**
     * Prepares and executes an SQL query and returns the first row of the result
     * as an associative array.
     *
     * @param string $statement The SQL query.
     * @param array $params The query parameters.
     * @return array
     */
    public function fetchAssoc($statement, array $params = array())
    {
        return $this->executeQuery($statement, $params)->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * Prepares and executes an SQL query and returns the first row of the result
     * as a numerically indexed array.
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @return array
     */
    public function fetchArray($statement, array $params = array())
    {
        return $this->executeQuery($statement, $params)->fetch(PDO::FETCH_NUM);
    }

    /**
     * Prepares and executes an SQL query and returns the value of a single column
     * of the first row of the result.
     *
     * @param string $statement         sql query to be executed
     * @param array $params             prepared statement params
     * @param int $colnum               0-indexed column number to retrieve
     * @return mixed
     */
    public function fetchColumn($statement, array $params = array(), $colnum = 0)
    {
        return $this->executeQuery($statement, $params)->fetchColumn($colnum);
    }

    /**
     * Whether an actual connection to the database is established.
     *
     * @return boolean
     */
    public function isConnected()
    {
        return $this->_isConnected;
    }

    /**
     * Checks whether a transaction is currently active.
     *
     * @return boolean TRUE if a transaction is currently active, FALSE otherwise.
     */
    public function isTransactionActive()
    {
        return $this->_transactionNestingLevel > 0;
    }

    /**
     * Executes an SQL DELETE statement on a table.
     *
     * @param string $table The name of the table on which to delete.
     * @param array $identifier The deletion criteria. An associateve array containing column-value pairs.
     * @return integer The number of affected rows.
     */
    public function delete($tableName, array $identifier)
    {
        $this->connect();

        $criteria = array();

        foreach (array_keys($identifier) as $columnName) {
            $criteria[] = $columnName . ' = ?';
        }

        $query = 'DELETE FROM ' . $tableName . ' WHERE ' . implode(' AND ', $criteria);

        return $this->executeUpdate($query, array_values($identifier));
    }

    /**
     * Closes the connection.
     *
     * @return void
     */
    public function close()
    {
        unset($this->_conn);

        $this->_isConnected = false;
    }

    /**
     * Sets the transaction isolation level.
     *
     * @param integer $level The level to set.
     */
    public function setTransactionIsolation($level)
    {
        $this->_transactionIsolationLevel = $level;

        return $this->executeUpdate($this->_platform->getSetTransactionIsolationSQL($level));
    }

    /**
     * Gets the currently active transaction isolation level.
     *
     * @return integer The current transaction isolation level.
     */
    public function getTransactionIsolation()
    {
        return $this->_transactionIsolationLevel;
    }

    /**
     * Executes an SQL UPDATE statement on a table.
     *
     * @param string $table The name of the table to update.
     * @param array $identifier The update criteria. An associative array containing column-value pairs.
     * @return integer The number of affected rows.
     */
    public function update($tableName, array $data, array $identifier)
    {
        $this->connect();
        $set = array();
        foreach ($data as $columnName => $value) {
            $set[] = $columnName . ' = ?';
        }

        $params = array_merge(array_values($data), array_values($identifier));

        $sql  = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $set)
                . ' WHERE ' . implode(' = ? AND ', array_keys($identifier))
                . ' = ?';

        return $this->executeUpdate($sql, $params);
    }

    /**
     * Inserts a table row with specified data.
     *
     * @param string $table The name of the table to insert data into.
     * @param array $data An associative array containing column-value pairs.
     * @return integer The number of affected rows.
     */
    public function insert($tableName, array $data)
    {
        $this->connect();

        // column names are specified as array keys
        $cols = array();
        $placeholders = array();

        foreach ($data as $columnName => $value) {
            $cols[] = $columnName;
            $placeholders[] = '?';
        }

        $query = 'INSERT INTO ' . $tableName
               . ' (' . implode(', ', $cols) . ')'
               . ' VALUES (' . implode(', ', $placeholders) . ')';

        return $this->executeUpdate($query, array_values($data));
    }

    /**
     * Sets the given charset on the current connection.
     *
     * @param string $charset The charset to set.
     */
    public function setCharset($charset)
    {
        $this->executeUpdate($this->_platform->getSetCharsetSQL($charset));
    }

    /**
     * Quote a string so it can be safely used as a table or column name, even if
     * it is a reserved name.
     *
     * Delimiting style depends on the underlying database platform that is being used.
     *
     * NOTE: Just because you CAN use quoted identifiers does not mean
     * you SHOULD use them. In general, they end up causing way more
     * problems than they solve.
     *
     * @param string $str The name to be quoted.
     * @return string The quoted name.
     */
    public function quoteIdentifier($str)
    {
        return $this->_platform->quoteIdentifier($str);
    }

    /**
     * Quotes a given input parameter.
     *
     * @param mixed $input Parameter to be quoted.
     * @param string $type Type of the parameter.
     * @return string The quoted parameter.
     */
    public function quote($input, $type = null)
    {
        $this->connect();

        return $this->_conn->quote($input, $type);
    }

    /**
     * Prepares and executes an SQL query and returns the result as an associative array.
     *
     * @param string $sql The SQL query.
     * @param array $params The query parameters.
     * @return array
     */
    public function fetchAll($sql, array $params = array())
    {
        return $this->executeQuery($sql, $params)->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * Prepares an SQL statement.
     *
     * @param string $statement The SQL statement to prepare.
     * @return Doctrine\DBAL\Driver\Statement The prepared statement.
     */
    public function prepare($statement)
    {
        $this->connect();

        return new Statement($statement, $this);
    }

    /**
     * Executes an, optionally parameterized, SQL query.
     *
     * If the query is parameterized, a prepared statement is used.
     * If an SQLLogger is configured, the execution is logged.
     *
     * @param string $query The SQL query to execute.
     * @param array $params The parameters to bind to the query, if any.
     * @return Doctrine\DBAL\Driver\Statement The executed statement.
     * @internal PERF: Directly prepares a driver statement, not a wrapper.
     */
    public function executeQuery($query, array $params = array(), $types = array())
    {
        $this->connect();

        $hasLogger = $this->_config->getSQLLogger() !== null;
        if ($hasLogger) {
            $this->_config->getSQLLogger()->startQuery($query, $params, $types);
        }

        if ($params) {
            list($query, $params, $types) = SQLParserUtils::expandListParameters($query, $params, $types);

            $stmt = $this->_conn->prepare($query);
            if ($types) {
                $this->_bindTypedValues($stmt, $params, $types);
                $stmt->execute();
            } else {
                $stmt->execute($params);
            }
        } else {
            $stmt = $this->_conn->query($query);
        }

        if ($hasLogger) {
            $this->_config->getSQLLogger()->stopQuery();
        }

        return $stmt;
    }

    /**
     * Executes an, optionally parameterized, SQL query and returns the result,
     * applying a given projection/transformation function on each row of the result.
     *
     * @param string $query The SQL query to execute.
     * @param array $params The parameters, if any.
     * @param Closure $mapper The transformation function that is applied on each row.
     *                        The function receives a single paramater, an array, that
     *                        represents a row of the result set.
     * @return mixed The projected result of the query.
     */
    public function project($query, array $params, Closure $function)
    {
        $result = array();
        $stmt = $this->executeQuery($query, $params ?: array());

        while ($row = $stmt->fetch()) {
            $result[] = $function($row);
        }

        $stmt->closeCursor();

        return $result;
    }

    /**
     * Executes an SQL statement, returning a result set as a Statement object.
     *
     * @param string $statement
     * @param integer $fetchType
     * @return Doctrine\DBAL\Driver\Statement
     */
    public function query()
    {
        $this->connect();

        $args = func_get_args();

        $logger = $this->getConfiguration()->getSQLLogger();
        if ($logger) {
            $logger->startQuery($args[0]);
        }

        $statement = call_user_func_array(array($this->_conn, 'query'), $args);

        if ($logger) {
            $logger->stopQuery();
        }

        return $statement;
    }

    /**
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
     * and returns the number of affected rows.
     *
     * This method supports PDO binding types as well as DBAL mapping types.
     *
     * @param string $query The SQL query.
     * @param array $params The query parameters.
     * @param array $types The parameter types.
     * @return integer The number of affected rows.
     * @internal PERF: Directly prepares a driver statement, not a wrapper.
     */
    public function executeUpdate($query, array $params = array(), array $types = array())
    {
        $this->connect();

        $hasLogger = $this->_config->getSQLLogger() !== null;
        if ($hasLogger) {
            $this->_config->getSQLLogger()->startQuery($query, $params, $types);
        }

        if ($params) {
            list($query, $params, $types) = SQLParserUtils::expandListParameters($query, $params, $types);

            $stmt = $this->_conn->prepare($query);
            if ($types) {
                $this->_bindTypedValues($stmt, $params, $types);
                $stmt->execute();
            } else {
                $stmt->execute($params);
            }
            $result = $stmt->rowCount();
        } else {
            $result = $this->_conn->exec($query);
        }

        if ($hasLogger) {
            $this->_config->getSQLLogger()->stopQuery();
        }

        return $result;
    }

    /**
     * Execute an SQL statement and return the number of affected rows.
     *
     * @param string $statement
     * @return integer The number of affected rows.
     */
    public function exec($statement)
    {
        $this->connect();
        return $this->_conn->exec($statement);
    }

    /**
     * Returns the current transaction nesting level.
     *
     * @return integer The nesting level. A value of 0 means there's no active transaction.
     */
    public function getTransactionNestingLevel()
    {
        return $this->_transactionNestingLevel;
    }

    /**
     * Fetch the SQLSTATE associated with the last database operation.
     *
     * @return integer The last error code.
     */
    public function errorCode()
    {
        $this->connect();
        return $this->_conn->errorCode();
    }

    /**
     * Fetch extended error information associated with the last database operation.
     *
     * @return array The last error information.
     */
    public function errorInfo()
    {
        $this->connect();
        return $this->_conn->errorInfo();
    }

    /**
     * Returns the ID of the last inserted row, or the last value from a sequence object,
     * depending on the underlying driver.
     *
     * Note: This method may not return a meaningful or consistent result across different drivers,
     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
     * columns or sequences.
     *
     * @param string $seqName Name of the sequence object from which the ID should be returned.
     * @return string A string representation of the last inserted ID.
     */
    public function lastInsertId($seqName = null)
    {
        $this->connect();
        return $this->_conn->lastInsertId($seqName);
    }

    /**
     * Executes a function in a transaction.
     *
     * The function gets passed this Connection instance as an (optional) parameter.
     *
     * If an exception occurs during execution of the function or transaction commit,
     * the transaction is rolled back and the exception re-thrown.
     *
     * @param Closure $func The function to execute transactionally.
     */
    public function transactional(Closure $func)
    {
        $this->beginTransaction();
        try {
            $func($this);
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            throw $e;
        }
    }

    /**
     * Set if nested transactions should use savepoints
     *
     * @param boolean
     * @return void
     */
    public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
    {
        if ($this->_transactionNestingLevel > 0) {
            throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
        }

        if (!$this->_platform->supportsSavepoints()) {
            throw ConnectionException::savepointsNotSupported();
        }

        $this->_nestTransactionsWithSavepoints = $nestTransactionsWithSavepoints;
    }

    /**
     * Get if nested transactions should use savepoints
     *
     * @return boolean
     */
    public function getNestTransactionsWithSavepoints()
    {
        return $this->_nestTransactionsWithSavepoints;
    }

    /**
     * Returns the savepoint name to use for nested transactions are false if they are not supported
     * "savepointFormat" parameter is not set
     *
     * @return mixed a string with the savepoint name or false
     */
    protected function _getNestedTransactionSavePointName()
    {
        return 'DOCTRINE2_SAVEPOINT_'.$this->_transactionNestingLevel;
    }

    /**
     * Starts a transaction by suspending auto-commit mode.
     *
     * @return void
     */
    public function beginTransaction()
    {
        $this->connect();

        ++$this->_transactionNestingLevel;

        if ($this->_transactionNestingLevel == 1) {
            $this->_conn->beginTransaction();
        } else if ($this->_nestTransactionsWithSavepoints) {
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
        }
    }

    /**
     * Commits the current transaction.
     *
     * @return void
     * @throws ConnectionException If the commit failed due to no active transaction or
     *                             because the transaction was marked for rollback only.
     */
    public function commit()
    {
        if ($this->_transactionNestingLevel == 0) {
            throw ConnectionException::noActiveTransaction();
        }
        if ($this->_isRollbackOnly) {
            throw ConnectionException::commitFailedRollbackOnly();
        }

        $this->connect();

        if ($this->_transactionNestingLevel == 1) {
            $this->_conn->commit();
        } else if ($this->_nestTransactionsWithSavepoints) {
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
        }

        --$this->_transactionNestingLevel;
    }

    /**
     * Cancel any database changes done during the current transaction.
     *
     * this method can be listened with onPreTransactionRollback and onTransactionRollback
     * eventlistener methods
     *
     * @throws ConnectionException If the rollback operation failed.
     */
    public function rollback()
    {
        if ($this->_transactionNestingLevel == 0) {
            throw ConnectionException::noActiveTransaction();
        }

        $this->connect();

        if ($this->_transactionNestingLevel == 1) {
            $this->_transactionNestingLevel = 0;
            $this->_conn->rollback();
            $this->_isRollbackOnly = false;
        } else if ($this->_nestTransactionsWithSavepoints) {
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
            --$this->_transactionNestingLevel;
        } else {
            $this->_isRollbackOnly = true;
            --$this->_transactionNestingLevel;
        }
    }

    /**
     * createSavepoint
     * creates a new savepoint
     *
     * @param string $savepoint     name of a savepoint to set
     * @return void
     */
    public function createSavepoint($savepoint)
    {
        if (!$this->_platform->supportsSavepoints()) {
            throw ConnectionException::savepointsNotSupported();
        }

        $this->_conn->exec($this->_platform->createSavePoint($savepoint));
    }

    /**
     * releaseSavePoint
     * releases given savepoint
     *
     * @param string $savepoint     name of a savepoint to release
     * @return void
     */
    public function releaseSavepoint($savepoint)
    {
        if (!$this->_platform->supportsSavepoints()) {
            throw ConnectionException::savepointsNotSupported();
        }

        if ($this->_platform->supportsReleaseSavepoints()) {
            $this->_conn->exec($this->_platform->releaseSavePoint($savepoint));
        }
    }

    /**
     * rollbackSavePoint
     * releases given savepoint
     *
     * @param string $savepoint     name of a savepoint to rollback to
     * @return void
     */
    public function rollbackSavepoint($savepoint)
    {
        if (!$this->_platform->supportsSavepoints()) {
            throw ConnectionException::savepointsNotSupported();
        }

        $this->_conn->exec($this->_platform->rollbackSavePoint($savepoint));
    }

    /**
     * Gets the wrapped driver connection.
     *
     * @return Doctrine\DBAL\Driver\Connection
     */
    public function getWrappedConnection()
    {
        $this->connect();

        return $this->_conn;
    }

    /**
     * Gets the SchemaManager that can be used to inspect or change the
     * database schema through the connection.
     *
     * @return Doctrine\DBAL\Schema\SchemaManager
     */
    public function getSchemaManager()
    {
        if ( ! $this->_schemaManager) {
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
        }

        return $this->_schemaManager;
    }

    /**
     * Marks the current transaction so that the only possible
     * outcome for the transaction to be rolled back.
     *
     * @throws ConnectionException If no transaction is active.
     */
    public function setRollbackOnly()
    {
        if ($this->_transactionNestingLevel == 0) {
            throw ConnectionException::noActiveTransaction();
        }
        $this->_isRollbackOnly = true;
    }

    /**
     * Check whether the current transaction is marked for rollback only.
     *
     * @return boolean
     * @throws ConnectionException If no transaction is active.
     */
    public function isRollbackOnly()
    {
        if ($this->_transactionNestingLevel == 0) {
            throw ConnectionException::noActiveTransaction();
        }
        return $this->_isRollbackOnly;
    }

    /**
     * Converts a given value to its database representation according to the conversion
     * rules of a specific DBAL mapping type.
     *
     * @param mixed $value The value to convert.
     * @param string $type The name of the DBAL mapping type.
     * @return mixed The converted value.
     */
    public function convertToDatabaseValue($value, $type)
    {
        return Type::getType($type)->convertToDatabaseValue($value, $this->_platform);
    }

    /**
     * Converts a given value to its PHP representation according to the conversion
     * rules of a specific DBAL mapping type.
     *
     * @param mixed $value The value to convert.
     * @param string $type The name of the DBAL mapping type.
     * @return mixed The converted type.
     */
    public function convertToPHPValue($value, $type)
    {
        return Type::getType($type)->convertToPHPValue($value, $this->_platform);
    }

    /**
     * Binds a set of parameters, some or all of which are typed with a PDO binding type
     * or DBAL mapping type, to a given statement.
     *
     * @param $stmt The statement to bind the values to.
     * @param array $params The map/list of named/positional parameters.
     * @param array $types The parameter types (PDO binding types or DBAL mapping types).
     * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
     *           raw PDOStatement instances.
     */
    private function _bindTypedValues($stmt, array $params, array $types)
    {
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
        if (is_int(key($params))) {
            // Positional parameters
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
            $bindIndex = 1;
            foreach ($params as $position => $value) {
                $typeIndex = $bindIndex + $typeOffset;
                if (isset($types[$typeIndex])) {
                    $type = $types[$typeIndex];
                    if (is_string($type)) {
                        $type = Type::getType($type);
                    }
                    if ($type instanceof Type) {
                        $value = $type->convertToDatabaseValue($value, $this->_platform);
                        $bindingType = $type->getBindingType();
                    } else {
                        $bindingType = $type; // PDO::PARAM_* constants
                    }
                    $stmt->bindValue($bindIndex, $value, $bindingType);
                } else {
                    $stmt->bindValue($bindIndex, $value);
                }
                ++$bindIndex;
            }
        } else {
            // Named parameters
            foreach ($params as $name => $value) {
                if (isset($types[$name])) {
                    $type = $types[$name];
                    if (is_string($type)) {
                        $type = Type::getType($type);
                    }
                    if ($type instanceof Type) {
                        $value = $type->convertToDatabaseValue($value, $this->_platform);
                        $bindingType = $type->getBindingType();
                    } else {
                        $bindingType = $type; // PDO::PARAM_* constants
                    }
                    $stmt->bindValue($name, $value, $bindingType);
                } else {
                    $stmt->bindValue($name, $value);
                }
            }
        }
    }

    /**
     * Create a new instance of a SQL query builder.
     *
     * @return Query\QueryBuilder
     */
    public function createQueryBuilder()
    {
        return new Query\QueryBuilder($this);
    }
}


text:
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL;

/**
 * Class to store and retrieve the version of Doctrine
 *
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @version $Revision$
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 */
class Version
{
    /**
     * Current Doctrine Version
     */
    const VERSION = '2.1.3-DEV';

    /**
     * Compares a Doctrine version with the current one.
     *
     * @param string $version Doctrine version to compare.
     * @return int Returns -1 if older, 0 if it is the same, 1 if version
     *             passed as argument is newer.
     */
    public static function compare($version)
    {
        $currentVersion = str_replace(' ', '', strtolower(self::VERSION));
        $version = str_replace(' ', '', $version);

        return version_compare($version, $currentVersion);
    }
}


text:
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
*/

namespace Doctrine\DBAL;

/**
 * Contains all DBAL LockModes
 *
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.doctrine-project.com
 * @since       1.0
 * @version     $Revision$
 * @author      Benjamin Eberlei <kontakt@beberlei.de>
 * @author      Roman Borschel <roman@code-factory.org>
 */
class LockMode
{
    const NONE = 0;
    const OPTIMISTIC = 1;
    const PESSIMISTIC_READ = 2;
    const PESSIMISTIC_WRITE = 4;

    final private function __construct() { }
}


text:
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL;

use Doctrine\DBAL\Logging\SQLLogger;

/**
 * Configuration container for the Doctrine DBAL.
 *
 * @since   2.0
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Roman Borschel <roman@code-factory.org>
 * @internal When adding a new configuration option just write a getter/setter
 *           pair and add the option to the _attributes array with a proper default value.
 */
class Configuration
{
    /**
     * The attributes that are contained in the configuration.
     * Values are default values.
     *
     * @var array
     */
    protected $_attributes = array();

    /**
     * Sets the SQL logger to use. Defaults to NULL which means SQL logging is disabled.
     *
     * @param SQLLogger $logger
     */
    public function setSQLLogger(SQLLogger $logger = null)
    {
        $this->_attributes['sqlLogger'] = $logger;
    }

    /**
     * Gets the SQL logger that is used.
     *
     * @return SQLLogger
     */
    public function getSQLLogger()
    {
        return isset($this->_attributes['sqlLogger']) ?
                $this->_attributes['sqlLogger'] : null;
    }
}


text:
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL;

use Doctrine\Common\EventManager;

/**
 * Factory for creating Doctrine\DBAL\Connection instances.
 *
 * @author Roman Borschel <roman@code-factory.org>
 * @since 2.0
 */
final class DriverManager
{
    /**
     * List of supported drivers and their mappings to the driver classes.
     *
     * @var array
     * @todo REMOVE. Users should directly supply class names instead.
     */
     private static $_driverMap = array(
            'pdo_mysql'  => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
            'pdo_sqlite' => 'Doctrine\DBAL\Driver\PDOSqlite\Driver',
            'pdo_pgsql'  => 'Doctrine\DBAL\Driver\PDOPgSql\Driver',
            'pdo_oci' => 'Doctrine\DBAL\Driver\PDOOracle\Driver',
            'oci8' => 'Doctrine\DBAL\Driver\OCI8\Driver',
            'ibm_db2' => 'Doctrine\DBAL\Driver\IBMDB2\DB2Driver',
            'pdo_ibm' => 'Doctrine\DBAL\Driver\PDOIbm\Driver',
            'pdo_sqlsrv' => 'Doctrine\DBAL\Driver\PDOSqlsrv\Driver',
            );

    /** Private constructor. This class cannot be instantiated. */
    private function __construct() { }

    /**
     * Creates a connection object based on the specified parameters.
     * This method returns a Doctrine\DBAL\Connection which wraps the underlying
     * driver connection.
     *
     * $params must contain at least one of the following.
     *
     * Either 'driver' with one of the following values:
     *     pdo_mysql
     *     pdo_sqlite
     *     pdo_pgsql
     *     pdo_oracle
     *     pdo_sqlsrv
     *
     * OR 'driverClass' that contains the full class name (with namespace) of the
     * driver class to instantiate.
     *
     * Other (optional) parameters:
     *
     * user (string):
     * The username to use when connecting.
     *
     * password (string):
     * The password to use when connecting.
     *
     * driverOptions (array):
     * Any additional driver-specific options for the driver. These are just passed
     * through to the driver.
     *
     * pdo:
     * You can pass an existing PDO instance through this parameter. The PDO
     * instance will be wrapped in a Doctrine\DBAL\Connection.
     *
     * wrapperClass:
     * You may specify a custom wrapper class through the 'wrapperClass'
     * parameter but this class MUST inherit from Doctrine\DBAL\Connection.
     *
     * @param array $params The parameters.
     * @param Doctrine\DBAL\Configuration The configuration to use.
     * @param Doctrine\Common\EventManager The event manager to use.
     * @return Doctrine\DBAL\Connection
     */
    public static function getConnection(
            array $params,
            Configuration $config = null,
            EventManager $eventManager = null)
    {
        // create default config and event manager, if not set
        if ( ! $config) {
            $config = new Configuration();
        }
        if ( ! $eventManager) {
            $eventManager = new EventManager();
        }

        // check for existing pdo object
        if (isset($params['pdo']) && ! $params['pdo'] instanceof \PDO) {
            throw DBALException::invalidPdoInstance();
        } else if (isset($params['pdo'])) {
            $params['pdo']->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            $params['driver'] = 'pdo_' . $params['pdo']->getAttribute(\PDO::ATTR_DRIVER_NAME);
        } else {
            self::_checkParams($params);
        }
        if (isset($params['driverClass'])) {
            $className = $params['driverClass'];
        } else {
            $className = self::$_driverMap[$params['driver']];
        }

        $driver = new $className();

        $wrapperClass = 'Doctrine\DBAL\Connection';
        if (isset($params['wrapperClass'])) {
            if (is_subclass_of($params['wrapperClass'], $wrapperClass)) {
               $wrapperClass = $params['wrapperClass'];
            } else {
                throw DBALException::invalidWrapperClass($params['wrapperClass']);
            }
        }

        return new $wrapperClass($params, $driver, $config, $eventManager);
    }

    /**
     * Checks the list of parameters.
     *
     * @param array $params
     */
    private static function _checkParams(array $params)
    {
        // check existance of mandatory parameters

        // driver
        if ( ! isset($params['driver']) && ! isset($params['driverClass'])) {
            throw DBALException::driverRequired();
        }

        // check validity of parameters

        // driver
        if ( isset($params['driver']) && ! isset(self::$_driverMap[$params['driver']])) {
            throw DBALException::unknownDriver($params['driver'], array_keys(self::$_driverMap));
        }

        if (isset($params['driverClass']) && ! in_array('Doctrine\DBAL\Driver', class_implements($params['driverClass'], true))) {
            throw DBALException::invalidDriverClass($params['driverClass']);
        }
    }
}


text:
<?php
/*
 *  $Id: Exception.php 4628 2008-07-04 16:32:19Z romanb $
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL;

/**
 * Doctrine\DBAL\ConnectionException
 *
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.doctrine-project.org
 * @since       2.0
 * @version     $Revision: 4628 $
 * @author      Jonathan H. Wage <jonwage@gmail.com
 */
class ConnectionException extends DBALException
{
    public static function commitFailedRollbackOnly()
    {
        return new self("Transaction commit failed because the transaction has been marked for rollback only.");
    }

    public static function noActiveTransaction()
    {
        return new self("There is no active transaction.");
    }

    public static function savepointsNotSupported()
    {
        return new self("Savepoints are not supported by this driver.");
    }

    public static function mayNotAlterNestedTransactionWithSavepointsInTransaction()
    {
        return new self("May not alter the nested transaction with savepoints behavior while a transaction is open.");
    }
}