paulgoughbooks_old
This repository has no backups
This repository's network speed is throttled to 100KB/sec
Upgrade your account to fix these warnings, or use backups.vc for automated backups
@ 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 |
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014-2019 British Columbia Institute of Technology * Copyright (c) 2019-2020 CodeIgniter Foundation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author CodeIgniter Dev Team * @copyright 2019-2020 CodeIgniter Foundation * @license https://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 4.0.0 * @filesource */ namespace CodeIgniter; use Closure; use CodeIgniter\Database\BaseBuilder; use CodeIgniter\Database\BaseConnection; use CodeIgniter\Database\BaseResult; use CodeIgniter\Database\ConnectionInterface; use CodeIgniter\Database\Exceptions\DatabaseException; use CodeIgniter\Database\Exceptions\DataException; use CodeIgniter\Exceptions\ModelException; use CodeIgniter\I18n\Time; use CodeIgniter\Pager\Pager; use CodeIgniter\Validation\ValidationInterface; use Config\Database; use ReflectionClass; use ReflectionProperty; use stdClass; /** * Class Model * * The Model class provides a number of convenient features that * makes working with a database table less painful. * * It will: * - automatically connect to database * - allow intermingling calls between db connection, the builder, * and methods in this class. * - simplifies pagination * - removes the need to use Result object directly in most cases * - allow specifying the return type (array, object, etc) with each call * - ensure validation is run against objects when saving items * * @package CodeIgniter * @mixin BaseBuilder */ class Model { /** * Pager instance. * Populated after calling $this->paginate() * * @var Pager */ public $pager; /** * Name of database table * * @var string */ protected $table; /** * The table's primary key. * * @var string */ protected $primaryKey = 'id'; /** * Last insert ID * * @var integer */ protected $insertID = 0; /** * The Database connection group that * should be instantiated. * * @var string */ protected $DBGroup; /** * The format that the results should be returned as. * Will be overridden if the as* methods are used. * * @var string */ protected $returnType = 'array'; /** * If this model should use "softDeletes" and * simply set a date when rows are deleted, or * do hard deletes. * * @var boolean */ protected $useSoftDeletes = false; /** * An array of field names that are allowed * to be set by the user in inserts/updates. * * @var array */ protected $allowedFields = []; /** * If true, will set created_at, and updated_at * values during insert and update routines. * * @var boolean */ protected $useTimestamps = false; /** * The type of column that created_at and updated_at * are expected to. * * Allowed: 'datetime', 'date', 'int' * * @var string */ protected $dateFormat = 'datetime'; //-------------------------------------------------------------------- /** * The column used for insert timestamps * * @var string */ protected $createdField = 'created_at'; /** * The column used for update timestamps * * @var string */ protected $updatedField = 'updated_at'; /** * Used by withDeleted to override the * model's softDelete setting. * * @var boolean */ protected $tempUseSoftDeletes; /** * The column used to save soft delete state * * @var string */ protected $deletedField = 'deleted_at'; /** * Used by asArray and asObject to provide * temporary overrides of model default. * * @var string */ protected $tempReturnType; /** * Whether we should limit fields in inserts * and updates to those available in $allowedFields or not. * * @var boolean */ protected $protectFields = true; /** * Database Connection * * @var ConnectionInterface */ protected $db; /** * Query Builder object * * @var BaseBuilder */ protected $builder; /** * Rules used to validate data in insert, update, and save methods. * The array must match the format of data passed to the Validation * library. * * @var array */ protected $validationRules = []; /** * Contains any custom error messages to be * used during data validation. * * @var array */ protected $validationMessages = []; /** * Skip the model's validation. Used in conjunction with skipValidation() * to skip data validation for any future calls. * * @var boolean */ protected $skipValidation = false; /** * Whether rules should be removed that do not exist * in the passed in data. Used between inserts/updates. * * @var boolean */ protected $cleanValidationRules = true; /** * Our validator instance. * * @var \CodeIgniter\Validation\Validation */ protected $validation; /* * Callbacks. Each array should contain the method * names (within the model) that should be called * when those events are triggered. With the exception * of 'afterFind', all methods are passed the same * items that are given to the update/insert method. * 'afterFind' will also include the results that were found. */ /** * Whether to trigger the defined callbacks * * @var boolean */ protected $allowCallbacks = true; /** * Used by allowCallbacks() to override the * model's allowCallbacks setting. * * @var boolean */ protected $tempAllowCallbacks; /** * Callbacks for beforeInsert * * @var array */ protected $beforeInsert = []; /** * Callbacks for afterInsert * * @var array */ protected $afterInsert = []; /** * Callbacks for beforeUpdate * * @var array */ protected $beforeUpdate = []; /** * Callbacks for afterUpdate * * @var array */ protected $afterUpdate = []; /** * Callbacks for afterFind * * @var array */ protected $afterFind = []; /** * Callbacks for beforeDelete * * @var array */ protected $beforeDelete = []; /** * Callbacks for afterDelete * * @var array */ protected $afterDelete = []; /** * Holds information passed in via 'set' * so that we can capture it (not the builder) * and ensure it gets validated first. * * @var array */ protected $tempData = []; //-------------------------------------------------------------------- /** * Model constructor. * * @param ConnectionInterface $db * @param ValidationInterface $validation */ public function __construct(ConnectionInterface &$db = null, ValidationInterface $validation = null) { if ($db instanceof ConnectionInterface) { $this->db = & $db; } else { $this->db = Database::connect($this->DBGroup); } $this->tempReturnType = $this->returnType; $this->tempUseSoftDeletes = $this->useSoftDeletes; $this->tempAllowCallbacks = $this->allowCallbacks; if (is_null($validation)) { $validation = \Config\Services::validation(null, false); } $this->validation = $validation; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // CRUD & FINDERS //-------------------------------------------------------------------- /** * Fetches the row of database from $this->table with a primary key * matching $id. * * @param mixed|array|null $id One primary key or an array of primary keys * * @return array|object|null The resulting row of data, or null. */ public function find($id = null) { $builder = $this->builder(); if ($this->tempUseSoftDeletes === true) { $builder->where($this->table . '.' . $this->deletedField, null); } if (is_array($id)) { $row = $builder->whereIn($this->table . '.' . $this->primaryKey, $id) ->get(); $row = $row->getResult($this->tempReturnType); } elseif (is_numeric($id) || is_string($id)) { $row = $builder->where($this->table . '.' . $this->primaryKey, $id) ->get(); $row = $row->getFirstRow($this->tempReturnType); } else { $row = $builder->get(); $row = $row->getResult($this->tempReturnType); } $eventData = $this->trigger('afterFind', ['id' => $id, 'data' => $row]); $this->tempReturnType = $this->returnType; $this->tempUseSoftDeletes = $this->useSoftDeletes; return $eventData['data']; } //-------------------------------------------------------------------- /** * Fetches the column of database from $this->table * * @param string $columnName * * @return array|null The resulting row of data, or null if no data found. * @throws \CodeIgniter\Database\Exceptions\DataException */ public function findColumn(string $columnName) { if (strpos($columnName, ',') !== false) { throw DataException::forFindColumnHaveMultipleColumns(); } $resultSet = $this->select($columnName) ->asArray() ->find(); return (! empty($resultSet)) ? array_column($resultSet, $columnName) : null; } //-------------------------------------------------------------------- /** * Works with the current Query Builder instance to return * all results, while optionally limiting them. * * @param integer $limit * @param integer $offset * * @return array */ public function findAll(int $limit = 0, int $offset = 0) { $builder = $this->builder(); if ($this->tempUseSoftDeletes === true) { $builder->where($this->table . '.' . $this->deletedField, null); } $row = $builder->limit($limit, $offset) ->get(); $row = $row->getResult($this->tempReturnType); $eventData = $this->trigger('afterFind', ['data' => $row, 'limit' => $limit, 'offset' => $offset]); $this->tempReturnType = $this->returnType; $this->tempUseSoftDeletes = $this->useSoftDeletes; return $eventData['data']; } //-------------------------------------------------------------------- /** * Returns the first row of the result set. Will take any previous * Query Builder calls into account when determining the result set. * * @return array|object|null */ public function first() { $builder = $this->builder(); if ($this->tempUseSoftDeletes === true) { $builder->where($this->table . '.' . $this->deletedField, null); } else { if ($this->useSoftDeletes === true && empty($builder->QBGroupBy) && ! empty($this->primaryKey)) { $builder->groupBy($this->table . '.' . $this->primaryKey); } } // Some databases, like PostgreSQL, need order // information to consistently return correct results. if (! empty($builder->QBGroupBy) && empty($builder->QBOrderBy) && ! empty($this->primaryKey)) { $builder->orderBy($this->table . '.' . $this->primaryKey, 'asc'); } $row = $builder->limit(1, 0) ->get(); $row = $row->getFirstRow($this->tempReturnType); $eventData = $this->trigger('afterFind', ['data' => $row]); $this->tempReturnType = $this->returnType; $this->tempUseSoftDeletes = $this->useSoftDeletes; return $eventData['data']; } //-------------------------------------------------------------------- /** * Captures the builder's set() method so that we can validate the * data here. This allows it to be used with any of the other * builder methods and still get validated data, like replace. * * @param mixed $key Field name, or an array of field/value pairs * @param string $value Field value, if $key is a single field * @param boolean $escape Whether to escape values and identifiers * * @return $this */ public function set($key, ?string $value = '', bool $escape = null) { $data = is_array($key) ? $key : [$key => $value]; $this->tempData['escape'] = $escape; $this->tempData['data'] = array_merge($this->tempData['data'] ?? [], $data); return $this; } //-------------------------------------------------------------------- /** * A convenience method that will attempt to determine whether the * data should be inserted or updated. Will work with either * an array or object. When using with custom class objects, * you must ensure that the class will provide access to the class * variables, even if through a magic method. * * @param array|object $data * * @return boolean * @throws \ReflectionException */ public function save($data): bool { if (empty($data)) { return true; } if (is_object($data) && isset($data->{$this->primaryKey})) { $response = $this->update($data->{$this->primaryKey}, $data); } elseif (is_array($data) && ! empty($data[$this->primaryKey])) { $response = $this->update($data[$this->primaryKey], $data); } else { $response = $this->insert($data, false); if ($response instanceof BaseResult) { $response = $response->resultID !== false; } elseif ($response !== false) { $response = true; } } return $response; } /** * Takes a class an returns an array of it's public and protected * properties as an array suitable for use in creates and updates. * * @param string|object $data * @param string|null $primaryKey * @param string $dateFormat * @param boolean $onlyChanged * * @return array * @throws \ReflectionException */ public static function classToArray($data, $primaryKey = null, string $dateFormat = 'datetime', bool $onlyChanged = true): array { if (method_exists($data, 'toRawArray')) { $properties = $data->toRawArray($onlyChanged); // Always grab the primary key otherwise updates will fail. if (! empty($properties) && ! empty($primaryKey) && ! in_array($primaryKey, $properties) && ! empty($data->{$primaryKey})) { $properties[$primaryKey] = $data->{$primaryKey}; } } else { $mirror = new ReflectionClass($data); $props = $mirror->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED); $properties = []; // Loop over each property, // saving the name/value in a new array we can return. foreach ($props as $prop) { // Must make protected values accessible. $prop->setAccessible(true); $propName = $prop->getName(); $properties[$propName] = $prop->getValue($data); } } // Convert any Time instances to appropriate $dateFormat if ($properties) { foreach ($properties as $key => $value) { if ($value instanceof Time) { switch ($dateFormat) { case 'datetime': $converted = $value->format('Y-m-d H:i:s'); break; case 'date': $converted = $value->format('Y-m-d'); break; case 'int': $converted = $value->getTimestamp(); break; default: $converted = (string)$value; } $properties[$key] = $converted; } } } return $properties; } //-------------------------------------------------------------------- /** * Returns last insert ID or 0. * * @return integer */ public function getInsertID(): int { return $this->insertID; } //-------------------------------------------------------------------- /** * Inserts data into the current table. If an object is provided, * it will attempt to convert it to an array. * * @param array|object $data * @param boolean $returnID Whether insert ID should be returned or not. * * @return BaseResult|integer|string|false * @throws \ReflectionException */ public function insert($data = null, bool $returnID = true) { $escape = null; $this->insertID = 0; if (empty($data)) { $data = $this->tempData['data'] ?? null; $escape = $this->tempData['escape'] ?? null; $this->tempData = []; } if (empty($data)) { throw DataException::forEmptyDataset('insert'); } // If $data is using a custom class with public or protected // properties representing the table elements, we need to grab // them as an array. if (is_object($data) && ! $data instanceof stdClass) { $data = static::classToArray($data, $this->primaryKey, $this->dateFormat, false); } // If it's still a stdClass, go ahead and convert to // an array so doProtectFields and other model methods // don't have to do special checks. if (is_object($data)) { $data = (array) $data; } if (empty($data)) { throw DataException::forEmptyDataset('insert'); } // Validate data before saving. if ($this->skipValidation === false) { if ($this->cleanRules()->validate($data) === false) { return false; } } // Must be called first so we don't // strip out created_at values. $data = $this->doProtectFields($data); // Set created_at and updated_at with same time $date = $this->setDate(); if ($this->useTimestamps && ! empty($this->createdField) && ! array_key_exists($this->createdField, $data)) { $data[$this->createdField] = $date; } if ($this->useTimestamps && ! empty($this->updatedField) && ! array_key_exists($this->updatedField, $data)) { $data[$this->updatedField] = $date; } $eventData = $this->trigger('beforeInsert', ['data' => $data]); // Must use the set() method to ensure objects get converted to arrays $result = $this->builder() ->set($eventData['data'], '', $escape) ->insert(); // If insertion succeeded then save the insert ID if ($result->resultID) { $this->insertID = $this->db->insertID(); } // Trigger afterInsert events with the inserted data and new ID $this->trigger('afterInsert', ['id' => $this->insertID, 'data' => $eventData['data'], 'result' => $result]); // If insertion failed, get out of here if (! $result) { return $result; } // otherwise return the insertID, if requested. return $returnID ? $this->insertID : $result; } //-------------------------------------------------------------------- /** * Compiles batch insert strings and runs the queries, validating each row prior. * * @param array $set An associative array of insert values * @param boolean $escape Whether to escape values and identifiers * @param integer $batchSize The size of the batch to run * @param boolean $testing True means only number of records is returned, false will execute the query * * @return integer|boolean Number of rows inserted or FALSE on failure */ public function insertBatch(array $set = null, bool $escape = null, int $batchSize = 100, bool $testing = false) { if (is_array($set) && $this->skipValidation === false) { foreach ($set as $row) { if ($this->cleanRules()->validate($row) === false) { return false; } } } return $this->builder()->testMode($testing)->insertBatch($set, $escape, $batchSize); } //-------------------------------------------------------------------- /** * Updates a single record in $this->table. If an object is provided, * it will attempt to convert it into an array. * * @param integer|array|string $id * @param array|object $data * * @return boolean * @throws \ReflectionException */ public function update($id = null, $data = null): bool { $escape = null; if (is_numeric($id) || is_string($id)) { $id = [$id]; } if (empty($data)) { $data = $this->tempData['data'] ?? null; $escape = $this->tempData['escape'] ?? null; $this->tempData = []; } if (empty($data)) { throw DataException::forEmptyDataset('update'); } // If $data is using a custom class with public or protected // properties representing the table elements, we need to grab // them as an array. if (is_object($data) && ! $data instanceof stdClass) { $data = static::classToArray($data, $this->primaryKey, $this->dateFormat); } // If it's still a stdClass, go ahead and convert to // an array so doProtectFields and other model methods // don't have to do special checks. if (is_object($data)) { $data = (array) $data; } // If it's still empty here, means $data is no change or is empty object if (empty($data)) { throw DataException::forEmptyDataset('update'); } // Validate data before saving. if ($this->skipValidation === false) { if ($this->cleanRules(true)->validate($data) === false) { return false; } } // Must be called first so we don't // strip out updated_at values. $data = $this->doProtectFields($data); if ($this->useTimestamps && ! empty($this->updatedField) && ! array_key_exists($this->updatedField, $data)) { $data[$this->updatedField] = $this->setDate(); } $eventData = $this->trigger('beforeUpdate', ['id' => $id, 'data' => $data]); $builder = $this->builder(); if ($id) { $builder = $builder->whereIn($this->table . '.' . $this->primaryKey, $id); } // Must use the set() method to ensure objects get converted to arrays $result = $builder ->set($eventData['data'], '', $escape) ->update(); $this->trigger('afterUpdate', ['id' => $id, 'data' => $eventData['data'], 'result' => $result]); return $result; } //-------------------------------------------------------------------- /** * Update_Batch * * Compiles an update string and runs the query * * @param array $set An associative array of update values * @param string $index The where key * @param integer $batchSize The size of the batch to run * @param boolean $returnSQL True means SQL is returned, false will execute the query * * @return mixed Number of rows affected or FALSE on failure * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function updateBatch(array $set = null, string $index = null, int $batchSize = 100, bool $returnSQL = false) { if (is_array($set) && $this->skipValidation === false) { foreach ($set as $row) { if ($this->cleanRules(true)->validate($row) === false) { return false; } } } return $this->builder()->testMode($returnSQL)->updateBatch($set, $index, $batchSize); } //-------------------------------------------------------------------- /** * Deletes a single record from $this->table where $id matches * the table's primaryKey * * @param integer|string|array|null $id The rows primary key(s) * @param boolean $purge Allows overriding the soft deletes setting. * * @return BaseResult|boolean * @throws \CodeIgniter\Database\Exceptions\DatabaseException */ public function delete($id = null, bool $purge = false) { if (! empty($id) && (is_numeric($id) || is_string($id))) { $id = [$id]; } $builder = $this->builder(); if (! empty($id)) { $builder = $builder->whereIn($this->primaryKey, $id); } $this->trigger('beforeDelete', ['id' => $id, 'purge' => $purge]); if ($this->useSoftDeletes && ! $purge) { if (empty($builder->getCompiledQBWhere())) { if (CI_DEBUG) { throw new DatabaseException('Deletes are not allowed unless they contain a "where" or "like" clause.'); } // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } $set[$this->deletedField] = $this->setDate(); if ($this->useTimestamps && ! empty($this->updatedField)) { $set[$this->updatedField] = $this->setDate(); } $result = $builder->update($set); } else { $result = $builder->delete(); } $this->trigger('afterDelete', ['id' => $id, 'purge' => $purge, 'result' => $result, 'data' => null]); return $result; } //-------------------------------------------------------------------- /** * Permanently deletes all rows that have been marked as deleted * through soft deletes (deleted = 1) * * @return boolean|mixed */ public function purgeDeleted() { if (! $this->useSoftDeletes) { return true; } return $this->builder() ->where($this->table . '.' . $this->deletedField . ' IS NOT NULL') ->delete(); } //-------------------------------------------------------------------- /** * Sets $useSoftDeletes value so that we can temporarily override * the softdeletes settings. Can be used for all find* methods. * * @param boolean $val * * @return Model */ public function withDeleted($val = true) { $this->tempUseSoftDeletes = ! $val; return $this; } //-------------------------------------------------------------------- /** * Works with the find* methods to return only the rows that * have been deleted. * * @return Model */ public function onlyDeleted() { $this->tempUseSoftDeletes = false; $this->builder() ->where($this->table . '.' . $this->deletedField . ' IS NOT NULL'); return $this; } //-------------------------------------------------------------------- /** * Replace * * Compiles an replace into string and runs the query * * @param null $data * @param boolean $returnSQL * * @return mixed */ public function replace($data = null, bool $returnSQL = false) { // Validate data before saving. if (! empty($data) && $this->skipValidation === false) { if ($this->cleanRules(true)->validate($data) === false) { return false; } } return $this->builder()->replace($data, $returnSQL); } //-------------------------------------------------------------------- // Utility //-------------------------------------------------------------------- /** * Sets the return type of the results to be as an associative array. * * @return Model */ public function asArray() { $this->tempReturnType = 'array'; return $this; } //-------------------------------------------------------------------- /** * Sets the return type to be of the specified type of object. * Defaults to a simple object, but can be any class that has * class vars with the same name as the table columns, or at least * allows them to be created. * * @param string $class * * @return Model */ public function asObject(string $class = 'object') { $this->tempReturnType = $class; return $this; } //-------------------------------------------------------------------- /** * Loops over records in batches, allowing you to operate on them. * Works with $this->builder to get the Compiled select to * determine the rows to operate on. * * @param integer $size * @param \Closure $userFunc * * @throws \CodeIgniter\Database\Exceptions\DataException */ public function chunk(int $size, Closure $userFunc) { $total = $this->builder() ->countAllResults(false); $offset = 0; while ($offset <= $total) { $builder = clone($this->builder()); $rows = $builder->get($size, $offset); if ($rows === false) { throw DataException::forEmptyDataset('chunk'); } $rows = $rows->getResult($this->tempReturnType); $offset += $size; if (empty($rows)) { continue; } foreach ($rows as $row) { if ($userFunc($row) === false) { return; } } } } //-------------------------------------------------------------------- /** * Works with $this->builder to get the Compiled Select to operate on. * Expects a GET variable (?page=2) that specifies the page of results * to display. * * @param integer $perPage * @param string $group Will be used by the pagination library * to identify a unique pagination set. * @param integer $page Optional page number (useful when the page number is provided in different way) * @param integer $segment Optional URI segment number (if page number is provided by URI segment) * * @return array|null */ public function paginate(int $perPage = null, string $group = 'default', int $page = null, int $segment = 0) { $pager = \Config\Services::pager(null, null, false); if ($segment) { $pager->setSegment($segment); } $page = $page >= 1 ? $page : $pager->getCurrentPage($group); $total = $this->countAllResults(false); // Store it in the Pager library so it can be // paginated in the views. $this->pager = $pager->store($group, $page, $perPage, $total, $segment); $perPage = $this->pager->getPerPage($group); $offset = ($page - 1) * $perPage; return $this->findAll($perPage, $offset); } //-------------------------------------------------------------------- /** * Sets whether or not we should whitelist data set during * updates or inserts against $this->availableFields. * * @param boolean $protect * * @return Model */ public function protect(bool $protect = true) { $this->protectFields = $protect; return $this; } //-------------------------------------------------------------------- /** * Provides a shared instance of the Query Builder. * * @param string $table * * @return BaseBuilder * @throws \CodeIgniter\Exceptions\ModelException; */ protected function builder(string $table = null) { if ($this->builder instanceof BaseBuilder) { return $this->builder; } // We're going to force a primary key to exist // so we don't have overly convoluted code, // and future features are likely to require them. if (empty($this->primaryKey)) { throw ModelException::forNoPrimaryKey(get_class($this)); } $table = empty($table) ? $this->table : $table; // Ensure we have a good db connection if (! $this->db instanceof BaseConnection) { $this->db = Database::connect($this->DBGroup); } $this->builder = $this->db->table($table); return $this->builder; } //-------------------------------------------------------------------- /** * Ensures that only the fields that are allowed to be updated * are in the data array. * * Used by insert() and update() to protect against mass assignment * vulnerabilities. * * @param array $data * * @return array * @throws \CodeIgniter\Database\Exceptions\DataException */ protected function doProtectFields(array $data): array { if ($this->protectFields === false) { return $data; } if (empty($this->allowedFields)) { throw DataException::forInvalidAllowedFields(get_class($this)); } if (is_array($data) && count($data)) { foreach ($data as $key => $val) { if (! in_array($key, $this->allowedFields)) { unset($data[$key]); } } } return $data; } //-------------------------------------------------------------------- /** * A utility function to allow child models to use the type of * date/time format that they prefer. This is primarily used for * setting created_at, updated_at and deleted_at values, but can be * used by inheriting classes. * * The available time formats are: * - 'int' - Stores the date as an integer timestamp * - 'datetime' - Stores the data in the SQL datetime format * - 'date' - Stores the date (only) in the SQL date format. * * @param integer $userData An optional PHP timestamp to be converted. * * @return mixed * @throws \CodeIgniter\Exceptions\ModelException; */ protected function setDate(int $userData = null) { $currentDate = is_numeric($userData) ? (int) $userData : time(); switch ($this->dateFormat) { case 'int': return $currentDate; case 'datetime': return date('Y-m-d H:i:s', $currentDate); case 'date': return date('Y-m-d', $currentDate); default: throw ModelException::forNoDateFormat(get_class($this)); } } //-------------------------------------------------------------------- /** * Specify the table associated with a model * * @param string $table * * @return Model */ public function setTable(string $table) { $this->table = $table; return $this; } //-------------------------------------------------------------------- /** * Grabs the last error(s) that occurred. If data was validated, * it will first check for errors there, otherwise will try to * grab the last error from the Database connection. * * @param boolean $forceDB Always grab the db error, not validation * * @return array|null */ public function errors(bool $forceDB = false) { // Do we have validation errors? if ($forceDB === false && $this->skipValidation === false) { $errors = $this->validation->getErrors(); if (! empty($errors)) { return $errors; } } // Still here? Grab the database-specific error, if any. $error = $this->db->error(); return $error['message'] ?? null; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // Validation //-------------------------------------------------------------------- /** * Set the value of the skipValidation flag. * * @param boolean $skip * * @return Model */ public function skipValidation(bool $skip = true) { $this->skipValidation = $skip; return $this; } //-------------------------------------------------------------------- /** * Allows to set validation messages. * It could be used when you have to change default or override current validate messages. * * @param array $validationMessages * * @return void */ public function setValidationMessages(array $validationMessages) { $this->validationMessages = $validationMessages; } //-------------------------------------------------------------------- /** * Allows to set field wise validation message. * It could be used when you have to change default or override current validate messages. * * @param string $field * @param array $fieldMessages * * @return void */ public function setValidationMessage(string $field, array $fieldMessages) { $this->validationMessages[$field] = $fieldMessages; } //-------------------------------------------------------------------- /** * Allows to set validation rules. * It could be used when you have to change default or override current validate rules. * * @param array $validationRules * * @return void */ public function setValidationRules(array $validationRules) { $this->validationRules = $validationRules; } //-------------------------------------------------------------------- /** * Allows to set field wise validation rules. * It could be used when you have to change default or override current validate rules. * * @param string $field * @param string|array $fieldRules * * @return void */ public function setValidationRule(string $field, $fieldRules) { $this->validationRules[$field] = $fieldRules; } //-------------------------------------------------------------------- /** * Should validation rules be removed before saving? * Most handy when doing updates. * * @param boolean $choice * * @return $this */ public function cleanRules(bool $choice = false) { $this->cleanValidationRules = $choice; return $this; } //-------------------------------------------------------------------- /** * Validate the data against the validation rules (or the validation group) * specified in the class property, $validationRules. * * @param array|object $data * * @return boolean */ public function validate($data): bool { $rules = $this->getValidationRules(); if ($this->skipValidation === true || empty($rules) || empty($data)) { return true; } // Query Builder works with objects as well as arrays, // but validation requires array, so cast away. if (is_object($data)) { $data = (array) $data; } // ValidationRules can be either a string, which is the group name, // or an array of rules. if (is_string($rules)) { $rules = $this->validation->loadRuleGroup($rules); } $rules = $this->cleanValidationRules ? $this->cleanValidationRules($rules, $data) : $rules; // If no data existed that needs validation // our job is done here. if (empty($rules)) { return true; } $this->validation->setRules($rules, $this->validationMessages); $valid = $this->validation->run($data, null, $this->DBGroup); return (bool) $valid; } //-------------------------------------------------------------------- /** * Removes any rules that apply to fields that have not been set * currently so that rules don't block updating when only updating * a partial row. * * @param array $rules * * @param array|null $data * * @return array */ protected function cleanValidationRules(array $rules, array $data = null): array { if (empty($data)) { return []; } foreach ($rules as $field => $rule) { if (! array_key_exists($field, $data)) { unset($rules[$field]); } } return $rules; } /** * Replace any placeholders within the rules with the values that * match the 'key' of any properties being set. For example, if * we had the following $data array: * * [ 'id' => 13 ] * * and the following rule: * * 'required|is_unique[users,email,id,{id}]' * * The value of {id} would be replaced with the actual id in the form data: * * 'required|is_unique[users,email,id,13]' * * @codeCoverageIgnore * * @deprecated use fillPlaceholders($rules, $data) from Validation instead * * @param array $rules * @param array $data * * @return array */ protected function fillPlaceholders(array $rules, array $data): array { $replacements = []; foreach ($data as $key => $value) { $replacements["{{$key}}"] = $value; } if (! empty($replacements)) { foreach ($rules as &$rule) { if (is_array($rule)) { foreach ($rule as &$row) { // Should only be an `errors` array // which doesn't take placeholders. if (is_array($row)) { continue; } $row = strtr($row, $replacements); } continue; } $rule = strtr($rule, $replacements); } } return $rules; } //-------------------------------------------------------------------- /** * Returns the model's defined validation rules so that they * can be used elsewhere, if needed. * * @param array $options * * @return array */ public function getValidationRules(array $options = []): array { $rules = $this->validationRules; // ValidationRules can be either a string, which is the group name, // or an array of rules. if (is_string($rules)) { $rules = $this->validation->loadRuleGroup($rules); } if (isset($options['except'])) { $rules = array_diff_key($rules, array_flip($options['except'])); } elseif (isset($options['only'])) { $rules = array_intersect_key($rules, array_flip($options['only'])); } return $rules; } //-------------------------------------------------------------------- /** * Returns the model's define validation messages so they * can be used elsewhere, if needed. * * @return array */ public function getValidationMessages(): array { return $this->validationMessages; } //-------------------------------------------------------------------- /** * Override countAllResults to account for soft deleted accounts. * * @param boolean $reset * @param boolean $test * * @return mixed */ public function countAllResults(bool $reset = true, bool $test = false) { if ($this->tempUseSoftDeletes === true) { $this->builder()->where($this->table . '.' . $this->deletedField, null); } // When $reset === false, the $tempUseSoftDeletes will be // dependant on $useSoftDeletes value because we don't // want to add the same "where" condition for the second time $this->tempUseSoftDeletes = ($reset === true) ? $this->useSoftDeletes : ($this->useSoftDeletes === true ? false : $this->useSoftDeletes); return $this->builder()->testMode($test)->countAllResults($reset); } /** * Sets $tempAllowCallbacks value so that we can temporarily override * the setting. Resets after the next trigger. * * @param boolean $val * * @return Model */ public function allowCallbacks(bool $val = true) { $this->tempAllowCallbacks = $val; return $this; } /** * A simple event trigger for Model Events that allows additional * data manipulation within the model. Specifically intended for * usage by child models this can be used to format data, * save/load related classes, etc. * * It is the responsibility of the callback methods to return * the data itself. * * Each $eventData array MUST have a 'data' key with the relevant * data for callback methods (like an array of key/value pairs to insert * or update, an array of results, etc) * * If callbacks are not allowed then returns $eventData immediately. * * @param string $event * @param array $eventData * * @return mixed * @throws \CodeIgniter\Database\Exceptions\DataException */ protected function trigger(string $event, array $eventData) { $allowed = $this->tempAllowCallbacks; $this->tempAllowCallbacks = $this->allowCallbacks; if (! $allowed) { return $eventData; } // Ensure it's a valid event if (! isset($this->{$event}) || empty($this->{$event})) { return $eventData; } foreach ($this->{$event} as $callback) { if (! method_exists($this, $callback)) { throw DataException::forInvalidMethodTriggered($callback); } $eventData = $this->{$callback}($eventData); } return $eventData; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // Magic //-------------------------------------------------------------------- /** * Provides/instantiates the builder/db connection and model's table/primary key names and return type. * * @param string $name * * @return mixed */ public function __get(string $name) { if (property_exists($this, $name)) { return $this->{$name}; } elseif (isset($this->db->$name)) { return $this->db->$name; } elseif (isset($this->builder()->$name)) { return $this->builder()->$name; } return null; } /** * Checks for the existence of properties across this model, builder, and db connection. * * @param string $name * * @return boolean */ public function __isset(string $name): bool { if (property_exists($this, $name)) { return true; } elseif (isset($this->db->$name)) { return true; } elseif (isset($this->builder()->$name)) { return true; } return false; } //-------------------------------------------------------------------- /** * Provides direct access to method in the builder (if available) * and the database connection. * * @param string $name * @param array $params * * @return Model|null */ public function __call(string $name, array $params) { $result = null; if (method_exists($this->db, $name)) { $result = $this->db->$name(...$params); } elseif (method_exists($builder = $this->builder(), $name)) { $result = $builder->$name(...$params); } // Don't return the builder object unless specifically requested //, since that will interrupt the usability flow // and break intermingling of model and builder methods. if ($name !== 'builder' && empty($result)) { if (! method_exists($this->builder(), $name)) { $className = get_class($this); throw new \BadMethodCallException("Call to undefined method $className::$name"); } return $result; } if ($name !== 'builder' && ! $result instanceof BaseBuilder) { return $result; } return $this; } //-------------------------------------------------------------------- } |
Commits for paulgoughbooks_old/trunk/system/Model.php
Revision | Author | Commited | Message |
---|---|---|---|
2 | tporter | Tue 03 Nov, 2020 08:50:21 +0000 | Migration of Paul Goughs Books site to Codeignitor 4 |