orm.abstract.class.php 12 KB

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