orm.abstract.class.php 11 KB

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