├── .github └── FUNDING.yml ├── LICENSE ├── changelog.txt ├── composer.json ├── lib └── db │ └── cortex.php ├── readme.md └── test ├── app ├── cortex.php └── cortex_benchmark.php ├── authormodel.php ├── bench ├── news.json └── user.json ├── bookmodel.php ├── newsmodel.ini ├── newsmodel.php ├── newsmodel2.php ├── productsmodel.php ├── profilemodel.php ├── tagmodel.php ├── test_common.php ├── test_filter.php ├── test_relation.php └── test_syntax.php /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: ikkez 2 | buy_me_a_coffee: ikkez 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /changelog.txt: -------------------------------------------------------------------------------- 1 | CHANGELOG - Cortex ORM 2 | 3 | 1.7.8 (25.02.2025) 4 | * fix: php 8.4 deprecations #137 5 | * fix: keep existing pivot records when updating m:m fields, #129 6 | 7 | 1.7.7 (06.03.2024) 8 | * fix #121: wrong condition variable used for orHas check 9 | * fix #125: ensure cached rel obj isn't altered by whitelist 10 | * chore: fix load() first parameter type 11 | 12 | 1.7.6 (23.01.2023) 13 | * fix: wrong driver method used 14 | 15 | 1.7.5 (27.02.2022) 16 | * fix: compare feature did not cleanup correctly old initial array values 17 | * add BETWEEN to to exclude list 18 | 19 | 1.7.4 (15.02.2022) 20 | * fix SQL function usage with multiple parameters, #110 21 | * php 8.1 fixes 22 | 23 | 1.7.3 (15.03.2021) 24 | * fix: getAll property on non-existing fields 25 | 26 | 1.7.2 (18.02.2021) 27 | * new: orHas feature 28 | 29 | 1.7.1 (06.12.2020) 30 | * fix primary key replacement in filter condition for custom pkeys, #106 31 | * fix dry/valid after factoring new mapper from raw SQL, #109 32 | * add feature to target nested fields in compare method 33 | * use static return doc hint for improved IDE autocompletion 34 | 35 | 1.7.0 (21.07.2020) 36 | * new: field mask feature for cast 37 | * new method findByRawSQL() to use find with a raw sql query 38 | * new method compare() to call custom functions to prepare new / cleanup old values 39 | * new method initial() which returns the initial field data after change 40 | * new method cleared() which returns the initial value if the field was cleared 41 | * new: allow custom timestamp in touch method 42 | * added more m:m relation options for pivot tables, #103, #54 43 | * added support for custom relation key usage in m:m pivot tables 44 | * added error handling for broken m:m relations 45 | * added failsafe for empty filter #104 46 | * added failsafe for broken relations in belongs-to-many 47 | * added shortcut for relation ordering, #104 48 | * changed: skip reset for resolving related mappers 49 | * countRel() can propagate to nested relations now 50 | * refactored save / insert / update event handling, #95 51 | * fixed: getAll for raw results with empty items 52 | * fixed: lost filter pre-binds and count fields on load method, #99 53 | * fixed: preserve logical || operator in filter condition for supported engines, #98 54 | * fixed: respect nullable boolean fields when casting 55 | * fixed: removed strtolower for tablename in setdown, #93 56 | * Fixed an issue with missing pkeys on results that had a HAS-filter applied 57 | * Fixed a bug in has( "something IN ?", array) 58 | * fixed wrong adhoc var usage for has filter 59 | * fixed nested has filter error, #74 60 | * fixed relation type regex 61 | * adjusted schema cache key name 62 | * clean-up adhoc fields in count queries 63 | * add possibility to exclude id in field list (for mysql 5.7+ ONLY FULL GROUP BY fix) 64 | * Avoid duplicated has-many relations 65 | * Avoid quoting "HAVING" and other subquery terms in filter conditions, #78 66 | * handle empty arrays for deleting relations, #76 67 | 68 | 1.6.0 (03.02.2019) 69 | * new: defaults() method to get/set schema default values 70 | * new: resetFields() method, to only reset specific fields back to defaults 71 | * new: copyto_flat(), it's like copyto plus simplified exporting of relation IDs 72 | * changed: return success state on load() instead of $this for better interoperability 73 | * added optimized exists-strategy for has-filter, #58 74 | * fix jig NULL compare on existing fields 75 | * fix double pkey in group when multiple has filters are active 76 | * fix error on self-reflection without DB, #67 77 | * fix to avoid saving empty string date values 78 | * fix loading of empty m:1 relation, #62 79 | * optimize count behaviour & performance 80 | * don't clear virtual fields automatically, fixes #64 81 | * loosen class matching for relation configuration 82 | * realign custom setter call before DT_JSON encoding, #49 83 | * added DB uuid to schema cache key 84 | 85 | 1.5.1 (25.04.2018) 86 | * new: Cortex->getMapper to access the raw mapper 87 | * added has-many <> belongs-to-one inverse save handler, which was not implemented before 88 | * clear virtual fields on reset 89 | * improved mongodb support 90 | * apply auto-quoting to order statement, if not already quoted, #60 91 | * reset internal schema cache upon setup 92 | * fix Jig sorting issue on camelCase fields 93 | * fix unit test for php7.2 94 | * fix field matching for jig filter 95 | * fix changed field check for `_id` field 96 | * fix custom primary key with m:m relation usage, #56 97 | * fix issue with certain whitespace in filters for mongodb 98 | * fix countRel mm-table quotation 99 | * fix jig order issue on count 100 | 101 | 1.5.0 (30.06.2017) 102 | * F3 3.6.2 compatibility fixes 103 | * new: Collection->contains method 104 | * new: Collection->compare method 105 | * allow a CortexCollection to be used as bind parameter for `IN` operators 106 | * allow to optionally set a table $charset 107 | * improved field whitelisting, #23 #24 108 | * include virtual fields in whitelist, #48 109 | * reduced schema queries 110 | * optimized table and field escaping in queries #46 111 | * use aliased table on join conditions 112 | * use class ttl defaults if any 113 | * added getRaw shortcut method 114 | * added space after `IN` group in query condition 115 | * added isSelf configuration existence check 116 | * Bug fix: issue with NULL-value as named bind parameter 117 | * Bug fix: table prefix on NULL comparison 118 | * Bug fix: invalid bind value on multiple rel counts 119 | 120 | 1.4.3 (01.03.2017) 121 | * Bug fix: fix NULL bind value issue, #40 122 | * Bug fix: fix NULL comparison, #40 123 | 124 | 1.4.2 (27.02.2017) 125 | * new: self-referencing m:m relations 126 | * new: support for NULL filter bind values (like `array('foo != ?',null)`) 127 | * raised error level (from NOTICE to USER_ERROR) 128 | * extended datetime recognition in fluid mode 129 | * refactored m:m reference clearing, #34 130 | * align primary key setter 131 | * use mapper setter for countRel fields 132 | * escape fields names in where conditions, #21 133 | * Bug fix: empty belongs-to-many relation, #35 134 | * Bug fix: countRel on m:1 with custom foreign keys 135 | * Bug fix: touch() method data type detection 136 | * Bug fix: regex character set on group by 137 | * Bug fix: case-insensitive LIKE search in postgre 138 | 139 | 1.4.1 (29.01.2016) 140 | * new: mergeFilter method, #7 141 | * fix column rel type recognition, #13 142 | * fix id assignments on collections, #8 143 | * fix relation updates on changed collections, #8 144 | * fix NULL filter arguments for Jig, #6 145 | * keep case-insensitivity for Jig & Mongo, #5 146 | * add return to erase method, #3 147 | * Bug fix: missing relation fields when whitelist is active 148 | * Bug fix: sql expressions in queries 149 | * Bug fix: drop obsolete has-many fields on setup 150 | * Bug fix: table detection 151 | 152 | 1.4.0 (04.06.2015) 153 | * experimental: nested has() propagation 154 | * new: nested filter() propagation (dot-style chaining) 155 | * new: composer support 156 | * new: touch() method to update date, datetime and timestamp fields 157 | * new: rel() method returns a new mapper of the given relation type 158 | * new: fine-grained option array for casting relations 159 | * refactored collection storage, uses references now 160 | * use a normal INT, not BIGINT, as default for foreign keys 161 | * allow custom local field on mm table 162 | * Bug fix: erase collections with $filter 163 | * Bug fix: getting m:m collections from dry mappers 164 | * Bug fix: return dereferenced collections on loading a subset 165 | * Bug fix: consider fieldConfig for new fluid fields 166 | * add new many-many relation with short array push syntax 167 | * and some more small fixes 168 | 169 | 1.3.0 (19.01.2015) 170 | * improved count() behaviour 171 | * MS SQL Server fixes 172 | * refactor grouping and virtual fields with F3 v3.4 173 | * clean up pivot table on deleting items with mm-relations 174 | * added support for the cursor event handlers 175 | * compatibility fixes for F3 v3.3.1 (ArrayAccess by Reference) 176 | * Bug fix: type-casting to int and bool in MongoDB 177 | * Bug fix: consider has-filter on count() method, #40 178 | * Bug fix: has-filter used wrong column on sql many-to-many 179 | * added possibility to add own virtual fields 180 | * renamed countResults() to loaded() to follow fatfree #581 syntax 181 | * Feature: countRel() to add a counter for related records 182 | * advanced MongoId recognition/conversion in filter query 183 | * added orderBy method to collection, for subsequent sorting 184 | * unified sorting of NULL values in postgreSQL 185 | * compatibility fixed for MongoDB 2.6.x 186 | * and a lot of other small fixes and improvements 187 | 188 | 1.2.0 (02.04.2014) 189 | * added whitelisting of own and related fields 190 | * added $option parameter to filter() method 191 | * support for custom primary fields in SQL 192 | * Bug fix: belongs-to-one linkage with non-primary fields 193 | * Bug fix: don't split DB functions in where condition 194 | * Bug fix: postgreSQL GROUP BY clause 195 | * compatibility fixes for F3 v.3.2.2 196 | * added NOT LIKE operator to query parser 197 | 198 | 1.1.0 (09.01.2014) 199 | * Feature: has-filter 200 | * allow case sensitive table names 201 | * addRelFilter renamed to filter 202 | * enhanced copyfrom 203 | * compatibility fixes for F3 v3.2.1 204 | * move castAll into CortexCollection 205 | * add castField function 206 | * add inverse has-one relations 207 | * use case-sensitive table names 208 | * Bug fix: casting many-many relations 209 | * Bug fix: Jig filter bind value 210 | 211 | 1.0.0 (30.11.2013) 212 | * init commit 213 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ikkez/f3-cortex", 3 | "description": "A multi-engine ORM / ODM for the PHP Fat-Free Framework", 4 | "keywords": ["F3","fatfree","sql","ORM", "Mongo"], 5 | "homepage": "https://github.com/ikkez/f3-cortex", 6 | "license": "GPL-3.0", 7 | "autoload": { 8 | "classmap": ["lib/"] 9 | }, 10 | "require": { 11 | "ikkez/f3-schema-builder": "2.*" 12 | } 13 | } -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ![Cortex](https://ikkez.de/linked/cortex_icon.png) 2 | *** 3 | 4 | ### A general purpose Data-Mapper for the PHP Fat-Free Framework 5 | 6 | [![Latest Stable Version](https://poser.pugx.org/ikkez/f3-cortex/v)](https://packagist.org/packages/ikkez/f3-cortex) 7 | [![Total Downloads](https://poser.pugx.org/ikkez/f3-cortex/downloads)](https://packagist.org/packages/ikkez/f3-cortex) 8 | 9 | Cortex is a multi-engine ActiveRecord ORM / ODM that offers easy object persistence. Some of its main features are: 10 | 11 | - It handles SQL, Jig and MongoDB database engines 12 | - Write queries in well-known SQL Syntax, they can be translated to Jig and Mongo 13 | - automated SQL table creation and column extension from defined schema configurations 14 | - Easy prototyping with the SQL Fluid Mode, which makes your RDBMS schema-less and adds new table columns automatically 15 | - Support for models and collections 16 | - Relationships: link multiple models together to one-to-one, one-to-many and many-to-many associations 17 | - smart-loading of related models (intelligent lazy and eager-loading with zero configuration) 18 | - useful methods for nested filtering through relations 19 | - lots of event handlers and custom setter / getter preprocessors for all fields 20 | - define default values and nullable fields for NoSQL 21 | - additional [validation plugin](https://github.com/ikkez/f3-validation-engine) available 22 | 23 | With Cortex you can create generic apps, that work with any DB of the users choice, no matter if it's SQlite, PostgreSQL, MongoDB or even none. 24 | You can also mash-up multiple engines or use them simultaneously. 25 | 26 | It's great for fast and easy data abstraction and offers a bunch of useful filter possibilities. 27 | 28 | 29 | --- 30 | 31 | ## Table of Contents 32 | 33 | 1. [Quick Start](#quick-start) 34 | 2. [SQL Fluid Mode](#sql-fluid-mode) 35 | 3. [Cortex Models](#cortex-models) 36 | 1. [Configuration](#configuration) 37 | 1. [Additional Data Types](#additional-data-types) 38 | 2. [Alternative Configuration](#alternative-configuration-method) 39 | 2. [Blacklist Fields](#blacklist-fields) 40 | 2. [Setup](#set-up) 41 | 3. [Setdown](#set-down) 42 | 4. [Relations](#relations) 43 | 1. [Setup the linkage](#setup-the-linkage) 44 | 2. [Working with Relations](#working-with-relations) 45 | 1. [One-To-One](#one-to-one) 46 | 2. [Many-To-Many, bidirectional](#many-to-many-bidirectional) 47 | 3. [Many-To-Many, unidirectional](#many-to-many-unidirectional) 48 | 4. [Many-To-Many, self-referencing](#many-to-many-self-referencing) 49 | 5. [Event Handlers](#event-handlers) 50 | 1. [Custom Field Handler](#custom-field-handler) 51 | 6. [Filter Query Syntax](#filter-query-syntax) 52 | 1. [Operators](#operators) 53 | 2. [Options Array](#options) 54 | 7. [Advanced Filter Techniques](#advanced-filter-techniques) 55 | 1. [has](#has) 56 | 2. [orHas](#orhas) 57 | 3. [filter](#filter) 58 | 8. [Insight into aggregation](#insight-into-aggregation) 59 | 1. [Counting Relations](#counting-relations) 60 | 2. [Virtual Fields](#virtual-fields) 61 | 9. [Mapper API](#mapper-api) 62 | 9. [Collection API](#collection-api) 63 | 10. [Additional notes](#additional-notes) 64 | 11. [Known Issues](#known-issues) 65 | 12. [Roadmap](#roadmap) 66 | 13. [License](#license) 67 | 68 | 69 | ## Quick Start 70 | 71 | ### System Requirements 72 | 73 | Cortex requires at least Fat-Free v3.4 and PHP 5.4. For some of the features, it also requires the F3 [SQL Schema Plugin](https://github.com/ikkez/f3-schema-builder/tree/master). 74 | 75 | ### Install 76 | 77 | To install Cortex, just copy the `/lib/db/cortex.php` file into your libs. For the SQL Schema Plugin, copy `lib/db/sql/schema.php` as well. 78 | 79 | If you use **composer**, all you need is to run `composer require ikkez/f3-cortex:1.*` and it'll include Cortex and its dependencies into your package. 80 | 81 | ### Setup a DB 82 | 83 | Create a DB object of your choice. You can choose between [SQL](http://fatfreeframework.com/sql), [Jig](http://fatfreeframework.com/jig) or [MongoDB](http://fatfreeframework.com/mongo). Here are some examples: 84 | 85 | ```php 86 | // SQL - MySQL 87 | $db = new \DB\SQL('mysql:host=localhost;port=3306;dbname=MyAppDB','user','pw'); 88 | // SQL - SQlite 89 | $db = new \DB\SQL('sqlite:db/database.sqlite'); 90 | // SQL - PostgreSQL 91 | $db = new \DB\SQL('pgsql:host=localhost;dbname=MyAppDB','user','pw'); 92 | // SQL - SQL Server 93 | $db = new \DB\SQL('sqlsrv:SERVER=LOCALHOST\SQLEXPRESS2012;Database=MyAppDB','user','pw'); 94 | // Jig 95 | $db = new \DB\Jig('data/'); 96 | // Mongo 97 | $db = new \DB\Mongo('mongodb://localhost:27017','testdb'); 98 | ``` 99 | 100 | ### Let's get it rolling 101 | 102 | If you are familiar with F3's own Data-Mappers, you already know all about the basic CRUD operations you can do with Cortex too. It implements the ActiveRecord [Cursor Class](http://fatfreeframework.com/cursor) with all its methods. So you can use Cortex as a **drop-in replacement** of the F3 mappers and it's basic usage will stay that simple: 103 | 104 | ```php 105 | $user = new \DB\Cortex($db, 'users'); 106 | $user->name = 'Jack Ripper'; 107 | $user->mail = 'jacky@email.com'; 108 | $user->save(); 109 | ``` 110 | 111 | Alright, that wasn't very impressive. But now let's find this guy again: 112 | 113 | ```php 114 | $user->load(['mail = ?','jacky@email.com']); 115 | echo $user->name; // shouts out: Jack Ripper 116 | ``` 117 | 118 | As you can see, the filter array is pure SQL syntax, that you would already use with the F3 SQL Mapper. In Cortex this will work with all 3 DB engines. Here is a little more complex `where` criteria: 119 | 120 | ```php 121 | $user->load(['name like ? AND (deleted = 0 OR rights > ?]', 'Jack%', 3)); 122 | ``` 123 | 124 | No need for complex criteria objects or confusing Mongo where-array constructions. It's just as simple as you're used to. Using a Jig DB will automatically translate that query into the appropriate Jig filter: 125 | 126 | ```php 127 | Array ( 128 | [0] => (isset(@name) && preg_match(?,@name)) AND ( (isset(@deleted) && (@deleted = 0)) OR (isset(@rights) && @rights > ?) ) 129 | [1] => /^Jack/ 130 | [2] => 3 131 | ) 132 | ``` 133 | 134 | And for MongoDB it translates into this: 135 | 136 | ```php 137 | Array ( 138 | [$and] => Array ( 139 | [0] => Array ( 140 | [name] => MongoRegex Object ( 141 | [regex] => ^Jack 142 | ) ) 143 | [1] => Array ( 144 | [$or] => Array ( 145 | [0] => Array ( 146 | [deleted] => 0 147 | ) 148 | [1] => Array ( 149 | [rights] => Array ( 150 | [$gt] => 3 151 | ) 152 | ))))) 153 | ``` 154 | 155 | You can use all the fancy methods from Cursor, like `load`, `find`, `cast`, `next` or `prev`. More about filtering and all the other methods a little later. 156 | 157 | ## SQL Fluid Mode 158 | 159 | When you are prototyping some new objects or just don't want to bother with a table schema, while using Cortex along with a SQL DB backend, you can enable the SQL Fluid Mode. 160 | This way Cortex will create all necessary tables and columns automatically, so you can focus on writing your application code. It will try to guess the right data type, based on the given sample data. To enable the fluid mode, just pass a third argument to the object's constructor: 161 | 162 | ```php 163 | $user = new \DB\Cortex($db, 'users', TRUE); 164 | $user->name = 'John'; // varchar(256) 165 | $user->age = 25; // integer 166 | $user->active = true; // boolean|tinyint 167 | $user->lastlogin = '2013-08-28'; // date 168 | ``` 169 | 170 | This way it also creates data types of datetime, float, text (when `strlen > 255`) and double. 171 | 172 | **Notice:** The fluid mode disables the caching of the underlying SQL table schema. This could slightly impact on performance, so keep in mind to deactivate this when you're done. Furthermore keep in mind that you are not able to load or find any records from tables that are not existing - consider to create and save some sample data first, so Cortex can create the tables. 173 | 174 | 175 | ## Cortex Models 176 | 177 | Using the Cortex class directly is easy for some CRUD operations, but to enable some more advanced features, you'll need to wrap Cortex into a Model class like this: 178 | 179 | ```php 180 | // file at app/model/user.php 181 | namespace Model; 182 | 183 | class User extends \DB\Cortex { 184 | protected 185 | $db = 'AppDB1', // F3 hive key of a valid DB object 186 | $table = 'users'; // the DB table to work on 187 | } 188 | ``` 189 | 190 | Now you can create your mapper object that easy: 191 | 192 | ```php 193 | $user = new \Model\Users(); 194 | ``` 195 | 196 | This is the minimal model configuration. Cortex needs at least a working DB object. You can also pass this through the constructor (`new \Model\Users($db);`) and drop it in the setup. 197 | `$db` must be a string of a hive key, where the DB object is stored *OR* the DB object itself. 198 | If no `$table` is provided, Cortex will use the class name as table name. 199 | 200 | ### Configuration 201 | 202 | Cortex does not need that much configuration. But at least it would be useful to have setup the field configuration. 203 | This way it's able to follow a defined schema of your data entity and enables you to use some auto-installation routines (see [setup](#set-up)). It looks like this: 204 | 205 | ```php 206 | // file at app/model/user.php 207 | namespace Model; 208 | 209 | class User extends \DB\Cortex { 210 | 211 | protected 212 | $fieldConf = [ 213 | 'name' => [ 214 | 'type' => 'VARCHAR256', 215 | 'nullable' => false, 216 | ], 217 | 'mail' => [ 218 | 'type' => 'VARCHAR128', 219 | 'index' => true, 220 | 'unique' => true, 221 | ], 222 | 'website' => [ 223 | 'type' => 'VARCHAR256' 224 | ], 225 | 'rights_level' => [ 226 | 'type' => 'TINYINT', 227 | 'default' => 3, 228 | ], 229 | ], 230 | $db = 'DB', 231 | $table = 'users', 232 | $primary = 'id'; // name of the primary key (auto-created), default: id 233 | } 234 | ``` 235 | 236 | In the `$fieldConf` array, you can set data types (`type`), `nullable` flags and `default` values for your columns. With `index` and `unique`, you can even setup an index for the columns. Doing so enables you to install new Models into your SQL database, adds some nullable validation checks and the ability for defaults to NoSQL engines. This makes your models easy interchangeable along various databases using this loosely coupled field definitions. 237 | 238 | **You don't need to configure all fields this way.** If you're working with existing tables, the underlying SQL Mapper exposes the existing table schema. So if you don't need that auto-installer feature, you can just skip the configuration for those fields, or just setup only those you need (i.e. for fields with relations). 239 | 240 | Because column data types are currently only needed for setting up the tables in SQL, it follows that [SQL Data Types Table](https://github.com/ikkez/f3-schema-builder/tree/master#column-class) from the required [SQL Schema Plugin](https://github.com/ikkez/f3-schema-builder/blob/master/lib/db/sql/schema.php). 241 | 242 | You may also extend this config array to have a place for own validation rules or whatever you like. 243 | 244 | The data type values are defined constants from the Schema Plugin. If you like to use some auto-completion in your IDE to find the right values, type in the longer path to the constants: 245 | 246 | ```php 247 | 'type' => \DB\SQL\Schema::DT_TIMESTAMP, 248 | 'default' => \DB\SQL\Schema::DF_CURRENT_TIMESTAMP, 249 | ``` 250 | 251 | #### Additional Data Types 252 | 253 | Cortex comes with two own data types for handling array values in fields. Even when Jig and Mongo support them naturally, most SQL engines do not yet. Therefore Cortex introduces: 254 | 255 | + `DT_SERIALIZED` 256 | + `DT_JSON` 257 | 258 | In example: 259 | 260 | ```php 261 | 'colors' => [ 262 | 'type' => self::DT_JSON, 263 | ], 264 | ``` 265 | 266 | Now you're able to save array data in your model field, which is json_encoded into a `text` field behind the scene (when using a SQL backend). 267 | 268 | ```php 269 | $mapper->colors = ['red','blue','green']; 270 | ``` 271 | 272 | 273 | #### Alternative Configuration 274 | 275 | In case you need some more flexible configuration and don't want to hard-wire it, you can overload the Model class constructor to load its config from an `ini`-file or elsewhere. In example: 276 | 277 | ```php 278 | class User extends \DB\Cortex { 279 | 280 | function __construct() { 281 | // get the DB from elsewhere 282 | $this->db = \Registry::get('DB'); 283 | $f3 = \Base::instance(); 284 | // load fields from .ini file 285 | if (!$f3->exists('usermodel')) 286 | $f3->config('app/models/usermodel.ini'); 287 | foreach ($f3->get('usermodel') as $key => $val) 288 | $this->{$key} = $val; 289 | parent::__construct(); 290 | } 291 | } 292 | ``` 293 | 294 | And in your `usermodel.ini` file: 295 | 296 | ``` ini 297 | [usermodel] 298 | table = users 299 | 300 | [usermodel.fieldConf] 301 | name.type = VARCHAR256 302 | name.nullable = FALSE 303 | mail.type = VARCHAR128 304 | website.type = VARCHAR256 305 | rights_level.type = TINYINT 306 | rights_level.default = 3 307 | ``` 308 | 309 | #### Blacklist Fields 310 | 311 | The `fields()` method can be used to return the available fields on the current model. If called with one simple array argument like `$news->fields(['title']);`, it'll apply the provided elements as a whitelist to the whole mapper. For the rest of its lifetime it'll only hydrate the fields you permitted here. 312 | If called with a 2nd argument like `$news->fields(['author']),true);`, the array is going to be uses as a blacklist instead, and restrict the access to the provided fields. 313 | You can also define deep nested fields using a **dot** as separator: `$news->fields(['tags.title']);` will only hydrate the tag title in your news model and wont load or save any other field that exists in your tag model. Subsequent calls to the `fields` method will merge with all already defined blacklist/whitelist definitions. 314 | 315 | 316 | ### Set up 317 | 318 | This method creates the SQL DB tables you need to run your Cortex model. **It also adds just missing fields to already existing tables.** 319 | 320 | If your Model has a valid field configuration, you are able to run this installation method: 321 | 322 | ```php 323 | \Model\User::setup(); 324 | ``` 325 | 326 | If you have no model class, you need to provide all of the setup method's parameters. 327 | 328 | ```php 329 | $fields = [ 330 | 'name' => ['type' => \DB\SQL\Schema::DT_TEXT], 331 | 'mail' => ['type' => \DB\SQL\Schema::DT_INT4], 332 | 'website' => ['type' => \DB\SQL\Schema::DT_INT4], 333 | ]; 334 | \DB\Cortex::setup($db, 'users', $fields); 335 | ``` 336 | 337 | 338 | ### Set down 339 | 340 | This method completely removes the specified table from the used database. So handle with care. 341 | 342 | ```php 343 | // With Model class 344 | \Model\User::setdown(); 345 | 346 | // Without Model class 347 | \DB\Cortex::setdown($db, 'users'); 348 | ``` 349 | 350 | 351 | ## Relations 352 | 353 | With Cortex you can create associations between multiple models. By linking them together, you can create all common relationships you need for smart and easy persistence. 354 | 355 | ### Setup the linkage 356 | 357 | To make relations work, you need to use a model class with field configuration. Cortex offers the following types of associations, that mostly **must be defined in both classes** of a relation: 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 |
TypeModel ADirectionModel B
1:1belongs-to-one<- ->has-one
1:mbelongs-to-one<- ->has-many
m:mhas-many<- ->has-many
m:mbelongs-to-many --->
391 | 392 | This is how a field config looks with a relation: 393 | 394 | ![Cortex Rel 1](https://ikkez.de/linked/cortex-class-conf.png) 395 | 396 | This creates an aggregation between Author and News, so 397 | 398 | > One News belongs to one Author. 399 | 400 | > One Author has written many News. 401 | 402 | ![UML 1](https://ikkez.de/linked/cortex-dia-1.png) 403 | 404 | As a side note: `belongs-to-*` definitions will create a new column in that table, that is used to save the id of the counterpart model (foreign key field). 405 | Whereas `has-*` definitions are just virtual fields which are going to query the linked models by their own id (the inverse way). This leads us to the following configuration schema: 406 | 407 | For **belongs-to-one** and **belongs-to-many** 408 | 409 | ```php 410 | 'realTableField' => [ 411 | 'relationType' => '\Namespace\ClassName', 412 | ], 413 | ``` 414 | 415 | Defining a foreign key for `belongs-to-*` is optional. The default way is to use the identifier field. For SQL engines this is either the default primary key `id` or the custom primary key that can be set with the `$primary` class property. NoSQL engines will use `_id`. If you need to define another non-primary field to join with, use `['\Namespace\ClassName','cKey']`. 416 | 417 | For **has-one** and **has-many** 418 | 419 | ```php 420 | 'virtualField' => [ 421 | 'relationType' => ['\Namespace\ClassName','foreignKey'], 422 | ], 423 | ``` 424 | 425 | The foreign key is the field name you used in the counterpart model to define the `belongs-to-one` connection. 426 | 427 | #### many-to-many 428 | 429 | There is one special case for many-to-many relations: here you use a `has-many` type on both models, which implies that there must be a 3rd pivot table that will be used for keeping the foreign keys that binds everything together. Usually Cortex will auto-create that table upon [setup](#set-up) method, using an auto-generated table name. If you like to use a custom name for that joining-table, add a 3rd parameter to the config array of *both* models, i.e.: 430 | 431 | ```php 432 | 'tags' => [ 433 | 'has-many' => [\Model\Tag::class,'news','news_tags'], 434 | ], 435 | ``` 436 | 437 | By default the primary key is used as reference for the record in the pivot table. In case you need to use a different field for the primary key, so can set a custom `localKey`. 438 | 439 | ```php 440 | 'tag_key' => [ 441 | 'type' => \DB\SQL\Schema::DT_VARCHAR128, 442 | ], 443 | 'tags' => [ 444 | 'has-many' => [\Model\Tag::class,'news','news_tags', 445 | 'localKey' => 'tag_key' 446 | ], 447 | ], 448 | ``` 449 | 450 | For a custom relation key (foreign key) use `relPK`: 451 | ```php 452 | 'tags' => [ 453 | 'has-many' => [\Model\Tag::class,'news','news_tags', 454 | 'relPK'=> 'news_id' 455 | ], 456 | ], 457 | ``` 458 | 459 | 460 | ##### Custom pivot column names 461 | 462 | If you're working with an existing database table, or want to use own field names for the column in the pivot table, you can set those up with the `relField` option: 463 | 464 | I.e. in the news model: 465 | 466 | ```php 467 | 'tags' => [ 468 | 'has-many' => [\Model\Tag::class,'news','news_tags', 469 | 'relField' => 'news_id' 470 | ], 471 | ], 472 | ``` 473 | 474 | and in the tag model: 475 | 476 | ```php 477 | 'news' => [ 478 | 'has-many' => [\Model\News::class,'tags','news_tags', 479 | 'relField' => 'tag_id' 480 | ], 481 | ], 482 | ``` 483 | 484 | That means that the 3rd pivot table constains `news_id` and `tag_id` fields. 485 | 486 | ### Working with Relations 487 | 488 | Okay finally we come to the cool part. When configuration is done and setup executed, you're ready to go. 489 | 490 | #### one-to-one 491 | 492 | To create a new relation: 493 | 494 | ```php 495 | // load a specific author 496 | $author = new \AuthorModel(); 497 | $author->load(['_id = ?', 2]); 498 | 499 | // create a new profile 500 | $profile = new ProfileModel(); 501 | $profile->status_message = 'Hello World'; 502 | 503 | // link author and profile together, just set the foreign model to the desired property 504 | $profile->author = $author; 505 | 506 | // OR you can also just put in the id instead of the whole object here 507 | // (means you don't need to load the author model upfront at all) 508 | $profile->author = 23; 509 | 510 | $profile->save(); 511 | ``` 512 | 513 | You can of course do it the other way around, starting from the author model: 514 | 515 | ```php 516 | // create a new profile 517 | $profile = new ProfileModel(); 518 | $profile->status_message = 'Hello World'; 519 | $profile->save(); 520 | 521 | // load a specific author and add that profile 522 | $author = new \AuthorModel(); 523 | $author->load(['_id = ?', 2]); 524 | $author->profile = $profile; 525 | $author->save(); 526 | ``` 527 | 528 | and to load it again: 529 | 530 | ```php 531 | $author->load(['_id = ?', 23]); 532 | echo $author->profile->status_message; // Hello World 533 | 534 | $profile->load(['_id = ?', 1]); 535 | echo $profile->author->name; // Johnny English 536 | ``` 537 | 538 | #### one-to-many, many-to-one 539 | 540 | Save an author to a news record. 541 | 542 | ```php 543 | $author->load(['name = ?','Johnny English']); 544 | $news->load(['_id = ?',42]); 545 | $news->author = $author; // set the object or the raw id 546 | $news->save(); 547 | ``` 548 | 549 | now you can get: 550 | 551 | ```php 552 | echo $news->author->name; // 'Johnny English' 553 | ``` 554 | 555 | The field `author` now holds the whole mapper object of the AuthorModel. So you can also update, delete or cast it. 556 | 557 | The getting all news by an author in the counterpart looks like this: 558 | 559 | ```php 560 | $author->load(['_id = ?', 42]); 561 | $author->news; // is now an array of NewsModel objects 562 | 563 | // if you like to cast them all you can use 564 | $allNewsByAuthorX = $author->castField('news'); // is now a multi-dimensional array 565 | ``` 566 | 567 | #### many-to-many, bidirectional 568 | 569 | When both models of a relation has a `has-many` configuration on their linkage fields, Cortex create a new reference table in setup, where the foreign keys of both models are linked together. This way you can query model A for related models of B and vice versa. 570 | 571 | To save many collections to a model you've got several ways: 572 | 573 | ```php 574 | $news->load(['_id = ?',1]); 575 | 576 | // array of IDs from TagModel 577 | $news->tags = [12, 5]; 578 | // OR a split-able string 579 | $news->tags = '12;5;3;9'; // delimiter: [,;|] 580 | // OR an array of single mapper objects 581 | $news->tags = [$tag,$tag2,$tag3]; 582 | // OR a hydrated mapper that may contain multiple results 583 | $tag->load(['_id != ?',42]); 584 | $news->tags = $tag; 585 | 586 | // you can also add a single tag to your existing tags 587 | $tag->load(['_id = ?',23]); 588 | $news->tags[] = $tag; 589 | 590 | $news->save(); 591 | ``` 592 | 593 | Now you can get all tags of a news entry: 594 | 595 | ```php 596 | $news->load(['_id = ?',1]); 597 | echo $news->tags[0]['title']; // Web Design 598 | echo $news->tags[1]['title']; // Responsive 599 | ``` 600 | 601 | And all news that are tagged with *Responsive*: 602 | 603 | ```php 604 | $tags->load(['title = ?','Responsive']); 605 | echo $tags->news[0]->title; // '10 Responsive Images Plugins' 606 | ``` 607 | 608 | This example shows the inverse way of querying (using the TagModel to find the corresponding news). Of course the can also use a more direct way that offers even more possibilities, therefore check the [has()](#has) method. 609 | 610 | #### many-to-many, unidirectional 611 | 612 | You can use a `belongs-to-many` field config to define a one-way m:m relation. 613 | This is a special type for many-to-many as it will not use a 3rd table for reference and just puts a list of IDs into the table field, as commonly practiced in NoSQL solutions. 614 | This is an unidirectional binding, because the counterpart wont know anything about its relation and it's harder to query the reserve way, but it's still a lightweight and useful solution in some cases. 615 | 616 | Saving works the same way like the other m:m type described above 617 | 618 | ```php 619 | $news->tags = [4,7]; // IDs of TagModel 620 | $news->save(); 621 | ``` 622 | 623 | and get them back: 624 | 625 | ```php 626 | $news->load(['_id = ?', 77]); 627 | echo $news->tags[0]->title; // Web Design 628 | echo $news->tags[1]->title; // Responsive 629 | ``` 630 | 631 | #### many-to-many, self-referencing 632 | 633 | In case you want to bind a many-to-many relation to itself, meaning that you'd like to add it to the own property of the same model, you can do this too, since these are detected as self-referenced fields now. 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 |
TypeModel ADirectionModel A
m:mhas-many<-->has-many
649 | 650 | A common scenario is where a `User` has friends and that relation target is also `User`. So it would bind the relation to itself: 651 | 652 | ```php 653 | namespace Model; 654 | class User extends \DB\Cortex { 655 | protected $fieldConf = [ 656 | 'friends' => [ 657 | 'has-many' => [\Model\User::class,'friends'] 658 | ] 659 | ]; 660 | } 661 | ``` 662 | 663 | To use a different field name in the pivot table for the reference field, use `selfRefField` option: 664 | 665 | ```php 666 | 'friends' => [ 667 | 'has-many' => [\Model\User::class,'friends', 668 | 'selfRefField' => 'friends_ref' 669 | ] 670 | ] 671 | ``` 672 | 673 | Because this is also a many to many relation, a pivot table is needed too. Its name is generated based on the table and fields name, but can also be defined as 3rd array parameter, i.e. `['\Model\User','friends','user_friends']`. 674 | 675 | ![Cortex m:m self-ref](http://ikkez.de/linked/cortex-self-ref.png) 676 | 677 | Usually, this is a bidirectional relation, meaning that you would get a direct linkage to your friends (`friends`), and another one to the inverse linkage (friends with me, `friends_ref`). As this is pretty inconvenient for further working and filtering on those, both 678 | fields are linked together internally and will always represent **all** relations, whether the relation was added from UserA or UserB. 679 | 680 | ```php 681 | $userA = new \Model\User(); 682 | $userA->load(['_id = ?', 1]); 683 | 684 | $userB = new \Model\User(); 685 | $userB->load(['_id = ?', 2]); 686 | 687 | $userC = new \Model\User(); 688 | $userC->load(['_id = ?', 3]); 689 | 690 | if ($userA->friends) 691 | $userA[] = $userB; 692 | else 693 | $userA = [$userB]; 694 | 695 | $userA->save(); 696 | 697 | $userC->friends = [$userA,$userB]; 698 | $userC->save(); 699 | ``` 700 | 701 | The only exception is, that the current record itself is always excluded, so you wont get UserA as friend of UserA: 702 | 703 | ```php 704 | $userA->load(['_id = ?', 1]); 705 | $userA->friends->getAll('_id'); // [2,3] 706 | $userB->load(['_id = ?', 2]); 707 | $userB->friends->getAll('_id'); // [1,3] 708 | $userC->load(['_id = ?', 3]); 709 | $userC->friends->getAll('_id'); // [1,2] 710 | ``` 711 | 712 | 713 | ## Event Handlers 714 | 715 | Cortex inherits all setters form the [Cursor Event Handlers](http://fatfreeframework.com/cursor#event-handlers) and additionally adds custom field handlers (setter/getter). These can be used to execute some extra code right before or after doing something. This could be useful for validation directly in your Model, or some extended save, load or delete cascades. 716 | 717 | The following events are supported: 718 | 719 | * `onload` 720 | * `onset` 721 | * `onget` 722 | * `beforeerase` 723 | * `aftererase` 724 | * `beforeinsert` 725 | * `afterinsert` 726 | * `beforeupdate` 727 | * `afterupdate` 728 | 729 | 730 | You can setup own handlers to this events like this: 731 | 732 | ```php 733 | $mapper->onload(function($self){ 734 | // custom code 735 | }); 736 | // or 737 | $mapper->onload('App/Foo/Bar::doSomething'); 738 | ``` 739 | 740 | You can provide anything that is accepted by the [Base->call](http://fatfreeframework.com/base#call) method as handler function. Notice to use the `$self->set('field','val')` instead of `$self->field=val`, if you define a handler within a child class of Cortex (i.e. an extended `__construct` in your own model class). 741 | 742 | If any `before*` event returns a `false` result, the action that is going to be performed will be aborted, and the `after*` events are skipped. 743 | 744 | ### Custom Field Handler 745 | 746 | The `onset` and `onget` events have slightly different parameters: 747 | 748 | ```php 749 | $mapper->onset('field',function($self, $val){ 750 | return md5($val); 751 | }); 752 | ``` 753 | 754 | You can also define these custom field preprocessors as a method within the class, named `set_*` or `get_*`, where `*` is the name of your field. In example: 755 | 756 | ```php 757 | class User extends \DB\Cortex { 758 | // [...] 759 | 760 | // validate email address 761 | public function set_mail($value) { 762 | if (\Audit::instance()->email($value) == false) { 763 | // no valid email address 764 | // throw exception or set an error var and display a flash message 765 | $value = null; 766 | } 767 | return $value; 768 | } 769 | // hash a password before saving 770 | public function set_password($value) { 771 | return \Bcrypt::instance()->hash($value); 772 | } 773 | public function get_name($value) { 774 | return ucfirst($value); 775 | } 776 | } 777 | ``` 778 | 779 | So setting these fields in your Model, like: 780 | 781 | ```php 782 | $user->password = 'secret'; 783 | $user->mail = 'foo@bar.com'; 784 | ``` 785 | 786 | will now trigger your custom setters, doing anything you like. 787 | 788 | 789 | 790 | ## Filter Query Syntax 791 | 792 | Well basically the `$filter` syntax for writing cortex queries is simple SQL. But there are some slightly modifications you should have read in these additional notes. 793 | 794 | ### Operators 795 | 796 | These common filter operators are supported: 797 | - relational operators: `<`, `>`, `<=`, `>=`, `==`, `=`, `!=`, `<>` 798 | - search operators: `LIKE`,`NOT LIKE`, `IN`, `NOT IN` (not case-sensitive) 799 | - logical operators: `(`, `)`, `AND`, `OR`, `&&`, (`||` only mysql and jig) 800 | 801 | **Comparison** 802 | 803 | With comparison operators, you can do the following things: 804 | 805 | * compare fields against other fields: 806 | 807 | `['foo < bar']` 808 | 809 | * compare fields against values: 810 | 811 | `['foo >= 1']` or `['foo == \'bar\'']` 812 | 813 | Especially for value comparison, it's **highly recommended** to use placeholders in your filter and bind their values accordingly. This ensures that the data mapper uses parameterized queries for better security. Placeholders go like this: 814 | 815 | * positional bind-parameters: 816 | 817 | `['foo = ?', 1]` or `['foo = ? AND bar < ?', 'baz', 7]` 818 | 819 | * named bind-parameters: 820 | 821 | `['foo = :foo',':foo'=>1]` 822 | 823 | `['foo = :foo AND bar < :bar',':foo'=>'hallo', ':bar'=>7]` 824 | 825 | **Sugar** 826 | 827 | * what's a special sugar in Cortex is, that you can also mix both types together: 828 | 829 | `['foo = ? AND bar < :bar', 'bar', ':bar'=>7]` 830 | 831 | * and you can also reuse named parameter (not possible in raw PDO): 832 | 833 | `['min > :num AND max < :num', ':num' => 7]` 834 | 835 | * comparison with `NULL` (nullable fields) works this easy: 836 | 837 | `['foo = ?', NULL]` or `['foo != ?', NULL]` 838 | 839 | **Search** 840 | 841 | * The `LIKE` operator works the same way like the [F3 SQL search syntax](http://www.fatfreeframework.com/sql-mapper#search). The search wildcard (`%`) belongs into the bind value, not the query string. 842 | 843 | `['title LIKE ?', '%castle%']` or `['email NOT LIKE ?', '%gmail.com']` 844 | 845 | * The `IN` operator usually needs multiple placeholders in raw PDO (like `foo IN (?,?,?)`). In Cortex queries you simply use an array for this, the QueryParser does the rest. 846 | 847 | `['foo IN ?', [1,2,3]]` 848 | 849 | You can also use a CortexCollection as bind parameter. In that case, the primary keys are automatically used for matching: 850 | 851 | ```php 852 | $fruits = $fruitModel->find(['taste = ?','sweet']); 853 | $result = $userModel->find(['favorite_fruit IN ?',$fruits]) 854 | ``` 855 | 856 | 857 | ### Options 858 | 859 | The `$options` array for load operations respects the following keys: 860 | 861 | - order 862 | - limit 863 | - offset 864 | 865 | Use `DESC` and `ASC` flags for sorting fields, just like in SQL. Additional `group` settings are currently just bypassed to the underlying mapper and should work dependant on the selected db engine. Any unification on that might be handled in a future version. 866 | 867 | #### Relational sorting 868 | 869 | > NB: This is currently experimental as of v1.7 870 | 871 | For 1-n relations, you can apply a sorting rule, based on a field of a relation to your order option. You need to prefix the field you used in your `$fieldConf` for the relation with an `@` in your order definition: 872 | 873 | Given the following field configuration: 874 | 875 | ```php 876 | // Contracts fieldConf: 877 | 'user' => ['belongs-to-one' => UserModel::class] 878 | 879 | // User fieldConf: 880 | 'contracts' => ['has-many' => [ContractsModel::class,'user']] 881 | ``` 882 | 883 | This example will paginate through all contracts records that are sorted by the relational user name: 884 | 885 | ```php 886 | $contracts = new Contracts(); 887 | $res = $contracts->paginate(0,10,null, ['order'=>'@user.name ASC']); 888 | ``` 889 | 890 | 891 | ## Advanced Filter Techniques 892 | 893 | When your application reaches the point where all basic CRUD operations are working, you probably need some more control about finding your records based on conditions for relations. 894 | Here comes the `has()` and `filter()` methods into play: 895 | 896 | ### has 897 | 898 | The has method adds some conditions to a related field, that must be fulfilled in addition, when the **next** find() or load() method of its parent is fired. So this is meant for limiting the main results. 899 | 900 | In other words: Let's find all news records that are tagged by "Responsive". 901 | 902 | ```php 903 | $news->has('tags', ['title = ?','Responsive']); 904 | $results = $news->find(); 905 | echo $results[0]->title; // '10 Responsive Images Plugins' 906 | ``` 907 | 908 | Of course you can also use the inverse way of querying, using the TagModel, load them by title and access the shared `$tags->news` property to find your records. 909 | The advantage of the "has" method is that you can also add a condition to the parent as well. This way you could edit the load line into something like this: 910 | `$news->find(['published = ?', 1]);`. Now you can limit your results based on two different models - you only load *published* news which were tagged "Responsive". 911 | 912 | You can also add multiple has-conditions to different relations: 913 | 914 | ```php 915 | $news->has('tags', ['title = ?','Responsive']); 916 | $news->has('author', ['username = ?','ikkez']); 917 | $results = $news->find(['published = ?', 1], ['limit'=>3, 'order'=>'date DESC']); 918 | ``` 919 | 920 | Now you only load the last 3 published news written by me, which were tagged "Responsive", sorted by release date. ;) 921 | 922 | If you like, you can also call them in a fluent style: `$news->has(...)->load(...);`. 923 | 924 | ### orHas 925 | 926 | Similar to has method, but adds the has condition with an OR operator. 927 | 928 | ### filter 929 | 930 | The filter method is meant for limiting the results of relations. In example: load author x and only his news from 2014. 931 | 932 | ```php 933 | $author->filter('news', ['date > ?','2014-01-01']); 934 | $author->load(['username = ?', 'ikkez']); 935 | ``` 936 | 937 | The same way like the `has()` method does, you can add multiple filter conditions. You can mix filter and has conditions too. 938 | Once a `load` or `find` function is executed, the filter (and has) conditions are cleared for the next upcoming query. 939 | 940 | Filter conditions are currently not inherited. That means if you recursively access the fields of a relation ($author->news[0]->author->news) they get not filtered, but fully lazy loaded again. 941 | 942 | ### Propagation 943 | 944 | It is also possible to filter deep nested relations using the `.` dot style syntax. The following example finds all authors and only loads its news that are tagged with "Responsive": 945 | 946 | ```php 947 | $author->filter('news.tags', ['title = ?','Responsive']); 948 | $author->find(); 949 | ``` 950 | 951 | The same applies for the has filter. The next example is similar to the previous one, but this time, instead of finding all authors, it only returns authors that have written a news entry that was tagged with "Responsive": 952 | 953 | ```php 954 | $author->has('news.tags', ['title = ?','Responsive']); 955 | $author->find(); 956 | ``` 957 | 958 | **Notice:** These nested filter techniques are still experimental, so please handle with care and test your application well. 959 | 960 | 961 | ## Insight into aggregation 962 | 963 | Cortex comes with some handy shortcuts that could be used for essential field aggregation. 964 | 965 | ### Counting relations 966 | 967 | Sometimes you need to know how many relations a record has - i.e. for some stats or sorting for top 10 list views. 968 | 969 | Therefore have a look at the *[countRel](#countrel)* method, which let you setup a new adhoc field to the resulting records that counts the related records on `has-many` fields. 970 | 971 | ```php 972 | // find all tags with the sum of all news that uses the tag, ordered by the top occurring tags first. 973 | $tag = new \Model\Tag(); 974 | $tag->countRel('news'); 975 | $result = $tag->find(null,['order'=>'count_news DESC, title']); 976 | ``` 977 | 978 | The new field is named like `count_{$key}`, but you can also set a custom alias. As you can see, you can also use that field for additional sorting of your results. You can also combine this with the `has()` and `filter()` methods and set relation counters to nested relations with the `.` separator. 979 | Notice that `countRel()` only applies to the next called `find()` operation. Currently, you cannot use those virtual count field in a `$filter` query. 980 | 981 | ### Virtual fields 982 | 983 | Cortex has some abilities for own custom virtual fields. These might be useful to add additional fields that may contain data that is not stored in the real db table or computes its value out of other fields or functions, similar to the [custom field setters and getters](#custom-field-handler). 984 | 985 | ```php 986 | // just set a simple value 987 | $user->virtual('is_online', TRUE); 988 | // or use a callback function 989 | $user->virtual('full_name', function($this) { 990 | return $this->name.' '.$this->surname; 991 | }); 992 | ``` 993 | 994 | You can also use this to count or sum fields together and even reorder your collection on this fields using `$collection->orderBy('foo DESC, bar ASC')`. Keep in mind that these virtual fields only applies to your final received collection - you cannot use these fields in your filter query or sort condition before the actual find. 995 | 996 | But if you use a SQL engine, you can use the underlying mapper abilities of virtual adhoc fields - just set this before any load or find operation is made: 997 | 998 | ```php 999 | $mapper->newField = 'SQL EXPRESSION'; 1000 | ``` 1001 | 1002 | ## Mapper API 1003 | 1004 | ### $db 1005 | **DB object** 1006 | 1007 | Can be an object of [\DB\SQL](http://fatfreeframework.com/sql), [\DB\Jig](http://fatfreeframework.com/jig) or [\DB\Mongo](http://fatfreeframework.com/sql), 1008 | *OR* a string containing a HIVE key where the actual database object is stored at. 1009 | 1010 | ### $table 1011 | **table to work with**, string 1012 | 1013 | If the table is not set, Cortex will use the `strtolower(get_class($this))` as table name. 1014 | 1015 | ### $fluid 1016 | **trigger SQL fluid schema mode**, boolean = false 1017 | 1018 | ### $fieldConf 1019 | **field configuration**, array 1020 | 1021 | The array scheme is: 1022 | 1023 | ```php 1024 | protected $fieldConf = [ 1025 | 'fieldName' => [ 1026 | 'type' => string 1027 | 'nullable' => bool 1028 | 'default' => mixed 1029 | 'index' => bool 1030 | 'unique' => bool 1031 | ] 1032 | ] 1033 | ``` 1034 | 1035 | Get the whole list of possible types from the [Data Types Table](https://github.com/ikkez/f3-schema-builder/tree/master#column-class). 1036 | 1037 | *NB:* You can also add `'passThrough' => true` in order to use the raw value in *type* as data type in case you need a custom type which is not available in the data types table. 1038 | 1039 | ### $ttl 1040 | **default mapper schema ttl**, int = 60 1041 | 1042 | This only affects the schema caching of the SQL mapper. 1043 | 1044 | ### $rel_ttl 1045 | **default mapper rel ttl**, int = 0 1046 | 1047 | This setting in your model will add a caching to all relational queries 1048 | 1049 | ### $primary 1050 | **SQL table primary key**, string 1051 | 1052 | Defines the used primary key of the table. Default is `id` for SQL engine, and *always* `_id` for JIG and Mongo engines. 1053 | The setup method respects this value for creating new SQL tables in your database and has to be an integer column. 1054 | 1055 | ### load 1056 | **Retrieve first object that satisfies criteria** 1057 | 1058 | ```php 1059 | bool load([ array $filter = NULL [, array $options = NULL [, int $ttl = 0 ]]]) 1060 | ``` 1061 | 1062 | Simple sample to load a user: 1063 | 1064 | ```php 1065 | $user->load(['username = ?','jacky']); 1066 | if (!$user->dry()) { 1067 | // user was found and loaded 1068 | echo $user->username; 1069 | } else { 1070 | // user was not found 1071 | } 1072 | ``` 1073 | 1074 | When called without any parameter, it loads the first record from the database. 1075 | The method returns `TRUE` if the load action was successful. 1076 | 1077 | ### loaded 1078 | **Count records that are currently loaded** 1079 | 1080 | ```php 1081 | int loaded() 1082 | ``` 1083 | 1084 | Sample: 1085 | 1086 | ```php 1087 | $user->load(['last_name = ?','Johnson']); 1088 | echo $user->loaded(); // 3 1089 | ``` 1090 | 1091 | ### first, last, next, prev, skip 1092 | **Methods to navigate the cursor position and map a record** 1093 | 1094 | See [http://fatfreeframework.com/cursor#CursorMethods](http://fatfreeframework.com/cursor#CursorMethods). 1095 | 1096 | ```php 1097 | $user->load(['last_name = ?','Johnson']); 1098 | echo $user->loaded(); // 3 1099 | echo $user->_id; // 1 1100 | $user->last(); 1101 | echo $user->_id; // 3 1102 | echo $user->prev()->_id; // 2 1103 | echo $user->first()->_id; // 1 1104 | echo $user->skip(2)->_id; // 3 1105 | ``` 1106 | 1107 | 1108 | ### cast 1109 | **Return fields of mapper object as an associative array** 1110 | 1111 | ```php 1112 | array cast ([ Cortex $obj = NULL [, int $rel_depths = 1]]) 1113 | ``` 1114 | 1115 | #### Field masks 1116 | 1117 | > NB: Since configuring *relations depths* seems more and more less practical, a new way of casting relations was introducted: "Field masks". This is the way to go and will replace the legacy "relations depths configuration" in a future release. 1118 | 1119 | 1120 | You can also use ``$rel_depths`` for defining a mask to mappers, so you can restrict the fields returned from a cast: 1121 | 1122 | ```php 1123 | $data = $item->cast(null,[ 1124 | '_id', 1125 | 'order.number', 1126 | 'product._id', 1127 | 'product.title', 1128 | 'product.features._id', 1129 | 'product.features.title', 1130 | 'product.features.icon', 1131 | ]); 1132 | ``` 1133 | 1134 | #### relation depths (old way) 1135 | 1136 | A simple cast sample. If the model contains relations, they are also casted for 1 level depth by default: 1137 | 1138 | ```php 1139 | $user->load(['_id = ?',3]); 1140 | var_dump($user->cast()); 1141 | /* Array ( 1142 | [_id] => 3 1143 | [first_name] => Steve 1144 | [last_name] => Johnson 1145 | [comments] => Array( 1146 | [1] => Array ( 1147 | [_id] = 23 1148 | [post] => 2 1149 | [message] => Foo Bar 1150 | ), 1151 | [2] => Array ( 1152 | [_id] = 28 1153 | [post] => 3 1154 | [message] => Lorem Ipsun 1155 | ) 1156 | ) 1157 | )*/ 1158 | ``` 1159 | 1160 | If you increase the `$rel_depths` value, you can also resolve further relations down the road: 1161 | 1162 | ```php 1163 | var_dump($user->cast(NULL, 2)); 1164 | /* Array ( 1165 | ... 1166 | [comments] => Array( 1167 | [1] => Array ( 1168 | [_id] = 23 1169 | [post] => Array( 1170 | [_id] => 2 1171 | [title] => Kittenz 1172 | [text] => ... 1173 | ) 1174 | [message] => Foo Bar 1175 | ), 1176 | ... 1177 | ) 1178 | )*/ 1179 | ``` 1180 | 1181 | #### relation depths configuration 1182 | 1183 | If you only want particular relation fields to be resolved, you can set an array to the ``$rel_depths`` parameter, with the following schema: 1184 | 1185 | ```php 1186 | $user->cast(NULL, [ 1187 | '*' => 0, // cast all own relations to the given depth, 1188 | // 0 doesn't cast any relation (default if this key is missing) 1189 | 'modelA' => 0,// if a relation key is defined here, modelA is being loaded and casted, 1190 | // but not its own relations, because the depth is 0 for it 1191 | 'modelB' => 1,// modelB and all its 1st level relations are loaded and casted 1192 | 'modelC' => [...] // you can recursively extend this cast array scheme 1193 | ]); 1194 | 1195 | // simple sample: only cast yourself and the author model without its childs 1196 | $news->cast(NULL,[ 1197 | '*'=>0, 1198 | 'author'=>0 1199 | ]); 1200 | 1201 | // nested sample: only cast yourself, 1202 | // your own author relation with its profile and all profile relations 1203 | $news->cast(NULL,[ 1204 | '*'=>0, 1205 | 'author'=>[ 1206 | '*'=>0, 1207 | 'profile'=>1 1208 | ] 1209 | ]); 1210 | ``` 1211 | 1212 | If you don't want any relation to be resolved and casted, just set `$rel_depths` to `0`. 1213 | Any one-to-many relation field then just contains the `_id` (or any other custom field binding from [$fieldConf](#fieldConf)) of the foreign record, 1214 | many-to-one and many-to-many fields are just empty. 1215 | 1216 | 1217 | ### castField 1218 | **Cast a related collection of mappers** 1219 | 1220 | ```php 1221 | array|null castField( string $key [, int $rel_depths = 0 ]) 1222 | ``` 1223 | 1224 | 1225 | ### find 1226 | **Return a collection of objects matching criteria** 1227 | 1228 | ```php 1229 | CortexCollection|false find([ array $filter = NULL [, array $options = NULL [, int $ttl = 0 ]]]) 1230 | ``` 1231 | 1232 | The resulting CortexCollection implements the ArrayIterator and can be treated like a usual array. All filters and counters which were set before are used once `find` is called: 1233 | 1234 | ```php 1235 | // find published #web-design news, sorted by approved user comments 1236 | $news->has('tags',['slug = ?','web-design']); 1237 | $news->filter('comments', ['approved = ?',1]); 1238 | $news->countRel('comments'); 1239 | $records = $news->find( 1240 | ['publish_date <= ? and published = ?', date('Y-m-d'), true], 1241 | ['order' => 'count_comments desc'] 1242 | ); 1243 | ``` 1244 | 1245 | ### findByRawSQL 1246 | **Use a raw SQL query to find results and factory them into models** 1247 | 1248 | ```php 1249 | CortexCollection findByRawSQL( string|array $query [, array $args = NULL [, int $ttl = 0 ]]) 1250 | ``` 1251 | 1252 | In case you want to write your own SQL query and factory the results into the appropriate model, you can use this method. I.e.: 1253 | 1254 | ```php 1255 | $news_records = $news->findByRawSQL('SELECT * from news where foo <= ? and active = ?',[42, 1]); 1256 | ``` 1257 | 1258 | 1259 | ### findone 1260 | **Return first record (mapper object) that matches criteria** 1261 | 1262 | ```php 1263 | Cortex|false findone([ array $filter = NULL [, array $options = NULL [, int $ttl = 0 ]]]) 1264 | ``` 1265 | 1266 | This method is inherited from the [Cursor](http://fatfreeframework.com/cursor) class. 1267 | 1268 | ### afind 1269 | **Return an array of result arrays matching criteria** 1270 | 1271 | ```php 1272 | array|null find([ array $filter = NULL [, array $options = NULL [, int $ttl = 0 [, int|array $rel_depths = 1 ]]]]) 1273 | ``` 1274 | 1275 | Finds a whole collection, matching the criteria and casts all mappers into an array, based on the `$rel_depths` configuration. 1276 | 1277 | 1278 | ### addToCollection 1279 | **Give this model a reference to the collection it is part of** 1280 | 1281 | ```php 1282 | null addToCollection( CortexCollection $cx ) 1283 | ``` 1284 | 1285 | 1286 | ### onload, aftererase, afterinsert, aftersave, afterupdate, beforeerase, beforeinsert, beforesave, beforeupdate 1287 | **Define an event trigger** 1288 | 1289 | ```php 1290 | callback onload( callback $func ) 1291 | ``` 1292 | 1293 | See the guide about [Event Handlers](#event-handlers) for more details. 1294 | 1295 | ### onget, onset 1296 | **Define a custom field getter/setter** 1297 | 1298 | ```php 1299 | callback onget( string $field, callback $func ) 1300 | ``` 1301 | 1302 | See the guide about [Custom Field Handler](#custom-field-handler) for more details. 1303 | 1304 | ### clear 1305 | **Clear any mapper field or relation** 1306 | 1307 | ```php 1308 | null clear( string $key ) 1309 | ``` 1310 | 1311 | 1312 | ### cleared 1313 | **Returns whether the field was cleared or not** 1314 | 1315 | ```php 1316 | mixed initial( string $key ) 1317 | ``` 1318 | 1319 | If the field initially had data, but the data was cleared from the field, it returns that old cleared data. If no initial data was present or the field has not changed (cleared) `FALSE` is returned. 1320 | 1321 | ### clearFilter 1322 | **Removes one or all relation filter** 1323 | 1324 | ```php 1325 | null clearFilter([ string $key = null ]) 1326 | ``` 1327 | 1328 | Removes only the given `$key` filter or all, if none was given. 1329 | 1330 | 1331 | ### compare 1332 | **Compare new data against existing initial values of certain fields** 1333 | 1334 | ```php 1335 | null compare( array $fields, callback $new [, callback $old = null ]) 1336 | ``` 1337 | 1338 | This method compares new data in form of an assoc array of [field => value] against the initial field values and 1339 | calls a callback functions for *$new* and *$old* values, which can be used to prepare new / cleanup old data. 1340 | 1341 | Updated fields are set, the *$new* callback MUST return a value. 1342 | 1343 | ```php 1344 | $uploads=[ 1345 | 'profile_image' => 'temp_uploads/thats_me.jpg', 1346 | 'pictures' => ['7bbn4ksw8m5', 'temp_uploads/random_pic.jpg'] 1347 | ]; 1348 | $this->model->compare($uploads,function($filepath) { 1349 | // new files 1350 | return $this->handleFileUpload($filepath); 1351 | }, function($fileId){ 1352 | // old files 1353 | $this->deleteFile($fileId); 1354 | }); 1355 | ``` 1356 | 1357 | In the example above, we handle multiple fields and compare their values with an incoming array for new data. For each new field value or changed / added array item value, the `$new` function is called. For existing data, that's not present in the new data anymore, the `$old` function is called. 1358 | 1359 | ### copyfrom 1360 | **Hydrate the mapper from hive key or given array** 1361 | 1362 | ```php 1363 | null copyfrom( string|array $key [, callback|array|string $fields = null ]) 1364 | ``` 1365 | 1366 | Use this method to set multiple values to the mapper at once. 1367 | The `$key` parameter must be an array or a string of a hive key, where the actual array can be found. 1368 | 1369 | The `$fields` parameter can be a splittable string: 1370 | 1371 | ```php 1372 | $news->copyfrom('POST','title;text'); 1373 | ``` 1374 | 1375 | Or an array: 1376 | 1377 | ```php 1378 | $news->copyfrom('POST',['title','text']); 1379 | ``` 1380 | 1381 | Or a callback function, which is used to filter the input array: 1382 | 1383 | 1384 | ```php 1385 | $news->copyfrom('POST',function($fields) { 1386 | return array_intersect_key($fields,array_flip(['title','text'])); 1387 | }); 1388 | ``` 1389 | 1390 | ### copyto 1391 | **Copy mapper values into hive key** 1392 | 1393 | ```php 1394 | null copyto( string $key [, array|string $relDepth = 0 ]) 1395 | ``` 1396 | 1397 | ### copyto_flat 1398 | **Copy mapper values to hive key with relations being simple arrays of keys** 1399 | 1400 | ```php 1401 | null copyto_flat( string $key ) 1402 | ``` 1403 | 1404 | All `has-many` relations are being returned as simple array lists of their primary keys. 1405 | 1406 | 1407 | ### count 1408 | **Count records that match criteria** 1409 | 1410 | ```php 1411 | null count([ array $filter [, array $options = NULL [, int $ttl = 60 ]]]) 1412 | ``` 1413 | 1414 | Just like `find()` but it only executes a count query instead of the real select. 1415 | 1416 | 1417 | ### countRel 1418 | **add a virtual field that counts occurring relations** 1419 | 1420 | ```php 1421 | null countRel( string $key [, string $alias [, array $filter [, array $option]]]) 1422 | ``` 1423 | 1424 | The `$key` parameter must be an existing relation field name. This adds a virtual counter field to your result, 1425 | which contains the count/sum of the matching relations to the current record, which is named `count_{$key}`, unless you define a custom `$alias` for it. 1426 | 1427 | It's also possible to define a `$filter` and `$options` to the query that's used for counting the relations. 1428 | 1429 | You can also use this counter for sorting, like in this tag-cloud sample: 1430 | 1431 | ```php 1432 | $tags = new \Model\Tag(); 1433 | $tags->filter('news',['published = ? and publish_date <= ?', true, date('Y-m-d')]); 1434 | $tags->countRel('news'); 1435 | $result = $tags->find(['deleted = ?',0], ['order'=>'count_news desc']); 1436 | ``` 1437 | 1438 | This method also supports propagation, so you can define counters on nested relations pretty straightforward: 1439 | 1440 | ```php 1441 | // fetch all posts, with comments and count its likes (reactions of type "like") on each comment 1442 | $post->countRel('comments.reaction','count_likes', ['type = ?', 'like']); 1443 | $results = $post->find(); 1444 | ``` 1445 | 1446 | 1447 | ### dbtype 1448 | **Returns the currently used db type** 1449 | 1450 | ```php 1451 | string dbtype() 1452 | ``` 1453 | 1454 | The type is `SQL`, `Mongo` or `Jig`. 1455 | 1456 | 1457 | ### defaults 1458 | **Return default values from schema configuration** 1459 | 1460 | ```php 1461 | array defaults([ bool $set = FALSE ]) 1462 | ``` 1463 | 1464 | Returns a `$key` => `$value` array of fields that has a default value different than `NULL`. 1465 | 1466 | ### dry 1467 | **Return TRUE if current cursor position is not mapped to any record** 1468 | 1469 | ```php 1470 | bool dry() 1471 | ``` 1472 | 1473 | Sample: 1474 | 1475 | ```php 1476 | $mapper->load(['_id = ?','234']); 1477 | if ($mapper->dry()) { 1478 | // not found 1479 | } else { 1480 | // record was loaded 1481 | } 1482 | ``` 1483 | 1484 | ### erase 1485 | **Delete object/s and reset ORM** 1486 | 1487 | ```php 1488 | null erase([ array $filter = null ]) 1489 | ``` 1490 | 1491 | When a `$filter` parameter is set, it deletes all matching records: 1492 | 1493 | ```php 1494 | $user->erase(['deleted = ?', 1]); 1495 | ``` 1496 | 1497 | It deletes the loaded record when called on a hydrated mapper without `$filter` parameter: 1498 | 1499 | ```php 1500 | $user->load(['_id = ?',6]); 1501 | $user->erase(); 1502 | ``` 1503 | 1504 | This also calls the `beforeerase` and `aftererase` events. 1505 | 1506 | ### exists 1507 | **Check if a certain field exists in the mapper or is a virtual relation field** 1508 | 1509 | ```php 1510 | bool exists( string $key [, bool $relField = false ]) 1511 | ``` 1512 | 1513 | If `$relField` is true, it also checks the [$fieldConf](#fieldConf) for defined relational fields. 1514 | 1515 | 1516 | ### fields 1517 | **get fields or set whitelist / blacklist of fields** 1518 | 1519 | ```php 1520 | array fields([ array $fields = [] [, bool $exclude = false ]) 1521 | ``` 1522 | 1523 | When you call this method without any parameter, it returns a list of available fields from the schema. 1524 | 1525 | ```php 1526 | var_dump( $user->fields() ); 1527 | /* Array( 1528 | '_id' 1529 | 'username' 1530 | 'password' 1531 | 'email' 1532 | 'active' 1533 | 'deleted' 1534 | )*/ 1535 | ``` 1536 | 1537 | If you set a `$fields` array, it'll enable the field whitelisting, and put the given fields to that whitelist. 1538 | All non-whitelisted fields on loaded records are not available, visible nor accessible anymore. This is useful when you don't want certain fields in a returned casted array. 1539 | 1540 | ```php 1541 | $user->fields(['username','email']); // only those fields 1542 | $user->load(); 1543 | var_dump($user->cast()); 1544 | /* Array( 1545 | '_id' => 5 1546 | 'username' => joe358 1547 | 'email' => joe@domain.com 1548 | )*/ 1549 | ``` 1550 | 1551 | Calling this method will re-initialize the mapper and takes effect on any further load or find action, so run this first of all. 1552 | 1553 | If you set the `$exclude` parameter to `true`, it'll also enable the whitelisting, but set all available fields, without the given, to the whitelist. 1554 | In other words, the given $fields become blacklisted, the only the remaining fields stay visible. 1555 | 1556 | ```php 1557 | $user->fields(['email'], true); // all fields, but not these 1558 | $user->load(); 1559 | var_dump($user->cast()); 1560 | /* Array( 1561 | '_id' => 5 1562 | 'username' => joe358 1563 | 'password' => $18m$fsk555a3f2f08ff28 1564 | 'active' => 1 1565 | 'deleted' => 0 1566 | )*/ 1567 | ``` 1568 | 1569 | In case you have relational fields configured on the model, you can also prohibit access for the fields of that relations. For that use the dot-notation: 1570 | 1571 | ```php 1572 | $comments->fields(['user.password'], true); // exclude the password field in user model 1573 | $comments->load(); 1574 | var_dump($comments->cast()); 1575 | /* Array( 1576 | '_id' => 53 1577 | 'message' => .... 1578 | 'user' => Array( 1579 | '_id' => 5 1580 | 'username' => joe358 1581 | 'active' => 1 1582 | 'deleted' => 0 1583 | ) 1584 | )*/ 1585 | ``` 1586 | 1587 | You can call this method multiple times in conjunction. It'll always merge with your previously set white and blacklisted fields. 1588 | `_id` is always present. 1589 | 1590 | 1591 | ### filter 1592 | **Add filter for loading related models** 1593 | 1594 | ```php 1595 | Cortex filter( string $key [, array $filter = null [, array $options = null ]]) 1596 | ``` 1597 | 1598 | See [Advanced Filter Techniques](#advanced-filter-techniques). 1599 | 1600 | ### get 1601 | **Retrieve contents of key** 1602 | 1603 | ```php 1604 | mixed get( string $key [, bool $raw = false ]) 1605 | ``` 1606 | 1607 | If `$raw` is `true`, it'll return the raw data from a field as is. No further processing, no relation is resolved, no get-event fired. 1608 | Useful if you only want the raw foreign key value of a relational field. 1609 | 1610 | ### getRaw 1611 | **Retrieve raw contents of key** 1612 | 1613 | ```php 1614 | mixed getRaw( string $key ) 1615 | ``` 1616 | 1617 | This is a shortcut method to `$mapper->get('key', TRUE)`. 1618 | 1619 | ### getFieldConfiguration 1620 | **Returns model $fieldConf array** 1621 | 1622 | ```php 1623 | array|null getFieldConfiguration() 1624 | ``` 1625 | 1626 | ### getTable 1627 | **returns model table name** 1628 | 1629 | ```php 1630 | string getTable() 1631 | ``` 1632 | 1633 | If no table was defined, it uses the current class name to lowercase as table name. 1634 | 1635 | ### has 1636 | **Add has-conditional filter to next find call** 1637 | 1638 | ```php 1639 | Cortex has( string $key [, array $filter = null [, array $options = null ]]) 1640 | ``` 1641 | 1642 | See [Advanced Filter Techniques](#advanced-filter-techniques). 1643 | 1644 | ### orHas 1645 | **Add has-conditional filter with OR operator to previous condition** 1646 | 1647 | Same as has filter, but chains with a logical OR to the previous condition. 1648 | 1649 | 1650 | ### initial 1651 | **Return initial field value** 1652 | 1653 | ```php 1654 | mixed initial( string $key ) 1655 | ``` 1656 | 1657 | Returns the initial data from a field, like it was fetched from the database, even if the field as changed afterwards. Array fields are decoded / unserialized properly before it's returned. 1658 | 1659 | ### mergeFilter 1660 | **Glue multiple filter arrays together into one** 1661 | 1662 | ```php 1663 | array mergeFilter( array $filters [, string $glue = 'and' ]) 1664 | ``` 1665 | 1666 | This is useful when you want to add more conditions to your filter array or want to merge multiple filter arrays together, i.e. when you assemble the filter for a complex search functionality which is based on conditions. 1667 | Use the `$glue` parameter to define the part that is used to merge two filters together (usually `AND` or `OR`). 1668 | 1669 | ```php 1670 | $filter1 = ['_id = ?', 999]; 1671 | $filter2 = ['published = ? or active = ?', true, false]; 1672 | 1673 | $new_filter = $mapper->mergeFilter([$filter1, $filter2]); 1674 | // array('(_id = ?) and (published = ? or active = ?)', 999, true, false) 1675 | ``` 1676 | 1677 | ### paginate 1678 | **Return array containing subset of records matching criteria** 1679 | 1680 | ```php 1681 | array paginate([ int $pos = 0 [, int $size = 10 [, array $filter = NULL [, array $options = NULL [, int $ttl = 0 ]]]]]) 1682 | ``` 1683 | 1684 | See [Cursor->paginate](http://fatfreeframework.com/cursor#paginate). Any *has* and *filter* filters can be used in conjunction with paginate as well. 1685 | 1686 | 1687 | ### rel 1688 | **returns a clean/dry model from a relation** 1689 | 1690 | ```php 1691 | Cortex rel( string $key ) 1692 | ``` 1693 | 1694 | For instance, if `comments` is a one-to-many relation to `\Model\Comment`: 1695 | 1696 | ```php 1697 | $user->load(); 1698 | var_dump($user->comments); // array of comments 1699 | $new_comment = $user->rel('comments'); 1700 | // $new_comment is a new empty \Model\Comment 1701 | ``` 1702 | 1703 | 1704 | ### reset 1705 | **reset and re-initialize the mapper** 1706 | 1707 | ```php 1708 | null reset([ bool $mapper = true ]) 1709 | ``` 1710 | 1711 | If `$mapper` is *false*, it only reset filter, default values and internal caches of the mapper, but leaves the hydrates record untouched. 1712 | 1713 | ### resetFields 1714 | **reset only specific fields and return to their default values** 1715 | 1716 | ```php 1717 | null resetFields( array $fields ) 1718 | ``` 1719 | 1720 | If any field doesn't have a default value, it's reset to `NULL`. 1721 | 1722 | ### resolveConfiguration 1723 | **kick start mapper to fetch its config** 1724 | 1725 | ```php 1726 | array resolveConfiguration() 1727 | ``` 1728 | 1729 | Returns an array that exposes a mapper configuration. The array includes: 1730 | 1731 | * table 1732 | * fieldConf 1733 | * db 1734 | * fluid 1735 | * primary 1736 | 1737 | 1738 | ### save 1739 | **Save mapped record** 1740 | 1741 | It is recommended to always use the save method. It'll automatically see if you want to save a new record or update an existing, loaded record. 1742 | 1743 | ```php 1744 | $user->username = 'admin' 1745 | $user->email = 'admin@domain.com'; 1746 | $user->save(); // insert 1747 | 1748 | $user->reset(); 1749 | $user->load(['username = ?','admin']); 1750 | $user->email = 'webmaster@domain.com'; 1751 | $user->save(); // update 1752 | ``` 1753 | 1754 | The save method also fires the `beforeinsert`, `beforeupdate`, `afterinsert` and `afterupdate` events. 1755 | There are also `insert`and `update`method, but using that methods directly, will skip the events and any cascading actions. 1756 | 1757 | 1758 | ### set 1759 | **Bind value to key** 1760 | 1761 | ```php 1762 | mixed set( string $key, mixed $val ) 1763 | ``` 1764 | 1765 | ### setdown 1766 | **erase all model data, handle with care** 1767 | 1768 | ```php 1769 | null setdown([ object|string $db = null [, string $table = null ]]) 1770 | ``` 1771 | 1772 | This method completely drops the own table, and used many-to-many pivot-tables from the database. 1773 | 1774 | 1775 | ### setFieldConfiguration 1776 | **set model definition** 1777 | 1778 | ```php 1779 | null setFieldConfiguration( array $config ) 1780 | ``` 1781 | 1782 | Used to set the **$fieldConf** array. 1783 | 1784 | 1785 | ### setup 1786 | **setup / update table schema** 1787 | 1788 | ```php 1789 | bool setup([ object|string $db = null [, string $table = null [, array $fields = null ]]]) 1790 | ``` 1791 | 1792 | This method creates the needed tables for the model itself and additionally required pivot tables. It uses the internal model properties *$db*, *$table* and *fieldConf*, 1793 | but can also be fed with method parameters which would take precedence. 1794 | 1795 | 1796 | ### touch 1797 | **update a given date or time field with the current time** 1798 | 1799 | ```php 1800 | null touch( string $key [, int $timestamp = NULL ]) 1801 | ``` 1802 | 1803 | If `$key` is a defined field in the *$fieldConf* array, and is a type of date, datetime or timestamp, 1804 | this method updates the field to the current time/date in the appropriate format. 1805 | 1806 | If a `$timestamp` is given, that value is used instead of the current time. 1807 | 1808 | 1809 | ### valid 1810 | **Return whether current iterator position is valid.** 1811 | 1812 | ```php 1813 | bool valid() 1814 | ``` 1815 | 1816 | It's the counterpart to [dry()](#dry). 1817 | 1818 | ```php 1819 | $mapper->load(['_id = ?','234']); 1820 | if ($mapper->valid()) { 1821 | // record was loaded 1822 | } else { 1823 | // not found 1824 | } 1825 | ``` 1826 | 1827 | 1828 | ### virtual 1829 | **virtual mapper field setter** 1830 | 1831 | ```php 1832 | null virtual( string $key, mixed $val ) 1833 | ``` 1834 | 1835 | This sets a custom virtual field to the mapper. Useful for some on-demand operations: 1836 | 1837 | ```php 1838 | $user->virtual('pw_unsecure', function($this) { 1839 | return \Bcrypt::instance()->needs_rehash($this->password, 10); 1840 | }); 1841 | ``` 1842 | 1843 | It is possible to use the virtual fields for a post-sorting on a selected collection, see [virtual fields](#virtual-fields). 1844 | 1845 | 1846 | ## Collection API 1847 | 1848 | Whenever you use the `find` method, it will return an instance of the new CortexCollection class. This way we are able determine the whole collection from the inside of every single mapper in the results, and that gives us some more advanced features, like the [smart-loading of relations](https://github.com/ikkez/F3-Sugar/issues/23#issuecomment-24956163). The CortexCollection implements the `ArrayIterator` interface, so it is accessible like an usual array. Here are some of the most useful methods the Cortex Collection offers: 1849 | 1850 | ### add 1851 | **add single model to collection** 1852 | 1853 | ```php 1854 | null add( Cortex $model ) 1855 | ``` 1856 | 1857 | It's also possible to use the array notation to add models: 1858 | 1859 | ```php 1860 | $news->load(); 1861 | $new_comment = $news->rel('comments'); 1862 | $new_comment->text = 'Foo Bar'; 1863 | $news->comments[] = $new_comment; 1864 | $news->save(); 1865 | ``` 1866 | 1867 | 1868 | ### castAll 1869 | **cast all contained mappers to a nested array** 1870 | 1871 | ```php 1872 | array castAll([ $reldepths = 1 ]) 1873 | ``` 1874 | 1875 | Similar to the `Cortex->cast` method for a single mapper, this automatically casts all containing mappers to a simple nested array. 1876 | 1877 | ```php 1878 | $result = $news->find(['published = ?',true]); 1879 | if ($result) 1880 | $json = json_encode($result->castAll()); 1881 | ``` 1882 | 1883 | Use the `$reldepths` parameter to define what to cast, see [cast](#cast) method for details. 1884 | 1885 | ### compare 1886 | **compare collection with a given ID stack** 1887 | 1888 | ```php 1889 | array compare( array|CortexCollection $stack [, string $cpm_key = '_id']) 1890 | ``` 1891 | 1892 | This method is useful to compare the current collection with another collection or a list of values that is checked for existence in the collection records. 1893 | 1894 | In example you got a relation collection that is about to be updated and you want to know which records are going to be removed or would be new in the collection: 1895 | 1896 | ```php 1897 | $res = $user->friends->compare($newFriendIds); 1898 | if (isset($res['old'])) { 1899 | // removed friends 1900 | } 1901 | if (isset($res['new'])) { 1902 | // added friends 1903 | foreach($res['new'] as $userId) { 1904 | // do something with $userId 1905 | } 1906 | } 1907 | ``` 1908 | 1909 | The compare result `$res` is an array that can contain the array keys `old` and `new`, which both represent an array of `$cpm_key` values. 1910 | 1911 | NB: This is just a comparison - it actually does not update any of the collections. Add a simple `$user->friends = $newFriendIds;` after comparison to update the collection. 1912 | 1913 | 1914 | ### contains 1915 | **check if the collection contains a record with the given key-val set** 1916 | 1917 | ```php 1918 | bool contains( mixed|Cortex $val [, string $key = '_id' ]) 1919 | ``` 1920 | 1921 | This method can come handy to check if a collections contains a given record, or has a record with a given value: 1922 | 1923 | ```php 1924 | if ($user->friends && $user->friends->contains($newFriend)) { 1925 | $f3->error(400,'This user is already your friend'); 1926 | return; 1927 | } 1928 | ``` 1929 | 1930 | With custom compare key: 1931 | 1932 | ```php 1933 | if ($user->blocked_users->contains($currentUserId,'target')) { 1934 | // this user has blocked you 1935 | } 1936 | ``` 1937 | 1938 | 1939 | ### expose 1940 | **return internal array representation** 1941 | 1942 | ```php 1943 | array expose() 1944 | ``` 1945 | 1946 | ### factory 1947 | **create a new collection instance from given records** 1948 | 1949 | ```php 1950 | CortexCollection factory( array $records ) 1951 | ``` 1952 | 1953 | `$records` must be an array, containing Cortex mapper objects. 1954 | 1955 | ### getAll 1956 | **returns all values of a specified property from all models** 1957 | 1958 | ```php 1959 | array getAll( string $prop [, bool $raw = false ]) 1960 | ``` 1961 | 1962 | You can fetch all values of a certain key from all containing mappers using `getAll()`. Set the 2nd argument to `true` to get only the raw DB results instead of resolved mappers on fields that are configured as a relation. 1963 | 1964 | ```php 1965 | $users = $user->find(['active = ?',1]); 1966 | $mails = $users->getAll('email'); 1967 | /* Array( 1968 | 'user1@domain.com', 1969 | 'user2@domain.com', 1970 | 'user3@domain.com' 1971 | )*/ 1972 | ``` 1973 | 1974 | 1975 | ### getBy 1976 | 1977 | ```php 1978 | array getBy( string $index [, bool $nested = false ]) 1979 | ``` 1980 | 1981 | You can transpose the results by a defined key using `getBy()`. 1982 | Therefore you need to provide an existing field in the mapper, like this; 1983 | 1984 | ```php 1985 | $pages = $page->find(); 1986 | $pages_by_slug = $pages->getBy('slug'); 1987 | ``` 1988 | 1989 | This will resort the resulting array by the email field of each mapper, which gives you a result array like `array("foo@domain.com"=>array(...))`. If you provide `true` as 2nd argument, the records are ordered into another array depth, to keep track of multiple results per key. 1990 | 1991 | ### hasChanged 1992 | **returns true if any model was modified after it was added to the collection** 1993 | 1994 | ```php 1995 | bool hasChanged() 1996 | ``` 1997 | 1998 | ### orderBy 1999 | **re-assort the current collection using a sql-like syntax** 2000 | 2001 | ```php 2002 | null orderBy( string $cond ) 2003 | ``` 2004 | 2005 | If you need to re-sort a result collection once more to another key, use this method like `$results->orderBy('name DESC');`. This also works with multiple sort keys. 2006 | 2007 | 2008 | ### setModels 2009 | **set a collection of models** 2010 | 2011 | ```php 2012 | array setModels( array $models [, bool $init = true ]) 2013 | ``` 2014 | 2015 | This adds multiple Cortex objects to the own collection. When `$init` is `true`, added models with this method wont effect the **changed** state. 2016 | 2017 | ### slice 2018 | **slice the collection** 2019 | 2020 | ```php 2021 | null slice( int $offset [, int $limit = null ]) 2022 | ``` 2023 | 2024 | This removes a part from the collection. 2025 | 2026 | 2027 | 2028 | ## Additional notes 2029 | 2030 | * To release any relation, just set the field to `NULL` and save the mapper. 2031 | 2032 | * All relations are lazy loaded to save performance. That means they won't get loaded until you access them by the linked property or cast the whole parent model. 2033 | 2034 | * lazy loading within a result collection will **automatically** invoke the eager loading of that property **to the whole set**. The results are saved to an [Identity Map](https://martinfowler.com/eaaCatalog/identityMap.html) to relieve the strain on further calls. I called this _smart loading_ and is used to get around the [1+N query problem](https://secure.phabricator.com/book/phabcontrib/article/n_plus_one/) with no need for extra configuration. 2035 | 2036 | * If you need to use a primary key in SQL that is different from `id` (for any legacy reason), you can use the `$primary` class property to set it to something else. You should use the new custom pkey in your queries now. Doing so will limit your app to SQL engines. 2037 | 2038 | * to get the id of any record use `$user->_id;`. This even works if you have setup a custom primary key. 2039 | 2040 | * To find any record by its **id** use the field `_id` in your filter array, like `['_id = ?', 123]`. 2041 | 2042 | * primary fields should not be included in the `$fieldConf` array. They could interfere with the [setup](#set-up) routine. 2043 | 2044 | * There are some little behaviours of Cortex you can control by these hive keys: 2045 | 2046 | * `CORTEX.queryParserCache`: if `TRUE` all query strings are going to be cached too (may add a lot of cache entries). Default: `FALSE` 2047 | 2048 | * `CORTEX.smartLoading`: triggers the intelligent-lazy-eager-loading. Default is `TRUE`, but turn it off if you think something works wrong. Could cause a lot of extra queries send to your DB, if deactivated. 2049 | 2050 | * `CORTEX.standardiseID`: Default `TRUE`. This moves any defined primary key into the `_id` field on returned arrays. 2051 | 2052 | * `CORTEX.quoteConditions`: Default `TRUE`. By default, all field names in where conditions are quoted automatically according to the used database engine. This helps to work around reserved names in SQL. However the detection of fields isn't perfect yet, so in case you want to add the correct backticks or other quotation yourself, set this to `FALSE`. 2053 | 2054 | ## Known Issues 2055 | 2056 | * Not really a bug, but returned collections (from relations, *find*, or *paginate* method) are not cloneable because they need to keep a unique references to the identity map of its relations. This leads to the point that all containing mappers are not automatically escaped in templates, regardless of the `ESCAPE` setting. Keep in mind to add the `| esc` filter to your tokens. 2057 | 2058 | If you find any issues or bugs, please file a [new Issue](https://github.com/ikkez/F3-Sugar/issues) on github or write a mail. Thanks. 2059 | 2060 | ## Roadmap 2061 | 2062 | If you have any ideas, suggestions or improvements, feel free to add an issue for this on github. 2063 | 2064 | 2065 | Cortex currently only reflects to the most common use cases. If you need more extensive control over your queries or the DB, you may consider to use the underlying mapper or DB directly. This could be done in custom methods or field preprocessors in your Model classes. 2066 | 2067 | Anyways, I hope you find this useful. If you like this plugin, why not make a donation? 2068 | 2069 | [![buy me a Beer](https://ikkez.de/linked/Beer/bdb_small_single.png)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=44UHPNUCVP7QG) 2070 | 2071 | If you like to see Cortex in action, have a look at [fabulog](https://github.com/ikkez/fabulog "the new fabulous blog-ware"). 2072 | 2073 | License 2074 | - 2075 | 2076 | GPLv3 2077 | 2078 | 2079 | 2080 | -------------------------------------------------------------------------------- /test/app/cortex.php: -------------------------------------------------------------------------------- 1 | set('QUIET', false); 11 | 12 | $dbs = array( 13 | 'sql-sqlite' => new \DB\SQL('sqlite:data/sqlite-cortex.db'), 14 | 'sql-mysql' => new \DB\SQL('mysql:host=f3-mysql;port=3306;dbname=fatfree', 'fatfree', 'fatfree'), 15 | 'sql-pgsql' => new \DB\SQL('pgsql:host=f3-pgsql;dbname=fatfree', 'fatfree', 'fatfree'), 16 | 'jig' => new \DB\Jig('data/',\DB\Jig::FORMAT_JSON,true), 17 | // 'mongo' => new \DB\Mongo('mongodb://localhost:27017', 'testdb'), 18 | // 'sqlsrv2008' => new \DB\SQL('sqlsrv:SERVER=WIN7\SQLEXPRESS2008;Database=fatfree','sa', 'fatfree'), 19 | // 'sqlsrv2012' => new \DB\SQL('sqlsrv:SERVER=WIN7\SQLEXPRESS2012;Database=fatfree','sa', 'fatfree'), 20 | // 'sqlsrv2014' => new \DB\SQL('sqlsrv:SERVER=WIN7\SQLEXPRESS2014;Database=fatfree','sa', 'fatfree'), 21 | ); 22 | $results = array(); 23 | 24 | // $dbs['mongo']->log(false); 25 | 26 | // Test Syntax 27 | foreach ($dbs as $type => $db) { 28 | $test = new \Test_Syntax(); 29 | $results = array_merge((array) $results, (array) $test->run($db, $type)); 30 | } 31 | 32 | // Test Relations 33 | foreach ($dbs as $type => $db) { 34 | $f3->set('DB',$db); 35 | $test = new \Test_Relation(); 36 | $results = array_merge((array) $results, (array) $test->run($db, $type)); 37 | } 38 | 39 | // Test Filter 40 | foreach ($dbs as $type => $db) { 41 | $f3->set('DB',$db); 42 | $test = new \Test_Filter(); 43 | $results = array_merge((array) $results, (array) $test->run($db, $type)); 44 | } 45 | 46 | // Further Common Tests 47 | if (isset($dbs['sql-mysql'])) { 48 | $test = new \Test_Common(); 49 | $f3->set('DB', $dbs['sql-mysql']); 50 | $results = array_merge((array) $results, (array) $test->run()); 51 | } 52 | 53 | $f3->set('results', $results); 54 | } 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /test/app/cortex_benchmark.php: -------------------------------------------------------------------------------- 1 | f3->get('timer') - $this->roundTime; 17 | $this->roundTime = microtime(TRUE) - $this->f3->get('timer'); 18 | return $this->currentType.' [ '.sprintf('%.3f', $time).'s ]'; 19 | } 20 | 21 | 22 | function get() 23 | { 24 | $this->f3 = \Base::instance(); 25 | $this->f3->set('AUTOLOAD', $this->f3->get('AUTOLOAD').';app/cortex/'); 26 | $this->f3->set('QUIET', false); 27 | 28 | $this->test = new \Test(); 29 | 30 | $dbs = array( 31 | 'sql' => new \DB\SQL('mysql:host=localhost;port=3306;dbname=fatfree', 'fatfree', ''), 32 | // 'jig' => new \DB\Jig('data/'), 33 | // 'mongo' => new \DB\Mongo('mongodb://localhost:27017', 'testdb') 34 | ); 35 | 36 | foreach ($dbs as $type => $db) { 37 | 38 | $this->f3->set('DB',$db); 39 | $this->currentType = $type; 40 | 41 | $this->roundTime = microtime(TRUE) - \Base::instance()->get('timer'); 42 | 43 | \AuthorModel::setdown(); 44 | \TagModel::setdown(); 45 | \NewsModel::setdown(); 46 | 47 | \AuthorModel::setup(); 48 | \TagModel::setup(); 49 | \NewsModel::setup(); 50 | 51 | $this->insert_tags(); 52 | $this->insert_authors(); 53 | $this->insert_news(); 54 | $this->insert_news(); 55 | 56 | $news = new \NewsModel(); 57 | // reset timer 58 | $this->getTime(); 59 | 60 | // $result = $news->find(null,array('limit'=>5000)); 61 | // $this->test->message($this->getTime()." hydrate 5000 records"); 62 | 63 | // unset($news,$result); 64 | // $news = new \NewsModel(); 65 | 66 | // $result = $news->find(null,array('limit' => 1000)); 67 | // $result[0]->author->name; 68 | // $this->test->message($this->getTime()." hydrate 1000 records with 1 relation fixed size"); 69 | 70 | // unset($result); 71 | $result = $news->find(null, array('limit' => 1000)); 72 | $result[0]->tags2[0]; 73 | $this->test->message($this->getTime()." hydrate 1000 records with 1 relation random size"); 74 | 75 | // $this->test->message($this->getTime()." hydrate 1000 records with 2 relations random size"); 76 | 77 | // $result = $news->find('author = 11'); 78 | // $this->test->message($this->getTime()." find news from a specific author(11): ".count($result).' news found'); 79 | 80 | // $result = $news->has('author',array('mail LIKE ?','%.co.uk%'))->find(); 81 | // $this->test->message($this->getTime()." find news with has condition on author: ".count($result).' news found'); 82 | 83 | // var_dump($this->f3->get('DB')->log()); 84 | 85 | } 86 | 87 | $this->f3->set('results', $this->test->results()); 88 | } 89 | 90 | function insert_tags() 91 | { 92 | $tags = new \TagModel(); 93 | $newTags = array( 94 | 'CSS','HTML','JavaScript','Techniques','Typography', 95 | 'Inspiration','Business','User Experience','E-Commerce','Design Pattern' 96 | ); 97 | 98 | foreach($newTags as $record) { 99 | $tags->title = $record; 100 | $tags->save(); 101 | $tags->reset(); 102 | } 103 | 104 | $this->test->message($this->getTime()." imported 10 Tags "); 105 | } 106 | 107 | function insert_authors() 108 | { 109 | $author = new \AuthorModel(); 110 | 111 | $author_data = json_decode($this->f3->read('app/cortex/bench/user.json'),true); 112 | 113 | foreach($author_data as $record) { 114 | $author->copyfrom($record); 115 | $author->save(); 116 | $author->reset(); 117 | } 118 | 119 | $this->test->message($this->getTime()." imported 20 Users"); 120 | } 121 | 122 | function insert_news() 123 | { 124 | $news = new \NewsModel(); 125 | $news_data = json_decode($this->f3->read('app/cortex/bench/news.json'),true); 126 | for($i=0;$i<5;$i++) 127 | foreach($news_data as $record) { 128 | $news->title = $record['title']; 129 | $news->text = $record['text']; 130 | $news->author = $record['author']; 131 | $news->tags2 = $record['tags2']; 132 | $news->save(); 133 | $news->reset(); 134 | } 135 | $this->test->message($this->getTime()." imported 500 News"); 136 | } 137 | 138 | } -------------------------------------------------------------------------------- /test/authormodel.php: -------------------------------------------------------------------------------- 1 | [ 8 | 'type' => \DB\SQL\Schema::DT_VARCHAR256 9 | ], 10 | 'mail' => [ 11 | 'type' => \DB\SQL\Schema::DT_VARCHAR256 12 | ], 13 | 'website' => [ 14 | 'type' => \DB\SQL\Schema::DT_VARCHAR256 15 | ], 16 | 'news' => [ 17 | 'has-many' => ['\NewsModel','author'], 18 | ], 19 | 'profile' => [ 20 | 'has-one' => ['\ProfileModel','author'], 21 | ], 22 | 'friends' => [ 23 | 'has-many' => ['\AuthorModel','friends'], 24 | ], 25 | ], 26 | $primary = 'id', 27 | $table = 'author', 28 | $db = 'DB'; 29 | 30 | } 31 | -------------------------------------------------------------------------------- /test/bench/news.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": 1, 4 | "title": "ullamcorper eu, euismod ac, fermentum vel,", 5 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu", 6 | "author": 9, 7 | "tags2": "3" 8 | }, 9 | { 10 | "id": 2, 11 | "title": "eu augue porttitor interdum. Sed auctor", 12 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin", 13 | "author": 16, 14 | "tags2": "9, 1, 5" 15 | }, 16 | { 17 | "id": 3, 18 | "title": "fermentum convallis ligula. Donec luctus aliquet", 19 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper.", 20 | "author": 5, 21 | "tags2": "6" 22 | }, 23 | { 24 | "id": 4, 25 | "title": "adipiscing fringilla, porttitor vulputate, posuere vulputate,", 26 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque", 27 | "author": 14, 28 | "tags2": "8" 29 | }, 30 | { 31 | "id": 5, 32 | "title": "orci. Ut sagittis lobortis mauris. Suspendisse", 33 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin", 34 | "author": 16, 35 | "tags2": "1, 10, 2" 36 | }, 37 | { 38 | "id": 6, 39 | "title": "ante. Nunc mauris sapien, cursus in,", 40 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque", 41 | "author": 19, 42 | "tags2": "4, 6" 43 | }, 44 | { 45 | "id": 7, 46 | "title": "blandit at, nisi. Cum sociis natoque", 47 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus.", 48 | "author": 6, 49 | "tags2": "6, 9" 50 | }, 51 | { 52 | "id": 8, 53 | "title": "Nam ligula elit, pretium et, rutrum", 54 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus.", 55 | "author": 1, 56 | "tags2": "7, 5, 1" 57 | }, 58 | { 59 | "id": 9, 60 | "title": "eu erat semper rutrum. Fusce dolor", 61 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida", 62 | "author": 11, 63 | "tags2": "" 64 | }, 65 | { 66 | "id": 10, 67 | "title": "orci, in consequat enim diam vel", 68 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede", 69 | "author": 8, 70 | "tags2": "" 71 | }, 72 | { 73 | "id": 11, 74 | "title": "libero lacus, varius et, euismod et,", 75 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor.", 76 | "author": 12, 77 | "tags2": "7, 4, 1" 78 | }, 79 | { 80 | "id": 12, 81 | "title": "Curabitur sed tortor. Integer aliquam adipiscing", 82 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna.", 83 | "author": 16, 84 | "tags2": "10" 85 | }, 86 | { 87 | "id": 13, 88 | "title": "in, dolor. Fusce feugiat. Lorem ipsum", 89 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam", 90 | "author": 1, 91 | "tags2": "" 92 | }, 93 | { 94 | "id": 14, 95 | "title": "vehicula aliquet libero. Integer in magna.", 96 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis", 97 | "author": 11, 98 | "tags2": "3, 4" 99 | }, 100 | { 101 | "id": 15, 102 | "title": "pharetra nibh. Aliquam ornare, libero at", 103 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis", 104 | "author": 11, 105 | "tags2": "9, 3" 106 | }, 107 | { 108 | "id": 16, 109 | "title": "sed, hendrerit a, arcu. Sed et", 110 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu", 111 | "author": 4, 112 | "tags2": "" 113 | }, 114 | { 115 | "id": 17, 116 | "title": "eget odio. Aliquam vulputate ullamcorper magna.", 117 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque", 118 | "author": 4, 119 | "tags2": "4" 120 | }, 121 | { 122 | "id": 18, 123 | "title": "sagittis. Duis gravida. Praesent eu nulla", 124 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis", 125 | "author": 11, 126 | "tags2": "2" 127 | }, 128 | { 129 | "id": 19, 130 | "title": "pellentesque, tellus sem mollis dui, in", 131 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper.", 132 | "author": 7, 133 | "tags2": "9, 2" 134 | }, 135 | { 136 | "id": 20, 137 | "title": "sit amet risus. Donec egestas. Aliquam", 138 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada", 139 | "author": 6, 140 | "tags2": "3, 1" 141 | }, 142 | { 143 | "id": 21, 144 | "title": "mus. Proin vel nisl. Quisque fringilla", 145 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper.", 146 | "author": 16, 147 | "tags2": "9" 148 | }, 149 | { 150 | "id": 22, 151 | "title": "Nunc sed orci lobortis augue scelerisque", 152 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum", 153 | "author": 19, 154 | "tags2": "" 155 | }, 156 | { 157 | "id": 23, 158 | "title": "mauris. Integer sem elit, pharetra ut,", 159 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum", 160 | "author": 18, 161 | "tags2": "2" 162 | }, 163 | { 164 | "id": 24, 165 | "title": "convallis est, vitae sodales nisi magna", 166 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis", 167 | "author": 12, 168 | "tags2": "4, 1" 169 | }, 170 | { 171 | "id": 25, 172 | "title": "Sed eget lacus. Mauris non dui", 173 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna.", 174 | "author": 2, 175 | "tags2": "2" 176 | }, 177 | { 178 | "id": 26, 179 | "title": "semper erat, in consectetuer ipsum nunc", 180 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor.", 181 | "author": 13, 182 | "tags2": "" 183 | }, 184 | { 185 | "id": 27, 186 | "title": "consequat nec, mollis vitae, posuere at,", 187 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada", 188 | "author": 18, 189 | "tags2": "4, 9" 190 | }, 191 | { 192 | "id": 28, 193 | "title": "gravida sagittis. Duis gravida. Praesent eu", 194 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien,", 195 | "author": 10, 196 | "tags2": "" 197 | }, 198 | { 199 | "id": 29, 200 | "title": "blandit enim consequat purus. Maecenas libero", 201 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis", 202 | "author": 9, 203 | "tags2": "" 204 | }, 205 | { 206 | "id": 30, 207 | "title": "amet ornare lectus justo eu arcu.", 208 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id,", 209 | "author": 8, 210 | "tags2": "9, 10, 7" 211 | }, 212 | { 213 | "id": 31, 214 | "title": "habitant morbi tristique senectus et netus", 215 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis", 216 | "author": 11, 217 | "tags2": "1" 218 | }, 219 | { 220 | "id": 32, 221 | "title": "elit, dictum eu, eleifend nec, malesuada", 222 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a,", 223 | "author": 9, 224 | "tags2": "" 225 | }, 226 | { 227 | "id": 33, 228 | "title": "montes, nascetur ridiculus mus. Aenean eget", 229 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus", 230 | "author": 7, 231 | "tags2": "" 232 | }, 233 | { 234 | "id": 34, 235 | "title": "Nam porttitor scelerisque neque. Nullam nisl.", 236 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada", 237 | "author": 15, 238 | "tags2": "7, 5" 239 | }, 240 | { 241 | "id": 35, 242 | "title": "magnis dis parturient montes, nascetur ridiculus", 243 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper.", 244 | "author": 15, 245 | "tags2": "" 246 | }, 247 | { 248 | "id": 36, 249 | "title": "dolor. Quisque tincidunt pede ac urna.", 250 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida", 251 | "author": 4, 252 | "tags2": "5, 3" 253 | }, 254 | { 255 | "id": 37, 256 | "title": "tristique senectus et netus et malesuada", 257 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis", 258 | "author": 16, 259 | "tags2": "8, 6" 260 | }, 261 | { 262 | "id": 38, 263 | "title": "amet ante. Vivamus non lorem vitae", 264 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque", 265 | "author": 16, 266 | "tags2": "6, 4" 267 | }, 268 | { 269 | "id": 39, 270 | "title": "dui quis accumsan convallis, ante lectus", 271 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum", 272 | "author": 18, 273 | "tags2": "4, 5, 3" 274 | }, 275 | { 276 | "id": 40, 277 | "title": "netus et malesuada fames ac turpis", 278 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus.", 279 | "author": 16, 280 | "tags2": "" 281 | }, 282 | { 283 | "id": 41, 284 | "title": "eros non enim commodo hendrerit. Donec", 285 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor.", 286 | "author": 3, 287 | "tags2": "" 288 | }, 289 | { 290 | "id": 42, 291 | "title": "scelerisque dui. Suspendisse ac metus vitae", 292 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque", 293 | "author": 3, 294 | "tags2": "3, 10" 295 | }, 296 | { 297 | "id": 43, 298 | "title": "odio. Etiam ligula tortor, dictum eu,", 299 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum", 300 | "author": 17, 301 | "tags2": "10" 302 | }, 303 | { 304 | "id": 44, 305 | "title": "posuere cubilia Curae; Donec tincidunt. Donec", 306 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque", 307 | "author": 6, 308 | "tags2": "8, 7, 2" 309 | }, 310 | { 311 | "id": 45, 312 | "title": "in felis. Nulla tempor augue ac", 313 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis", 314 | "author": 20, 315 | "tags2": "9" 316 | }, 317 | { 318 | "id": 46, 319 | "title": "eget metus. In nec orci. Donec", 320 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin", 321 | "author": 13, 322 | "tags2": "" 323 | }, 324 | { 325 | "id": 47, 326 | "title": "sagittis. Duis gravida. Praesent eu nulla", 327 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt", 328 | "author": 1, 329 | "tags2": "1, 6" 330 | }, 331 | { 332 | "id": 48, 333 | "title": "nibh vulputate mauris sagittis placerat. Cras", 334 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id,", 335 | "author": 13, 336 | "tags2": "1, 8, 5" 337 | }, 338 | { 339 | "id": 49, 340 | "title": "urna. Ut tincidunt vehicula risus. Nulla", 341 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida", 342 | "author": 9, 343 | "tags2": "7" 344 | }, 345 | { 346 | "id": 50, 347 | "title": "ligula. Aliquam erat volutpat. Nulla dignissim.", 348 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque", 349 | "author": 18, 350 | "tags2": "" 351 | }, 352 | { 353 | "id": 51, 354 | "title": "Phasellus dolor elit, pellentesque a, facilisis", 355 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac", 356 | "author": 15, 357 | "tags2": "" 358 | }, 359 | { 360 | "id": 52, 361 | "title": "malesuada id, erat. Etiam vestibulum massa", 362 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis", 363 | "author": 5, 364 | "tags2": "1" 365 | }, 366 | { 367 | "id": 53, 368 | "title": "Nulla interdum. Curabitur dictum. Phasellus in", 369 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt", 370 | "author": 6, 371 | "tags2": "1, 10" 372 | }, 373 | { 374 | "id": 54, 375 | "title": "viverra. Maecenas iaculis aliquet diam. Sed", 376 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum", 377 | "author": 12, 378 | "tags2": "9, 5" 379 | }, 380 | { 381 | "id": 55, 382 | "title": "vel quam dignissim pharetra. Nam ac", 383 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras", 384 | "author": 16, 385 | "tags2": "" 386 | }, 387 | { 388 | "id": 56, 389 | "title": "neque vitae semper egestas, urna justo", 390 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis", 391 | "author": 11, 392 | "tags2": "6, 2, 7" 393 | }, 394 | { 395 | "id": 57, 396 | "title": "congue, elit sed consequat auctor, nunc", 397 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna.", 398 | "author": 17, 399 | "tags2": "7, 1" 400 | }, 401 | { 402 | "id": 58, 403 | "title": "imperdiet non, vestibulum nec, euismod in,", 404 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin", 405 | "author": 18, 406 | "tags2": "10" 407 | }, 408 | { 409 | "id": 59, 410 | "title": "nibh sit amet orci. Ut sagittis", 411 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus", 412 | "author": 5, 413 | "tags2": "10, 7" 414 | }, 415 | { 416 | "id": 60, 417 | "title": "eu dolor egestas rhoncus. Proin nisl", 418 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id,", 419 | "author": 12, 420 | "tags2": "4, 8, 3" 421 | }, 422 | { 423 | "id": 61, 424 | "title": "consequat nec, mollis vitae, posuere at,", 425 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin", 426 | "author": 19, 427 | "tags2": "3, 9, 5" 428 | }, 429 | { 430 | "id": 62, 431 | "title": "eros non enim commodo hendrerit. Donec", 432 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id,", 433 | "author": 18, 434 | "tags2": "9" 435 | }, 436 | { 437 | "id": 63, 438 | "title": "natoque penatibus et magnis dis parturient", 439 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper.", 440 | "author": 10, 441 | "tags2": "10, 5" 442 | }, 443 | { 444 | "id": 64, 445 | "title": "tempor, est ac mattis semper, dui", 446 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at", 447 | "author": 20, 448 | "tags2": "" 449 | }, 450 | { 451 | "id": 65, 452 | "title": "mi lorem, vehicula et, rutrum eu,", 453 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non,", 454 | "author": 8, 455 | "tags2": "9, 3" 456 | }, 457 | { 458 | "id": 66, 459 | "title": "sapien, cursus in, hendrerit consectetuer, cursus", 460 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida", 461 | "author": 4, 462 | "tags2": "7" 463 | }, 464 | { 465 | "id": 67, 466 | "title": "tellus justo sit amet nulla. Donec", 467 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada", 468 | "author": 18, 469 | "tags2": "6" 470 | }, 471 | { 472 | "id": 68, 473 | "title": "ultrices iaculis odio. Nam interdum enim", 474 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque", 475 | "author": 11, 476 | "tags2": "10, 3" 477 | }, 478 | { 479 | "id": 69, 480 | "title": "est, mollis non, cursus non, egestas", 481 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet", 482 | "author": 1, 483 | "tags2": "10" 484 | }, 485 | { 486 | "id": 70, 487 | "title": "Etiam ligula tortor, dictum eu, placerat", 488 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque", 489 | "author": 12, 490 | "tags2": "3, 6" 491 | }, 492 | { 493 | "id": 71, 494 | "title": "sapien, cursus in, hendrerit consectetuer, cursus", 495 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus", 496 | "author": 7, 497 | "tags2": "3, 7" 498 | }, 499 | { 500 | "id": 72, 501 | "title": "erat semper rutrum. Fusce dolor quam,", 502 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus", 503 | "author": 2, 504 | "tags2": "5, 2" 505 | }, 506 | { 507 | "id": 73, 508 | "title": "lacus, varius et, euismod et, commodo", 509 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus", 510 | "author": 16, 511 | "tags2": "" 512 | }, 513 | { 514 | "id": 74, 515 | "title": "Vestibulum ante ipsum primis in faucibus", 516 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque", 517 | "author": 10, 518 | "tags2": "" 519 | }, 520 | { 521 | "id": 75, 522 | "title": "quis arcu vel quam dignissim pharetra.", 523 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus.", 524 | "author": 8, 525 | "tags2": "4, 10, 7" 526 | }, 527 | { 528 | "id": 76, 529 | "title": "tristique senectus et netus et malesuada", 530 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada", 531 | "author": 16, 532 | "tags2": "7, 3, 1" 533 | }, 534 | { 535 | "id": 77, 536 | "title": "fringilla cursus purus. Nullam scelerisque neque", 537 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut", 538 | "author": 6, 539 | "tags2": "7" 540 | }, 541 | { 542 | "id": 78, 543 | "title": "vel pede blandit congue. In scelerisque", 544 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis", 545 | "author": 1, 546 | "tags2": "4" 547 | }, 548 | { 549 | "id": 79, 550 | "title": "et malesuada fames ac turpis egestas.", 551 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien,", 552 | "author": 13, 553 | "tags2": "" 554 | }, 555 | { 556 | "id": 80, 557 | "title": "varius orci, in consequat enim diam", 558 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id,", 559 | "author": 5, 560 | "tags2": "10" 561 | }, 562 | { 563 | "id": 81, 564 | "title": "egestas hendrerit neque. In ornare sagittis", 565 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras", 566 | "author": 4, 567 | "tags2": "7, 10, 5" 568 | }, 569 | { 570 | "id": 82, 571 | "title": "neque. Nullam nisl. Maecenas malesuada fringilla", 572 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras", 573 | "author": 19, 574 | "tags2": "2, 5" 575 | }, 576 | { 577 | "id": 83, 578 | "title": "Proin eget odio. Aliquam vulputate ullamcorper", 579 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada", 580 | "author": 13, 581 | "tags2": "" 582 | }, 583 | { 584 | "id": 84, 585 | "title": "urna convallis erat, eget tincidunt dui", 586 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac", 587 | "author": 5, 588 | "tags2": "8, 4" 589 | }, 590 | { 591 | "id": 85, 592 | "title": "Vivamus non lorem vitae odio sagittis", 593 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis", 594 | "author": 9, 595 | "tags2": "" 596 | }, 597 | { 598 | "id": 86, 599 | "title": "elit, pretium et, rutrum non, hendrerit", 600 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis", 601 | "author": 7, 602 | "tags2": "6, 1, 3" 603 | }, 604 | { 605 | "id": 87, 606 | "title": "faucibus id, libero. Donec consectetuer mauris", 607 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis", 608 | "author": 12, 609 | "tags2": "1, 3, 4" 610 | }, 611 | { 612 | "id": 88, 613 | "title": "sem. Nulla interdum. Curabitur dictum. Phasellus", 614 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras", 615 | "author": 4, 616 | "tags2": "1, 9, 2" 617 | }, 618 | { 619 | "id": 89, 620 | "title": "odio. Phasellus at augue id ante", 621 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a,", 622 | "author": 1, 623 | "tags2": "" 624 | }, 625 | { 626 | "id": 90, 627 | "title": "quam dignissim pharetra. Nam ac nulla.", 628 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non,", 629 | "author": 10, 630 | "tags2": "3" 631 | }, 632 | { 633 | "id": 91, 634 | "title": "penatibus et magnis dis parturient montes,", 635 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque", 636 | "author": 15, 637 | "tags2": "1, 4, 9" 638 | }, 639 | { 640 | "id": 92, 641 | "title": "fermentum vel, mauris. Integer sem elit,", 642 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna.", 643 | "author": 15, 644 | "tags2": "" 645 | }, 646 | { 647 | "id": 93, 648 | "title": "magnis dis parturient montes, nascetur ridiculus", 649 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis", 650 | "author": 8, 651 | "tags2": "" 652 | }, 653 | { 654 | "id": 94, 655 | "title": "egestas lacinia. Sed congue, elit sed", 656 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu", 657 | "author": 8, 658 | "tags2": "8" 659 | }, 660 | { 661 | "id": 95, 662 | "title": "a ultricies adipiscing, enim mi tempor", 663 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna. Ut", 664 | "author": 1, 665 | "tags2": "4, 2" 666 | }, 667 | { 668 | "id": 96, 669 | "title": "ultrices sit amet, risus. Donec nibh", 670 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin", 671 | "author": 15, 672 | "tags2": "10, 7" 673 | }, 674 | { 675 | "id": 97, 676 | "title": "urna justo faucibus lectus, a sollicitudin", 677 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor.", 678 | "author": 9, 679 | "tags2": "" 680 | }, 681 | { 682 | "id": 98, 683 | "title": "et ultrices posuere cubilia Curae; Phasellus", 684 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna.", 685 | "author": 1, 686 | "tags2": "9" 687 | }, 688 | { 689 | "id": 99, 690 | "title": "quis, pede. Praesent eu dui. Cum", 691 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat.", 692 | "author": 17, 693 | "tags2": "" 694 | }, 695 | { 696 | "id": 100, 697 | "title": "bibendum. Donec felis orci, adipiscing non,", 698 | "text": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed tortor. Integer aliquam adipiscing lacus. Ut nec urna et arcu imperdiet ullamcorper. Duis at lacus. Quisque purus sapien, gravida non, sollicitudin a, malesuada id, erat. Etiam vestibulum massa rutrum magna. Cras convallis convallis dolor. Quisque tincidunt pede ac urna.", 699 | "author": 12, 700 | "tags2": "" 701 | } 702 | ] -------------------------------------------------------------------------------- /test/bench/user.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": 1, 4 | "name": "Bethany", 5 | "mail": "eget@Sedeget.com" 6 | }, 7 | { 8 | "id": 2, 9 | "name": "Carter", 10 | "mail": "lectus@nonummy.edu" 11 | }, 12 | { 13 | "id": 3, 14 | "name": "Blaze", 15 | "mail": "enim@lectusconvallisest.com" 16 | }, 17 | { 18 | "id": 4, 19 | "name": "Ali", 20 | "mail": "facilisis.non.bibendum@urna.co.uk" 21 | }, 22 | { 23 | "id": 5, 24 | "name": "Callie", 25 | "mail": "nec@nibhdolor.co.uk" 26 | }, 27 | { 28 | "id": 6, 29 | "name": "Cecilia", 30 | "mail": "Aliquam.adipiscing.lobortis@risusvariusorci.org" 31 | }, 32 | { 33 | "id": 7, 34 | "name": "Audra", 35 | "mail": "nec.luctus@bibendum.org" 36 | }, 37 | { 38 | "id": 8, 39 | "name": "Tanya", 40 | "mail": "sodales.purus.in@tellussem.co.uk" 41 | }, 42 | { 43 | "id": 9, 44 | "name": "Daniel", 45 | "mail": "pede.blandit.congue@nec.org" 46 | }, 47 | { 48 | "id": 10, 49 | "name": "Sydney", 50 | "mail": "augue@blandit.ca" 51 | }, 52 | { 53 | "id": 11, 54 | "name": "Juliet", 55 | "mail": "scelerisque.lorem@tempor.co.uk" 56 | }, 57 | { 58 | "id": 12, 59 | "name": "Isabella", 60 | "mail": "bibendum.Donec.felis@nuncInat.edu" 61 | }, 62 | { 63 | "id": 13, 64 | "name": "Shoshana", 65 | "mail": "Aliquam.tincidunt.nunc@sagittisplaceratCras.net" 66 | }, 67 | { 68 | "id": 14, 69 | "name": "Amela", 70 | "mail": "bibendum.ullamcorper@egestaslacinia.net" 71 | }, 72 | { 73 | "id": 15, 74 | "name": "Bevis", 75 | "mail": "habitant.morbi.tristique@ipsumdolor.org" 76 | }, 77 | { 78 | "id": 16, 79 | "name": "Jillian", 80 | "mail": "massa.rutrum.magna@nuncullamcorper.ca" 81 | }, 82 | { 83 | "id": 17, 84 | "name": "Alexis", 85 | "mail": "nascetur.ridiculus@auctorodioa.edu" 86 | }, 87 | { 88 | "id": 18, 89 | "name": "Melvin", 90 | "mail": "eget.metus.eu@Crasvulputatevelit.ca" 91 | }, 92 | { 93 | "id": 19, 94 | "name": "Zephania", 95 | "mail": "interdum.libero.dui@per.net" 96 | }, 97 | { 98 | "id": 20, 99 | "name": "Clark", 100 | "mail": "in@Vestibulumaccumsanneque.net" 101 | } 102 | ] -------------------------------------------------------------------------------- /test/bookmodel.php: -------------------------------------------------------------------------------- 1 | [ 8 | 'type' => \DB\SQL\Schema::DT_VARCHAR128 9 | ], 10 | 'text' => [ 11 | 'type' => \DB\SQL\Schema::DT_TEXT 12 | ], 13 | 'text2' => [ 14 | 'type' => \DB\SQL\Schema::DT_TEXT 15 | ], 16 | ]; 17 | 18 | protected 19 | $fluid = true, 20 | $table = 'books6', 21 | $db = 'DB'; 22 | 23 | } -------------------------------------------------------------------------------- /test/newsmodel.ini: -------------------------------------------------------------------------------- 1 | [globals] 2 | newsmodel.db = DB 3 | newsmodel.table = news 4 | newsmodel.fieldConf.title.type = VARCHAR128 5 | newsmodel.fieldConf.text.type = TEXT 6 | newsmodel.fieldConf.author.belongs-to = \AuthorModel 7 | newsmodel.fieldConf.tags.belongs-to-many = \TagModel 8 | newsmodel.fieldConf.tags2.has-many = \TagModel,news -------------------------------------------------------------------------------- /test/newsmodel.php: -------------------------------------------------------------------------------- 1 | [ 8 | 'type' => \DB\SQL\Schema::DT_VARCHAR128 9 | ], 10 | 'text' => [ 11 | 'type' => \DB\SQL\Schema::DT_TEXT, 12 | ], 13 | 'author' => [ 14 | 'index'=>true, 15 | 'belongs-to-one' => '\AuthorModel', 16 | ], 17 | 'tags' => [ 18 | 'belongs-to-many' => '\TagModel', 19 | ], 20 | 'tags2' => [ 21 | 'has-many' => ['\TagModel','news','news_tags', 22 | 'relField' => 'neeeews' 23 | ], 24 | ], 25 | 'created_at' => [ 26 | 'type' => \DB\SQL\Schema::DT_DATETIME 27 | ], 28 | 'options' => [ 29 | 'type' => self::DT_JSON 30 | ], 31 | 32 | ], 33 | $table = 'news', 34 | $db = 'DB'; 35 | 36 | public function getBySQL($query) { 37 | $result = $this->db->exec($query); 38 | $cx = new \DB\CortexCollection(); 39 | foreach($result as $row) { 40 | $new = $this->factory($row); 41 | $cx->add($new); 42 | unset($new); 43 | } 44 | return $cx; 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /test/newsmodel2.php: -------------------------------------------------------------------------------- 1 | fieldConf = array( 12 | 'author' => array( 13 | 'belongs-to-one' => '\AuthorModel', 14 | ), 15 | 'tags' => array( 16 | 'belongs-to-many' => '\TagModel', 17 | ), 18 | 'tags2' => array( 19 | 'has-many' => array('\TagModel', 'news'), 20 | ), 21 | ); 22 | parent::__construct(); 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /test/productsmodel.php: -------------------------------------------------------------------------------- 1 | array('type' => \DB\SQL\Schema::DT_VARCHAR128), 8 | 'prize' => array('type' => \DB\SQL\Schema::DT_DECIMAL, 'default' => 123), 9 | 'stock' => array('type' => \DB\Cortex::DT_INT, 'default' => 0), 10 | 'description' => array('type' => \DB\SQL\Schema::DT_TEXT), 11 | ); 12 | 13 | public function __construct() { 14 | $db = \Base::instance()->get('SQLDB'); 15 | parent::__construct($db,'products'); 16 | } 17 | 18 | } 19 | 20 | 21 | class ManufacturerModel extends \DB\Cortex { 22 | 23 | protected static 24 | $fieldConf = array( 25 | 'title' => array('type' => \DB\SQL\Schema::DT_VARCHAR128), 26 | 'location' => array('type' => \DB\SQL\Schema::DT_VARCHAR128), 27 | ); 28 | 29 | public function __construct() { 30 | $db = \Base::instance()->get('SQLDB'); 31 | parent::__construct($db,'manufacturer'); 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /test/profilemodel.php: -------------------------------------------------------------------------------- 1 | [ 8 | 'type' => \DB\SQL\Schema::DT_TEXT 9 | ], 10 | 'image' => [ 11 | 'type' => \DB\SQL\Schema::DT_VARCHAR256 12 | ], 13 | 'author' => [ 14 | 'belongs-to-one' => '\AuthorModel' 15 | ] 16 | ], 17 | // $primary = 'profile_id', 18 | $table = 'profile', 19 | $db = 'DB'; 20 | 21 | } -------------------------------------------------------------------------------- /test/tagmodel.php: -------------------------------------------------------------------------------- 1 | [ 8 | 'type' => \DB\SQL\Schema::DT_VARCHAR128 9 | ], 10 | 'news' => [ 11 | 'has-many' => ['\NewsModel','tags2','news_tags', 12 | 'relField' => 'taaags' 13 | ], 14 | ], 15 | ], 16 | $table = 'tags', 17 | $db = 'DB'; 18 | 19 | } -------------------------------------------------------------------------------- /test/test_common.php: -------------------------------------------------------------------------------- 1 | load(); 15 | 16 | $dummy = array( 17 | 'title'=>'copy test', 18 | 'text'=>'Lorem ipsum dolor sit amet.', 19 | 'author'=>1, 20 | 'tags'=>array(3) 21 | ); 22 | $f3->set('record1', $dummy); 23 | $news->copyto('record2'); 24 | 25 | $test->expect( 26 | $f3->exists('record2'), 27 | 'copyto: raw record copied to hive' 28 | ); 29 | 30 | $news->copyto_flat('news'); 31 | 32 | $author = new AuthorModel(); 33 | $author->load(); 34 | $author->copyto_flat('author'); 35 | $test->expect( 36 | is_array($f3->news['tags']) && 37 | is_int($f3->news['tags'][0]) && 38 | is_array($f3->author['news']) && 39 | is_int($f3->author['news'][0]), 40 | 'copyto_flat: record copied to hive with relations being flat arrays of IDs' 41 | ); 42 | 43 | $news->reset(); 44 | 45 | $news->copyfrom('record1'); 46 | 47 | $test->expect( 48 | $news->title = 'copy test' && 49 | $news->text = 'Lorem ipsum dolor sit amet.', 50 | 'copyfrom: hydrate from hive key' 51 | ); 52 | $test->expect( 53 | $news->author instanceof AuthorModel 54 | && !$news->author->dry() && 55 | $news->tags instanceof \DB\CortexCollection, 56 | 'copyfrom: relations hydrated successful' 57 | ); 58 | 59 | $test->expect( 60 | $news->get('author',true) == 1, 61 | 'get raw data from relational field' 62 | ); 63 | 64 | $news->reset(); 65 | $news->copyfrom('record2','title;author'); 66 | 67 | $test->expect( 68 | $news->title = 'Responsive Images' && 69 | $news->get('author',true) == 2 && 70 | $news->text == NULL, 71 | 'copyfrom: limit fields with split-able string' 72 | ); 73 | 74 | $news->reset(); 75 | $news->copyfrom('record2',array('title')); 76 | 77 | $test->expect( 78 | $news->title = 'Responsive Images' && $news->text == NULL, 79 | 'copyfrom: limit fields by array' 80 | ); 81 | 82 | $news->reset(); 83 | $news->copyfrom($dummy,function($fields) { 84 | return array_intersect_key($fields,array_flip(array('title'))); 85 | }); 86 | 87 | $test->expect( 88 | $news->title = 'copy test', 89 | 'copyfrom: copy from array instead of hive key' 90 | ); 91 | 92 | $test->expect( 93 | $news->title = 'copy test' && $news->text == NULL, 94 | 'copyfrom: limit fields by callback function' 95 | ); 96 | 97 | $all = $news->find(); 98 | $allTitle = $all->getAll('title'); 99 | 100 | $test->expect( 101 | count($allTitle) == 3 && 102 | $allTitle[0] == 'Responsive Images' && 103 | $allTitle[1] == 'CSS3 Showcase' && 104 | $allTitle[2] == 'Touchable Interfaces', 105 | 'collection getAll returns all values of selected field' 106 | ); 107 | 108 | $newsByID = $all->getBy('_id'); 109 | $test->expect( 110 | array_keys($newsByID) == array(1,2,3), 111 | 'collection getBy sorts by given field' 112 | ); 113 | 114 | $newsByAuthorID = $all->getBy('author',true); 115 | $test->expect( 116 | array_keys($newsByAuthorID) == array(2, 1) && 117 | count($newsByAuthorID[2]) == 2 && 118 | count($newsByAuthorID[1]) == 1, 119 | 'collection getBy nested sort by author' 120 | ); 121 | 122 | $allTitle = array(); 123 | foreach($all as $record) 124 | $allTitle[] = $record->title; 125 | 126 | $test->expect( 127 | count($allTitle) == 3 && 128 | $allTitle[0] == 'Responsive Images' && 129 | $allTitle[1] == 'CSS3 Showcase' && 130 | $allTitle[2] == 'Touchable Interfaces', 131 | 'collection is traversable' 132 | ); 133 | 134 | $news->reset(); 135 | $news->load(); 136 | $r = $news->cast(null,0); 137 | $test->expect($r['tags2']==null && is_int($r['author']), 138 | 'simple cast without relations'); 139 | 140 | $r = $news->cast(null,1); 141 | $test->expect(is_array($r['tags2']) && is_array($r['author']), 142 | '1-level nested cast'); 143 | 144 | $r = $news->cast(null,2); 145 | $test->expect(is_array($r['author']['profile']), 146 | '2-level nested cast'); 147 | 148 | $r = $news->cast(null,array('*'=>2)); 149 | $test->expect(is_array($r['author']['profile']), 150 | '2-level nested cast, alternative'); 151 | 152 | $r = $news->cast(null,array( 153 | '*'=>0, 154 | 'author'=>0 155 | )); 156 | $test->expect(is_array($r['author']) && $r['tags2']==null 157 | && $r['author']['news']==null && $r['author']['profile']==null, 158 | 'custom cast'); 159 | 160 | $r = $news->cast(null,array( 161 | '*'=>0, 162 | 'author'=>array( 163 | '*'=>1 164 | ) 165 | )); 166 | $test->expect(is_array($r['author']) && $r['tags2']==null 167 | && is_array($r['author']['news']) && is_array($r['author']['profile']), 168 | 'custom nested cast'); 169 | 170 | $r = $news->cast(null,array( 171 | '*'=>0, 172 | 'author'=>array( 173 | '*'=>0, 174 | 'profile'=>0 175 | ) 176 | )); 177 | $test->expect(is_array($r['author']) && $r['tags2']==null 178 | && $r['author']['news']==null && is_array($r['author']['profile']) 179 | && is_int($r['author']['profile']['author']), 180 | 'custom nested cast with exclusions'); 181 | 182 | $r = $news->cast(null,array( 183 | '*'=>0, 184 | 'author'=>array( 185 | '*'=>0, 186 | 'profile'=>1 187 | ) 188 | )); 189 | $test->expect(is_array($r['author']) && $r['tags2']==null 190 | && $r['author']['news']==null && is_array($r['author']['profile']) 191 | && is_array($r['author']['profile']['author']), 192 | 'custom multi-level nested cast'); 193 | 194 | $filterA = array('foo1 = ? and bar1 = ?',10,20); 195 | $filterB = array('foo2 = ? and bar2 = ?',30,40); 196 | $filterC = array('foo3 = ? and bar3 = ?',50,60); 197 | $filter = $news->mergeFilter(array($filterA, $filterB, $filterC),'or'); 198 | $test->expect($filter == array('( foo1 = ? and bar1 = ? ) or ( foo2 = ? and bar2 = ? ) or ( foo3 = ? and bar3 = ? )', 199 | 10,20,30,40,50,60), 200 | 'merge multiple filters'); 201 | 202 | $qp = new \DB\CortexQueryParser(); 203 | 204 | $test->expect( 205 | $qp->prepareFilter(['foo > bar'],'sql', $f3->DB) === ['`foo` > `bar`'], 206 | 'auto-escape fields' 207 | ); 208 | $test->expect( 209 | $qp->prepareFilter(['created_at > DATE_SUB(NOW(), INTERVAL 1 DAY)'],'sql', $f3->DB) === ['`created_at` > DATE_SUB(NOW(), INTERVAL 1 DAY)'], 210 | 'respect function when auto-escaping' 211 | ); 212 | $test->expect( 213 | $qp->prepareFilter(['foo(?,?,3,?)',1,2,4],'sql', $f3->DB) === ['foo(?,?,3,?)',1,2,4], 214 | 'query parser: correct function args' 215 | ); 216 | 217 | /////////////////////////////////// 218 | return $test->results(); 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /test/test_filter.php: -------------------------------------------------------------------------------- 1 | find()->getAll('_id'); 28 | $all = $news->find(null,['order'=>'id']); 29 | $newsIDs = $all->getAll('_id'); 30 | sort($newsIDs); 31 | $profileIDs = $profile->find()->getAll('_id'); 32 | $tagIDs = $tag->find()->getAll('_id'); 33 | 34 | // add another relation 35 | $news->load(array('title = ?','CSS3 Showcase')); 36 | $author->load(array($author_pk.' = ?',$authorIDs[0])); 37 | $news->author = $author; 38 | $news->save(); 39 | $news->reset(); 40 | $author->reset(); 41 | 42 | $page=$news->paginate(0,2,null,['order'=>'title DESC']); 43 | $test->expect( 44 | $page['subset'][0]->get('title')=='Touchable Interfaces' && 45 | $page['subset'][1]->get('title')=='Responsive Images', 46 | $type.': pagination: first page' 47 | ); 48 | $page=$news->paginate(1,2,null,['order'=>'title DESC']); 49 | $test->expect( 50 | $page['subset'][0]->get('title')=='CSS3 Showcase', 51 | $type.': pagination: last page' 52 | ); 53 | 54 | // has-filter on belongs-to relation 55 | /////////////////////////////////// 56 | $result = $author->has('news', array('title like ?', '%Image%'))->afind(); 57 | 58 | $test->expect( 59 | count($result) == 1 && 60 | $result[0]['name'] == 'Johnny English', 61 | $type.': has filter on many-to-one field' 62 | ); 63 | \Matrix::instance()->sort($result[0]['news'],'title'); 64 | $test->expect( 65 | count($result[0]['news']) == 2 && 66 | $result[0]['news'][0]['title'] == 'CSS3 Showcase' && 67 | $result[0]['news'][1]['title'] == 'Responsive Images', 68 | $type.': has filter does not prune relation set' 69 | ); 70 | 71 | $result = $news->has('author', array('name = ?', 'Johnny English'))->afind(null,array('order'=>'title DESC')); 72 | $test->expect( 73 | count($result) == 2 && // has 2 news 74 | $result[0]['title'] == 'Responsive Images' && 75 | $result[1]['title'] == 'CSS3 Showcase', 76 | $type.': has filter on one-to-many field' 77 | ); 78 | 79 | // add another profile 80 | $profile->message = 'Beam me up, Scotty!'; 81 | $profile->author = $authorIDs[2]; 82 | $profile->save(); 83 | $profile->reset(); 84 | 85 | $result = $author->has('profile',array('message LIKE ?','%Scotty%'))->afind(); 86 | $test->expect( 87 | count($result) == 1 && 88 | $result[0]['name'] == 'James T. Kirk' && 89 | $result[0]['profile']['message'] == 'Beam me up, Scotty!', 90 | $type.': has filter on one-to-one field' 91 | ); 92 | 93 | $result = $profile->has('author',array('name LIKE ?','%Kirk%'))->afind(); 94 | $test->expect( 95 | count($result) == 1 && 96 | $result[0]['message'] == 'Beam me up, Scotty!' && 97 | $result[0]['author']['name'] == 'James T. Kirk', 98 | $type.': has filter on one-to-one field, inverse' 99 | ); 100 | 101 | // add mm tags 102 | $news->load(array('title = ?','Responsive Images')); 103 | $news->tags2 = array($tagIDs[0],$tagIDs[1]); 104 | $news->save(); 105 | $news->load(array('title = ?','CSS3 Showcase')); 106 | $news->tags2 = array($tagIDs[1],$tagIDs[2]); 107 | $news->save(); 108 | $news->reset(); 109 | 110 | $result = $news->has('tags2',array('title like ?','%Design%'))->find(); 111 | $test->expect( 112 | count($result) == 1 && 113 | $result[0]['title'] == 'Responsive Images', 114 | $type.': has filter on many-to-many field' 115 | ); 116 | 117 | $result = $news->has('tags2',array('title = ?','Responsive'))->find(); 118 | $test->expect( 119 | count($result) == 2 && 120 | $result[0]['title'] == 'Responsive Images' && 121 | $result[1]['title'] == 'CSS3 Showcase', 122 | $type.': has filter on many-to-many field, additional test' 123 | ); 124 | 125 | 126 | $result = $tag->has('news',array('title = ?','Responsive Images'))->find(); 127 | $test->expect( 128 | count($result) == 2 && 129 | $result[0]['title'] == 'Web Design' && 130 | $result[1]['title'] == 'Responsive', 131 | $type.': has filter on many-to-many field, inverse' 132 | ); 133 | 134 | // add another tag 135 | $news->load(array('title = ?', 'Touchable Interfaces')); 136 | $news->tags2 = array($tagIDs[1]); 137 | $news->save(); 138 | $news->reset(); 139 | 140 | $tag->has('news',array('text LIKE ? and title LIKE ?', '%Lorem%', '%Interface%')); 141 | $result = $tag->find(); 142 | $test->expect( 143 | count($result) == 1 && 144 | $result[0]['title'] == 'Responsive', 145 | $type.': has filter with multiple conditions' 146 | ); 147 | 148 | $news->has('tags2', array('title = ? OR title = ?', 'Usability', 'Web Design')); 149 | $result = $news->afind(array('text = ?', 'Lorem Ipsun')); 150 | $test->expect( 151 | count($result) == 1 && 152 | $result[0]['title'] == 'Responsive Images', 153 | $type.': find with condition and has filter' 154 | ); 155 | 156 | $news->load(array('title = ?', 'Responsive Images')); 157 | $news->author = $authorIDs[1]; 158 | $news->save(); 159 | $news->reset(); 160 | 161 | 162 | $news->has('tags2', array('title = ? OR title = ?', 'Usability', 'Web Design')); 163 | $news->has('author', array('name = ?', 'Ridley Scott')); 164 | $result = $news->afind(); 165 | $test->expect( 166 | count($result) == 1 && 167 | $result[0]['title'] == 'Responsive Images', 168 | $type.': find with multiple has filters on different relations' 169 | ); 170 | 171 | // add another news to author 2 172 | $news->load(array($news_pk.' = ?',$newsIDs[2])); 173 | $news->author = $authorIDs[1]; 174 | $news->save(); 175 | 176 | $news->reset(); 177 | $news->has('author', array('name = ?', 'Ridley Scott')); 178 | $news->load(null,array('order'=>'title')); 179 | $res = array(); 180 | while (!$news->dry()) { 181 | $res[] = $news->title; 182 | $news->next(); 183 | } 184 | 185 | $test->expect( 186 | count($res) == 2 && 187 | $res[0] == 'Responsive Images' && 188 | $res[1] == 'Touchable Interfaces' 189 | , 190 | $type.': has filter in load context' 191 | ); 192 | 193 | $news->reset(); 194 | $news->fields(array('title')); 195 | $news->load(); 196 | 197 | $test->expect( 198 | !empty($news->title) && 199 | empty($news->author) && 200 | empty($news->text) && 201 | empty($news->tags) && 202 | empty($news->tags2), 203 | $type.': use a whitelist to restrict fields' 204 | ); 205 | 206 | unset($news); 207 | $news = new \NewsModel(); 208 | 209 | $news->fields(array('title','tags','tags2','author'),true); 210 | $news->load(); 211 | 212 | $test->expect( 213 | empty($news->title) && 214 | empty($news->author) && 215 | !empty($news->text) && 216 | empty($news->tags) && 217 | empty($news->tags2), 218 | $type.': use a blacklist to restrict fields' 219 | ); 220 | 221 | unset($news); 222 | $news = new \NewsModel(); 223 | 224 | $news->fields(array('tags.title')); 225 | $news->load(); 226 | 227 | $test->expect( 228 | !empty($news->tags[0]->title) && 229 | empty($news->tags[0]->news), 230 | $type.': set restricted fields to related mappers' 231 | ); 232 | 233 | $news->fields(array('tags2')); 234 | $news->filter('tags2',null,array('order'=>'title ASC')); 235 | $news->load(array('title = ?','Responsive Images')); 236 | $test->expect( 237 | $news->tags2[0]->title == 'Responsive' && 238 | $news->tags2[1]->title == 'Web Design', 239 | $type.': filter with sorting of related records' 240 | ); 241 | 242 | unset($news); 243 | $news = new \NewsModel(); 244 | 245 | // get all tags sorted by their usage in news articles 246 | $tag->reset(); 247 | $tag->countRel('news'); 248 | $result = $tag->find(null,array('order'=>'count_news DESC, title'))->castAll(0); 249 | 250 | $test->expect( 251 | $result[0]['title'] == 'Responsive' && 252 | $result[0]['count_news'] == 3 && 253 | $result[1]['title'] == 'Usability' && 254 | $result[1]['count_news'] == 1 && 255 | $result[2]['title'] == 'Web Design' && 256 | $result[2]['count_news'] == 1, 257 | $type.': count and sort on many-to-many relation' 258 | ); 259 | 260 | // get all authors sorted by the amount of news they have written 261 | $author->reset(); 262 | $author->countRel('news'); 263 | $result = $author->find(null,array('order'=>'count_news DESC'))->castAll(0); 264 | 265 | $test->expect( 266 | $result[0]['name'] == 'Ridley Scott' && 267 | $result[0]['count_news'] == 2 && 268 | $result[1]['name'] == 'Johnny English' && 269 | $result[1]['count_news'] == 1 && 270 | $result[2]['name'] == 'James T. Kirk' && 271 | $result[2]['count_news'] == null, 272 | $type.': count and sort on one-to-many relation' 273 | ); 274 | 275 | $tag->reset(); 276 | 277 | if ($type != 'sqlsrv2008') { 278 | $tag->countRel('news'); 279 | $result=$tag->find(NULL, 280 | array('order'=>'count_news DESC, title DESC','limit'=>1,'offset'=>1)) 281 | ->castAll(0); 282 | 283 | $test->expect( 284 | $result[0]['title']=='Web Design' && 285 | $result[0]['count_news']==1, 286 | $type.': apply limit and offset on aggregated collection' 287 | ); 288 | } else { 289 | $test->expect( 290 | false, 291 | $type.': apply limit and offset on aggregated collection' 292 | ); 293 | } 294 | 295 | $author->reset(); 296 | $author->countRel('news'); 297 | $author->has('news',array('text like ?','%Lorem%')); 298 | $result = $author->find()->castAll(0); 299 | 300 | $test->expect( 301 | count($result) == 1 && 302 | $result[0]['name'] == 'Ridley Scott' && 303 | $result[0]['count_news'] == 2 , 304 | $type.': has-filter and 1:M relation counter' 305 | ); 306 | 307 | 308 | $author->reset(); 309 | $author->load(); 310 | $id = $author->next()->_id; 311 | $tag->reset(); 312 | $tag->countRel('news'); 313 | $tag->has('news',array('author = ?',$id)); 314 | $result = $tag->find(null,array('order'=>'count_news desc'))->castAll(0); 315 | 316 | $test->expect( 317 | count($result) == 2 && 318 | $result[0]['title'] == 'Responsive' && 319 | $result[0]['count_news'] == 3 && 320 | $result[1]['title'] == 'Web Design' && 321 | $result[1]['count_news'] == 1, 322 | $type.': has-filter and M:M relation counter' 323 | ); 324 | 325 | 326 | $author = new AuthorModel(); 327 | $author->has('friends', ['name LIKE ?','%Scott%']); 328 | $res = $author->find(); 329 | $ids = $res->getAll('_id'); 330 | $test->expect( 331 | $res && count($res) == 2 && 332 | in_array($authorIDs[0],$ids) && in_array($authorIDs[2],$ids), 333 | $type.': has-filter on self-ref relation' 334 | ); 335 | 336 | $author = new AuthorModel(); 337 | $author->has('friends.news', ['title LIKE ?','%Interface%']); 338 | $res = $author->find(); 339 | $test->expect( 340 | $res && ($ids = $res->getAll('_id')) && count($res) == 2 && 341 | in_array($authorIDs[0],$ids) && in_array($authorIDs[2],$ids), 342 | $type.': has-filter, nested on self-ref relation' 343 | ); 344 | 345 | $author = new AuthorModel(); 346 | $author->has('friends', ['name LIKE ?','%Scott%']); 347 | $author->has('news', ['title LIKE ?','%CSS%']); 348 | $res = $author->find(); 349 | $ids = $res ? $res->getAll('_id') : []; 350 | $test->expect( 351 | $res && count($res) == 1 && 352 | in_array($authorIDs[0],$ids), 353 | $type.': multiple has-filter on self-ref relation' 354 | ); 355 | 356 | $news->reset(); 357 | $news->load(array('_id = ?',$newsIDs[0])); 358 | $time = date('Y-m-d H:i:s'); 359 | $news->touch('created_at'); 360 | $news->save(); 361 | $news->reset(); 362 | $news->load(array('_id = ?',$newsIDs[0])); 363 | $test->expect( 364 | substr($news->created_at,0,strlen($time)) == $time, 365 | $type.': update datetime field' 366 | ); 367 | /////////////////////////////////// 368 | return $test->results(); 369 | } 370 | 371 | } -------------------------------------------------------------------------------- /test/test_relation.php: -------------------------------------------------------------------------------- 1 | cast(); 16 | unset($row['_id']); 17 | unset($row['id']); 18 | unset($row['aid']); 19 | unset($row['uid']); 20 | unset($row['nid']); 21 | unset($row['tid']); 22 | unset($row['pid']); 23 | unset($row['profile_id']); 24 | foreach ($row as $col => $val) { 25 | if (empty($val) || is_null($val)) 26 | unset($row[$col]); 27 | } 28 | $out[] = $row; 29 | } 30 | return $out; 31 | } 32 | 33 | function run($db,$type) 34 | { 35 | $test = new \Test(); 36 | 37 | // clear existing data 38 | \AuthorModel::setdown(); 39 | \TagModel::setdown(); 40 | \NewsModel::setdown(); 41 | \ProfileModel::setdown(); 42 | 43 | // setup models 44 | \AuthorModel::setup(); 45 | \TagModel::setup(); 46 | \NewsModel::setup(); 47 | \ProfileModel::setup(); 48 | 49 | // setup Author 50 | /////////////////////////////////// 51 | $author_id = array(); 52 | 53 | $author = new \AuthorModel(); 54 | $ac=$author::resolveConfiguration(); 55 | $author_pk = (is_int(strpos($type,'sql'))?$ac['primary']:'_id'); 56 | 57 | $author->name = 'Johnny English'; 58 | $author->mail = 'user1@domain.com'; 59 | $author->save(); 60 | $author_id[] = $author->_id; 61 | $author->reset(); 62 | $author->name = 'Ridley Scott'; 63 | $author->mail = 'user2@domain.com'; 64 | $author->save(); 65 | $author_id[] = $author->_id; 66 | $author->reset(); 67 | $author->name = 'James T. Kirk'; 68 | $author->mail = 'user3@domain.com'; 69 | $author->save(); 70 | $author_id[] = $author->_id; 71 | $author->reset(); 72 | 73 | $allauthors = $author->find()->castAll(); 74 | $allauthors = $this->getResult($allauthors); 75 | $test->expect( 76 | json_encode($allauthors) == 77 | '[{"name":"Johnny English","mail":"user1@domain.com"},{"name":"Ridley Scott","mail":"user2@domain.com"},{"name":"James T. Kirk","mail":"user3@domain.com"}]', 78 | $type.': all AuthorModel items created' 79 | ); 80 | 81 | // setup Tags 82 | /////////////////////////////////// 83 | $tag_id = array(); 84 | 85 | $tag = new \TagModel(); 86 | $tc=$tag::resolveConfiguration(); 87 | $tag_pk = (is_int(strpos($type,'sql'))?$tc['primary']:'_id'); 88 | 89 | $tag->title = 'Web Design'; 90 | $tag->save(); 91 | $tag_id[] = $tag->_id; 92 | $tag->reset(); 93 | $tag->title = 'Responsive'; 94 | $tag->save(); 95 | $tag_id[] = $tag->_id; 96 | $tag->reset(); 97 | $tag->title = 'Usability'; 98 | $tag->save(); 99 | $tag_id[] = $tag->_id; 100 | $tag->reset(); 101 | 102 | $allTags = $this->getResult($tag->find()); 103 | $test->expect( 104 | json_encode($allTags) == 105 | '[{"title":"Web Design"},{"title":"Responsive"},{"title":"Usability"}]', 106 | $type.': all TagModel items created' 107 | ); 108 | 109 | // setup News 110 | /////////////////////////////////// 111 | $news_id = array(); 112 | 113 | $news = new \NewsModel(); 114 | $nc=$news::resolveConfiguration(); 115 | $news_pk = (is_int(strpos($type,'sql'))?$nc['primary']:'_id'); 116 | 117 | $news->title = 'Responsive Images'; 118 | $news->text = 'Lorem Ipsun'; 119 | $news->save(); 120 | $news_id[] = $news->_id; 121 | $news->reset(); 122 | $news->title = 'CSS3 Showcase'; 123 | $news->text = 'News Text 2'; 124 | $news->save(); 125 | $news_id[] = $news->_id; 126 | $news->reset(); 127 | $news->title = 'Touchable Interfaces'; 128 | $news->text = 'Lorem Foo'; 129 | $news->save(); 130 | $news_id[] = $news->_id; 131 | $news->reset(); 132 | 133 | $allnews = $this->getResult($news->find(null,array('order'=>'title'))); 134 | $test->expect( 135 | count($allnews) == 3 && 136 | $allnews[0]['title'] == 'CSS3 Showcase' && 137 | $allnews[1]['title'] == 'Responsive Images' && 138 | $allnews[2]['title'] == 'Touchable Interfaces', 139 | $type.': all NewsModel items created' 140 | ); 141 | 142 | // belongs-to author relation 143 | /////////////////////////////////// 144 | 145 | $author->load(); 146 | $news->load(array($news_pk.' = ?',$news_id[0])); 147 | $news->author = $author; 148 | $news->save(); 149 | $news->reset(); 150 | $news->load(array($news_pk.' = ?', $news_id[0])); 151 | $test->expect( 152 | $news->author->name == 'Johnny English', 153 | $type.': belongs-to-one: author relation created' 154 | ); 155 | 156 | $news->author = NULL; 157 | $news->save(); 158 | $news->reset(); 159 | $news->load(array($news_pk.' = ?', $news_id[0])); 160 | $test->expect( 161 | empty($news->author), 162 | $type.': belongs-to-one: author relation released' 163 | ); 164 | 165 | $news->author = $author->_id; 166 | $news->save(); 167 | $news->reset(); 168 | $news->load(array($news_pk.' = ?', $news_id[0])); 169 | $test->expect( 170 | $news->author->name == 'Johnny English', 171 | $type.': belongs-to-one: relation created by raw id' 172 | ); 173 | 174 | // belongs-to-many tag relation 175 | /////////////////////////////////// 176 | 177 | $tag1 = new \TagModel(); 178 | $tag1->load(array($tag_pk.' = ?', $tag_id[0])); 179 | $tag2 = new \TagModel(); 180 | $tag2->load(array($tag_pk.' = ?', $tag_id[1])); 181 | $news->tags = array($tag1,$tag2); 182 | $news->save(); 183 | $news->reset(); 184 | $news->load(array($news_pk.' = ?', $news_id[0])); 185 | $test->expect( 186 | $news->tags[0]->title == 'Web Design' && $news->tags[1]->title == 'Responsive', 187 | $type.': belongs-to-many: relations created with array of mapper objects' 188 | ); 189 | 190 | $news->reset(); 191 | $news->load(array($news_pk.' = ?', $news_id[1])); 192 | $news->tags = array($tag_id[1],$tag_id[2]); 193 | $news->save(); 194 | $news->reset(); 195 | $news->load(array($news_pk.' = ?', $news_id[1])); 196 | $test->expect( 197 | count($news->tags) == 2 && 198 | $news->tags[0]->title == 'Responsive' && $news->tags[1]->title == 'Usability', 199 | $type.': belongs-to-many: relations created with array of IDs' 200 | ); 201 | 202 | $news->tags = null; 203 | $news->save(); 204 | $news->reset(); 205 | $news->load(array($news_pk.' = ?', $news_id[1])); 206 | $test->expect( 207 | empty($news->tags), 208 | $type.': belongs-to-many: relations released' 209 | ); 210 | 211 | $tag->reset(); 212 | $news->load(array($news_pk.' = ?', $news_id[1])); 213 | $tag->load(array($tag_pk.' != ?',$tag_id[0])); 214 | $news->tags = $tag; 215 | $news->save(); 216 | $news->reset(); 217 | $news->load(array($news_pk.' = ?', $news_id[1])); 218 | $test->expect( 219 | $news->tags[0]->title == 'Responsive' && $news->tags[1]->title == 'Usability', 220 | $type.': belongs-to-many: relations created with hydrated mapper' 221 | ); 222 | 223 | 224 | $news->reset(); 225 | $tag->reset(); 226 | $news->load(array($news_pk.' = ?', $news_id[2])); 227 | $news->tags = $tag_id[0].';'.$tag_id[2]; 228 | $news->save(); 229 | $news->reset(); 230 | $news->load(array($news_pk.' = ?', $news_id[2])); 231 | $test->expect( 232 | $news->tags[0]->title == 'Web Design' && $news->tags[1]->title == 'Usability', 233 | $type.': belongs-to-many: relations created with split-able string' 234 | ); 235 | $test->expect( 236 | is_object($news->tags) && $news->tags instanceof \DB\CortexCollection, 237 | $type.': belongs-to-many: result is collection' 238 | ); 239 | 240 | 241 | // has-one relation 242 | /////////////////////////////////// 243 | $profile = new ProfileModel(); 244 | $pc=$profile::resolveConfiguration(); 245 | $profile_pk = (is_int(strpos($type,'sql'))?$pc['primary']:'_id'); 246 | 247 | $profile->message = 'Hello World'; 248 | $author->load(array($author_pk.' = ?',$author_id[0])); 249 | $profile->author = $author; 250 | $profile->save(); 251 | $profile_id = $profile->_id; 252 | $profile->reset(); 253 | $author->reset(); 254 | $author->load(array($author_pk.' = ?', $author_id[0])); 255 | $profile->load(array($profile_pk.' = ?', $profile_id)); 256 | $test->expect( 257 | $author->profile->message == 'Hello World' && 258 | $profile->author->name == "Johnny English", 259 | $type.': has-one: relation assigned' 260 | ); 261 | 262 | $profile->reset(); 263 | $profile->message = 'I\'m feeling lucky'; 264 | $profile->image = 'lolcat.jpg'; 265 | $author->reset(); 266 | $author->load(array($author_pk.' = ?',$author_id[1])); 267 | $author->profile = $profile; 268 | $author->save(); 269 | $profile->reset(); 270 | $author->reset(); 271 | $author->load(array($author_pk.' = ?', $author_id[1])); 272 | $test->expect( 273 | $author->profile->message == 'I\'m feeling lucky', 274 | $type.': has-one: inverse relation' 275 | ); 276 | 277 | 278 | // has-many relation 279 | /////////////////////////////////// 280 | 281 | $author->load(array($author_pk.' = ?', $author_id[0])); 282 | $result = $this->getResult($author->news); 283 | $test->expect( 284 | $result[0]['title'] == "Responsive Images" && 285 | $result[0]['tags'][0]['title'] == 'Web Design' && 286 | $result[0]['tags'][1]['title'] == 'Responsive', 287 | $type.': has-many inverse relation' 288 | ); 289 | 290 | $author->news[] = $news_id[1]; 291 | $author->save(); 292 | $author->reset(); 293 | $author->load(array($author_pk.' = ?', $author_id[0])); 294 | $result = $this->getResult($author->news); 295 | $test->expect( 296 | count($result)==2 && 297 | $result[0]['title'] == "Responsive Images" && 298 | $result[1]['title'] == "CSS3 Showcase", 299 | $type.': has-many add relation, inverse ways' 300 | ); 301 | 302 | $author->news = [$news_id[1]]; 303 | $author->save(); 304 | $author->reset(); 305 | $author->load(array($author_pk.' = ?', $author_id[0])); 306 | $result = $this->getResult($author->news); 307 | $test->expect( 308 | $result[0]['title'] == "CSS3 Showcase", 309 | $type.': has-many remove relation, inverse ways' 310 | ); 311 | 312 | $author->news = null; 313 | $author->save(); 314 | $author->reset(); 315 | $author->load(array($author_pk.' = ?', $author_id[0])); 316 | $result = $this->getResult($author->news); 317 | $test->expect( 318 | empty($result), 319 | $type.': has-many clear relation, inverse ways' 320 | ); 321 | $author->news = [$news_id[0]]; 322 | $author->save(); 323 | $author->reset(); 324 | 325 | // many to many relation 326 | /////////////////////////////////// 327 | 328 | $news->load(array($news_pk.' = ?',$news_id[0])); 329 | $news->tags2 = array($tag_id[0],$tag_id[1]); 330 | $news->save(); 331 | $news->reset(); 332 | $news->load(array($news_pk.' = ?',$news_id[0])); 333 | $test->expect( 334 | $news->tags2[0]['title'] == 'Web Design' && 335 | $news->tags2[1]['title'] == 'Responsive', 336 | $type.': many-to-many relation created' 337 | ); 338 | 339 | $test->expect( 340 | is_object($news->tags2) && $news->tags2 instanceof \DB\CortexCollection, 341 | $type.': many-to-many: result is collection' 342 | ); 343 | 344 | 345 | $tag->load(array($tag_pk.' = ?',$tag_id[2])); 346 | $tag3 = $tag; 347 | $news->tags2[] = $tag3; 348 | $news->save(); 349 | $a=count($news->tags2); 350 | $news->reset(); 351 | $news->load(array($news_pk.' = ?',$news_id[0])); 352 | $test->expect( 353 | count($news->tags2) == 3 && $a == 3, 354 | $type.': many-to-many relation added implicitly' 355 | ); 356 | 357 | $news->load(array($news_pk.' = ?', $news_id[0])); 358 | $news->tags2 = NULL; 359 | $news->save(); 360 | $news->reset(); 361 | $news->load(array($news_pk.' = ?', $news_id[0])); 362 | $test->expect( 363 | is_null($news->tags2), 364 | $type.': many-to-many relation released' 365 | ); 366 | 367 | $news->reset(); 368 | $news->title='Can it run Crysis?'; 369 | $news->text='XOXO'; 370 | $news->tags2 = array($tag_id[0]); 371 | $news->save(); 372 | $news_id[] = $news->_id; 373 | $news->reset(); 374 | $news->load(array($news_pk.' = ?', $news_id[3])); 375 | $a=count($news->tags2); 376 | $tag1 = $tag->find(array($tag_pk.' = ?',$tag_id[0])); 377 | $b=count($tag1[0]->news); 378 | $c=$tag1[0]->news[0]->title == 'Can it run Crysis?'; 379 | $news->erase(); 380 | $tag1 = $tag->find(array($tag_pk.' = ?',$tag_id[0])); 381 | $d=count($tag1[0]->news?:[]); 382 | $test->expect( 383 | $a == 1 && $b == 1 && $c && $d == 0, 384 | $type.': many-to-many relation cleaned by erase cascade' 385 | ); 386 | 387 | $news->load(array($news_pk.' = ?', $news_id[0])); 388 | $all = $news->find(null,['order'=>'title']); 389 | 390 | $test->expect( 391 | $all[0]->tags2 === NULL 392 | && $all[2]->author === NULL, 393 | $type.': empty relations are NULL' 394 | ); 395 | 396 | $arr = $news->cast(); 397 | $test->expect( 398 | is_array($arr['tags']), 399 | $type.': collection becomes array in casted model' 400 | ); 401 | 402 | if ($type == 'mongo') { 403 | $test->expect( 404 | is_string($arr['_id']), 405 | $type.': id becomes string in casted model' 406 | ); 407 | } 408 | 409 | $author = new AuthorModel(); 410 | $author->load(array($author_pk.' = ?',$author_id[0])); 411 | $test->expect( 412 | $author->friends === NULL, 413 | $type.': self-ref relation is empty' 414 | ); 415 | 416 | $author->friends = [$author_id[1]]; 417 | $author->save(); 418 | $author->reset(); 419 | $author->load(array($author_pk.' = ?',$author_id[0])); 420 | $test->expect( 421 | $author->friends && $author->friends[0]->get('_id') == $author_id[1], 422 | $type.': self-ref relation populated' 423 | ); 424 | $authorB = $author->findone([$author_pk.' = ?',$author_id[1]]); 425 | $test->expect( 426 | $authorB->friends && $authorB->friends[0]->get('_id') == $author_id[0], 427 | $type.': self-ref relation inverse way' 428 | ); 429 | 430 | $authorB->friends[] = $author_id[2]; 431 | $authorB->save(); 432 | $authorB = new AuthorModel(); 433 | $authorB->load(array($author_pk.' = ?',$author_id[1])); 434 | $ids = $authorB->friends->getAll('_id'); 435 | $test->expect( 436 | $authorB->friends && count($authorB->friends) == 2 && 437 | in_array($author_id[0],$ids) && in_array($author_id[2],$ids), 438 | $type.': self-ref relation collection merging' 439 | ); 440 | 441 | $news = new NewsModel(); 442 | $news->load([$news_pk.' = ?', $news_id[1]]); 443 | $news->author = $author_id[1]; 444 | $news->save(); 445 | 446 | $news1 = new NewsModel(); 447 | $news1->fields([$news_pk, "author.name"]); 448 | $news1->load([$news_pk.' = ?', $news_id[0]]); 449 | 450 | $news2 = new NewsModel(); 451 | $news2->load([$news_pk.' = ?', $news_id[1]]); 452 | 453 | $test->expect( 454 | $news1->author->mail === null && $news2->author->mail === 'user2@domain.com', 455 | $type.': whitelist on relations does not persist' 456 | ); 457 | 458 | /////////////////////////////////// 459 | return $test->results(); 460 | } 461 | } -------------------------------------------------------------------------------- /test/test_syntax.php: -------------------------------------------------------------------------------- 1 | array('type' => \DB\SQL\Schema::DT_TEXT), 16 | 'num1' => array('type' => \DB\SQL\Schema::DT_INT4), 17 | 'num2' => array('type' => \DB\SQL\Schema::DT_INT4), 18 | ); 19 | \DB\Cortex::setup($db, $tname, $fields); 20 | 21 | // adding some testing data 22 | $cx = new \DB\Cortex($db, $tname); 23 | $cx->title = 'bar1'; 24 | $cx->save(); 25 | $cx->reset(); 26 | 27 | $cx->title = 'baz2'; 28 | $cx->num1 = 1; 29 | $cx->save(); 30 | $cx->reset(); 31 | 32 | $cx->title = 'foo3'; 33 | $cx->num1 = 4; 34 | $cx->save(); 35 | $cx->reset(); 36 | 37 | $cx->title = 'FOO4'; 38 | $cx->num1 = 3; 39 | $cx->save(); 40 | $cx->reset(); 41 | 42 | $cx->title = 'foo5'; 43 | $cx->num1 = 3; 44 | $cx->num2 = 5; 45 | $cx->save(); 46 | $cx->reset(); 47 | 48 | $cx->title = 'foo6'; 49 | $cx->num1 = 3; 50 | $cx->num2 = 1; 51 | $cx->save(); 52 | $cx->reset(); 53 | 54 | $cx->title = 'foo7'; 55 | $cx->num1 = 3; 56 | $cx->num2 = 10; 57 | $cx->save(); 58 | $cx->reset(); 59 | 60 | $cx->title = 'foo8'; 61 | $cx->num1 = 5; 62 | $cx->save(); 63 | $cx->reset(); 64 | 65 | $cx->title = 'foo9'; 66 | $cx->num1 = 8; 67 | $cx->save(); 68 | $cx->reset(); 69 | 70 | $result = $this->getResult($cx->find()); 71 | 72 | $expected = array( 73 | 0 => array( 74 | 'title' => 'bar1', 75 | ), 76 | 1 => array( 77 | 'num1' => 1, 78 | 'title' => 'baz2', 79 | ), 80 | 2 => array( 81 | 'num1' => 4, 82 | 'title' => 'foo3', 83 | ), 84 | 3 => array( 85 | 'num1' => 3, 86 | 'title' => 'FOO4', 87 | ), 88 | 4 => array( 89 | 'num1' => 3, 90 | 'num2' => 5, 91 | 'title' => 'foo5', 92 | ), 93 | 5 => array( 94 | 'num1' => 3, 95 | 'num2' => 1, 96 | 'title' => 'foo6', 97 | ), 98 | 6 => array( 99 | 'num1' => 3, 100 | 'num2' => 10, 101 | 'title' => 'foo7', 102 | ), 103 | 7 => array( 104 | 'num1' => 5, 105 | 'title' => 'foo8', 106 | ), 107 | 8 => array( 108 | 'num1' => 8, 109 | 'title' => 'foo9', 110 | ), 111 | ); 112 | 113 | $test->expect( 114 | json_encode($result) == json_encode($expected), 115 | $type.': init mapper, adding records' 116 | ); 117 | 118 | // operator = 119 | $result = $this->getResult($cx->find(array('title = ?', 'foo7'))); 120 | $expected = array( 121 | 0 => array( 122 | 'num1' => 3, 123 | 'num2' => 10, 124 | 'title' => 'foo7', 125 | ), 126 | ); 127 | $test->expect( 128 | json_encode($result) == json_encode($expected), 129 | $type.': operator check: =' 130 | ); 131 | 132 | // operator > 133 | $result = $this->getResult($cx->find(array('num1 > ?', 4))); 134 | $expected = array( 135 | 0 => array( 136 | 'num1' => 5, 137 | 'title' => 'foo8', 138 | ), 139 | 1 => array( 140 | 'num1' => 8, 141 | 'title' => 'foo9', 142 | ), 143 | ); 144 | $test->expect( 145 | json_encode($result) == json_encode($expected), 146 | $type.': operator check: >' 147 | ); 148 | 149 | // operator >= 150 | $result = $this->getResult($cx->find(array('num1 >= ?', 5))); 151 | $test->expect( 152 | json_encode($result) == json_encode($expected), 153 | $type.': operator check: >=' 154 | ); 155 | 156 | // operator < 157 | $result = $this->getResult($cx->find(array('num2 < ?', 2))); 158 | $expected = array( 159 | 0 => array( 160 | 'num1' => 3, 161 | 'num2' => 1, 162 | 'title' => 'foo6', 163 | ), 164 | ); 165 | $test->expect( 166 | json_encode($result) == json_encode($expected), 167 | $type.': operator check: <' 168 | ); 169 | 170 | // operator <= 171 | $result = $this->getResult($cx->find(array('num2 <= ?', 1))); 172 | $test->expect( 173 | json_encode($result) == json_encode($expected), 174 | $type.': operator check: <=' 175 | ); 176 | 177 | // operator without binding 178 | $result = $this->getResult($cx->find(array('num1 > 4'))); 179 | $expected = array( 180 | 0 => array( 181 | 'num1' => 5, 182 | 'title' => 'foo8', 183 | ), 184 | 1 => array( 185 | 'num1' => 8, 186 | 'title' => 'foo9', 187 | ), 188 | ); 189 | $test->expect( 190 | json_encode($result) == json_encode($expected), 191 | $type.': operator without binding' 192 | ); 193 | 194 | // field comparision 195 | $result = $this->getResult($cx->find( 196 | array('num2 > num1', 1))); 197 | $expected = array( 198 | 0 => array( 199 | 'num1' => 3, 200 | 'num2' => 5, 201 | 'title' => 'foo5', 202 | ), 203 | 1 => array( 204 | 'num1' => 3, 205 | 'num2' => 10, 206 | 'title' => 'foo7', 207 | ), 208 | ); 209 | $test->expect( 210 | json_encode($result) == json_encode($expected), 211 | $type.': check field comparision' 212 | ); 213 | 214 | // lookahead search 215 | $result = $this->getResult($cx->find(array('title like ?', '%o6'))); 216 | $expected = array( 217 | 0 => array( 218 | 'num1' => 3, 219 | 'num2' => 1, 220 | 'title' => 'foo6', 221 | ), 222 | ); 223 | $test->expect( 224 | json_encode($result) == json_encode($expected), 225 | $type.': lookahead search' 226 | ); 227 | 228 | // lookbehind search 229 | $result = $this->getResult($cx->find(array('title like ?', 'bar%'))); 230 | $expected = array( 231 | 0 => array( 232 | 'title' => 'bar1', 233 | ), 234 | ); 235 | $test->expect( 236 | json_encode($result) == json_encode($expected), 237 | $type.': lookbehind search' 238 | ); 239 | 240 | // full search 241 | $result = $this->getResult($cx->find(array('title like ?', '%a%'))); 242 | $expected = array( 243 | 0 => array( 244 | 'title' => 'bar1', 245 | ), 246 | 1 => array( 247 | 'num1' => 1, 248 | 'title' => 'baz2', 249 | ), 250 | ); 251 | $test->expect( 252 | json_encode($result) == json_encode($expected), 253 | $type.': full search' 254 | ); 255 | 256 | // negated search 257 | $result = $this->getResult($cx->find(array('title not like ?', 'foo%'))); 258 | $test->expect( 259 | json_encode($result) == json_encode($expected), 260 | $type.': negated search' 261 | ); 262 | 263 | // AND / OR chaining 264 | $result = $this->getResult($cx->find( 265 | array('(num2 < ? AND num1 > ?) OR title like ?', 2, 1, '%o9'))); 266 | $expected = array( 267 | 0 => array( 268 | 'num1' => 3, 269 | 'num2' => 1, 270 | 'title' => 'foo6', 271 | ), 272 | 1 => array( 273 | 'num1' => 8, 274 | 'title' => 'foo9', 275 | ), 276 | ); 277 | $test->expect( 278 | json_encode($result) == json_encode($expected), 279 | $type.': check logical operator chaining' 280 | ); 281 | 282 | // check limit 283 | $result = $this->getResult($cx->find(null, array('limit' => 2))); 284 | $expected = array( 285 | 0 => array( 286 | 'title' => 'bar1', 287 | ), 288 | 1 => array( 289 | 'num1' => 1, 290 | 'title' => 'baz2', 291 | ), 292 | ); 293 | $test->expect( 294 | json_encode($result) == json_encode($expected), 295 | $type.': check limit' 296 | ); 297 | 298 | // check order 299 | $result = $this->getResult($cx->find( 300 | array('num2 >= ?', 1), array('order' => 'num2 desc'))); 301 | $expected = array( 302 | 0 => array( 303 | 'num1' => 3, 304 | 'num2' => 10, 305 | 'title' => 'foo7', 306 | ), 307 | 1 => array( 308 | 'num1' => 3, 309 | 'num2' => 5, 310 | 'title' => 'foo5', 311 | ), 312 | 2 => array( 313 | 'num1' => 3, 314 | 'num2' => 1, 315 | 'title' => 'foo6', 316 | ), 317 | ); 318 | 319 | $test->expect( 320 | json_encode($result) == json_encode($expected), 321 | $type.': check order' 322 | ); 323 | 324 | // IN search 325 | $rc = $cx->find(array('num1 IN ?',array(4,5,8))); 326 | $result = $rc->getAll('title'); 327 | sort($result); 328 | $test->expect( 329 | json_encode($result) == json_encode(array('foo3','foo8','foo9')), 330 | $type.': IN operator' 331 | ); 332 | 333 | $rc = $cx->find(array('num1 IN ? && num2 > ? && num2 NOT IN ?',array(3,4),1,array(10))); 334 | $result = $rc->getAll('title'); 335 | $test->expect( 336 | json_encode($result) == json_encode(array('foo5')), 337 | $type.': enhanced IN, NOT IN operator' 338 | ); 339 | 340 | $result = $cx->find(array('num1 = ?',NULL)); 341 | $test->expect( 342 | count($result) == 1 && $result[0]->title == 'bar1', 343 | $type.': check NULL' 344 | ); 345 | 346 | $result = $cx->find(array('num2 != ?',NULL)); 347 | $test->expect( 348 | count($result) == 3, 349 | $type.': check NOT NULL' 350 | ); 351 | 352 | /////////////////////////////////// 353 | return $test->results(); 354 | } 355 | 356 | /** 357 | * unify results for better comparison 358 | */ 359 | private function getResult($result) 360 | { 361 | $out = array(); 362 | foreach ($result?:[] as $row) { 363 | $row = $row->cast(); 364 | unset($row['_id']); 365 | unset($row['id']); 366 | ksort($row); 367 | foreach ($row as $col => $val) { 368 | if (empty($val) || is_null($val)) 369 | unset($row[$col]); 370 | } 371 | $out[] = $row; 372 | } 373 | return $out; 374 | } 375 | } --------------------------------------------------------------------------------