orm.abstract.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. $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 'pdo':
  97. return static::pdo();
  98. case 'table':
  99. return static::table();
  100. case 'name':
  101. return static::table_name();
  102. case 'primary_key':
  103. return static::primary_key();
  104. case 'foreign_key_suffix':
  105. return static::foreign_key_suffix();
  106. case 'has_one':case 'has_many':case 'belongs_to':
  107. return self::$aliases[$this->name][$name];
  108. case 'id':
  109. $pk = static::primary_key();
  110. return $this->has($pk) ? $this->get($pk) : null;
  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 table(){
  165. if(is_null(static::$table) || static::$table->name !== static::table_name()){
  166. static::$table = self::$pdo->table(static::table_name());
  167. }
  168. return static::$table;
  169. }
  170. public static function primary_key(){
  171. return static::$primary_key;
  172. }
  173. public static function foreign_key_suffix(){
  174. return static::$foreign_key_suffix;
  175. }
  176. public static function bind($pdo){
  177. if(is_string($pdo)){
  178. $pdo = PDO::from($pdo);
  179. }
  180. if($pdo instanceof SecureString){
  181. $pdo = PDO::from((string)$pdo);
  182. }
  183. if($pdo instanceof PDO){
  184. self::$pdo = $pdo;
  185. // @todo handle updating live instances
  186. }else{
  187. throw new \Exception("Invalid argument. Must pass a DSN string or a PDO instance");
  188. }
  189. }
  190. public static function pdo(){
  191. return static::$pdo;
  192. }
  193. public static function query(...$args){
  194. return self::$pdo->query(...$args);
  195. }
  196. public static function exec(...$args){
  197. return self::$pdo->exec(...$args);
  198. }
  199. public static function prepare(...$args){
  200. return self::$pdo->prepare(...$args);
  201. }
  202. public static function quote(...$args){
  203. return self::$pdo->quote(...$args);
  204. }
  205. public static function instance(int $id){
  206. $instance = self::cached_instance($id);
  207. if(!is_null($instance)){
  208. return $instance;
  209. }elseif(self::exists($id)){
  210. return new static($id);
  211. }
  212. return null;
  213. }
  214. public static function create(array $data){
  215. return new static($data);
  216. }
  217. public static function exists(int $id){
  218. $query = self::query(
  219. "select count(1) as count ".
  220. "from `".static::table_name().'` '.
  221. "where `".static::primary_key()."` = ".self::quote($id)
  222. );
  223. $count = $query->fetch()['count'];
  224. $query->closeCursor();
  225. return (int)$count > 0;
  226. }
  227. public static function cached_instance(int $id){
  228. $name = static::table_name();
  229. if(isset(self::$instances[$name])){
  230. $instances = array_filter(self::$instances[$name], function(&$instance){
  231. return $instance->id === $id;
  232. });
  233. return isset($instances[0]) ? $instances[0] : null;
  234. }
  235. return null;
  236. }
  237. public static function cached(int $id){
  238. return !is_null(self::cached_instance($id));
  239. }
  240. public static function delete(int $id){
  241. return static::table()->delete([
  242. static::primary_key() => $id
  243. ]) > 0;
  244. }
  245. public static function each_cached(callable $fn){
  246. $name = static::table_name();
  247. if(self::$instances[$name]){
  248. array_walk(self::$instances[$name], $fn);
  249. }
  250. }
  251. public static function each(callable $fn, array $filter = null, int $start = null, int $amount = null){
  252. static::table()->each(function($row) use($fn){
  253. $fn(self::instance((int)$row['id']));
  254. }, [static::primary_key()], $filter, $start, $amount);
  255. }
  256. public static function fetch(array $filter = null, int $start = null, int $amount = null){
  257. $results = [];
  258. self::each(function($item) use($results){
  259. $results[] = $item;
  260. }, $filter, $start, $amount);
  261. return $results;
  262. }
  263. public static function str_replace_first($search, $replace, $source) {
  264. $explode = explode($search, $source);
  265. $shift = array_shift($explode);
  266. $implode = implode($search, $explode);
  267. return $shift.$replace.$implode;
  268. }
  269. public static function models(){
  270. array_filter(get_declared_classes(), function($class){
  271. return 0 === strpos($class, "Model\\");
  272. });
  273. }
  274. public static function count(array $filter = null){
  275. return static::table()->count($filter);
  276. }
  277. // Instance Api
  278. public function values($values){
  279. foreach($values as $key => $val){
  280. $this->set($key, $val);
  281. }
  282. return $this;
  283. }
  284. public function load(bool $force = false){
  285. if(!$force && $this->dirty()){
  286. throw new \Exception('Cannot load, there are pending changes');
  287. }else{
  288. if(!is_null($this->id)){
  289. $query = self::query(
  290. "select * " .
  291. "from {$this->name} ".
  292. "where ".static::primary_key()." = ".self::quote($this->id)
  293. );
  294. $data = $query->fetch();
  295. $query->closeCursor();
  296. if($data === false){
  297. throw new \Exception("{$this->name} with ".static::primary_key()." of {$this->id} does not exist");
  298. }
  299. $this->_data = $data;
  300. }
  301. }
  302. return $this;
  303. }
  304. public function save(){
  305. if($this->dirty()){
  306. $data = [];
  307. foreach($this->_changed as $key){
  308. if(isset($this->_data[$key]) || is_null($this->_data[$key])){
  309. $data[$key] = $this->_data[$key];
  310. }else{
  311. $data[$key] = null;
  312. }
  313. }
  314. $pk = static::primary_key();
  315. $table = static::table();
  316. if($this->has($pk) && !is_null($this->id) && !in_array($pk, $this->_changed)){
  317. $table->update($data, [
  318. $pk => $this->id
  319. ]);
  320. }else{
  321. $table->insert($data);
  322. $this->_data[$pk] = self::$pdo->lastInsertId();
  323. }
  324. foreach($this->_related as $related){
  325. $related->save();
  326. }
  327. }
  328. // Always fetch again from the database in case saving
  329. // forces something to change at the database level
  330. return $this->reload(true);
  331. }
  332. public function reload(bool $force = false){
  333. if($force){
  334. $this->_changed = [];
  335. }
  336. return $this->load($force);
  337. }
  338. public function clear(){
  339. return $this->reload(true);
  340. }
  341. public function get($key){
  342. return $this->_data[$key];
  343. }
  344. public function set($key, $val){
  345. if($key === static::primary_key() && !is_null($this->id)){
  346. throw new \Exception('You are not allowed to change the primary key');
  347. }
  348. $this->_data[$key] = $val;
  349. $this->_changed = array_merge($this->_changed, [$key]);
  350. return $this;
  351. }
  352. public function unset($key){
  353. unset($this->_data[$key]);
  354. return $this;
  355. }
  356. public function has($key){
  357. return isset($this->_data[$key]);
  358. }
  359. public function dirty(string $key = null){
  360. if(is_null($key)){
  361. $dirty = count($this->_changed) > 0;
  362. if(!$dirty){
  363. foreach($this->_related as $rel){
  364. if($rel instanceof Relationship){
  365. $dirty = $rel->dirty();
  366. }
  367. if($dirty){
  368. break;
  369. }
  370. }
  371. }
  372. return $dirty;
  373. }else{
  374. return in_array($key, $this->_changed);
  375. }
  376. }
  377. public function related(string $name){
  378. if(!isset($this->_related[$name])){
  379. $aliases = self::$aliases[$this->name];
  380. if(isset($aliases['belongs_to'][$name])){
  381. $alias = $aliases['has_many'][$name];
  382. $class = "\\Model\\{$alias['model']}";
  383. $this->_related[$name] = $class::fetch([$alias['foreign_key'] => $this->id])[0];
  384. }elseif(isset($aliases['has_one'][$name])){
  385. $alias = $aliases['has_many'][$name];
  386. $class = "\\Model\\{$alias['model']}";
  387. $this->_related[$name] = $class::instance($this[$alias['foreign_key']]);
  388. }elseif(isset($aliases['has_many'][$name])){
  389. $alias = $aliases['has_many'][$name];
  390. $class = "\\Model\\{$alias['model']}";
  391. $sql = "select ";
  392. if($alias['through']){
  393. $sql .= $class::table_name().$class::foreign_key_suffix()." id from {$alias['through']} ";
  394. }else{
  395. $sql .= $class::primary_key()." id from {$alias['model']} ";
  396. }
  397. $sql .= "where ".$alias['foreign_key']." = ".self::quote($this->id);
  398. $related = [];
  399. $query = self::query($sql);
  400. foreach($query->fetchAll() as $row){
  401. $related[$row['id']] = new $class($row['id']);
  402. }
  403. $query->closeCursor();
  404. $this->_related[$name] = Relationship::from($this, $name, $alias, $related);
  405. }
  406. }
  407. if(isset($this->_related[$name])){
  408. return $this->_related[$name];
  409. }else{
  410. throw new \Exception("Relationship {$name} does not exist");
  411. }
  412. }
  413. public function release(string $name){
  414. if(isset($this->_related[$name])){
  415. unset($this->_related[$name]);
  416. }
  417. }
  418. }
  419. ?>