crud.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. <?php
  2. /**
  3. * Part of the Fuel framework.
  4. *
  5. * @package Fuel
  6. * @version 1.5
  7. * @author Fuel Development Team
  8. * @license MIT License
  9. * @copyright 2010 - 2013 Fuel Development Team
  10. * @link http://fuelphp.com
  11. */
  12. namespace Fuel\Core;
  13. class Model_Crud extends \Model implements \Iterator, \ArrayAccess, \Serializable
  14. {
  15. /**
  16. * @var string $_table_name The table name (must set this in your Model)
  17. */
  18. // protected static $_table_name = '';
  19. /**
  20. * @var string $_primary_key The primary key for the table
  21. */
  22. // protected static $_primary_key = 'id';
  23. /**
  24. * @var string $_connection The database connection to use
  25. */
  26. // protected static $_connection = null;
  27. /**
  28. * @var string $_write_connection The database connection to use for writes
  29. */
  30. // protected static $_write_connection = null;
  31. /**
  32. * @var array $_rules The validation rules (must set this in your Model to use)
  33. */
  34. // protected static $_rules = array();
  35. /**
  36. * @var array $_properties The table column names (must set this in your Model to use)
  37. */
  38. // protected static $_properties = array();
  39. /**
  40. * @var array $_labels Field labels (must set this in your Model to use)
  41. */
  42. // protected static $_labels = array();
  43. /**
  44. * @var array $_defaults Field defaults (must set this in your Model to use)
  45. */
  46. // protected static $_defaults = array();
  47. /**
  48. * @var bool set true to use MySQL timestamp instead of UNIX timestamp
  49. */
  50. //protected static $_mysql_timestamp = false;
  51. /**
  52. * @var string fieldname of created_at field, uncomment to use.
  53. */
  54. //protected static $_created_at = 'created_at';
  55. /**
  56. * @var string fieldname of updated_at field, uncomment to use.
  57. */
  58. //protected static $_updated_at = 'updated_at';
  59. /**
  60. * Forges new Model_Crud objects.
  61. *
  62. * @param array $data Model data
  63. * @return Model_Crud
  64. */
  65. public static function forge(array $data = array())
  66. {
  67. return new static($data);
  68. }
  69. /**
  70. * Finds a row with the given primary key value.
  71. *
  72. * @param mixed $value The primary key value to find
  73. * @return null|object Either null or a new Model object
  74. */
  75. public static function find_by_pk($value)
  76. {
  77. return static::find_one_by(static::primary_key(), $value);
  78. }
  79. /**
  80. * Finds a row with the given column value.
  81. *
  82. * @param mixed $column The column to search
  83. * @param mixed $value The value to find
  84. * @return null|object Either null or a new Model object
  85. */
  86. public static function find_one_by($column, $value = null, $operator = '=')
  87. {
  88. $config = array(
  89. 'limit' => 1,
  90. );
  91. if (is_array($column) or ($column instanceof \Closure))
  92. {
  93. $config['where'] = $column;
  94. }
  95. else
  96. {
  97. $config['where'] = array(array($column, $operator, $value));
  98. }
  99. $result = static::find($config);
  100. if ($result !== null)
  101. {
  102. return reset($result);
  103. }
  104. return null;
  105. }
  106. /**
  107. * Finds all records where the given column matches the given value using
  108. * the given operator ('=' by default). Optionally limited and offset.
  109. *
  110. * @param string $column The column to search
  111. * @param mixed $value The value to find
  112. * @param string $operator The operator to search with
  113. * @param int $limit Number of records to return
  114. * @param int $offset What record to start at
  115. * @return null|object Null if not found or an array of Model object
  116. */
  117. public static function find_by($column = null, $value = null, $operator = '=', $limit = null, $offset = 0)
  118. {
  119. $config = array(
  120. 'limit' => $limit,
  121. 'offset' => $offset,
  122. );
  123. if ($column !== null)
  124. {
  125. if (is_array($column) or ($column instanceof \Closure))
  126. {
  127. $config['where'] = $column;
  128. }
  129. else
  130. {
  131. $config['where'] = array(array($column, $operator, $value));
  132. }
  133. }
  134. return static::find($config);
  135. }
  136. /**
  137. * Finds all records in the table. Optionally limited and offset.
  138. *
  139. * @param int $limit Number of records to return
  140. * @param int $offset What record to start at
  141. * @return null|object Null if not found or an array of Model object
  142. */
  143. public static function find_all($limit = null, $offset = 0)
  144. {
  145. return static::find(array(
  146. 'limit' => $limit,
  147. 'offset' => $offset,
  148. ));
  149. }
  150. /**
  151. * Finds all records.
  152. *
  153. * @param array $config array containing query settings
  154. * @param string $key optional array index key
  155. * @return array|null an array containing models or null if none are found
  156. */
  157. public static function find($config = array(), $key = null)
  158. {
  159. $query = \DB::select()
  160. ->from(static::$_table_name)
  161. ->as_object(get_called_class());
  162. if ($config instanceof \Closure)
  163. {
  164. $config($query);
  165. }
  166. else
  167. {
  168. $config = $config + array(
  169. 'select' => array(static::$_table_name.'.*'),
  170. 'where' => array(),
  171. 'order_by' => array(),
  172. 'limit' => null,
  173. 'offset' => 0,
  174. );
  175. extract($config);
  176. is_string($select) and $select = array($select);
  177. $query->select_array($select);
  178. if ( ! empty($where))
  179. {
  180. $query->where($where);
  181. }
  182. if (is_array($order_by))
  183. {
  184. foreach ($order_by as $_field => $_direction)
  185. {
  186. $query->order_by($_field, $_direction);
  187. }
  188. }
  189. else
  190. {
  191. $query->order_by($order_by);
  192. }
  193. if ($limit !== null)
  194. {
  195. $query = $query->limit($limit)->offset($offset);
  196. }
  197. }
  198. static::pre_find($query);
  199. $result = $query->execute(static::get_connection());
  200. $result = ($result->count() === 0) ? null : $result->as_array($key);
  201. return static::post_find($result);
  202. }
  203. /**
  204. * Count all of the rows in the table.
  205. *
  206. * @param string Column to count by
  207. * @param bool Whether to count only distinct rows (by column)
  208. * @param array Query where clause(s)
  209. * @param string Column to group by
  210. * @return int The number of rows OR false
  211. */
  212. public static function count($column = null, $distinct = true, $where = array(), $group_by = null)
  213. {
  214. $select = $column ?: static::primary_key();
  215. // Get the database group / connection
  216. $connection = static::get_connection();
  217. // Get the columns
  218. $columns = \DB::expr('COUNT('.($distinct ? 'DISTINCT ' : '').
  219. \Database_Connection::instance($connection)->quote_identifier($select).
  220. ') AS count_result');
  221. // Remove the current select and
  222. $query = \DB::select($columns);
  223. // Set from table
  224. $query = $query->from(static::$_table_name);
  225. if ( ! empty($where))
  226. {
  227. //is_array($where) or $where = array($where);
  228. if ( ! is_array($where) and ($where instanceof \Closure) === false)
  229. {
  230. throw new \FuelException(get_called_class().'::count where statement must be an array or a closure.');
  231. }
  232. $query = $query->where($where);
  233. }
  234. if ( ! empty($group_by))
  235. {
  236. $result = $query->select($group_by)->group_by($group_by)->execute($connection)->as_array();
  237. $counts = array();
  238. foreach ($result as $res)
  239. {
  240. $counts[$res[$group_by]] = $res['count_result'];
  241. }
  242. return $counts;
  243. }
  244. $count = $query->execute($connection)->get('count_result');
  245. if ($count === null)
  246. {
  247. return false;
  248. }
  249. return (int) $count;
  250. }
  251. /**
  252. * Implements dynamic Model_Crud::find_by_{column} and Model_Crud::find_one_by_{column}
  253. * methods.
  254. *
  255. * @param string $name The method name
  256. * @param string $args The method args
  257. * @return mixed Based on static::$return_type
  258. * @throws BadMethodCallException
  259. */
  260. public static function __callStatic($name, $args)
  261. {
  262. if (strncmp($name, 'find_by_', 8) === 0)
  263. {
  264. return static::find_by(substr($name, 8), reset($args));
  265. }
  266. elseif (strncmp($name, 'find_one_by_', 12) === 0)
  267. {
  268. return static::find_one_by(substr($name, 12), reset($args));
  269. }
  270. throw new \BadMethodCallException('Method "'.$name.'" does not exist.');
  271. }
  272. /**
  273. * Get the connection to use for reading or writing
  274. *
  275. * @param boolean $writeable Get a writeable connection
  276. * @return Database_Connection
  277. */
  278. protected static function get_connection($writeable = false)
  279. {
  280. if ($writeable and isset(static::$_write_connection))
  281. {
  282. return static::$_write_connection;
  283. }
  284. return isset(static::$_connection) ? static::$_connection : null;
  285. }
  286. /**
  287. * Get the primary key for the current Model
  288. *
  289. * @return string
  290. */
  291. protected static function primary_key()
  292. {
  293. return isset(static::$_primary_key) ? static::$_primary_key : 'id';
  294. }
  295. /**
  296. * Gets called before the query is executed. Must return the query object.
  297. *
  298. * @param Database_Query $query The query object
  299. * @return void
  300. */
  301. protected static function pre_find(&$query){}
  302. /**
  303. * Gets called after the query is executed and right before it is returned.
  304. * $result will be null if 0 rows are returned.
  305. *
  306. * @param array|null $result the result array or null when there was no result
  307. * @return array|null
  308. */
  309. protected static function post_find($result)
  310. {
  311. return $result;
  312. }
  313. /**
  314. * @var bool $_is_new If this is a new record
  315. */
  316. protected $_is_new = true;
  317. /**
  318. * @var bool $_is_frozen If this is a record is frozen
  319. */
  320. protected $_is_frozen = false;
  321. /**
  322. * @var object $_validation The validation instance
  323. */
  324. protected $_validation = null;
  325. /**
  326. * Sets up the object.
  327. *
  328. * @param array $data The data array
  329. * @return void
  330. */
  331. public function __construct(array $data = array())
  332. {
  333. if (isset($this->{static::primary_key()}))
  334. {
  335. $this->is_new(false);
  336. }
  337. if ( ! empty($data))
  338. {
  339. foreach ($data as $key => $value)
  340. {
  341. $this->{$key} = $value;
  342. }
  343. }
  344. }
  345. /**
  346. * Magic setter so new objects can be assigned values
  347. *
  348. * @param string $property The property name
  349. * @param mixed $value The property value
  350. * @return void
  351. */
  352. public function __set($property, $value)
  353. {
  354. $this->{$property} = $value;
  355. }
  356. /**
  357. * Sets an array of values to class properties
  358. *
  359. * @param array $data The data
  360. * @return $this
  361. */
  362. public function set(array $data)
  363. {
  364. foreach ($data as $key => $value)
  365. {
  366. $this->{$key} = $value;
  367. }
  368. return $this;
  369. }
  370. /**
  371. * Saves the object to the database by either creating a new record
  372. * or updating an existing record. Sets the default values if set.
  373. *
  374. * @param bool $validate wether to validate the input
  375. * @return mixed Rows affected and or insert ID
  376. */
  377. public function save($validate = true)
  378. {
  379. if ($this->frozen())
  380. {
  381. throw new \Exception('Cannot modify a frozen row.');
  382. }
  383. $vars = $this->to_array();
  384. // Set default if there are any
  385. isset(static::$_defaults) and $vars = $vars + static::$_defaults;
  386. if ($validate and isset(static::$_rules) and ! empty(static::$_rules))
  387. {
  388. $vars = $this->pre_validate($vars);
  389. $validated = $this->post_validate($this->run_validation($vars));
  390. if ($validated)
  391. {
  392. $validated = array_filter($this->validation()->validated(), function($val){
  393. return ($val !== null);
  394. });
  395. $vars = $validated + $vars;
  396. }
  397. else
  398. {
  399. return false;
  400. }
  401. }
  402. $vars = $this->prep_values($vars);
  403. if (isset(static::$_properties))
  404. {
  405. $vars = \Arr::filter_keys($vars, static::$_properties);
  406. }
  407. if(isset(static::$_updated_at))
  408. {
  409. if(isset(static::$_mysql_timestamp) and static::$_mysql_timestamp === true)
  410. {
  411. $vars[static::$_updated_at] = \Date::forge()->format('mysql');
  412. }
  413. else
  414. {
  415. $vars[static::$_updated_at] = \Date::forge()->get_timestamp();
  416. }
  417. }
  418. if ($this->is_new())
  419. {
  420. if(isset(static::$_created_at))
  421. {
  422. if(isset(static::$_mysql_timestamp) and static::$_mysql_timestamp === true)
  423. {
  424. $vars[static::$_created_at] = \Date::forge()->format('mysql');
  425. }
  426. else
  427. {
  428. $vars[static::$_created_at] = \Date::forge()->get_timestamp();
  429. }
  430. }
  431. $query = \DB::insert(static::$_table_name)
  432. ->set($vars);
  433. $this->pre_save($query);
  434. $result = $query->execute(static::get_connection(true));
  435. if ($result[1] > 0)
  436. {
  437. // workaround for PDO connections not returning the insert_id
  438. if ($result[0] === false and isset($vars[static::primary_key()]))
  439. {
  440. $result[0] = $vars[static::primary_key()];
  441. }
  442. $this->set($vars);
  443. empty($result[0]) or $this->{static::primary_key()} = $result[0];
  444. $this->is_new(false);
  445. }
  446. return $this->post_save($result);
  447. }
  448. $query = \DB::update(static::$_table_name)
  449. ->set($vars)
  450. ->where(static::primary_key(), '=', $this->{static::primary_key()});
  451. $this->pre_update($query);
  452. $result = $query->execute(static::get_connection(true));
  453. $result > 0 and $this->set($vars);
  454. return $this->post_update($result);
  455. }
  456. /**
  457. * Deletes this record and freezes the object
  458. *
  459. * @return mixed Rows affected
  460. */
  461. public function delete()
  462. {
  463. $this->frozen(true);
  464. $query = \DB::delete(static::$_table_name)
  465. ->where(static::primary_key(), '=', $this->{static::primary_key()});
  466. $this->pre_delete($query);
  467. $result = $query->execute(static::get_connection(true));
  468. return $this->post_delete($result);
  469. }
  470. /**
  471. * Either checks if the record is new or sets whether it is new or not.
  472. *
  473. * @param bool|null $new Whether this is a new record
  474. * @return bool|$this
  475. */
  476. public function is_new($new = null)
  477. {
  478. if ($new === null)
  479. {
  480. return $this->_is_new;
  481. }
  482. $this->_is_new = (bool) $new;
  483. return $this;
  484. }
  485. /**
  486. * Either checks if the record is frozen or sets whether it is frozen or not.
  487. *
  488. * @param bool|null $new Whether this is a frozen record
  489. * @return bool|$this
  490. */
  491. public function frozen($frozen = null)
  492. {
  493. if ($frozen === null)
  494. {
  495. return $this->_is_frozen;
  496. }
  497. $this->_is_frozen = (bool) $frozen;
  498. return $this;
  499. }
  500. /**
  501. * Returns the a validation object for the model.
  502. *
  503. * @return object Validation object
  504. */
  505. public function validation()
  506. {
  507. if( ! $this->_validation)
  508. {
  509. $this->_validation = \Validation::forge(\Str::random('alnum', 32));
  510. if (isset(static::$_rules) and count(static::$_rules))
  511. {
  512. foreach (static::$_rules as $field => $rules)
  513. {
  514. $label = (isset(static::$_labels) and array_key_exists($field, static::$_labels)) ? static::$_labels[$field] : $field;
  515. $this->_validation->add_field($field, $label, $rules);
  516. }
  517. }
  518. }
  519. return $this->_validation;
  520. }
  521. /**
  522. * Returns all of $this object's public properties as an associative array.
  523. *
  524. * @return array
  525. */
  526. public function to_array()
  527. {
  528. return get_object_public_vars($this);
  529. }
  530. /**
  531. * Implementation of the Iterator interface
  532. */
  533. protected $_iterable = array();
  534. public function rewind()
  535. {
  536. $this->_iterable = $this->to_array();
  537. reset($this->_iterable);
  538. }
  539. public function current()
  540. {
  541. return current($this->_iterable);
  542. }
  543. public function key()
  544. {
  545. return key($this->_iterable);
  546. }
  547. public function next()
  548. {
  549. return next($this->_iterable);
  550. }
  551. public function valid()
  552. {
  553. return key($this->_iterable) !== null;
  554. }
  555. /**
  556. * Sets the value of the given offset (class property).
  557. *
  558. * @param string $offset class property
  559. * @param string $value value
  560. * @return void
  561. */
  562. public function offsetSet($offset, $value)
  563. {
  564. $this->{$offset} = $value;
  565. }
  566. /**
  567. * Checks if the given offset (class property) exists.
  568. *
  569. * @param string $offset class property
  570. * @return bool
  571. */
  572. public function offsetExists($offset)
  573. {
  574. return property_exists($this, $offset);
  575. }
  576. /**
  577. * Unsets the given offset (class property).
  578. *
  579. * @param string $offset class property
  580. * @return void
  581. */
  582. public function offsetUnset($offset)
  583. {
  584. unset($this->{$offset});
  585. }
  586. /**
  587. * Gets the value of the given offset (class property).
  588. *
  589. * @param string $offset class property
  590. * @return mixed
  591. */
  592. public function offsetGet($offset)
  593. {
  594. if (property_exists($this, $offset))
  595. {
  596. return $this->{$offset};
  597. }
  598. throw new \OutOfBoundsException('Property "'.$offset.'" not found for '.get_called_class().'.');
  599. }
  600. /**
  601. * Returns wether the instance will pass validation.
  602. *
  603. * @return bool wether the instance passed validation
  604. */
  605. public function validates()
  606. {
  607. if ( ! isset(static::$_rules) or count(static::$_rules) < 0)
  608. {
  609. return true;
  610. }
  611. $vars = $this->to_array();
  612. // Set default if there are any
  613. isset(static::$_defaults) and $vars = $vars + static::$_defaults;
  614. $vars = $this->pre_validate($vars);
  615. return $this->run_validation($vars);
  616. }
  617. /**
  618. * Run validation
  619. *
  620. * @param array $vars array to validate
  621. * @return bool validation result
  622. */
  623. protected function run_validation($vars)
  624. {
  625. if ( ! isset(static::$_rules) or count(static::$_rules) < 0)
  626. {
  627. return true;
  628. }
  629. $this->_validation = $this->validation();
  630. return $this->_validation->run($vars);
  631. }
  632. /**
  633. * Gets called before the insert query is executed. Must return
  634. * the query object.
  635. *
  636. * @param Database_Query $query The query object
  637. * @return void
  638. */
  639. protected function pre_save(&$query){}
  640. /**
  641. * Gets called after the insert query is executed and right before
  642. * it is returned.
  643. *
  644. * @param array $result insert id and number of affected rows
  645. * @return array
  646. */
  647. protected function post_save($result)
  648. {
  649. return $result;
  650. }
  651. /**
  652. * Gets called before the update query is executed. Must return the query object.
  653. *
  654. * @param Database_Query $query The query object
  655. * @return void
  656. */
  657. protected function pre_update(&$query){}
  658. /**
  659. * Gets called after the update query is executed and right before
  660. * it is returned.
  661. *
  662. * @param int $result Number of affected rows
  663. * @return int
  664. */
  665. protected function post_update($result)
  666. {
  667. return $result;
  668. }
  669. /**
  670. * Gets called before the delete query is executed. Must return the query object.
  671. *
  672. * @param Database_Query $query The query object
  673. * @return void
  674. */
  675. protected function pre_delete(&$query){}
  676. /**
  677. * Gets called after the delete query is executed and right before
  678. * it is returned.
  679. *
  680. * @param int $result Number of affected rows
  681. * @return int
  682. */
  683. protected function post_delete($result)
  684. {
  685. return $result;
  686. }
  687. /**
  688. * Gets called before the validation is ran.
  689. *
  690. * @param array $data The validation data
  691. * @return array
  692. */
  693. protected function pre_validate($data)
  694. {
  695. return $data;
  696. }
  697. /**
  698. * Called right after the validation is ran.
  699. *
  700. * @param bool $result Validation result
  701. * @return bool
  702. */
  703. protected function post_validate($result)
  704. {
  705. return $result;
  706. }
  707. /**
  708. * Called right after values retrieval, before save,
  709. * update, setting defaults and validation.
  710. *
  711. * @param array $values input array
  712. * @return array
  713. */
  714. protected function prep_values($values)
  715. {
  716. return $values;
  717. }
  718. /**
  719. * Serializable implementation: serialize
  720. *
  721. * @return array model data
  722. */
  723. public function serialize()
  724. {
  725. $data = $this->to_array();
  726. $data['_is_new'] = $this->_is_new;
  727. $data['_is_frozen'] = $this->_is_frozen;
  728. return serialize($data);
  729. }
  730. /**
  731. * Serializable implementation: unserialize
  732. *
  733. * @return array model data
  734. */
  735. public function unserialize($data)
  736. {
  737. $data = unserialize($data);
  738. foreach ($data as $key => $value)
  739. {
  740. $this->__set($key, $value);
  741. }
  742. }
  743. }