orm.abstract.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. <?php
  2. namespace Juju {
  3. require_once('sql.class.php');
  4. require_once('ORM/relationship.class.php');
  5. use \Juju\ORM\Relationship as Relationship;
  6. abstract class ORM implements \ArrayAccess, \JsonSerializable {
  7. // Model definition
  8. protected static $table_name = null;
  9. protected static $primary_key = 'id';
  10. protected static $foreign_key_suffix = '_id';
  11. protected static $has_one = [];
  12. protected static $has_many = [];
  13. protected static $belongs_to = [];
  14. // Data tracking
  15. private $_data = [];
  16. private $_changed = [];
  17. private $_related = [];
  18. private static $aliases = [];
  19. private static $instances = [];
  20. private static $sql;
  21. // Magic functions
  22. private function __construct($idOrData){
  23. if(!isset(self::$aliases[$this->name])){
  24. $aliases = [
  25. 'belongs_to' => [],
  26. 'has_one' => [],
  27. 'has_many' => []
  28. ];
  29. if(is_array(static::$belongs_to)){
  30. foreach(static::$belongs_to as $alias => $details){
  31. $aliases['belongs_to'][$alias] = array_merge(
  32. [
  33. 'model'=>$alias,
  34. 'foreign_key'=>$this->name.static::foreign_key_suffix()
  35. ],
  36. $details
  37. );
  38. }
  39. }
  40. if(is_array(static::$has_one)){
  41. foreach(static::$has_one as $alias => $details){
  42. $aliases['has_one'][$alias] = array_merge(
  43. [
  44. 'model'=>$alias,
  45. 'foreign_key'=>$alias.static::foreign_key_suffix()
  46. ],
  47. $details
  48. );
  49. }
  50. }
  51. if(is_array(static::$has_many)){
  52. foreach(static::$has_many as $alias => $details){
  53. $aliases['has_many'][$alias] = array_merge(
  54. [
  55. 'model'=>$alias,
  56. 'foreign_key'=>$this->name.static::foreign_key_suffix(),
  57. 'through'=> null
  58. ],
  59. $details
  60. );
  61. }
  62. }
  63. self::$aliases[$this->name] = $aliases;
  64. // Clear relationship definitions to save memory
  65. static::$belongs_to = static::$has_one = static::$has_many = null;
  66. }
  67. if(is_array($idOrData)){
  68. if(isset($idOrData[static::primary_key()]) && self::cached($idOrData[static::primary_key()])){
  69. throw new \Exception('Instance already cached');
  70. }
  71. foreach($idOrData as $key => $val){
  72. $this->_data[$key] = $val;
  73. }
  74. }else{
  75. if(self::cached($idOrData)){
  76. throw new \Exception('Instance already cached');
  77. }
  78. $this->_data[static::primary_key()] = (int)$idOrData;
  79. }
  80. self::$instances[] = $this;
  81. }
  82. private function __destruct(){
  83. $this->__sleep();
  84. $this->_changed = [];
  85. $this->_data = [];
  86. $this->_related = [];
  87. $key = array_search($this, self::$instances);
  88. if($key !== false){
  89. array_splice(self::$instances, $key, 1);
  90. }
  91. }
  92. public function __get(string $name){
  93. switch($name){
  94. case 'name':
  95. return static::table_name();
  96. break;
  97. case 'primary_key':
  98. return static::primary_key();
  99. break;
  100. case 'foreign_key_suffix':
  101. return static::foreign_key_suffix();
  102. break;
  103. case 'has_one':case 'has_many':case 'belongs_to':
  104. return self::$aliases[$this->name][$name];
  105. break;
  106. case 'id':
  107. return $this->get(static::primary_key());
  108. break;
  109. default:
  110. throw new \Exception('Unknown property '.$name);
  111. }
  112. }
  113. public function __set(string $name, $val){
  114. switch($name){
  115. case 'id':case 'name':
  116. throw new \Exception('Property '.$name.' is read only');
  117. break;
  118. default:
  119. throw new \Exception('Unknown property '.$name);
  120. }
  121. }
  122. public function __sleep(){
  123. $this->save();
  124. }
  125. public function __wakeup(){
  126. $this->reload(true);
  127. }
  128. public function __toString(){
  129. return $this->name.'('.$this->id.')';
  130. }
  131. public function __invoke(){
  132. return $this->_data;
  133. }
  134. public function __clone(){
  135. unset($this->$_data[static::primary_key()]);
  136. }
  137. // JsonSerializable
  138. public function jsonSerialize(){
  139. return $this->_data;
  140. }
  141. // ArrayAccess
  142. public function offsetSet($key, $val){
  143. $this->set($key, $val);
  144. }
  145. public function offsetExists($key){
  146. return $this->has($key);
  147. }
  148. public function offsetUnset($key){
  149. return $this->unset($key);
  150. }
  151. public function offsetGet($key){
  152. return $this->get($key);
  153. }
  154. // Main API
  155. public static function table_name(){
  156. if(is_null(static::$table_name)){
  157. $name = get_called_class();
  158. return substr($name, strrpos($name, '\\') + 1);
  159. }
  160. return static::$table_name;
  161. }
  162. public static function primary_key(){
  163. return static::$primary_key;
  164. }
  165. public static function foreign_key_suffix(){
  166. return static::$foreign_key_suffix;
  167. }
  168. public static function bind(SQL $sql){
  169. self::$sql = $sql;
  170. // @todo handle updating live instances
  171. }
  172. public static function query(...$args){
  173. return self::$sql->query(...$args);
  174. }
  175. public static function instance(int $id){
  176. $instance = self::cached_instance($id);
  177. if(!is_null($instance)){
  178. return $instance;
  179. }elseif(self::exists($id)){
  180. return new static($id);
  181. }
  182. return null;
  183. }
  184. public static function exists(int $id){
  185. return (int)self::query(
  186. "select count(1) as count ".
  187. "from ".static::table_name().' '.
  188. "where ".static::primary_key()." = ?",
  189. 'i',
  190. $id
  191. )->assoc_result["count"] > 0;
  192. }
  193. public static function cached_instance(int $id){
  194. $name = static::table_name();
  195. if(isset(self::$instances[$name])){
  196. $instances = array_filter(self::$instances[$name], function(&$instance){
  197. return $instance->id === $id;
  198. });
  199. return isset($instances[0]) ? $instances[0] : null;
  200. }
  201. return null;
  202. }
  203. public static function cached(int $id){
  204. return !is_null(self::cached_instance($id));
  205. }
  206. public static function delete(int $id){
  207. $query = self::query(
  208. "delete from ".static::table_name().' '.
  209. "where ".static::primary_key()." = ?",
  210. 'i',
  211. $id
  212. );
  213. return $query->execute() && $query->affected_rows > 0;
  214. }
  215. public static function each_cached(callable $fn){
  216. $name = static::table_name();
  217. if(self::$instances[$name]){
  218. array_walk(self::$instances[$name], $fn);
  219. }
  220. }
  221. public static function each_where(callable $fn, array $filter = null, int $start = null, int $amount = null){
  222. $limit = ' ';
  223. if(!is_null($start) && !is_null($amount)){
  224. $limit .= "limit {$start}, {$amount}";
  225. }
  226. $where = ' ';
  227. $types = null;
  228. $bindings = null;
  229. if(!is_null($filter)){
  230. $types = '';
  231. $bindings = array();
  232. foreach($filter as $key => $val){
  233. if(is_string($val)){
  234. $types .= 's';
  235. }elseif(is_double($val)){
  236. $types .= 'd';
  237. }elseif(is_int($val)){
  238. $types .= 'i';
  239. }else{
  240. throw new \Exception("Unknown data type");
  241. }
  242. $where .= 'and {$key} = ? ';
  243. $bindings[] = $val;
  244. }
  245. $where = self::str_replace_first(' and ', ' ', $where);
  246. }
  247. self::query(
  248. "select ".static::primary_key().' id '.
  249. "from ".static::table_name().
  250. $where.
  251. $limit,
  252. $types,
  253. $bindings
  254. )->each_assoc(function($row) use($fn){
  255. $fn(self::instance((int)$row['id']));
  256. });
  257. }
  258. public static function each(callable $fn, int $start = null, int $amount = null){
  259. self::each_where($fn, null, $start, $amount);
  260. }
  261. public static function fetch(array $filter = null, int $start = null, int $amount = null){
  262. $results = [];
  263. self::each_where(function($item) use($results){
  264. $results[] = $item;
  265. }, $filter, $start, $amount);
  266. return $results;
  267. }
  268. public static function str_replace_first($search, $replace, $source) {
  269. $explode = explode($search, $source);
  270. $shift = array_shift($explode);
  271. $implode = implode($search, $explode);
  272. return $shift.$replace.$implode;
  273. }
  274. // Instance Api
  275. public function values($values){
  276. foreach($values as $key => $val){
  277. $this->set($key, $val);
  278. }
  279. return $this;
  280. }
  281. public function load(bool $force = false){
  282. if(!$force && $this->dirty()){
  283. throw new \Exception('Cannot load, there are pending changes');
  284. }else{
  285. if(!is_null($this->id)){
  286. $data = self::query(
  287. "select * " .
  288. "from {$this->name} ".
  289. "where ".static::primary_key()." = ?",
  290. 'i',
  291. $this->id
  292. )->assoc_result;
  293. if($data === false){
  294. throw new \Exception("{$this->name} with ".static::primary_key()." of {$this->id} does not exist");
  295. }
  296. $this->_data = $data;
  297. }
  298. }
  299. return $this;
  300. }
  301. public function save(){
  302. if($this->dirty()){
  303. $data = [];
  304. $set = "set ";
  305. $types = '';
  306. foreach($this->_changed as $key){
  307. if(isset($this->_data[$key]) || is_null($this->_data[$key])){
  308. $data[$key] = $this->_data[$key];
  309. }else{
  310. $set .= "{$key} = null";
  311. }
  312. }
  313. foreach($data as $key => $val){
  314. if(is_string($val)){
  315. $types .= 's';
  316. }elseif(is_double($val)){
  317. $types .= 'd';
  318. }elseif(is_int($val)){
  319. $types .= 'i';
  320. }else{
  321. throw new \Exception('Unknown data type');
  322. }
  323. $set .= "{$key} = ? ";
  324. }
  325. if(!is_null($this->id) && !in_array(static::primary_key(), $this->_changed)){
  326. $data = array_merge(array_values($data), [$this->id]);
  327. self::query(
  328. "update {$this->name} {$set} where ".static::primary_key()." = ?",
  329. $types.'i',
  330. $data
  331. )->execute();
  332. }else{
  333. self::query(
  334. "insert {$this->name} {$set}"
  335. )->execute();
  336. $this->_data[static::primary_key()] = self::$sql->insert_id;
  337. }
  338. foreach($this->_related as $related){
  339. $related->save();
  340. }
  341. }
  342. // Always fetch again from the database in case saving
  343. // forces something to change at the database level
  344. return $this->reload(true);
  345. }
  346. public function reload(bool $force = false){
  347. if($force){
  348. $this->_changed = [];
  349. }
  350. return $this->load($force);
  351. }
  352. public function clear(){
  353. return $this->reload(true);
  354. }
  355. public function get($key){
  356. return $this->_data[$key];
  357. }
  358. public function set($key, $val){
  359. if($key === static::primary_key() && !is_null($this->id)){
  360. throw new \Exception('You are not allowed to change the primary key');
  361. }
  362. $this->_data[$key] = $val;
  363. $this->_changed = array_merge($this->_changed, [$key]);
  364. return $this;
  365. }
  366. public function unset($key){
  367. unset($this->_data[$key]);
  368. return $this;
  369. }
  370. public function has($key){
  371. return isset($this->_data[$key]);
  372. }
  373. public function dirty(string $key = null){
  374. if(is_null($key)){
  375. return count($this->_changed) > 0;
  376. }else{
  377. return in_array($key, $this->_changed);
  378. }
  379. }
  380. public function related(string $name){
  381. if(!isset($this->_related[$name])){
  382. $aliases = self::$aliases[$this->name];
  383. if(isset($aliases['belongs_to'][$name])){
  384. $alias = $aliases['has_many'][$name];
  385. $class = "\\Models\\{$alias['model']}";
  386. $this->_related[$name] = $class::fetch([$alias['foreign_key'] => $this->id])[0];
  387. }elseif(isset($aliases['has_one'][$name])){
  388. $alias = $aliases['has_many'][$name];
  389. $class = "\\Models\\{$alias['model']}";
  390. $this->_related[$name] = $class::instance($this[$alias['foreign_key']]);
  391. }elseif(isset($aliases['has_many'][$name])){
  392. $alias = $aliases['has_many'][$name];
  393. $class = "\\Models\\{$alias['model']}";
  394. $sql = "select ";
  395. if($alias['through']){
  396. $sql .= $class::table_name().$class::foreign_key_suffix()." id from {$alias['through']} ";
  397. }else{
  398. $sql .= $class::primary_key()." id from {$alias['model']} ";
  399. }
  400. $sql .= "where ".$alias['foreign_key']." = ?";
  401. $related = [];
  402. self::query(
  403. $sql,
  404. 'i',
  405. $this->id
  406. )->each_assoc(function($row) use(&$related, $class){
  407. $related[] = new $class($row['id']);
  408. });
  409. $this->_related[$name] = Relationship::from($this, $name, $alias, $related);
  410. }
  411. }
  412. if(isset($this->_related[$name])){
  413. return $this->_related[$name];
  414. }else{
  415. throw new \Exception("Relationship {$name} does not exist");
  416. }
  417. }
  418. }
  419. }
  420. ?>