orm.abstract.class.php 12 KB

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