Commit ff99e2e3 authored by doctrine's avatar doctrine

Removed file/folder

parent 98dc74b6
<?php
/**
* Doctrine_Access
*
* the purpose of Doctrine_Access is to provice array access
* and property overload interface for subclasses
*
* @package Doctrine ORM
* @url www.phpdoctrine.com
* @license LGPL
*/
abstract class Doctrine_Access implements ArrayAccess {
/**
* setArray
* @param array $array an array of key => value pairs
*/
public function setArray(array $array) {
foreach($array as $k=>$v):
$this->set($k,$v);
endforeach;
}
/**
* __set -- an alias of set()
* @see set, offsetSet
* @param $name
* @param $value
*/
public function __set($name,$value) {
$this->set($name,$value);
}
/**
* __get -- an alias of get()
* @see get, offsetGet
* @param mixed $name
* @return mixed
*/
public function __get($name) {
return $this->get($name);
}
/**
* @param mixed $offset
* @return boolean -- whether or not the data has a field $offset
*/
public function offsetExists($offset) {
return (bool) isset($this->data[$offset]);
}
/**
* offsetGet -- an alias of get()
* @see get, __get
* @param mixed $offset
* @return mixed
*/
public function offsetGet($offset) {
return $this->get($offset);
}
/**
* sets $offset to $value
* @see set, __set
* @param mixed $offset
* @param mixed $value
* @return void
*/
public function offsetSet($offset, $value) {
if( ! isset($offset)) {
$this->add($value);
} else
$this->set($offset,$value);
}
/**
* unset a given offset
* @see set, offsetSet, __set
* @param mixed $offset
*/
public function offsetUnset($offset) {
if($this instanceof Doctrine_Collection) {
return $this->remove($offset);
} else {
$this->set($offset,null);
}
}
}
?>
<?php
require_once("Relation.class.php");
/**
* Doctrine_Association this class takes care of association mapping
* (= many-to-many relationships, where the relationship is handled with an additional relational table
* which holds 2 foreign keys)
*
*
* @package Doctrine ORM
* @url www.phpdoctrine.com
* @license LGPL
*/
class Doctrine_Association extends Doctrine_Relation {
/**
* @var Doctrine_Table $associationTable
*/
private $associationTable;
/**
* the constructor
* @param Doctrine_Table $table foreign factory object
* @param Doctrine_Table $associationTable factory which handles the association
* @param string $local local field name
* @param string $foreign foreign field name
* @param integer $type type of relation
* @see Doctrine_Table constants
*/
public function __construct(Doctrine_Table $table, Doctrine_Table $associationTable, $local, $foreign, $type) {
parent::__construct($table, $local, $foreign, $type);
$this->associationTable = $associationTable;
}
/**
* @return Doctrine_Table
*/
public function getAssociationFactory() {
return $this->associationTable;
}
}
?>
<?php
interface iDoctrine_Cache {
public function store(Doctrine_Record $record);
public function clean();
public function delete($id);
public function fetch($id);
public function exists($id);
}
class Doctrine_Cache implements iDoctrine_Cache {
/**
* implemented by child classes
* @param Doctrine_Record $record
* @return boolean
*/
public function store(Doctrine_Record $record) {
return false;
}
/**
* implemented by child classes
* @return boolean
*/
public function clean() {
return false;
}
/**
* implemented by child classes
* @return boolean
*/
public function delete($id) {
return false;
}
/**
* implemented by child classes
* @throws InvalidKeyException
* @return Doctrine_Record found Data Access Object
*/
public function fetch($id) {
throw new InvalidKeyException();
}
/**
* implemented by child classes
* @param array $keys
* @return boolean
*/
public function fetchMultiple($keys) {
return false;
}
/**
* implemented by child classes
* @param integer $id
* @return boolean
*/
public function exists($id) {
return false;
}
/**
* implemented by child classes
*/
public function deleteMultiple($keys) {
return 0;
}
/**
* implemented by child classes
* @return integer
*/
public function deleteAll() {
return 0;
}
}
?>
<?php
/**
* Doctrine_CacheFile
* @author Konsta Vesterinen
* @package Doctrine ORM
* @url www.phpdoctrine.com
* @license LGPL
* @version 1.0 alpha
*/
class Doctrine_Cache_File implements Countable {
const STATS_FILE = "stats.cache";
/**
* @var string $path path for the cache files
*/
private $path;
/**
* @var array $fetched an array of fetched primary keys
*/
private $fetched = array();
/**
* @var Doctrine_Table $objTable
*/
private $objTable;
/**
* constructor
* @param Doctrine_Table $objTable
*/
public function __construct(Doctrine_Table $objTable) {
$this->objTable = $objTable;
$name = $this->getTable()->getTableName();
$manager = Doctrine_Manager::getInstance();
$dir = $manager->getAttribute(Doctrine::ATTR_CACHE_DIR);
if( ! is_dir($dir))
mkdir($dir, 0777);
if( ! is_dir($dir.DIRECTORY_SEPARATOR.$name))
mkdir($dir.DIRECTORY_SEPARATOR.$name, 0777);
$this->path = $dir.DIRECTORY_SEPARATOR.$name.DIRECTORY_SEPARATOR;
/**
* create stats file
*/
if( ! file_exists($this->path.self::STATS_FILE))
touch($this->path.self::STATS_FILE);
}
/**
* @return Doctrine_Table
*/
public function getTable() {
return $this->objTable;
}
/**
* @return integer number of cache files
*/
public function count() {
$c = -1;
foreach(glob($this->path."*.cache") as $file) {
$c++;
}
return $c;
}
/**
* getStats
* @return array an array of fetch statistics, keys as primary keys
* and values as fetch times
*/
public function getStats() {
$f = file_get_contents($this->path.self::STATS_FILE);
// every cache file starts with a ":"
$f = substr(trim($f),1);
$e = explode(":",$f);
return array_count_values($e);
}
/**
* store store a Doctrine_Record into file cache
* @param Doctrine_Record $record data access object to be stored
* @return boolean whether or not storing was successful
*/
public function store(Doctrine_Record $record) {
if($record->getState() != Doctrine_Record::STATE_CLEAN)
return false;
$file = $this->path.$record->getID().".cache";
if(file_exists($file))
return false;
$clone = clone $record;
$id = $clone->getID();
$fp = fopen($file,"w+");
fwrite($fp,serialize($clone));
fclose($fp);
$this->fetched[] = $id;
return true;
}
/**
* clean
* @return void
*/
public function clean() {
$stats = $this->getStats();
arsort($stats);
$size = $this->objTable->getAttribute(Doctrine::ATTR_CACHE_SIZE);
$count = count($stats);
$i = 1;
$preserve = array();
foreach($stats as $id => $count) {
if($i > $size)
break;
$preserve[$id] = true;
$i++;
}
foreach(glob($this->path."*.cache") as $file) {
$e = explode(".",basename($file));
$c = count($e);
$id = $e[($c - 2)];
if( ! isset($preserve[$id]))
@unlink($this->path.$id.".cache");
}
$fp = fopen($this->path.self::STATS_FILE,"w+");
fwrite($fp,"");
fclose($fp);
}
/**
* @param integer $id primary key of the DAO
* @return string filename and path
*/
public function getFileName($id) {
return $this->path.$id.".cache";
}
/**
* @return array an array of fetched primary keys
*/
public function getFetched() {
return $this->fetched;
}
/**
* fetch fetch a Doctrine_Record from the file cache
* @param integer $id
*/
public function fetch($id) {
$name = $this->getTable()->getComponentName();
$file = $this->path.$id.".cache";
if( ! file_exists($file))
throw new InvalidKeyException();
$data = file_get_contents($file);
$record = unserialize($data);
if( ! ($record instanceof Doctrine_Record)) {
// broken file, delete silently
$this->delete($id);
throw new InvalidKeyException();
}
$this->fetched[] = $id;
return $record;
}
/**
* exists check the existence of a cache file
* @param integer $id primary key of the cached DAO
* @return boolean whether or not a cache file exists
*/
public function exists($id) {
$name = $this->getTable()->getComponentName();
$file = $this->path.$id.".cache";
return file_exists($file);
}
/**
* deleteAll
* @return void
*/
public function deleteAll() {
foreach(glob($this->path."*.cache") as $file) {
@unlink($file);
}
$fp = fopen($this->path.self::STATS_FILE,"w+");
fwrite($fp,"");
fclose($fp);
}
/**
* delete delete a cache file
* @param integer $id primary key of the cached DAO
*/
public function delete($id) {
$file = $this->path.$id.".cache";
if( ! file_exists($file))
return false;
@unlink($file);
return true;
}
/**
* deleteMultiple delete multiple cache files
* @param array $ids an array containing cache file ids
* @return integer the number of files deleted
*/
public function deleteMultiple(array $ids) {
$deleted = 0;
foreach($ids as $id) {
if($this->delete($id)) $deleted++;
}
return $deleted;
}
/**
* destructor
* the purpose of this destructor is to save all the fetched
* primary keys into the cache stats
*/
public function __destruct() {
if( ! empty($this->fetched)) {
$fp = fopen($this->path.self::STATS_FILE,"a");
fwrite($fp,":".implode(":",$this->fetched));
fclose($fp);
}
/**
*
* cache auto-cleaning algorithm
* $ttl is the number of page loads between each cache cleaning
* the default is 100 page loads
*
* this means that the average number of page loads between
* each cache clean is 100 page loads (= 100 constructed Doctrine_Managers)
*
*/
$ttl = $this->objTable->getAttribute(Doctrine::ATTR_CACHE_TTL);
$l1 = (mt_rand(1,$ttl) / $ttl);
$l2 = (1 - 1/$ttl);
if($l1 > $l2)
$this->clean();
}
}
?>
<?php
class Doctrine_Cache_Sqlite {
/**
* STATS_FILE constant
* the name of the statistics file
*/
const STATS_FILE = "stats.cache";
/**
* SELECT constant
* used as a base for SQL SELECT queries
*/
const SELECT = "SELECT object FROM %s WHERE id %s";
/**
* INSERT constant
* used as a base for SQL INSERT queries
*/
const INSERT = "REPLACE INTO %s (id, object) VALUES (?, ?)";
/**
* DELETE constant
* used as a base for SQL DELETE queries
*/
const DELETE = "DELETE FROM %s WHERE id %s";
/**
* @var Doctrine_Table $table
*/
private $table;
/**
* @var PDO $dbh
*/
private $dbh;
/**
* @var array $fetched an array of fetched primary keys
*/
private $fetched = array();
public function __construct(Doctrine_Table $table) {
$this->table = $table;
$dir = $this->table->getSession()->getAttribute(Doctrine::ATTR_CACHE_DIR);
if( ! is_dir($dir))
mkdir($dir, 0777);
$this->path = $dir.DIRECTORY_SEPARATOR;
$this->dbh = $this->table->getSession()->getCacheHandler();
try {
$this->dbh->query("CREATE TABLE ".$this->table->getTableName()." (id INTEGER UNIQUE, object TEXT)");
} catch(PDOException $e) {
}
/**
* create stats file
*/
if( ! file_exists($this->path.self::STATS_FILE))
touch($this->path.self::STATS_FILE);
}
/*
* stores a Doctrine_Record into cache
* @param Doctrine_Record $record record to be stored
* @return boolean whether or not storing was successful
*/
public function store(Doctrine_Record $record) {
if($record->getState() != Doctrine_Record::STATE_CLEAN)
return false;
$clone = clone $record;
$id = $clone->getID();
$stmt = $this->dbh->query(sprintf(self::INSERT,$this->table->getTableName()));
$stmt->execute(array($id, serialize($clone)));
return true;
}
/**
* fetches a Doctrine_Record from the cache
* @param mixed $id
* @return mixed false on failure, Doctrine_Record on success
*/
public function fetch($id) {
$stmt = $this->dbh->query(sprintf(self::SELECT,$this->table->getTableName(),"= ?"));
$stmt->execute(array($id));
$data = $stmt->fetch(PDO::FETCH_NUM);
if($data === false)
throw new InvalidKeyException();
$this->fetched[] = $id;
$record = unserialize($data[0]);
if(is_string($record)) {
$this->delete($id);
throw new InvalidKeyException();
}
return $record;
}
/**
* fetches multiple records from the cache
* @param array $keys
* @return mixed false on failure, an array of Doctrine_Record objects on success
*/
public function fetchMultiple(array $keys) {
$count = (count($keys)-1);
$keys = array_values($keys);
$sql = sprintf(self::SELECT,$this->table->getTableName(),"IN (".str_repeat("?, ",$count)."?)");
$stmt = $this->dbh->query($sql);
$stmt->execute($keys);
while($data = $stmt->fetch(PDO::FETCH_NUM)) {
$array[] = unserialize($data[0]);
}
$this->fetched = array_merge($this->fetched, $keys);
if( ! isset($array))
return false;
return $array;
}
/**
* deletes all records from cache
* @return void
*/
public function deleteAll() {
$stmt = $this->dbh->query("DELETE FROM ".$this->table->getTableName());
return $stmt->rowCount();
}
/**
* @param mixed $id
* @return void
*/
public function delete($id) {
$stmt = $this->dbh->query(sprintf(self::DELETE,$this->table->getTableName(),"= ?"));
$stmt->execute(array($id));
if($stmt->rowCount() > 0)
return true;
return false;
}
/**
* count
* @return integer
*/
public function count() {
$stmt = $this->dbh->query("SELECT COUNT(*) FROM ".$this->table->getTableName());
$data = $stmt->fetch(PDO::FETCH_NUM);
// table has two columns so we have to divide the count by two
return ($data[0] / 2);
}
/**
* @param array $keys
* @return integer
*/
public function deleteMultiple(array $keys) {
if(empty($keys))
return 0;
$keys = array_values($keys);
$count = (count($keys)-1);
$sql = sprintf(self::DELETE,$this->table->getTableName(),"IN (".str_repeat("?, ",$count)."?)");
$stmt = $this->dbh->query($sql);
$stmt->execute($keys);
return $stmt->rowCount();
}
/**
* getStats
* @return array an array of fetch statistics, keys as primary keys
* and values as fetch times
*/
public function getStats() {
$f = file_get_contents($this->path.self::STATS_FILE);
// every cache file starts with a ":"
$f = substr(trim($f),1);
$e = explode(":",$f);
return array_count_values($e);
}
/**
* clean
* @return void
*/
public function clean() {
$stats = $this->getStats();
asort($stats);
$size = $this->table->getAttribute(Doctrine::ATTR_CACHE_SIZE);
$count = count($stats);
if($count <= $size)
return 0;
$e = $count - $size;
$keys = array();
foreach($stats as $id => $count) {
if( ! $e--)
break;
$keys[] = $id;
}
return $this->deleteMultiple($keys);
}
/**
* saves statistics
* @return boolean
*/
public function saveStats() {
if( ! empty($this->fetched)) {
$fp = fopen($this->path.self::STATS_FILE,"a");
fwrite($fp,":".implode(":",$this->fetched));
fclose($fp);
$this->fetched = array();
return true;
}
return false;
}
/**
* autoClean
* $ttl is the number of page loads between each cache cleaning
* the default is 100 page loads
*
* this means that the average number of page loads between
* each cache clean is 100 page loads (= 100 constructed Doctrine_Managers)
* @return boolean
*/
public function autoClean() {
$ttl = $this->table->getAttribute(Doctrine::ATTR_CACHE_TTL);
$l1 = (mt_rand(1,$ttl) / $ttl);
$l2 = (1 - 1/$ttl);
if($l1 > $l2) {
$this->clean();
return true;
}
return false;
}
/**
* @param mixed $id
*/
public function addDelete($id) {
$this->delete[] = $id;
}
/**
* destructor
* the purpose of this destructor is to save all the fetched
* primary keys into the cache stats and to clean cache if necessary
*
*/
public function __destruct() {
$this->saveStats();
$this->autoClean();
}
}
?>
This diff is collapsed.
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Collection.class.php");
/**
* Doctrine_Collection_Batch a collection of records,
* with batch load strategy
*
*
* @author Konsta Vesterinen
* @package Doctrine ORM
* @url www.phpdoctrine.com
* @license LGPL
* @version 1.0 alpha
*/
class Doctrine_Collection_Batch extends Doctrine_Collection {
/**
* @var integer $batchSize batch size
*/
private $batchSize;
/**
* @var array $loaded an array containing the loaded batches, keys representing the batch indexes
*/
private $loaded = array();
public function __construct(Doctrine_Table $table) {
parent::__construct($table);
$this->batchSize = $this->getTable()->getAttribute(Doctrine::ATTR_BATCH_SIZE);
}
/**
* @param integer $batchSize batch size
* @return boolean
*/
public function setBatchSize($batchSize) {
$batchSize = (int) $batchSize;
if($batchSize <= 0)
return false;
$this->batchSize = $batchSize;
return true;
}
/**
* returns the batch size of this collection
*
* @return integer
*/
public function getBatchSize() {
return $this->batchSize;
}
/**
* load
* loads a specified element, by loading the batch the element is part of
*
* @param Doctrine_Record $record record to be loaded
* @return boolean whether or not the load operation was successful
*/
public function load(Doctrine_Record $record) {
if(empty($this->data))
return false;
$id = $record->getID();
$identifier = $this->table->getIdentifier();
foreach($this->data as $key => $v) {
if(is_object($v)) {
if($v->getID() == $id)
break;
} elseif(is_array($v[$identifier])) {
if($v[$identifier] == $id)
break;
}
}
$x = floor($key / $this->batchSize);
if( ! isset($this->loaded[$x])) {
$e = $x * $this->batchSize;
$e2 = ($x + 1)* $this->batchSize;
$a = array();
$proxies = array();
for($i = $e; $i < $e2 && $i < $this->count(); $i++):
if($this->data[$i] instanceof Doctrine_Record)
$id = $this->data[$i]->getID();
elseif(is_array($this->data[$i]))
$id = $this->data[$i][$identifier];
$a[$i] = $id;
endfor;
$c = count($a);
$pk = $this->table->getPrimaryKeys();
$query = $this->table->getQuery()." WHERE ";
$query .= ($c > 1)?$identifier." IN (":$pk[0]." = ";
$query .= substr(str_repeat("?, ",count($a)),0,-2);
$query .= ($c > 1)?") ORDER BY ".$pk[0]." ASC":"";
$stmt = $this->table->getSession()->execute($query,array_values($a));
foreach($a as $k => $id) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row === false)
break;
$this->table->setData($row);
if(is_object($this->data[$k])) {
$this->data[$k]->factoryRefresh($this->table);
} else {
$this->data[$k] = $this->table->getRecord();
}
}
$this->loaded[$x] = true;
return true;
} else {
return false;
}
}
/**
* get
* @param mixed $key the key of the record
* @return object Doctrine_Record record
*/
public function get($key) {
if(isset($this->data[$key])) {
switch(gettype($this->data[$key])):
case "array":
// Doctrine_Record didn't exist in cache
$this->table->setData($this->data[$key]);
$this->data[$key] = $this->table->getProxy();
$this->data[$key]->addCollection($this);
break;
endswitch;
} else {
$this->expand($key);
if( ! isset($this->data[$key]))
$this->data[$key] = $this->table->create();
}
if(isset($this->reference_field))
$this->data[$key]->rawSet($this->reference_field,$this->reference);
return $this->data[$key];
}
/**
* @return Doctrine_Iterator
*/
public function getIterator() {
return new Doctrine_Iterator_Expandable($this);
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Collection.class.php");
/**
* @author Konsta Vesterinen
* @package Doctrine ORM
* @url www.phpdoctrine.com
* @license LGPL
* @version 1.0 alpha
*/
class Doctrine_Collection_Immediate extends Doctrine_Collection {
/**
* @param Doctrine_DQL_Parser $graph
* @param integer $key
*/
public function __construct(Doctrine_Table $table) {
parent::__construct($table);
}
}
?>
<?php
require_once("Batch.class.php");
/**
* a collection of Doctrine_Record objects with lazy load strategy
* (batch load strategy with batch size 1)
*/
class Doctrine_Collection_Lazy extends Doctrine_Collection_Batch {
/**
* constructor
* @param Doctrine_DQL_Parser $graph
* @param string $key
*/
public function __construct(Doctrine_Table $table) {
parent::__construct($table);
parent::setBatchSize(1);
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Collection.class.php");
/**
* Offset Collection
*/
class Doctrine_Collection_Offset extends Doctrine_Collection {
/**
* @var integer $limit
*/
private $limit;
/**
* @param Doctrine_Table $table
*/
public function __construct(Doctrine_Table $table) {
parent::__construct($table);
$this->limit = $table->getAttribute(Doctrine::ATTR_COLL_LIMIT);
}
/**
* @return integer
*/
public function getLimit() {
return $this->limit;
}
/**
* @return Doctrine_Iterator_Offset
*/
public function getIterator() {
return new Doctrine_Iterator_Expandable($this);
}
}
?>
<?php
/**
* Doctrine_Configurable
* the base for Doctrine_Table, Doctrine_Manager and Doctrine_Session
*
*
* @package Doctrine ORM
* @url www.phpdoctrine.com
* @license LGPL
*/
abstract class Doctrine_Configurable {
/**
* @var array $attributes an array of containing all attributes
*/
private $attributes = array();
/**
* @var $parent the parents of this component
*/
private $parent;
/**
* sets a given attribute
*
* @throws Doctrine_Exception if the value is invalid
* @param integer $attribute
* @param mixed $value
* @return void
*/
final public function setAttribute($attribute,$value) {
switch($attribute):
case Doctrine::ATTR_BATCH_SIZE:
if($value < 0)
throw new Doctrine_Exception("Batch size should be greater than or equal to zero");
break;
case Doctrine::ATTR_CACHE_DIR:
if(substr(trim($value),0,6) == "%ROOT%") {
$dir = dirname(__FILE__);
$value = $dir.substr($value,6);
}
if(! is_dir($value) && ! file_exists($value))
mkdir($value,0777);
break;
case Doctrine::ATTR_CACHE_TTL:
if($value < 1)
throw new Doctrine_Exception("Cache TimeToLive should be greater than or equal to 1");
break;
case Doctrine::ATTR_CACHE_SIZE:
if($value < 1)
throw new Doctrine_Exception("Cache size should be greater than or equal to 1");
break;
case Doctrine::ATTR_CACHE_SLAM:
if($value < 0 || $value > 1)
throw new Doctrine_Exception("Cache slam defense should be a floating point number between 0 and 1");
break;
case Doctrine::ATTR_FETCHMODE:
if($value < 0)
throw new Doctrine_Exception("Unknown fetchmode. See Doctrine::FETCH_* constants.");
break;
case Doctrine::ATTR_LISTENER:
$this->setEventListener($value);
break;
case Doctrine::ATTR_PK_COLUMNS:
if( ! is_array($value))
throw new Doctrine_Exception("The value of Doctrine::ATTR_PK_COLUMNS attribute must be an array");
break;
case Doctrine::ATTR_PK_TYPE:
if($value != Doctrine::INCREMENT_KEY && $value != Doctrine::UNIQUE_KEY)
throw new Doctrine_Exception("The value of Doctrine::ATTR_PK_TYPE attribute must be either Doctrine::INCREMENT_KEY or Doctrine::UNIQUE_KEY");
break;
case Doctrine::ATTR_LOCKMODE:
if($this instanceof Doctrine_Session) {
if($this->getState() != Doctrine_Session::STATE_OPEN)
throw new Doctrine_Exception("Couldn't set lockmode. There are transactions open.");
} elseif($this instanceof Doctrine_Manager) {
foreach($this as $session) {
if($session->getState() != Doctrine_Session::STATE_OPEN)
throw new Doctrine_Exception("Couldn't set lockmode. There are transactions open.");
}
} else {
throw new Doctrine_Exception("Lockmode attribute can only be set at the global or session level.");
}
break;
case Doctrine::ATTR_CREATE_TABLES:
$value = (bool) $value;
break;
case Doctrine::ATTR_COLL_LIMIT:
if($value < 1) {
throw new Doctrine_Exception("Collection limit should be a value greater than or equal to 1.");
}
break;
case Doctrine::ATTR_COLL_KEY:
if( ! ($this instanceof Doctrine_Table))
throw new Doctrine_Exception("This attribute can only be set at table level.");
if( ! $this->hasColumn($value))
throw new Doctrine_Exception("Couldn't set collection key attribute. No such column '$value'");
break;
case Doctrine::ATTR_VLD:
break;
case Doctrine::ATTR_CACHE:
if($value != Doctrine::CACHE_SQLITE && $value != Doctrine::CACHE_NONE)
throw new Doctrine_Exception("Unknown cache container. See Doctrine::CACHE_* constants for availible containers.");
break;
default:
throw new Doctrine_Exception("Unknown attribute.");
endswitch;
$this->attributes[$attribute] = $value;
}
/**
* @param Doctrine_EventListener $listener
* @return void
*/
final public function setEventListener(Doctrine_EventListener $listener) {
$i = Doctrine::ATTR_LISTENER;
$this->attributes[$i] = $listener;
}
/**
* returns the value of an attribute
*
* @param integer $attribute
* @return mixed
*/
final public function getAttribute($attribute) {
$attribute = (int) $attribute;
if($attribute < 1 || $attribute > 16)
throw new InvalidKeyException();
if( ! isset($this->attributes[$attribute])) {
if(isset($this->parent))
return $this->parent->getAttribute($attribute);
return null;
}
return $this->attributes[$attribute];
}
/**
* getAttributes
* returns all attributes as an array
*
* @return array
*/
final public function getAttributes() {
return $this->attributes;
}
/**
* sets a parent for this configurable component
* the parent must be configurable component itself
*
* @param Doctrine_Configurable $component
* @return void
*/
final public function setParent(Doctrine_Configurable $component) {
$this->parent = $component;
}
/**
* getParent
* returns the parent of this component
*
* @return Doctrine_Configurable
*/
final public function getParent() {
return $this->parent;
}
}
?>
<?php
class Doctrine_DB extends PDO implements Countable, IteratorAggregate {
/**
* default DSN
*/
const DSN = "mysql://root:dc34@localhost/test";
/**
* executed queries
*/
private $queries = array();
/**
* execution times of the executed queries
*/
private $exectimes = array();
/**
* constructor
* @param string $dsn
* @param string $username
* @param string $password
*/
public function __construct($dsn,$username,$password) {
parent::__construct($dsn,$username,$password);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array("Doctrine_DBStatement",array($this)));
}
public static function getConn($dsn,$username = null, $password = null) {
static $instance;
if( ! isset($instance)) {
$instance = new Doctrine_DB($dsn,$username,$password);
}
return $instance;
}
/**
* @param string $dsn PEAR::DB like DSN
* format: schema://user:password@address/dbname
*/
public static function getConnection($dsn = null) {
static $instance = array();
$md5 = md5($dsn);
if( ! isset($instance[$md5])) {
if( ! isset($dsn)) {
$a = parse_url(self::DSN);
} else {
$a = parse_url($dsn);
}
$e = array();
$e[0] = $a["scheme"].":host=".$a["host"].";dbname=".substr($a["path"],1);
$e[1] = $a["user"];
$e[2] = $a["pass"];
$instance[$md5] = new Doctrine_DB($e[0],$e[1],$e[2]);
}
return $instance[$md5];
}
/**
* @param string $query query to be executed
*/
public function query($query) {
try {
$this->queries[] = $query;
$time = microtime();
$stmt = parent::query($query);
$this->exectimes[] = (microtime() - $time);
return $stmt;
} catch(PDOException $e) {
throw $e;
}
}
/**
* @param string $query query to be prepared
*/
public function prepare($query) {
$this->queries[] = $query;
return parent::prepare($query);
}
/**
* @param string $time exectime of the last executed query
* @return void
*/
public function addExecTime($time) {
$this->exectimes[] = $time;
}
public function getExecTimes() {
return $this->exectimes;
}
/**
* @return array an array of executed queries
*/
public function getQueries() {
return $this->queries;
}
/**
* @return ArrayIterator
*/
public function getIterator() {
return new ArrayIterator($this->queries);
}
/**
* returns the number of executed queries
* @return integer
*/
public function count() {
return count($this->queries);
}
}
class Doctrine_DBStatement extends PDOStatement {
/**
* @param Doctrine_DB $dbh Doctrine Database Handler
*/
private $dbh;
/**
* @param Doctrine_DB $dbh
*/
private function __construct(Doctrine_DB $dbh) {
$this->dbh = $dbh;
}
/**
* @param array $params
*/
public function execute(array $params = null) {
$time = microtime();
$result = parent::execute($params);
$exectime = (microtime() - $time);
$this->dbh->addExecTime($exectime);
return $result;
}
}
?>
<?php
class Doctrine_DataDict {
private $dbh;
public function __construct(PDO $dbh) {
$manager = Doctrine_Manager::getInstance();
require_once($manager->getRoot()."/adodb-hack/adodb.inc.php");
$this->dbh = $dbh;
$this->dict = NewDataDictionary($dbh);
}
public function metaColumns(Doctrine_Table $table) {
return $this->dict->metaColumns($table->getTableName());
}
public function createTable($tablename, $columns) {
foreach($columns as $name => $args) {
$r[] = $name." ".$this->getADOType($args[0],$args[1])." ".str_replace("|"," ",$args[2]);
}
$r = implode(", ",$r);
$a = $this->dict->createTableSQL($tablename,$r);
$return = true;
foreach($a as $sql) {
try {
$this->dbh->query($sql);
} catch(PDOException $e) {
if($this->dbh->getAttribute(PDO::ATTR_DRIVER_NAME) == "sqlite")
throw $e;
$return = false;
}
}
return $return;
}
/**
* converts doctrine type to adodb type
*
* @param string $type column type
* @param integer $length column length
*/
public function getADOType($type,$length) {
switch($type):
case "string":
case "s":
if($length < 255)
return "C($length)";
elseif($length < 4000)
return "X";
else
return "X2";
break;
case "mbstring":
if($length < 255)
return "C2($length)";
return "X2";
case "clob":
return "XL";
break;
case "d":
case "date":
return "D";
break;
case "float":
case "f":
case "double":
return "F";
break;
case "timestamp":
case "t":
return "T";
break;
case "boolean":
case "bool":
return "L";
break;
case "integer":
case "int":
case "i":
if(empty($length))
return "I8";
elseif($length < 4)
return "I1";
elseif($length < 6)
return "I2";
elseif($length < 10)
return "I4";
elseif($length <= 20)
return "I8";
else
throw new Doctrine_Exception("Too long integer (max length is 20).");
break;
endswitch;
}
}
?>
<?php
require_once("EventListener.class.php");
class Doctrine_DebugMessage {
private $code;
private $object;
public function __construct($object, $code) {
$this->object = $object;
$this->code = $code;
}
final public function getCode() {
return $this->code;
}
final public function getObject() {
return $this->object;
}
}
class Doctrine_Debugger extends Doctrine_EventListener {
const EVENT_LOAD = 1;
const EVENT_PRELOAD = 2;
const EVENT_SLEEP = 3;
const EVENT_WAKEUP = 4;
const EVENT_UPDATE = 5;
const EVENT_PREUPDATE = 6;
const EVENT_CREATE = 7;
const EVENT_PRECREATE = 8;
const EVENT_SAVE = 9;
const EVENT_PRESAVE = 10;
const EVENT_INSERT = 11;
const EVENT_PREINSERT = 12;
const EVENT_DELETE = 13;
const EVENT_PREDELETE = 14;
const EVENT_EVICT = 15;
const EVENT_PREEVICT = 16;
const EVENT_CLOSE = 17;
const EVENT_PRECLOSE = 18;
const EVENT_OPEN = 19;
const EVENT_COMMIT = 20;
const EVENT_PRECOMMIT = 21;
const EVENT_ROLLBACK = 22;
const EVENT_PREROLLBACK = 23;
const EVENT_BEGIN = 24;
const EVENT_PREBEGIN = 25;
const EVENT_COLLDELETE = 26;
const EVENT_PRECOLLDELETE = 27;
private $debug;
public function getMessages() {
return $this->debug;
}
public function onLoad(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_LOAD);
}
public function onPreLoad(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PRELOAD);
}
public function onSleep(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_SLEEP);
}
public function onWakeUp(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_WAKEUP);
}
public function onUpdate(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_UPDATE);
}
public function onPreUpdate(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PREUPDATE);
}
public function onCreate(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_CREATE);
}
public function onPreCreate(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PRECREATE);
}
public function onSave(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_SAVE);
}
public function onPreSave(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PRESAVE);
}
public function onInsert(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_INSERT);
}
public function onPreInsert(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PREINSERT);
}
public function onDelete(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_DELETE);
}
public function onPreDelete(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PREDELETE);
}
public function onEvict(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_EVICT);
}
public function onPreEvict(Doctrine_Record $record) {
$this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PREEVICT);
}
public function onClose(Doctrine_Session $session) {
$this->debug[] = new Doctrine_DebugMessage($session,self::EVENT_CLOSE);
}
public function onPreClose(Doctrine_Session $session) {
$this->debug[] = new Doctrine_DebugMessage($session,self::EVENT_PRECLOSE);
}
public function onOpen(Doctrine_Session $session) {
$this->debug[] = new Doctrine_DebugMessage($session,self::EVENT_OPEN);
}
public function onTransactionCommit(Doctrine_Session $session) {
$this->debug[] = new Doctrine_DebugMessage($session,self::EVENT_COMMIT);
}
public function onPreTransactionCommit(Doctrine_Session $session) {
$this->debug[] = new Doctrine_DebugMessage($session,self::EVENT_PRECOMMIT);
}
public function onTransactionRollback(Doctrine_Session $session) {
$this->debug[] = new Doctrine_DebugMessage($session,self::EVENT_ROLLBACK);
}
public function onPreTransactionRollback(Doctrine_Session $session) {
$this->debug[] = new Doctrine_DebugMessage($session,self::EVENT_PREROLLBACK);
}
public function onTransactionBegin(Doctrine_Session $session) {
$this->debug[] = new Doctrine_DebugMessage($session,self::EVENT_BEGIN);
}
public function onPreTransactionBegin(Doctrine_Session $session) {
$this->debug[] = new Doctrine_DebugMessage($session,self::EVENT_PREBEGIN);
}
public function onCollectionDelete(Doctrine_Collection $collection) {
$this->debug[] = new Doctrine_DebugMessage($collection,self::EVENT_COLLDELETE);
}
public function onPreCollectionDelete(Doctrine_Collection $collection) {
$this->debug[] = new Doctrine_DebugMessage($collection,self::EVENT_PRECOLLDELETE);
}
}
?>
<?php
require_once("Exception.class.php");
/**
* Doctrine
* the base class of Doctrine framework
*
* @package Doctrine ORM
* @url www.phpdoctrine.com
* @license LGPL
*/
final class Doctrine {
/**
* ERROR MODE CONSTANTS
*/
/**
* NO PRIMARY KEY COLUMN ERROR
* no primary key column found error code
*/
const ERR_NO_PK = 0;
/**
* PRIMARY KEY MISMATCH ERROR
* this error code is used when user uses factory refresh for a
* given Doctrine_Record and the old primary key doesn't match the new one
*/
const ERR_REFRESH = 1;
/**
* FIND ERROR
* this code used when for example Doctrine_Table::find() is called and
* a Data Access Object is not found
*/
const ERR_FIND = 2;
/**
* TABLE NOT FOUND ERROR
* this error code is used when user tries to initialize
* a table and there is no database table for this factory
*/
const ERR_NOSUCH_TABLE = 3;
/**
* NAMING ERROR
* this code is used when user defined Doctrine_Table is badly named
*/
const ERR_NAMING = 5;
/**
* TABLE INSTANCE ERROR
* this code is used when user tries to initialize
* a table that is already initialized
*/
const ERR_TABLE_INSTANCE = 6;
/**
* NO OPEN SESSIONS ERROR
* error code which is used when user tries to get
* current session are there are no sessions open
*/
const ERR_NO_SESSIONS = 7;
/**
* MAPPING ERROR
* if there is something wrong with mapping logic
* this error code is used
*/
const ERR_MAPPING = 8;
/**
* ATTRIBUTE CONSTANTS
*/
/**
* event listener attribute
*/
const ATTR_LISTENER = 1;
/**
* fetchmode attribute
*/
const ATTR_FETCHMODE = 2;
/**
* cache directory attribute
*/
const ATTR_CACHE_DIR = 3;
/**
* cache time to live attribute
*/
const ATTR_CACHE_TTL = 4;
/**
* cache size attribute
*/
const ATTR_CACHE_SIZE = 5;
/**
* cache slam defense probability
*/
const ATTR_CACHE_SLAM = 6;
/**
* cache container attribute
*/
const ATTR_CACHE = 7;
/**
* batch size attribute
*/
const ATTR_BATCH_SIZE = 8;
/**
* primary key columns attribute
*/
const ATTR_PK_COLUMNS = 9;
/**
* primary key type attribute
*/
const ATTR_PK_TYPE = 10;
/**
* locking attribute
*/
const ATTR_LOCKMODE = 11;
/**
* validatate attribute
*/
const ATTR_VLD = 12;
/**
* name prefix attribute
*/
const ATTR_NAME_PREFIX = 13;
/**
* create tables attribute
*/
const ATTR_CREATE_TABLES = 14;
/**
* collection key attribute
*/
const ATTR_COLL_KEY = 15;
/**
* collection limit attribute
*/
const ATTR_COLL_LIMIT = 16;
/**
* CACHE CONSTANTS
*/
/**
* sqlite cache constant
*/
const CACHE_SQLITE = 0;
/**
* constant for disabling the caching
*/
const CACHE_NONE = 1;
/**
* FETCHMODE CONSTANTS
*/
/**
* IMMEDIATE FETCHING
* mode for immediate fetching
*/
const FETCH_IMMEDIATE = 0;
/**
* BATCH FETCHING
* mode for batch fetching
*/
const FETCH_BATCH = 1;
/**
* LAZY FETCHING
* mode for lazy fetching
*/
const FETCH_LAZY = 2;
/**
* LAZY FETCHING
* mode for offset fetching
*/
const FETCH_OFFSET = 3;
/**
* LAZY OFFSET FETCHING
* mode for lazy offset fetching
*/
const FETCH_LAZY_OFFSET = 4;
/**
* LOCKMODE CONSTANTS
*/
/**
* mode for optimistic locking
*/
const LOCK_OPTIMISTIC = 0;
/**
* mode for pessimistic locking
*/
const LOCK_PESSIMISTIC = 1;
/**
* PRIMARY KEY TYPE CONSTANTS
*/
/**
* auto-incremented/(sequence updated) primary key
*/
const INCREMENT_KEY = 0;
/**
* unique key
*/
const UNIQUE_KEY = 1;
/**
* @var string $path doctrine root directory
*/
private static $path;
/**
* returns the doctrine root
*
* @return string
*/
public static function getPath() {
if(! self::$path)
self::$path = dirname(__FILE__);
return self::$path;
}
/**
* loads all runtime classes
*
* @return void
*/
public static function loadAll() {
if(! self::$path)
self::$path = dirname(__FILE__);
$dir = dir(self::$path);
$a = array();
while (false !== ($entry = $dir->read())) {
switch($entry):
case ".":
case "..":
break;
case "Cache":
case "Record":
case "Collection":
case "Table":
case "Validator":
case "Exception":
case "Session":
case "DQL":
case "Sensei":
case "Iterator":
$a[] = self::$path.DIRECTORY_SEPARATOR.$entry;
break;
default:
if(is_file(self::$path.DIRECTORY_SEPARATOR.$entry) && substr($entry,-4) == ".php") {
require_once($entry);
}
endswitch;
}
foreach($a as $dirname) {
$dir = dir($dirname);
$path = $dirname.DIRECTORY_SEPARATOR;
while (false !== ($entry = $dir->read())) {
if(is_file($path.$entry) && substr($entry,-4) == ".php") {
require_once($path.$entry);
}
}
}
}
/**
* simple autoload function
* returns true if the class was loaded, otherwise false
*
* @param string $classname
* @return boolean
*/
public static function autoload($classname) {
if(! self::$path)
self::$path = dirname(__FILE__);
$e = explode("_",$classname);
if($e[0] != "Doctrine")
return false;
if(end($e) != "Exception") {
if(count($e) > 2) {
array_shift($e);
$dir = array_shift($e);
$class = self::$path.DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.implode('',$e).".class.php";
} elseif(count($e) > 1) {
$class = self::$path.DIRECTORY_SEPARATOR.$e[1].".class.php";
} else
return false;
} else {
$class = self::$path.DIRECTORY_SEPARATOR."Exception".DIRECTORY_SEPARATOR.$e[1].".class.php";
}
if( ! file_exists($class)) {
return false;
}
require_once($class);
return true;
}
}
?>
<?php
/**
* interface for event listening, forces all classes that extend
* Doctrine_EventListener to have the same method arguments as their parent
*/
interface iDoctrine_EventListener {
public function onLoad(Doctrine_Record $record);
public function onPreLoad(Doctrine_Record $record);
public function onUpdate(Doctrine_Record $record);
public function onPreUpdate(Doctrine_Record $record);
public function onCreate(Doctrine_Record $record);
public function onPreCreate(Doctrine_Record $record);
public function onSave(Doctrine_Record $record);
public function onPreSave(Doctrine_Record $record);
public function onInsert(Doctrine_Record $record);
public function onPreInsert(Doctrine_Record $record);
public function onDelete(Doctrine_Record $record);
public function onPreDelete(Doctrine_Record $record);
public function onEvict(Doctrine_Record $record);
public function onPreEvict(Doctrine_Record $record);
public function onSaveCascade(Doctrine_Record $record);
public function onPreSaveCascade(Doctrine_Record $record);
public function onDeleteCascade(Doctrine_Record $record);
public function onPreDeleteCascade(Doctrine_Record $record);
public function onSleep(Doctrine_Record $record);
public function onWakeUp(Doctrine_Record $record);
public function onClose(Doctrine_Session $session);
public function onPreClose(Doctrine_Session $session);
public function onOpen(Doctrine_Session $session);
public function onTransactionCommit(Doctrine_Session $session);
public function onPreTransactionCommit(Doctrine_Session $session);
public function onTransactionRollback(Doctrine_Session $session);
public function onPreTransactionRollback(Doctrine_Session $session);
public function onTransactionBegin(Doctrine_Session $session);
public function onPreTransactionBegin(Doctrine_Session $session);
public function onCollectionDelete(Doctrine_Collection $collection);
public function onPreCollectionDelete(Doctrine_Collection $collection);
}
/**
* Doctrine_EventListener all event listeners extend this base class
* the empty methods allow child classes to only implement the methods they need to implement
*
*
* @author Konsta Vesterinen
* @package Doctrine ORM
* @url www.phpdoctrine.com
* @license LGPL
* @version 1.0 alpha
*
*/
abstract class Doctrine_EventListener implements iDoctrine_EventListener {
public function onLoad(Doctrine_Record $record) { }
public function onPreLoad(Doctrine_Record $record) { }
public function onSleep(Doctrine_Record $record) { }
public function onWakeUp(Doctrine_Record $record) { }
public function onUpdate(Doctrine_Record $record) { }
public function onPreUpdate(Doctrine_Record $record) { }
public function onCreate(Doctrine_Record $record) { }
public function onPreCreate(Doctrine_Record $record) { }
public function onSave(Doctrine_Record $record) { }
public function onPreSave(Doctrine_Record $record) { }
public function onInsert(Doctrine_Record $record) { }
public function onPreInsert(Doctrine_Record $record) { }
public function onDelete(Doctrine_Record $record) { }
public function onPreDelete(Doctrine_Record $record) { }
public function onEvict(Doctrine_Record $record) { }
public function onPreEvict(Doctrine_Record $record) { }
public function onSaveCascade(Doctrine_Record $record) { }
public function onPreSaveCascade(Doctrine_Record $record) { }
public function onDeleteCascade(Doctrine_Record $record) { }
public function onPreDeleteCascade(Doctrine_Record $record) { }
public function onClose(Doctrine_Session $session) { }
public function onPreClose(Doctrine_Session $session) { }
public function onOpen(Doctrine_Session $session) { }
public function onTransactionCommit(Doctrine_Session $session) { }
public function onPreTransactionCommit(Doctrine_Session $session) { }
public function onTransactionRollback(Doctrine_Session $session) { }
public function onPreTransactionRollback(Doctrine_Session $session) { }
public function onTransactionBegin(Doctrine_Session $session) { }
public function onPreTransactionBegin(Doctrine_Session $session) { }
public function onCollectionDelete(Doctrine_Collection $collection) { }
public function onPreCollectionDelete(Doctrine_Collection $collection) { }
}
/**
* an emtpy listener all components use this by default
*/
class EmptyEventListener extends Doctrine_EventListener { }
?>
<?php
class InvalidKeyException extends Exception { }
class InvalidTypeException extends Exception { }
class Doctrine_Exception extends Exception { }
class DQLException extends Doctrine_Exception { }
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Exception.class.php");
/**
* thrown when user tries to find a Doctrine_Record for given primary key and that object is not found
*/
class Doctrine_Find_Exception extends Doctrine_Exception {
public function __construct() {
parent::__construct("Couldn't find Data Access Object.",Doctrine::ERR_FIND);
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Exception.class.php");
/**
* thrown when user tries to get a foreign key object but the mapping is not done right
*/
class Doctrine_Mapping_Exception extends Doctrine_Exception {
public function __construct($message = "An error occured in the mapping logic.") {
parent::__construct($message,Doctrine::ERR_MAPPING);
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Exception.class.php");
/**
* thrown when user defined Doctrine_Table is badly named
*/
class Doctrine_Naming_Exception extends Doctrine_Exception {
public function __construct() {
parent::__construct("Badly named Doctrine_Table. Each Doctrine_Table
must be in format [Name]Table.", Doctrine::ERR_NAMING);
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Exception.class.php");
/**
* thrown when Doctrine_Record is loaded and there is no primary key field
*/
class Doctrine_PrimaryKey_Exception extends Doctrine_Exception {
public function __construct() {
parent::__construct("No primary key column found. Each data set must have primary key column.", Doctrine::ERR_NO_PK);
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Exception.class.php");
/**
* thrown when Doctrine_Record is refreshed and the refreshed primary key doens't match the old one
*/
class Doctrine_Refresh_Exception extends Doctrine_Exception {
public function __construct() {
parent::__construct("The refreshed primary key doesn't match the
one in the record memory.", Doctrine::ERR_REFRESH);
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Exception.class.php");
/**
* thrown when user tries to get the current
* session and there are no open sessions
*/
class Doctrine_Session_Exception extends Doctrine_Exception {
public function __construct() {
parent::__construct("There are no opened sessions. Use
Doctrine_Manager::getInstance()->openSession() to open a new session.",Doctrine::ERR_NO_SESSIONS);
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Exception.class.php");
/**
* thrown when user tries to initialize a new instance of Doctrine_Table,
* while there already exists an instance of that table
*/
class Doctrine_Table_Exception extends Doctrine_Exception {
public function __construct() {
parent::__construct("Couldn't initialize table. One instance of this
tabke already exists. Always use Doctrine_Session::getTable(\$name)
to get on instance of a Doctrine_Table.",Doctrine::ERR_TABLE_INSTANCE);
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Exception.class.php");
class Doctrine_Validator_Exception extends Doctrine_Exception {
private $validator;
public function __construct(Doctrine_Validator $validator) {
$this->validator = $validator;
}
public function getErrorStack() {
return $this->validator->getErrorStack();
}
}
?>
<?php
require_once("Relation.class.php");
/**
* Foreign Key
*/
class Doctrine_ForeignKey extends Doctrine_Relation { }
?>
<?php
class Doctrine_Identifier {
/**
* constant for unique identifier
*/
const UNIQUE = 0;
/**
* constant for auto_increment identifier
*/
const AUTO_INCREMENT = 1;
/**
* constant for sequence identifier
*/
const SEQUENCE = 2;
/**
* constant for normal identifier
*/
const NORMAL = 3;
/**
* constant for composite identifier
*/
const COMPOSITE = 4;
}
?>
<?php
class Doctrine_IndexGenerator {
/**
* @var string $name
*/
private $name;
/**
* @param string $name
*/
public function __construct($name) {
$this->name = $name;
}
/**
* @param Doctrine_Record $record
* @return mixed
*/
public function getIndex(Doctrine_Record $record) {
$value = $record->get($this->name);
if($value === null)
throw new Doctrine_Exception("Couldn't create collection index. Record field '".$this->name."' was null.");
return $value;
}
}
?>
<?php
/**
* Doctrine_Iterator
* iterates through Doctrine_Collection
*
* @package Doctrine ORM
* @url www.phpdoctrine.com
* @license LGPL
*/
abstract class Doctrine_Iterator implements Iterator {
/**
* @var Doctrine_Collection $collection
*/
protected $collection;
/**
* @var array $keys
*/
protected $keys;
/**
* @var mixed $key
*/
protected $key;
/**
* @var integer $index
*/
protected $index;
/**
* @var integer $count
*/
protected $count;
/**
* constructor
* @var Doctrine_Collection $collection
*/
public function __construct(Doctrine_Collection $collection) {
$this->collection = $collection;
$this->keys = $this->collection->getKeys();
$this->count = $this->collection->count();
}
/**
* rewinds the iterator
*
* @return void
*/
public function rewind() {
$this->index = 0;
$i = $this->index;
if(isset($this->keys[$i]))
$this->key = $this->keys[$i];
}
/**
* returns the current key
*
* @return integer
*/
public function key() {
return $this->key;
}
/**
* returns the current record
*
* @return Doctrine_Record
*/
public function current() {
return $this->collection->get($this->key);
}
/**
* advances the internal pointer
*
* @return void
*/
public function next() {
$this->index++;
$i = $this->index;
if(isset($this->keys[$i]))
$this->key = $this->keys[$i];
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Iterator.class.php");
class Doctrine_Iterator_Expandable extends Doctrine_Iterator {
public function valid() {
if($this->index < $this->count)
return true;
elseif($this->index == $this->count) {
$coll = $this->collection->expand($this->index);
if($coll instanceof Doctrine_Collection) {
$count = count($coll);
if($count > 0) {
$this->keys = array_merge($this->keys, $coll->getKeys());
$this->count += $count;
return true;
}
}
return false;
}
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Iterator.class.php");
class Doctrine_Iterator_Normal extends Doctrine_Iterator {
/**
* @return boolean whether or not the iteration will continue
*/
public function valid() {
return ($this->index < $this->count);
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Iterator.class.php");
class Doctrine_Iterator_Offset extends Doctrine_Iterator {
public function valid() { }
}
?>
<?php
class Doctrine_Lib {
/**
* @param integer $state the state of record
* @see Doctrine_Record::STATE_* constants
* @return string string representation of given state
*/
public static function getRecordStateAsString($state) {
switch($state):
case Doctrine_Record::STATE_PROXY:
return "proxy";
break;
case Doctrine_Record::STATE_CLEAN:
return "persistent clean";
break;
case Doctrine_Record::STATE_DIRTY:
return "persistent dirty";
break;
case Doctrine_Record::STATE_TDIRTY:
return "transient dirty";
break;
case Doctrine_Record::STATE_TCLEAN:
return "transient clean";
break;
endswitch;
}
/**
* returns a string representation of Doctrine_Record object
* @param Doctrine_Record $record
* @return string
*/
public function getRecordAsString(Doctrine_Record $record) {
$r[] = "<pre>";
$r[] = "Component : ".$record->getTable()->getComponentName();
$r[] = "ID : ".$record->getID();
$r[] = "References : ".count($record->getReferences());
$r[] = "State : ".Doctrine_Lib::getRecordStateAsString($record->getState());
$r[] = "OID : ".$record->getOID();
$r[] = "</pre>";
return implode("\n",$r)."<br />";
}
/**
* getStateAsString
* returns a given session state as string
* @param integer $state session state
*/
public static function getSessionStateAsString($state) {
switch($state):
case Doctrine_Session::STATE_OPEN:
return "open";
break;
case Doctrine_Session::STATE_CLOSED:
return "closed";
break;
case Doctrine_Session::STATE_BUSY:
return "busy";
break;
case Doctrine_Session::STATE_ACTIVE:
return "active";
break;
endswitch;
}
/**
* returns a string representation of Doctrine_Session object
* @param Doctrine_Session $session
* @return string
*/
public function getSessionAsString(Doctrine_Session $session) {
$r[] = "<pre>";
$r[] = "Doctrine_Session object";
$r[] = "State : ".Doctrine_Lib::getSessionStateAsString($session->getState());
$r[] = "Open Transactions : ".$session->getTransactionLevel();
$r[] = "Open Factories : ".$session->count();
$sum = 0;
$rsum = 0;
$csum = 0;
foreach($session->getTables() as $objTable) {
if($objTable->getCache() instanceof Doctrine_Cache_File) {
$sum += array_sum($objTable->getCache()->getStats());
$rsum += $objTable->getRepository()->count();
$csum += $objTable->getCache()->count();
}
}
$r[] = "Cache Hits : ".$sum." hits ";
$r[] = "Cache : ".$csum." objects ";
$r[] = "Repositories : ".$rsum." objects ";
$queries = false;
if($session->getDBH() instanceof Doctrine_DB) {
$handler = "Doctrine Database Handler";
$queries = count($session->getDBH()->getQueries());
$sum = array_sum($session->getDBH()->getExecTimes());
} elseif($session->getDBH() instanceof PDO) {
$handler = "PHP Native PDO Driver";
} else
$handler = "Unknown Database Handler";
$r[] = "DB Handler : ".$handler;
if($queries) {
$r[] = "Executed Queries : ".$queries;
$r[] = "Sum of Exec Times : ".$sum;
}
$r[] = "</pre>";
return implode("\n",$r)."<br>";
}
/**
* returns a string representation of Doctrine_Table object
* @param Doctrine_Table $table
* @return string
*/
public function getTableAsString(Doctrine_Table $table) {
$r[] = "<pre>";
$r[] = "Component : ".$this->getComponentName();
$r[] = "Table : ".$this->getTableName();
$r[] = "Repository : ".$this->getRepository()->count()." objects";
if($table->getCache() instanceof Doctrine_Cache_File) {
$r[] = "Cache : ".$this->getCache()->count()." objects";
$r[] = "Cache hits : ".array_sum($this->getCache()->getStats())." hits";
}
$r[] = "</pre>";
return implode("\n",$r)."<br>";
}
/**
* returns a string representation of Doctrine_Collection object
* @param Doctrine_Collection $collection
* @return string
*/
public function getCollectionAsString(Doctrine_Collection $collection) {
$r[] = "<pre>";
$r[] = get_class($collection);
foreach($collection as $key => $record) {
$r[] = "Key : ".$key." ID : ".$record->getID();
}
$r[] = "</pre>";
return implode("\n",$r);
}
}
?>
<?php
require_once("Relation.class.php");
/**
* Local Key
*/
class Doctrine_LocalKey extends Doctrine_Relation { }
?>
<?php
require_once("Configurable.class.php");
require_once("EventListener.class.php");
/**
* @package Doctrine ORM
* @url www.phpdoctrine.com
* @license LGPL
*
* Doctrine_Manager is the base component of all doctrine based projects.
* It opens and keeps track of all sessions (database connections).
*/
class Doctrine_Manager extends Doctrine_Configurable implements Countable, IteratorAggregate {
/**
* @var array $session an array containing all the opened sessions
*/
private $sessions = array();
/**
* @var integer $index the incremented index
*/
private $index = 0;
/**
* @var integer $currIndex the current session index
*/
private $currIndex = 0;
/**
* @var string $root root directory
*/
private $root;
/**
* @var Doctrine_Null $null Doctrine_Null object, used for extremely fast null value checking
*/
private $null;
/**
* constructor
*/
private function __construct() {
$this->root = dirname(__FILE__);
$this->null = new Doctrine_Null;
Doctrine_Record::initNullObject($this->null);
Doctrine_Collection::initNullObject($this->null);
}
/**
* @return Doctrine_Null
*/
final public function getNullObject() {
return $this->null;
}
/**
* setDefaultAttributes
* sets default attributes
*
* @return boolean
*/
final public function setDefaultAttributes() {
static $init = false;
if( ! $init) {
$init = true;
$attributes = array(
Doctrine::ATTR_CACHE_DIR => "%ROOT%".DIRECTORY_SEPARATOR."cachedir",
Doctrine::ATTR_FETCHMODE => Doctrine::FETCH_LAZY,
Doctrine::ATTR_CACHE_TTL => 100,
Doctrine::ATTR_CACHE_SIZE => 100,
Doctrine::ATTR_CACHE => Doctrine::CACHE_NONE,
Doctrine::ATTR_BATCH_SIZE => 5,
Doctrine::ATTR_COLL_LIMIT => 5,
Doctrine::ATTR_LISTENER => new EmptyEventListener(),
Doctrine::ATTR_PK_COLUMNS => array("id"),
Doctrine::ATTR_PK_TYPE => Doctrine::INCREMENT_KEY,
Doctrine::ATTR_LOCKMODE => 1,
Doctrine::ATTR_VLD => false,
Doctrine::ATTR_CREATE_TABLES => true
);
foreach($attributes as $attribute => $value) {
$old = $this->getAttribute($attribute);
if($old === null)
$this->setAttribute($attribute,$value);
}
return true;
}
return false;
}
/**
* returns the root directory of Doctrine
*
* @return string
*/
final public function getRoot() {
return $this->root;
}
/**
* getInstance
* returns an instance of this class
* (this class uses the singleton pattern)
*
* @return Doctrine_Manager
*/
final public static function getInstance() {
static $instance;
if( ! isset($instance))
$instance = new self();
return $instance;
}
/**
* openSession
* opens a new session and saves it to Doctrine_Manager->sessions
*
* @param PDO $pdo PDO database driver
* @param string $name name of the session, if empty numeric key is used
* @return Doctrine_Session
*/
final public function openSession(PDO $pdo, $name = null) {
// initialize the default attributes
$this->setDefaultAttributes();
if($name !== null) {
$name = (string) $name;
if(isset($this->sessions[$name]))
throw new InvalidKeyException();
} else {
$name = $this->index;
$this->index++;
}
switch($pdo->getAttribute(PDO::ATTR_DRIVER_NAME)):
case "mysql":
$this->sessions[$name] = new Doctrine_Session_Mysql($this,$pdo);
break;
case "sqlite":
$this->sessions[$name] = new Doctrine_Session_Sqlite($this,$pdo);
break;
case "pgsql":
$this->sessions[$name] = new Doctrine_Session_Pgsql($this,$pdo);
break;
case "oci":
$this->sessions[$name] = new Doctrine_Session_Oracle($this,$pdo);
break;
case "mssql":
$this->sessions[$name] = new Doctrine_Session_Mssql($this,$pdo);
break;
case "firebird":
$this->sessions[$name] = new Doctrine_Session_Firebird($this,$pdo);
break;
case "informix":
$this->sessions[$name] = new Doctrine_Session_Informix($this,$pdo);
break;
endswitch;
$this->currIndex = $name;
return $this->sessions[$name];
}
/**
* getSession
* @param integer $index
* @return object Doctrine_Session
* @throws InvalidKeyException
*/
final public function getSession($index) {
if( ! isset($this->sessions[$index]))
throw new InvalidKeyException();
$this->currIndex = $index;
return $this->sessions[$index];
}
/**
* closes the session
*
* @param Doctrine_Session $session
* @return void
*/
final public function closeSession(Doctrine_Session $session) {
$session->close();
unset($session);
}
/**
* getSessions
* returns all opened sessions
*
* @return array
*/
final public function getSessions() {
return $this->sessions;
}
/**
* setCurrentSession
* sets the current session to $key
*
* @param mixed $key the session key
* @throws InvalidKeyException
* @return void
*/
final public function setCurrentSession($key) {
$key = (string) $key;
if( ! isset($this->sessions[$key]))
throw new InvalidKeyException();
$this->currIndex = $key;
}
/**
* count
* returns the number of opened sessions
*
* @return integer
*/
public function count() {
return count($this->sessions);
}
/**
* getIterator
* returns an ArrayIterator that iterates through all sessions
*
* @return ArrayIterator
*/
public function getIterator() {
return new ArrayIterator($this->sessions);
}
/**
* getCurrentSession
* returns the current session
*
* @throws Doctrine_Session_Exception if there are no open sessions
* @return Doctrine_Session
*/
final public function getCurrentSession() {
$i = $this->currIndex;
if( ! isset($this->sessions[$i]))
throw new Doctrine_Session_Exception();
return $this->sessions[$i];
}
/**
* __toString
* returns a string representation of this object
*
* @return string
*/
public function __toString() {
$r[] = "<pre>";
$r[] = "Doctrine_Manager";
$r[] = "Sessions : ".count($this->sessions);
$r[] = "</pre>";
return implode("\n",$r);
}
}
?>
<?php
/**
* Doctrine_Null
*/
class Doctrine_Null { }
?>
This diff is collapsed.
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Exception.class.php");
class Doctrine_Query_Exception extends Doctrine_Exception { }
?>
This diff is collapsed.
<?php
/**
* Doctrine_Relation
*
* @package Doctrine ORM
* @url www.phpdoctrine.com
* @license LGPL
*/
class Doctrine_Relation {
/**
* RELATION CONSTANTS
*/
/**
* constant for ONE_TO_ONE and MANY_TO_ONE aggregate relationships
*/
const ONE_AGGREGATE = 0;
/**
* constant for ONE_TO_ONE and MANY_TO_ONE composite relationships
*/
const ONE_COMPOSITE = 1;
/**
* constant for MANY_TO_MANY and ONE_TO_MANY aggregate relationships
*/
const MANY_AGGREGATE = 2;
/**
* constant for MANY_TO_MANY and ONE_TO_MANY composite relationships
*/
const MANY_COMPOSITE = 3;
/**
* @var Doctrine_Table $table foreign factory
*/
private $table;
/**
* @var string $local local field
*/
private $local;
/**
* @var string $foreign foreign field
*/
private $foreign;
/**
* @var integer $type bind type
*/
private $type;
/**
* @param Doctrine_Table $table
* @param string $local
* @param string $foreign
* @param integer $type
*/
public function __construct(Doctrine_Table $table,$local,$foreign,$type) {
$this->table = $table;
$this->local = $local;
$this->foreign = $foreign;
$this->type = $type;
}
/**
* @return integer bind type 1 or 0
*/
public function getType() {
return $this->type;
}
/**
* @return object Doctrine_Table foreign factory object
*/
public function getTable() {
return $this->table;
}
/**
* @return string the name of the local column
*/
public function getLocal() {
return $this->local;
}
/**
* @return string the name of the foreign column where
* the local column is pointing at
*/
public function getForeign() {
return $this->foreign;
}
/**
* __toString
*/
public function __toString() {
$r[] = "<pre>";
$r[] = "Class : ".get_class($this);
$r[] = "Component : ".$this->table->getComponentName();
$r[] = "Table : ".$this->table->getTableName();
$r[] = "Local key : ".$this->local;
$r[] = "Foreign key : ".$this->foreign;
$r[] = "Type : ".$this->type;
$r[] = "</pre>";
return implode("\n", $r);
}
}
?>
<?php
/**
* Doctrine_Repository
* each record is added into Doctrine_Repository at the same time they are created,
* loaded from the database or retrieved from the cache
*
* @author Konsta Vesterinen
* @package Doctrine ORM
* @url www.phpdoctrine.com
* @license LGPL
* @version 1.0 alpha
*
*/
class Doctrine_Repository implements Countable, IteratorAggregate {
/**
* @var object Doctrine_Table $table
*/
private $table;
/**
* @var array $registry
* an array of all records
* keys representing record object identifiers
*/
private $registry = array();
/**
* constructor
*/
public function __construct(Doctrine_Table $table) {
$this->table = $table;
}
/**
* @return object Doctrine_Table
*/
public function getTable() {
return $this->table;
}
/**
* add
* @param Doctrine_Record $record record to be added into registry
*/
public function add(Doctrine_Record $record) {
$oid = $record->getOID();
if(isset($this->registry[$oid]))
return false;
$this->registry[$oid] = $record;
return true;
}
/**
* get
* @param integer $oid
* @throws InvalidKeyException
*/
public function get($oid) {
if( ! isset($this->registry[$oid]))
throw new InvalidKeyException();
return $this->registry[$oid];
}
/**
* count
* Doctrine_Registry implements interface Countable
* @return integer the number of records this registry has
*/
public function count() {
return count($this->registry);
}
/**
* @param integer $oid object identifier
* @return boolean whether ot not the operation was successful
*/
public function evict($oid) {
if( ! isset($this->registry[$oid]))
return false;
unset($this->registry[$oid]);
return true;
}
/**
* @return integer number of records evicted
*/
public function evictAll() {
$evicted = 0;
foreach($this->registry as $oid=>$record) {
if($this->evict($oid))
$evicted++;
}
return $evicted;
}
/**
* getIterator
* @return ArrayIterator
*/
public function getIterator() {
return new ArrayIterator($this->registry);
}
/**
* contains
* @param integer $oid object identifier
*/
public function contains($oid) {
return isset($this->registry[$oid]);
}
/**
* loadAll
* @return void
*/
public function loadAll() {
$this->table->findAll();
}
}
?>
<?php
class Sensei_Group extends Doctrine_Record { }
class Sensei_Company extends Sensei_Group { }
class Sensei_User extends Doctrine_Record { }
class Sensei_Customer extends Sensei_User { }
class Sensei_Entity extends Doctrine_Record {
/**
* setTableDefinition
* initializes column definitions
*
* @return void
*/
public function setTableDefinition() {
$this->hasColumn("loginname","string",32,"unique");
$this->hasColumn("password","string",32);
}
}
class Sensei_Variable extends Doctrine_Record {
/**
* setUp
* initializes relations and options
*
* @return void
*/
public function setUp() {
//$this->setAttribute(Doctrine::ATTR_COLL_KEY, "name");
}
/**
* setTableDefinition
* initializes column definitions
*
* @return void
*/
public function setTableDefinition() {
$this->hasColumn("name","string",50,"unique");
$this->hasColumn("value","string",10000);
$this->hasColumn("session_id","integer");
}
}
class Sensei_Session extends Doctrine_Record {
/**
* setUp
* initializes relations and options
*
* @return void
*/
public function setUp() {
$this->ownsMany("Sensei_Variable","Sensei_Variable.session_id");
$this->hasOne("Sensei_Entity","Sensei_Session.entity_id");
}
/**
* setTableDefinition
* initializes column definitions
*
* @return void
*/
public function setTableDefinition() {
$this->hasColumn("session_id","string",32);
$this->hasColumn("logged_in","integer",1);
$this->hasColumn("entity_id","integer");
$this->hasColumn("user_agent","string",200);
$this->hasColumn("updated","integer");
$this->hasColumn("created","integer");
}
}
class Sensei_Exception extends Exception { }
class Sensei extends Doctrine_Access {
const ATTR_LIFESPAN = 0;
/**
* @var Sensei_Session $record
*/
private $record;
/**
* @var Doctrine_Session $session
*/
private $session;
/**
* @var Doctrine_Table $table
*/
private $table;
/**
* @var array $attributes
*/
private $attributes = array();
/**
* @var Doctrine_Collection $vars
*/
private $vars;
public function __construct() {
if(headers_sent())
throw new Sensei_Exception("Headers already sent. Couldn't initialize session.");
$this->session = Doctrine_Manager::getInstance()->getCurrentSession();
$this->table = $this->session->getTable("Sensei_session");
$this->init();
$this->gc(1);
if( ! isset($_SESSION))
session_start();
}
/**
* getRecord
*/
public function getRecord() {
return $this->record;
}
/**
* init
*/
private function init() {
session_set_save_handler(
array($this,"open"),
array($this,"close"),
array($this,"read"),
array($this,"write"),
array($this,"destroy"),
array($this,"gc")
);
}
/**
* @param string $username
* @param string $password
* @return boolean
*/
public function login($username,$password) {
$coll = $this->session->query("FROM Sensei_Entity WHERE Sensei_Entity.loginname = ? && Sensei_Entity.password = ?",array($username,$password));
if(count($coll) > 0) {
$this->record->logged_in = 1;
$this->record->entity_id = $coll[0]->getID();
$this->record->save();
return true;
}
return false;
}
/**
* logout
* @return boolean
*/
public function logout() {
if( $this->record->logged_in == true) {
$this->record->logged_in = 0;
$this->record->entity_id = 0;
return true;
} else {
return false;
}
}
/**
* returns a session variable
*
* @param mixed $name
* @return mixed
*/
public function get($name) {
foreach($this->vars as $var) {
if($var->name == $name) {
return $var->value;
}
}
}
/**
* sets a session variable
* returns true on success, false on failure
*
* @param mixed $name
* @param mixed $value
* @return boolean
*/
public function set($name,$value) {
foreach($this->vars as $var) {
if($var->name == $name) {
$var->value = $value;
return true;
}
}
return false;
}
/**
* @param integer $attr
* @param mixed $value
*/
public function setAttribute($attr, $value) {
switch($attr):
case Sensei::ATTR_LIFESPAN:
break;
default:
throw new Sensei_Exception("Unknown attribute");
endswitch;
$this->attributes[$attr] = $value;
}
/**
* @return boolean
*/
private function open($save_path,$session_name) {
return true;
}
/**
* @return boolean
*/
public function close() {
return true;
}
/**
* always returns an empty string
*
* @param string $id php session identifier
* @return string
*/
private function read($id) {
$coll = $this->session->query("FROM Sensei_Session, Sensei_Session.Sensei_Variable WHERE Sensei_Session.session_id = ?",array($id));
$this->record = $coll[0];
$this->record->user_agent = $_SERVER['HTTP_USER_AGENT'];
$this->record->updated = time();
$this->record->session_id = $id;
$this->vars = $this->record->Sensei_Variable;
if($this->record->getState() == Doctrine_Record::STATE_TDIRTY) {
$this->record->created = time();
$this->record->save();
}
return "";
}
/**
* @return boolean
*/
public function write($id,$sess_data) {
return true;
}
/**
* @param string $id php session identifier
* @return Doctrine_Record
*/
private function destroy($id) {
$this->record->delete();
return $this->record;
}
/**
* @param integer $maxlifetime
*/
private function gc($maxlifetime) {
return true;
}
/**
* flush
* makes all changes persistent
*/
public function flush() {
$this->record->save();
}
/**
* destructor
*/
public function __destruct() {
$this->flush();
}
}
?>
This diff is collapsed.
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Session.class.php");
/**
* standard session, the parent of pgsql, mysql and sqlite
*/
class Doctrine_Session_Common extends Doctrine_Session {
public function modifyLimitQuery($query,$limit = false,$offset = false) {
if($limit && $offset) {
$query .= " LIMIT ".$limit." OFFSET ".$offset;
} elseif($limit && ! $offset) {
$query .= " LIMIT ".$limit;
} elseif( ! $limit && $offset) {
$query .= " LIMIT 999999999999 OFFSET ".$offset;
}
return $query;
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Exception.class.php");
/**
* thrown when user tries to get the current
* session and there are no open sessions
*/
class Doctrine_Session_Exception extends Doctrine_Exception {
public function __construct() {
parent::__construct("There are no opened sessions. Use
Doctrine_Manager::getInstance()->openSession() to open a new session.",Doctrine::ERR_NO_SESSIONS);
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Session.class.php");
/**
* firebird driver
*/
class Doctrine_Session_Firebird extends Doctrine_Session {
public function modifyLimitQuery($query,$limit,$offset) {
return preg_replace("/([\s(])*SELECT/i","\\1SELECT TOP($from, $count)", $query);
}
/**
* returns the next value in the given sequence
* @param string $sequence
* @return integer
*/
public function getNextID($sequence) {
$stmt = $this->query("SELECT UNIQUE FROM ".$sequence);
$data = $stmt->fetch(PDO::FETCH_NUM);
return $data[0];
}
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Session.class.php");
/**
* informix database driver
*/
class Doctrine_Session_Informix extends Doctrine_Session { }
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Session.class.php");
/**
* mssql driver
*/
class Doctrine_Session_Mssql extends Doctrine_Session {
/**
* returns the next value in the given sequence
* @param string $sequence
* @return integer
*/
public function getNextID($sequence) {
$this->query("INSERT INTO $sequence (vapor) VALUES (0)");
$stmt = $this->query("SELECT @@IDENTITY FROM $sequence");
$data = $stmt->fetch(PDO::FETCH_NUM);
return $data[0];
}
}
?>
<?php
require_once("Common.class.php");
/**
* mysql driver
*/
class Doctrine_Session_Mysql extends Doctrine_Session_Common {
/**
* the constructor
* @param PDO $pdo -- database handle
*/
public function __construct(Doctrine_Manager $manager,PDO $pdo) {
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
parent::__construct($manager,$pdo);
}
/**
* deletes all data access object from the collection
* @param Doctrine_Collection $coll
*/
/**
public function deleteCollection(Doctrine_Collection $coll) {
$a = $coll->getTable()->getCompositePaths();
$a = array_merge(array($coll->getTable()->getComponentName()),$a);
$graph = new Doctrine_DQL_Parser($this);
foreach($coll as $k=>$record) {
switch($record->getState()):
case Doctrine_Record::STATE_DIRTY:
case Doctrine_Record::STATE_CLEAN:
$ids[] = $record->getID();
break;
endswitch;
}
if(empty($ids))
return array();
$graph->parseQuery("FROM ".implode(", ",$a)." WHERE ".$coll->getTable()->getTableName().".id IN(".implode(", ",$ids).")");
$query = $graph->buildDelete();
$this->getDBH()->query($query);
return $ids;
}
*/
/**
* returns maximum identifier values
*
* @param array $names an array of component names
* @return array
*/
public function getMaximumValues2(array $names) {
$values = array();
foreach($names as $name) {
$table = $this->tables[$name];
$keys = $table->getPrimaryKeys();
$tablename = $table->getTableName();
if(count($keys) == 1 && $keys[0] == $table->getIdentifier()) {
// record uses auto_increment column
$sql[] = "SELECT MAX(".$tablename.".".$table->getIdentifier().") as $tablename FROM ".$tablename;
$values[$tablename] = 0;
$array[] = $tablename;
}
}
$sql = implode(" UNION ",$sql);
$stmt = $this->getDBH()->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_NUM);
foreach($data as $k => $v) {
$values[$array[$k]] = $v[0];
}
return $values;
}
/**
* bulkInsert
* inserts all the objects in the pending insert list into database
* TODO: THIS IS NOT WORKING YET AS THERE ARE BUGS IN COMPONENTS USING SELF-REFERENCENCING
*
* @return boolean
*/
/**
public function bulkInsert() {
if(empty($this->insert))
return false;
foreach($this->insert as $name => $inserts) {
if( ! isset($inserts[0]))
continue;
$record = $inserts[0];
$table = $record->getTable();
$seq = $table->getSequenceName();
$keys = $table->getPrimaryKeys();
$marks = array();
$params = array();
foreach($inserts as $k => $record) {
$record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onPreSave($record);
// listen the onPreInsert event
$record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onPreInsert($record);
$array = $record->getPrepared();
if(isset($this->validator)) {
if( ! $this->validator->validateRecord($record)) {
continue;
}
}
$key = implode(", ",array_keys($array));
if( ! isset($params[$key]))
$params[$key] = array();
$marks[$key][] = "(".substr(str_repeat("?, ",count($array)),0,-2).")";
$params[$key] = array_merge($params[$key], array_values($array));
// listen the onInsert event
$record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onInsert($record);
$record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onSave($record);
}
if( ! empty($marks)) {
foreach($marks as $key => $list) {
$query = "INSERT INTO ".$table->getTableName()." (".$key.") VALUES ".implode(", ", $list);
$stmt = $this->getDBH()->prepare($query);
$stmt->execute($params[$key]);
}
}
if(count($keys) == 1 && $keys[0] == $table->getIdentifier()) {
// record uses auto_increment column
$sql = "SELECT MAX(".$table->getIdentifier().") FROM ".$record->getTable()->getTableName();
$stmt = $this->getDBH()->query($sql);
$data = $stmt->fetch(PDO::FETCH_NUM);
$id = $data[0];
$stmt->closeCursor();
foreach(array_reverse($inserts) as $record) {
$record->setID((int) $id);
$id--;
}
}
}
$this->insert = array();
return true;
}
*/
}
?>
<?php
require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Session.class.php");
/**
* oracle driver
*/
class Doctrine_Session_Oracle extends Doctrine_Session {
public function modifyLimitQuery($query,$limit,$offset) {
$e = explode("select ",strtolower($query));
$e2 = explode(" from ",$e[1]);
$fields = $e2[0];
$query = "SELECT $fields FROM (SELECT rownum as linenum, $fields FROM ($query) WHERE rownum <= ($offset + $limit)) WHERE linenum >= ".++$offset;
return $query;
}
/**
* returns the next value in the given sequence
* @param string $sequence
* @return integer
*/
public function getNextID($sequence) {
$stmt = $this->query("SELECT $sequence.nextval FROM dual");
$data = $stmt->fetch(PDO::FETCH_NUM);
return $data[0];
}
}
?>
<?php
require_once("Common.class.php");
/**
* pgsql driver
*/
class Doctrine_Session_Pgsql extends Doctrine_Session_Common {
/**
* returns the next value in the given sequence
* @param string $sequence
* @return integer
*/
public function getNextID($sequence) {
$stmt = $this->query("SELECT NEXTVAL('$sequence')");
$data = $stmt->fetch(PDO::FETCH_NUM);
return $data[0];
}
}
?>
<?php
require_once("Common.class.php");
/**
* sqlite driver
*/
class Doctrine_Session_Sqlite extends Doctrine_Session_Common { }
?>
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
<?php
class Doctrine_Validator_Date {
/**
* @param Doctrine_Record $record
* @param string $key
* @param mixed $value
* @param string $args
* @return boolean
*/
public function validate(Doctrine_Record $record, $key, $value, $args) {
return checkdate($value);
}
}
?>
<?php
class Doctrine_Validator_Email {
/**
* @param Doctrine_Record $record
* @param string $key
* @param mixed $value
* @param string $args
* @return boolean
*/
public function validate(Doctrine_Record $record, $key, $value, $args) {
$parts = explode("@", $value);
if(count($parts) != 2)
return false;
if(strlen($parts[0]) < 1 || strlen($parts[0]) > 64)
return false;
if(strlen($parts[1]) < 1 || strlen($parts[1]) > 255)
return false;
$local_array = explode(".", $parts[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $parts[$i])) {
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $parts[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $parts[1]);
if (count($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
return false;
}
}
}
if(function_exists("checkdnsrr")) {
if( ! checkdnsrr($parts[1], "MX"))
return false;
}
return true;
}
}
?>
<?php
class Doctrine_Validator_Enum {
/**
* @param Doctrine_Record $record
* @param string $key
* @param mixed $value
* @param string $args
* @return boolean
*/
public function validate(Doctrine_Record $record, $key, $value, $args) {
$max = substr_count($args, "-");
$int = (int) $value;
if($int != $value)
return false;
if($int < 0 || $int > $max)
return false;
return true;
}
}
?>
<?php
class Doctrine_Validator_HtmlColor {
/**
* @param Doctrine_Record $record
* @param string $key
* @param mixed $value
* @param string $args
* @return boolean
*/
public function validate(Doctrine_Record $record, $key, $value, $args) {
if( ! preg_match("/^#{0,1}[0-9]{6}$/",$color)) {
return false;
}
return true;
}
}
?>
<?php
class Doctrine_Validator_Ip {
/**
* @param Doctrine_Record $record
* @param string $key
* @param mixed $value
* @param string $args
* @return boolean
*/
public function validate(Doctrine_Record $record, $key, $value, $args) {
$e = explode(".",$request);
if(count($e) != 4) return false;
foreach($e as $k=>$v):
if(! is_numeric($v)) return false;
$v = (int) $v;
if($v < 0 || $v > 255) return false;
endforeach;
return true;
}
}
?>
<?php
class Doctrine_Validator_NoSpace {
/**
* @param Doctrine_Record $record
* @param string $key
* @param mixed $value
* @param string $args
* @return boolean
*/
public function validate(Doctrine_Record $record, $key, $value, $args) {
if(trim($value) === '')
return false;
return true;
}
}
?>
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment