123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341 |
- <?php
- require_once('sql.class.php');
- abstract class ORM implements ArrayAccess, JsonSerializable {
- // Model definition
- protected static $primary_key = 'id';
- protected static $foreign_key_suffix = '_id';
- protected static $has_one = [];
- protected static $has_many = [];
- protected static $belongs_to = [];
- // Data tracking
- private $_data = [];
- private $_changed = [];
- private $_related = [];
- private static $aliases = [];
- private static $instances = [];
- private static $sql;
- protected static $name = null;
- // Magic functions
- private function __construct($idOrData){
- if(!isset(self::$aliases[$this->name])){
- foreach(static::$belongs_to as $alias => $details){
- self::$aliases[$this->name]['belongs_to'][$alias] = array_merge(
- [
- 'model'=>$alias,
- 'foreign_key'=>$alias.static::$foreign_key_suffix
- ],
- $details
- );
- }
- foreach(static::$has_one as $alias => $details){
- self::$aliases[$this->name]['has_one'][$alias] = array_merge(
- [
- 'model'=>$alias,
- 'foreign_key'=>$alias.static::$foreign_key_suffix
- ],
- $details
- );
- }
- foreach(static::$has_many as $alias => $details){
- self::$aliases[$this->name]['has_many'][$alias] = array_merge(
- [
- 'model'=>$alias,
- 'foreign_key'=>$alias.static::$foreign_key_suffix,
- 'through'=> null
- ],
- $details
- );
- }
- }
- // Clear relationship definitions to save memory
- static::$belongs_to = static::$has_one = static::$has_many =null;
- if(is_array($idOrData)){
- if(isset($idOrData[static::$primary_key]) && self::cached($idOrData[static::$primary_key])){
- throw new Exception('Instance already cached');
- }
- foreach($idOrData as $key => $val){
- $this->_data[$key] = $val;
- }
- }else{
- if(self::cached($idOrData)){
- throw new Exception('Instance already cached');
- }
- $this->_data[static::$primary_key] = (int)$idOrData;
- }
- self::$instances[] = $this;
- }
- private function __destruct(){
- $this->__sleep();
- $this->_changed = [];
- $this->_data = [];
- $this->_related = [];
- $key = array_search(self::$instances, $this);
- if($key !== false){
- array_splice(self::$instances, $key, 1);
- }
- }
- public function __get(string $name){
- switch($name){
- case 'name':
- return static::name();
- break;
- case 'id':
- return $this->get(static::$primary_key);
- break;
- default:
- throw new Exception('Unknown property '.$name);
- }
- }
- public function __set(string $name, $val){
- switch($name){
- case 'id':case 'name':
- throw new Exception('Property '.$name.' is read only');
- break;
- default:
- throw new Exception('Unknown property '.$name);
- }
- }
- public function __sleep(){
- $this->save();
- }
- public function __wakeup(){
- $this->reload(true);
- }
- public function __toString(){
- return $this->name.'('.$this->id.')';
- }
- public function __invoke(){
- return $this->_data;
- }
- public function __clone(){
- unset($this->$_data[static::$primary_key]);
- }
- // JsonSerializable
- public function jsonSerialize(){
- return $this->_data;
- }
- // ArrayAccess
- public function offsetSet($key, $val){
- $this->set($key, $val);
- }
- public function offsetExists($key){
- return $this->has($key);
- }
- public function offsetUnset($key){
- return $this->unset($key);
- }
- public function offsetGet($key){
- return $this->get($key);
- }
- // Main API
- public static function name(){
- if(is_null(static::$name)){
- $name = get_called_class();
- static::$name = substr($name, strrpos($name, '\\') + 1);
- }
- return static::$name;
- }
- public static function bind(SQL $sql){
- self::$sql = $sql;
- // @todo handle updating live instances
- }
- public static function query(...$args){
- return self::$sql->query(...$args);
- }
- public static function instance(int $id){
- $instance = self::cached_instance($id);
- if(!is_null($instance)){
- return $instance;
- }elseif(self::exists($id)){
- return new static($id);
- }
- return null;
- }
- public static function exists(int $id){
- return (int)self::query(
- "select count(1) as count ".
- "from ".static::name().' '.
- "where ".static::$primary_key." = ?",
- 'i',
- $id
- )->assoc_result["count"] > 0;
- }
- public static function cached_instance(int $id){
- $name = static::name();
- if(isset(self::$instances[$name])){
- $instances = array_filter(self::$instances[$name], function(&$instance){
- return $instance->id === $id;
- });
- return isset($instances[0]) ? $instances[0] : null;
- }
- return null;
- }
- public static function cached(int $id){
- return !is_null(self::cached_instance($id));
- }
- public static function delete(int $id){
- $query = self::query(
- "delete from ".static::name().' '.
- "where ".static::$primary_key." = ?",
- 'i',
- $id
- );
- return $query->execute() && $query->affected_rows > 0;
- }
- public static function each_cached(callable $fn){
- $name = static::name();
- if(self::$instances[$name]){
- array_walk(self::$instances[$name], $fn);
- }
- }
- public static function each_where(callable $fn, array $filter = null, int $start = null, int $amount = null){
- $limit = ' ';
- if(!is_null($start) && !is_null($amount)){
- $limit .= "limit {$start}, {$amount}";
- }
- $where = ' ';
- $types = null;
- $bindings = null;
- if(!is_null($filter)){
- $types = '';
- $bindings = array();
- foreach($filter as $key => $val){
- if(is_string($val)){
- $types .= 's';
- }elseif(is_double($val)){
- $types .= 'd';
- }elseif(is_int($val)){
- $types .= 'i';
- }else{
- throw new Exception("Unknown data type");
- }
- $where .= 'and {$key} = ? ';
- $bindings[] = $val;
- }
- $where = self::str_replace_first(' and ', ' ', $where);
- }
- self::query(
- "select ".static::$primary_key.' id '.
- "from ".static::name().
- $where.
- $limit,
- $types,
- $bindings
- )->each_assoc(function($row) use($fn){
- $fn(self::instance((int)$row['id']));
- });
- }
- public static function each(callable $fn, int $start = null, int $amount = null){
- self::each_where($fn, null, $start, $amount);
- }
- public static function str_replace_first($search, $replace, $source) {
- $explode = explode($search, $source);
- $shift = array_shift($explode);
- $implode = implode($search, $explode);
- return $shift.$replace.$implode;
- }
- // Instance Api
- public function values($values){
- foreach($values as $key => $val){
- $this->set($key, $val);
- }
- return $this;
- }
- public function load(bool $force = false){
- if(!$force && $this->dirty()){
- throw new Exception('Cannot load, there are pending changes');
- }else{
- if(!is_null($this->id)){
- $data = self::query(
- "select * " .
- "from {$this->name} ".
- "where ".static::$primary_key." = ?",
- 'i',
- $this->id
- )->assoc_result;
- if($data === false){
- throw new Exception("{$this->name} with ".static::$primary_key." of {$this->id} does not exist");
- }
- $this->_data = $data;
- }
- }
- return $this;
- }
- public function save(){
- if($this->dirty()){
- $data = [];
- $set = "set ";
- $types = '';
- foreach($this->_changed as $key){
- if(isset($this->_data[$key]) || is_null($this->_data[$key])){
- $data[$key] = $this->_data[$key];
- }else{
- $set .= "{$key} = null";
- }
- }
- foreach($data as $key => $val){
- if(is_string($val)){
- $types .= 's';
- }elseif(is_double($val)){
- $types .= 'd';
- }elseif(is_int($val)){
- $types .= 'i';
- }else{
- throw new Exception('Unknown data type');
- }
- $set .= "{$key} = ? ";
- }
- if(!is_null($this->id) && !in_array(static::$primary_key, $this->_changed)){
- $data = array_merge(array_values($data), [$this->id]);
- self::query(
- "update {$this->name} {$set} where ".static::$primary_key." = ?",
- $types.'i',
- $data
- )->execute();
- }else{
- self::query(
- "insert {$this->name} {$set}"
- )->execute();
- $this->_data[static::$primary_key] = self::$sql->insert_id;
- }
- }
- // Always fetch again from the database in case saving
- // forces something to change at the database level
- return $this->reload(true);
- }
- public function reload(bool $force = false){
- if($force){
- $this->_changed = [];
- }
- return $this->load($force);
- }
- public function clear(){
- return $this->reload(true);
- }
- public function get($key){
- return $this->_data[$key];
- }
- public function set($key, $val){
- if($key === static::$primary_key && !is_null($this->id)){
- throw new Exception('You are not allowed to change the primary key');
- }
- $this->_data[$key] = $val;
- $this->_changed = array_merge($this->_changed, [$key]);
- return $this;
- }
- public function unset($key){
- unset($this->_data[$key]);
- return $this;
- }
- public function has($key){
- return isset($this->_data[$key]);
- }
- public function dirty(string $key = null){
- if(is_null($key)){
- return count($this->_changed) > 0;
- }else{
- return in_array($key, $this->_changed);
- }
- }
- }
- ?>
|