orm.abstract.class.php 12 KB

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