├── LICENSE.md
├── README.md
├── composer.json
├── config
└── restql.php
├── src
├── Argument.php
├── Arguments
│ ├── SelectArgument.php
│ ├── SortArgument.php
│ ├── WhereArgument.php
│ ├── WhereInOrNotInArgument.php
│ └── WithArgument.php
├── Authorizer.php
├── Authorizers
│ └── PermissiveAuthorizer.php
├── Builder.php
├── Clausule.php
├── ClausuleExecutor.php
├── Clausules
│ ├── SelectClausule.php
│ ├── SortClausule.php
│ ├── TakeClausule.php
│ ├── WhereClausule.php
│ ├── WhereInClausule.php
│ ├── WhereNotInClausule.php
│ └── WithClausule.php
├── Console
│ ├── AuthorizerMakeCommand.php
│ ├── ClausuleMakeCommand.php
│ ├── ResolverMakeCommand.php
│ └── SchemaRestqlCommand.php
├── Contracts
│ ├── ArgumentContract.php
│ ├── AuthorizerContract.php
│ └── SchemaHandlerContract.php
├── Exceptions
│ ├── AccessDeniedHttpException.php
│ ├── InvalidSchemaDefinitionException.php
│ └── MissingArgumentException.php
├── ModelArgument.php
├── Providers
│ └── RestqlServiceProvider.php
├── RequestParser.php
├── Resolver.php
├── Resolvers
│ ├── QueryBuilderResolver.php
│ └── WhoamiResolver.php
├── Restql.php
├── SchemaDefinition.php
├── Services
│ └── ConfigService.php
├── Support
│ └── ReflectionSupport.php
└── Traits
│ ├── HasConfigService.php
│ ├── ModelResolver.php
│ └── RestqlAttributes.php
└── stubs
├── authorizer.stub
├── clausule.stub
└── resolver.stub
/LICENSE.md:
--------------------------------------------------------------------------------
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 |
635 | Copyright (C)
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 | Copyright (C)
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # RestQL
2 |
3 | [](//packagist.org/packages/gregorip02/restql)
4 | [](//packagist.org/packages/gregorip02/restql)
5 | [](//packagist.org/packages/gregorip02/restql)
6 | [](https://github.com/gregorip02/restql/actions)
7 |
8 | RestQL is a Laravel eloquent-based data resolution package. This package tries to adopt **GraphQL** principles solving only the data that the client requests. RestQL uses your **Laravel** models as an entry point to add queries to then based in the eloquent methods.
9 |
10 | **Please see the [documentation](https://github.com/gregorip02/restql/wiki).**
11 |
12 |
13 |
14 | ## **Why?**
15 |
16 | Imagine you have an application that manages authors, these authors can publish articles and those articles can have comments from different authors. You have a web client, for example, that uses **fetch** to consume the data offered by your service and somewhere in your code, you need a list of the **author's names only**.
17 |
18 | They wear something like that.
19 |
20 | ```js
21 | fetch('https://laravel.app/api/authors')
22 | .then((res) => res.json())
23 | .then(({ data }) => console.log(data.authors));
24 | ```
25 |
26 | So, you have a route like this.
27 |
28 | `routes/api.php`
29 |
30 | ```php
31 | get();
38 |
39 | return ['data' => compact('authors')];
40 | });
41 | ```
42 |
43 | Most likely you will use a controller, then use the author model and query the data.
44 | Finally you would have a response similar to this.
45 |
46 | ```javascript
47 | {
48 | "data": {
49 | "authors": [
50 | {
51 | "id": 1,
52 | "name": "Lazaro Kohler",
53 | "email": "greenfelder.jenifer@example.org",
54 | "email_verified_at": "2020-03-19T18:11:36.000000Z",
55 | "created_at": "2020-03-19T18:11:36.000000Z",
56 | "updated_at": "2020-03-19T18:11:36.000000Z"
57 | },
58 | {
59 | "id": 2,
60 | "name": "Miss Anastasia Klocko DVM",
61 | "email": "lemke.trinity@example.org",
62 | "email_verified_at": "2020-03-19T18:11:36.000000Z",
63 | "created_at": "2020-03-19T18:11:36.000000Z",
64 | "updated_at": "2020-03-19T18:11:36.000000Z"
65 | },
66 | { /* 23 more authors */ }
67 | ]
68 | }
69 | }
70 | ```
71 |
72 | But what if you only need a **author's names** collection for example? Imagine that your application becomes huge and your user model handles a large number of attributes.
73 |
74 | ## **Get started**
75 |
76 | Install RestQL using composer.
77 |
78 | ```bash
79 | composer require gregorip02/restql
80 | ```
81 |
82 | Publish the package configuration.
83 |
84 | ```bash
85 | php artisan restql:schema
86 | ```
87 |
88 | Add the `RestqlAttributes` trait to your eloquent models.
89 |
90 | > **2.2** This is recomended because you can determine the selectable attributes with `onSelectFillable`.
91 |
92 | ```php
93 | Since version 2.x of this package the configuration has been updated to increase flexibility and internal behavior modification.
155 |
156 | You must define your entire schema in the config file, RestQL will then interpret it and execute the queries based on this file. With this there is a possibility that you can remove internal functions, modify them or even create your own implementations. See Schema definition.
157 |
158 | `config/restql.php`
159 |
160 | ```php
161 | [
170 | 'authors' => [
171 | 'class' => Author::class,
172 | 'authorizer' => AuthorAuthorizer::class,
173 | 'middlewares' => []
174 | ]
175 | ],
176 |
177 | // ...
178 | ];
179 | ```
180 |
181 | The developer must specify the return type of the relationships defined in the eloquent model. **You should set the return type of your associative methods** (relationships). For example.
182 |
183 | `app/Models/Author.php`
184 |
185 | ```php
186 | Restql::resolve($request));
216 | ```
217 |
218 | ## **Refactor time**
219 |
220 | Now, you can re-factor your client's code so that it sends a parameter in the request with the data it needs, in this case a collection of author names. They wear something like that.
221 |
222 | ```js
223 | const { stringify } = require('qs');
224 |
225 | // Define your queries.
226 | const getAuthorsQuery = {
227 | authors: {
228 | select: ['name']
229 | }
230 | };
231 |
232 | // Consume the restql endpoint.
233 | fetch(`https://laravel.app/restql?${stringify(getAuthorsQuery)}`)
234 | .then((res) => res.json())
235 | .then((res) => console.log(res));
236 | ```
237 |
238 | The parameters of the query should be a parsed objects that defines the clauses accepted by your schema definition. For your web clients **we recommend [qs](https://www.npmjs.com/package/qs).** Instead of having a long JSON response with unnecessary data, you would get something like this.
239 |
240 | ```javascript
241 | {
242 | "data": {
243 | "authors": [
244 | { "id": 1, "name": "Kasey Yost" },
245 | { "id": 2, "name": "Ike Barton" },
246 | { "id": 3, "name": "Emie Daniel" },
247 | { /* 22 more authors */ }
248 | ]
249 | }
250 | }
251 | ```
252 |
253 | Likewise, this will considerably optimize your queries to the database management system. In this case, it will run just a `select id, name from authors` for example.
254 |
255 |
256 |
257 | ## **The good parts**
258 |
259 | So, let's say you now have a requirement in your application that tells you to have the `id` and `title` of the last **two** articles published by each author.
260 |
261 | ```js
262 | const { stringify } = require('qs');
263 |
264 | // Define your queries.
265 | const getAuthorsAndTwoLatestArticlesQuery = {
266 | authors: {
267 | select: ['name'],
268 | with: {
269 | articles: {
270 | take: 2
271 | select: 'title',
272 | sort: {
273 | column: 'published_at',
274 | direction: 'desc'
275 | },
276 | }
277 | }
278 | }
279 | };
280 |
281 | // Consume the restql endpoint.
282 | fetch(`https://laravel.app/restql?${stringify(getAuthorsAndTwoLatestArticlesQuery)}`)
283 | .then((res) => res.json())
284 | .then((res) => console.log(res));
285 | ```
286 |
287 | You wold get a response like this.
288 |
289 | ```json
290 | {
291 | "data": {
292 | "authors": [
293 | {
294 | "id": 1,
295 | "name": "Kasey Yost",
296 | "articles": [
297 | {
298 | "id": 3434,
299 | "title": "My awesome article"
300 | }
301 | ]
302 | },
303 | { /* 24 more authors */ }
304 | ]
305 | }
306 | }
307 | ```
308 |
309 |
310 |
311 | ## **How it works**
312 |
313 | Basically, RestQL filters the keys of the models received in the HTTP request and compares them with the keys of the user configuration. These keys represent a specific eloquent model. The values of these keys are eloquent clauses (methods) accepted by RestQL and the arguments of these clauses are sent as values.
314 |
315 | For example, if a params like the following is sent in the request.
316 |
317 | ```javascript
318 | {
319 | "authors": {
320 | "select": "name",
321 | "with": {
322 | "articles": {
323 | "select": "title"
324 | }
325 | }
326 | }
327 | }
328 | ```
329 |
330 | RestQL will interpret this as the following.
331 |
332 | ```php
333 | select(['name'])->with([
339 | 'articles' => static function (Relation $relation) {
340 | $relation->select(['title']);
341 | }
342 | ]);
343 | ```
344 |
345 | You can read more about the RestQL Clausules here.
347 |
348 | # **What's next?**
349 |
350 | Are you interested on contrib to this project? see the NEXT.md file.
352 |
353 | # **Contributing**
354 |
355 | Thanks for consider contrib to this project, please see the development docs at this
356 | page.
357 |
358 | # **Please support it**
359 |
360 | This is a personal project that can be very useful, if you believe it, help me
361 | develop new functionalities and create a pull request, I will be happy to review
362 | and add it. So, You can also contribute to the team by buying a coffee.
363 |
364 |
365 |
370 |
371 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "gregorip02/restql",
3 | "description": "A data resolution package for Laravel",
4 | "type": "library",
5 | "keywords": ["restql", "eloquent", "laravel", "graphql"],
6 | "url": "https://github.com/gregorip02/restql",
7 | "license": "LGPL-3.0",
8 | "authors": [
9 | {
10 | "name": "Gregori Piñeres",
11 | "email": "gregori.pineres02@gmail.com",
12 | "homepage": "https://github.com/gregorip02"
13 | }
14 | ],
15 | "support": {
16 | "issues": "https://github.com/gregorip02/restql/issues",
17 | "source": "https://github.com/gregorip02/restql"
18 | },
19 | "require": {
20 | "php": "^7.2|^8.0",
21 | "laravel/framework": "^6|^7|^8"
22 | },
23 | "require-dev": {
24 | "phpunit/phpunit": "^7.5|^8",
25 | "orchestra/testbench": "^4|^5|^6",
26 | "friendsofphp/php-cs-fixer": "^2.18"
27 | },
28 | "autoload": {
29 | "psr-4": {
30 | "Restql\\": "src/"
31 | }
32 | },
33 | "autoload-dev": {
34 | "psr-4": {
35 | "Testing\\": "tests/",
36 | "Testing\\App\\": "tests/App/app/"
37 | }
38 | },
39 | "extra": {
40 | "laravel": {
41 | "providers": [
42 | "Restql\\Providers\\RestqlServiceProvider"
43 | ]
44 | }
45 | },
46 | "scripts": {
47 | "test": "vendor/bin/phpunit"
48 | },
49 | "minimum-stability": "dev",
50 | "prefer-stable": true
51 | }
52 |
--------------------------------------------------------------------------------
/config/restql.php:
--------------------------------------------------------------------------------
1 | env('RESTQL_PARAM_NAME', ''),
14 |
15 | /*
16 | |--------------------------------------------------------------------------
17 | | Data resolution schema
18 | |--------------------------------------------------------------------------
19 | |
20 | | Define a list of the models that RestQL can manipulate, create
21 | | authorizers and middlewares to protect your schema definition
22 | | resources.
23 | |
24 | | see https://github.com/gregorip02/restql/wiki/Install#schema-definition
25 | */
26 |
27 | 'schema' => [],
28 |
29 | /*
30 | |--------------------------------------------------------------------------
31 | | Custom resolvers definition
32 | |--------------------------------------------------------------------------
33 | |
34 | | Define custom data resolvers, you can also define permissions
35 | | and middlewares for clients to access it.
36 | |
37 | | see https://github.com/gregorip02/restql/wiki/Resolvers
38 | */
39 |
40 | 'resolvers' => [
41 | // Uncoment this and get the currently authenticated user.
42 | // 'whoami' => [
43 | // 'class' => 'Restql\Resolvers\WhoamiResolver',
44 | // 'authorizer' => 'Restql\Authorizers\PermissiveAuthorizer',
45 | // 'middlewares' => ['auth']
46 | // ]
47 | ],
48 |
49 | /*
50 | |--------------------------------------------------------------------------
51 | | Allowed clausules
52 | |--------------------------------------------------------------------------
53 | |
54 | | Define a list of clauses that are available. Modify or delete the clauses
55 | | that do not interest you.
56 | |
57 | | see https://github.com/gregorip02/restql/wiki/Clausules
58 | */
59 |
60 | 'clausules' => [
61 | 'select' => 'Restql\Clausules\SelectClausule',
62 | 'where' => 'Restql\Clausules\WhereClausule',
63 | 'whereIn' => 'Restql\Clausules\WhereInClausule',
64 | 'whereNotIn' => 'Restql\Clausules\WhereNotInClausule',
65 | 'take' => 'Restql\Clausules\TakeClausule',
66 | 'sort' => 'Restql\Clausules\SortClausule',
67 | 'with' => 'Restql\Clausules\WithClausule',
68 | // Add your custom clausules here
69 | ]
70 | ];
71 |
--------------------------------------------------------------------------------
/src/Argument.php:
--------------------------------------------------------------------------------
1 | values = $values;
34 | }
35 |
36 | /**
37 | * Get the default argument values.
38 | *
39 | * @return array
40 | */
41 | public function getDefaultArgumentValues(): array
42 | {
43 | return [];
44 | }
45 |
46 | /**
47 | * Get an attribute from the argument.
48 | *
49 | * @param string $keyname
50 | * @param mixed $default
51 | * @return mixed
52 | */
53 | public function getAttribute(string $keyname, $default = null)
54 | {
55 | return $this->values[$keyname] ?? $default;
56 | }
57 |
58 | /**
59 | * Get an attribute from the argument or throw an exception.
60 | *
61 | * @param string $keyname
62 | * @return mixed|Exception
63 | */
64 | public function getAttributeOrFail(string $keyname)
65 | {
66 | return $this->getAttribute($keyname, false) ?: new Exception("Error getting attribute ${keyname}");
67 | }
68 |
69 | /**
70 | * Get the first argument values.
71 | *
72 | * @return mixed
73 | */
74 | public function first(callable $callback = null, $default = null)
75 | {
76 | return Arr::first($this->values, $callback, $default);
77 | }
78 |
79 | /**
80 | * Get the argument values as array.
81 | *
82 | * @return array
83 | */
84 | public function values(): array
85 | {
86 | return $this->values;
87 | }
88 |
89 | /**
90 | * Create a new collection instance based on the argument values.
91 | *
92 | * @return \Illuminate\Support\Collection
93 | */
94 | public function collection(): Collection
95 | {
96 | return Collection::make($this->values);
97 | }
98 |
99 | /**
100 | * Determine if the incoming values are associative array.
101 | *
102 | * @return bool
103 | */
104 | public function isAssoc(): bool
105 | {
106 | return Arr::isAssoc($this->values);
107 | }
108 |
109 | /**
110 | * Determine if the incoming value is only one and also implicit.
111 | *
112 | * @return bool
113 | */
114 | public function isImplicitValue(): bool
115 | {
116 | return ! $this->isAssoc() && $this->countValues() === 1;
117 | }
118 |
119 | /**
120 | * Count the client incoming values.
121 | *
122 | * @return int
123 | */
124 | public function countValues(): int
125 | {
126 | return count($this->values);
127 | }
128 |
129 | /**
130 | * Merge the user argument values with defaults data.
131 | *
132 | * @return array
133 | */
134 | public function data(): array
135 | {
136 | $default = $this->getDefaultArgumentValues();
137 |
138 | $values = $this->values();
139 |
140 | if (! (bool) $values && (bool) $default) {
141 | /// Return the default values, if defined and also,
142 | /// the client sends null values as arguments.
143 | return $default;
144 | } elseif ((bool) $default) {
145 | /// Some arguments admit values of implicit type, that is, they
146 | /// can be interpreted by the clause in different ways.
147 | if (! Arr::isAssoc($values) && $this->hasImplicitValues) {
148 | /// Prevent exception with "Both parameters should have an equal
149 | /// number of elements" slicing the values.
150 | $slice = array_slice(array_keys($default), 0, count($values));
151 |
152 | return array_combine($slice, array_slice($values, 0, count($default)));
153 | }
154 |
155 | /// Combine the default values with the values sent by the client.
156 | /// The default values of these attributes are required to be associative.
157 | return array_merge($default, $values);
158 | }
159 |
160 | /// Returns the raw data.
161 | return $values;
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/src/Arguments/SelectArgument.php:
--------------------------------------------------------------------------------
1 | excludeHiddenAttributes();
19 |
20 | /// The onSelectFillables method allow to developers to determine
21 | /// what attributes can be obtained for clients based on
22 | /// your roles or pemissions.
23 | if ($this->unsingRestqlTrait()) {
24 | $values = Collection::make(array_combine($values, $values))
25 | ->only($this->model->onSelectFillables())
26 | ->keys()
27 | ->toArray();
28 | }
29 |
30 | /// By default we include the model primary key on every
31 | /// select clausule because is necesary for add correctly
32 | /// the model releationships eager loaded.
33 | $primaryKeyName = $this->getKeyName();
34 |
35 | if (! in_array($primaryKeyName, $values)) {
36 | $values[] = $primaryKeyName;
37 | }
38 |
39 | return $values;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/Arguments/SortArgument.php:
--------------------------------------------------------------------------------
1 | $this->getKeyName(),
25 | 'direction' => 'asc'
26 | ];
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/Arguments/WhereArgument.php:
--------------------------------------------------------------------------------
1 | isImplicitValue()) {
25 | /// When an implicit type value is received, it will be assumed that
26 | /// it corresponds to the value of the primary column of the model.
27 | return [
28 | 'value' => $this->first()
29 | ];
30 | }
31 |
32 | return parent::values();
33 | }
34 |
35 | /**
36 | * Get default argument values.
37 | *
38 | * @return array
39 | */
40 | public function getDefaultArgumentValues(): array
41 | {
42 | return [
43 | 'column' => $this->getKeyName(),
44 | 'operator' => '=',
45 | 'value' => null,
46 | 'boolean' => 'and'
47 | ];
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/Arguments/WhereInOrNotInArgument.php:
--------------------------------------------------------------------------------
1 | isImplicitValue()) {
25 | /// When an implicit type value is received, it will be assumed that
26 | /// it corresponds to the value of the primary column of the model.
27 | return [
28 | 'value' => (array) $this->first()
29 | ];
30 | }
31 |
32 | return parent::values();
33 | }
34 |
35 | /**
36 | * Get default argument values.
37 | *
38 | * @return array
39 | */
40 | public function getDefaultArgumentValues(): array
41 | {
42 | return [
43 | 'column' => $this->getKeyName(),
44 | 'value' => []
45 | ];
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/Arguments/WithArgument.php:
--------------------------------------------------------------------------------
1 | getModel();
23 |
24 | return $this->collection()->filter(function ($_, $method) use ($model) {
25 | if (! method_exists($model, $method)) {
26 | /// Exclude methods not found in the model
27 | return false;
28 | }
29 |
30 | $reflection = new ReflectionSupport($model);
31 | $methodType = $reflection->getMethodReturnType($method);
32 |
33 | /// Excluding untyped methods in eloquent models.
34 | if ($methodType === '') {
35 | return false;
36 | }
37 |
38 | /// From this change, the developer needs to set the return type in
39 | /// its eloquent relationships. This will greatly optimize the
40 | /// algorithm speed and consequently server responses.
41 | $parentClasses = class_parents($methodType) ?? [];
42 |
43 | /// A stupid way to determine if the property typed in the method is
44 | /// of type "\Illuminate\Database\Eloquent\Relation".
45 | return array_key_exists(Relation::class, $parentClasses);
46 | })->map(function ($clausules) {
47 | /// Build the related model query.
48 | return $this->buildRelationQuery(Collection::make($clausules));
49 | })->toArray();
50 | }
51 |
52 | /**
53 | * Build the clousure called in the select clausule.
54 | *
55 | * @param \Illuminate\Support\Collection $clausules
56 | * @return Clousure
57 | */
58 | protected function buildRelationQuery(Collection $clausules)
59 | {
60 | return static function (Relation $relation) use ($clausules) {
61 | if ($selects = (array) $clausules->get('select', null)) {
62 | /// Add the foreign key name in HasMany type relationships
63 | if ($relation instanceof HasMany) {
64 | $foreignKeyName = $relation->getForeignKeyName();
65 | if (! in_array($foreignKeyName, $selects, true)) {
66 | $selects[] = $foreignKeyName;
67 | $clausules->put('select', $selects);
68 | }
69 | }
70 | }
71 |
72 | /// Unnecesary include the take or limit clausule.
73 | $clausules->forget(['take', 'limit']);
74 |
75 | ClausuleExecutor::exec($relation->getRelated(), $clausules, $relation->getQuery());
76 | };
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/Authorizer.php:
--------------------------------------------------------------------------------
1 | query = $query;
44 |
45 | $this->routeMiddleware = app('router')->getMiddleware();
46 | }
47 |
48 | /**
49 | * Static class instance.
50 | *
51 | * @param \Illuminate\Support\Collection $query
52 | * @return \Illuminate\Support\Collection
53 | */
54 | public static function make(Collection $query): Collection
55 | {
56 | return (new Builder($query))->dispatch();
57 | }
58 |
59 | /**
60 | * Chains the methods to the eloquent query.
61 | *
62 | * @return \Illuminate\Support\Collection
63 | */
64 | protected function dispatch(): Collection
65 | {
66 | $schema = $this->schema();
67 |
68 | $this->checkMiddlewares($schema);
69 |
70 | $this->checkAuthorizers($schema);
71 |
72 | $schema->each(function (SchemaDefinition $schema) {
73 | /// Executing the "handle" method in the schema definition, this will
74 | /// return a collection with data resolved independently.
75 | $this->response[$schema->getKeyName()] = $schema->handle();
76 | });
77 |
78 | return Collection::make($this->response);
79 | }
80 |
81 | /**
82 | * Checks middlewares for incoming request.
83 | *
84 | * @param \Illuminate\Support\Collection $schema
85 | * @return void
86 | */
87 | protected function checkAuthorizers(Collection $schema): void
88 | {
89 | $method = Str::lower(request()->method());
90 |
91 | $schema->each(function (SchemaDefinition $schema) use ($method) {
92 | $instance = $schema->getAuthorizerInstance();
93 |
94 | $clausules = $schema->getClausules();
95 |
96 | if (! call_user_func([$instance, $method], $clausules)) {
97 | throw new AccessDeniedHttpException(
98 | $schema->getKeyName(),
99 | $method
100 | );
101 | }
102 | });
103 | }
104 |
105 | /**
106 | * Checks middlewares for incoming request.
107 | *
108 | * @param \Illuminate\Support\Collection $schema
109 | * @return void
110 | */
111 | protected function checkMiddlewares(Collection $schema): void
112 | {
113 | $middlewares = $this->getMiddlewareClasses($schema);
114 |
115 | $request = app('request');
116 |
117 | app(Pipeline::class)->send($request)->through($middlewares)->thenReturn();
118 | }
119 |
120 | /**
121 | * Create an array of middlewares classess.
122 | *
123 | * @param \Illuminate\Support\Collection $schema
124 | * @return array
125 | */
126 | protected function getMiddlewareClasses(Collection $schema): array
127 | {
128 | return $schema->reduce(
129 | function (array $reducer, SchemaDefinition $schemaDefinition) {
130 | foreach ($schemaDefinition->getMiddlewares() as $key => $value) {
131 | $middlewareClass = $this->routeMiddleware[$value] ?? false;
132 | if ($middlewareClass && ! in_array($middlewareClass, $reducer)) {
133 | $reducer[] = $middlewareClass;
134 | }
135 | }
136 |
137 | return $reducer;
138 | },
139 | []
140 | );
141 | }
142 |
143 | /**
144 | * Remove unknow model key and resolvers names from the incoming query.
145 | *
146 | * @return \Illuminate\Support\Collection
147 | */
148 | public function schema(): Collection
149 | {
150 | return $this->query->map(function ($arguments, $schemaKeyName) {
151 | /// Create an SchemaDefinition instance.
152 | return new SchemaDefinition($schemaKeyName, (array) $arguments);
153 | })->filter(function (SchemaDefinition $schema) {
154 | /// Checks if the schema class exists and be a
155 | /// 'Illuminate\Database\Eloquent\Model' or 'Restql\Resolver' children.
156 | return $schema->imValid();
157 | });
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/src/Clausule.php:
--------------------------------------------------------------------------------
1 | executor = $executor;
41 | $this->arguments = $this->createArgumentsInstance($arguments);
42 | $this->canBuild();
43 | }
44 |
45 | /**
46 | * Prepare the clausule builder.
47 | *
48 | * @return void
49 | */
50 | public function prepare(): void
51 | {
52 | $this->executor->executeQuery(function (QueryBuilder $builder) {
53 | $this->build($builder);
54 | });
55 | }
56 |
57 | /**
58 | * Get the clausule arguments instance.
59 | *
60 | * @return \Restql\Argument
61 | */
62 | public function arguments(): Argument
63 | {
64 | return $this->arguments;
65 | }
66 |
67 | /**
68 | * Get a new instance of the clausule argument.
69 | *
70 | * @param array $values
71 | * @return \Restql\Argument
72 | */
73 | protected function createArgumentsInstance(array $values = []): Argument
74 | {
75 | return new Argument($values);
76 | }
77 |
78 | /**
79 | * Returns the request access method for a determinated clausule.
80 | *
81 | * @return string
82 | */
83 | protected function accessMethod(): string
84 | {
85 | $method = request()->method();
86 |
87 | return Str::lower($method);
88 | }
89 |
90 | /**
91 | * Determine if the incoming request method is allowed for a determinated clausule.
92 | *
93 | * @return boolean
94 | */
95 | protected function isAllowedMethod(): bool
96 | {
97 | $method = $this->accessMethod();
98 |
99 | return in_array($method, $this->allowedVerbs) || in_array('all', $this->allowedVerbs);
100 | }
101 |
102 | /**
103 | * Has method not allowed hook.
104 | *
105 | * @param string $name
106 | * @throws \Restql\Exceptions\AccessDeniedHttpException
107 | */
108 | protected function throwIfMethodIsNotAllowed(string $name): void
109 | {
110 | if (! $this->isAllowedMethod()) {
111 | throw new AccessDeniedHttpException($name, $this->accessMethod());
112 | }
113 | }
114 |
115 | /**
116 | * Has argument missing hook.
117 | *
118 | * @param string $class
119 | * @throws Exception
120 | */
121 | protected function throwIfArgumentIsMissing(string $class): void
122 | {
123 | //
124 | }
125 |
126 | /**
127 | * Throw a exception if can't build this clausule.
128 | *
129 | * @return void
130 | */
131 | protected function canBuild(): void
132 | {
133 | $this->throwIfMethodIsNotAllowed(class_basename(self::class));
134 | // $this->throwIfArgumentIsMissing(class_basename(self::class));
135 | }
136 |
137 | /**
138 | * Implement the clausule query builder.
139 | *
140 | * @param \Illuminate\Database\Eloquent\Builder $builder
141 | * @return void
142 | */
143 | abstract public function build(QueryBuilder $builder): void;
144 | }
145 |
--------------------------------------------------------------------------------
/src/ClausuleExecutor.php:
--------------------------------------------------------------------------------
1 | model = $model;
46 |
47 | $this->clausules = $clausules;
48 |
49 | $this->query = $query ?? $model->query();
50 | }
51 |
52 | /**
53 | * Static class instance.
54 | *
55 | * @param \Illuminate\Database\Eloquent\Model $model
56 | * @param \Illuminate\Support\Collection $clausules
57 | * @param \Illuminate\Database\Eloquent\Builder $query
58 | * @return Illuminate\Database\Eloquent\Builder
59 | */
60 | public static function exec(Model $model, Collection $clausules, QueryBuilder $query = null): QueryBuilder
61 | {
62 | return (new ClausuleExecutor(...func_get_args()))->make();
63 | }
64 |
65 | /**
66 | * Instance all the recived clausules and built it.
67 | *
68 | * @return \Illuminate\Database\Eloquent\Builder
69 | */
70 | protected function make(): QueryBuilder
71 | {
72 | $configService = $this->getConfigService();
73 |
74 | $this->clausules->filter(function ($_, $clausuleKeyName) use ($configService) {
75 | /// Determine if a key or className is registered in the config.
76 | return $configService->hasClausule($clausuleKeyName);
77 | })->map(function ($arguments, string $clausuleKeyName) use ($configService) {
78 | /// Create a instance of Clausule based on the key name.
79 | return $configService->createClasuleInstance($this, $clausuleKeyName, (array) $arguments);
80 | })->each(function (Clausule $clausule) {
81 | /// Prepare and run the clausule builder method.
82 | $clausule->prepare();
83 | });
84 |
85 | return $this->query;
86 | }
87 |
88 | /**
89 | * Get the model instance being queried.
90 | *
91 | * @return \Illuminate\Database\Eloquent\Model
92 | */
93 | public function getModel()
94 | {
95 | return $this->model;
96 | }
97 |
98 | /**
99 | * Get the relations key name in the with clausule.
100 | *
101 | * @return \Illuminate\Support\Collection
102 | */
103 | public function getWithModelKeyNames(): Collection
104 | {
105 | $withKeys = array_keys($this->clausules->get('with', []));
106 |
107 | return Collection::make($withKeys);
108 | }
109 |
110 | /**
111 | * Execute and mutate the model query.
112 | *
113 | * @param Closure $callback
114 | * @return void
115 | */
116 | public function executeQuery(Closure $callback): void
117 | {
118 | $callback($this->query);
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/src/Clausules/SelectClausule.php:
--------------------------------------------------------------------------------
1 | arguments->data();
31 |
32 | /// You have to determine if the client requests BelongsTo
33 | /// relationships in the next "with" clause. If true, the foreign key
34 | /// name must be added to the query so that the eloquent collection
35 | /// knows where it belongs.
36 | $this->pushBelongsToForeignKeyName($arguments);
37 |
38 | $builder->select($arguments);
39 | }
40 |
41 | /**
42 | * Push belongsTo foreign key names to the selec clausule.
43 | *
44 | * @param array &$arguments
45 | * @return void
46 | */
47 | protected function pushBelongsToForeignKeyName(array &$arguments): void
48 | {
49 | $withModelNames = $this->executor->getWithModelKeyNames();
50 |
51 | if ($withModelNames->count()) {
52 | $belongsTo = $this->getBelongsToAttributes($withModelNames);
53 | if (count($belongsTo)) {
54 | foreach ($belongsTo as $belongsToAttribute) {
55 | $arguments[] = $belongsToAttribute;
56 | }
57 | }
58 | }
59 | }
60 |
61 | /**
62 | * Gets the names of the foreign keys for relationships of type BelongsTo.
63 | *
64 | * @param \Illuminate\Support\Collection $withParams
65 | * @return array
66 | */
67 | protected function getBelongsToAttributes(Collection $withParams): array
68 | {
69 | $model = $this->executor->getModel();
70 |
71 | return $withParams->filter(function ($method) use ($model) {
72 | if (! method_exists($model, $method)) {
73 | /// Exclude methods not found in the model
74 | return false;
75 | }
76 |
77 | /// From this change, the developer needs to set the return type in
78 | /// its eloquent relationships. This will greatly optimize the
79 | /// algorithm speed and consequently server responses.
80 | return (new ReflectionSupport($model))->methodIs($method, BelongsTo::class);
81 | })->map(function ($method) use ($model) {
82 | /// Get the foreign key of the relationship.
83 | return call_user_func([$model, $method])->getForeignKeyName();
84 | })->unique()->toArray();
85 | }
86 |
87 | /**
88 | * Get a new instance of the clausule argument.
89 | *
90 | * @param array $values
91 | * @return \Restql\Argument
92 | */
93 | protected function createArgumentsInstance(array $values = []): Argument
94 | {
95 | return new SelectArgument($this->executor->getModel(), $values);
96 | }
97 |
98 | /**
99 | * Throw a exception if can't build this clausule.
100 | *
101 | * @return void
102 | */
103 | protected function canBuild(): void
104 | {
105 | parent::throwIfMethodIsNotAllowed('select');
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/src/Clausules/SortClausule.php:
--------------------------------------------------------------------------------
1 | arguments->data());
29 |
30 | $builder->orderBy(...$arguments);
31 | }
32 |
33 | /**
34 | * Get a new instance of the clausule argument.
35 | *
36 | * @param array $values
37 | * @return \Restql\Arguments\WhereArgument
38 | */
39 | protected function createArgumentsInstance(array $values = []): Argument
40 | {
41 | return new SortArgument($this->executor->getModel(), $values);
42 | }
43 |
44 | /**
45 | * Throw a exception if can't build this clausule.
46 | *
47 | * @return void
48 | */
49 | protected function canBuild(): void
50 | {
51 | parent::throwIfMethodIsNotAllowed('sort');
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/Clausules/TakeClausule.php:
--------------------------------------------------------------------------------
1 | take($this->arguments->first(null, 15));
26 | }
27 |
28 | /**
29 | * Throw a exception if can't build this clausule.
30 | *
31 | * @return void
32 | */
33 | protected function canBuild(): void
34 | {
35 | parent::throwIfMethodIsNotAllowed('take');
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/Clausules/WhereClausule.php:
--------------------------------------------------------------------------------
1 | arguments->data());
30 |
31 | $builder->where(...$args);
32 | }
33 |
34 | /**
35 | * Get a new instance of the clausule argument.
36 | *
37 | * @param array $values
38 | * @return \Restql\Arguments\WhereArgument
39 | */
40 | protected function createArgumentsInstance(array $values = []): Argument
41 | {
42 | return new WhereArgument($this->executor->getModel(), $values);
43 | }
44 |
45 | /**
46 | * Has argument missing hook.
47 | *
48 | * @param string $class
49 | * @throws Exception
50 | */
51 | protected function throwIfArgumentIsMissing(string $class): void
52 | {
53 | if ($this->arguments->isAssoc() && ! $this->arguments->getAttribute('value', false)) {
54 | throw new MissingArgumentException('value', $class);
55 | }
56 | }
57 |
58 | /**
59 | * Throw a exception if can't build this clausule.
60 | *
61 | * @return void
62 | */
63 | protected function canBuild(): void
64 | {
65 | parent::throwIfMethodIsNotAllowed('where');
66 | $this->throwIfArgumentIsMissing('where');
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/Clausules/WhereInClausule.php:
--------------------------------------------------------------------------------
1 | arguments->data());
21 |
22 | $builder->whereIn(...$args);
23 | }
24 |
25 | /**
26 | * Get a new instance of the clausule argument.
27 | *
28 | * @param array $values
29 | * @return \Restql\Arguments\WhereArgument
30 | */
31 | protected function createArgumentsInstance(array $values = []): Argument
32 | {
33 | return new WhereInOrNotInArgument($this->executor->getModel(), $values);
34 | }
35 |
36 | /**
37 | * Throw a exception if can't build this clausule.
38 | *
39 | * @return void
40 | */
41 | protected function canBuild(): void
42 | {
43 | parent::throwIfMethodIsNotAllowed('whereIn');
44 | $this->throwIfArgumentIsMissing('whereIn');
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/Clausules/WhereNotInClausule.php:
--------------------------------------------------------------------------------
1 | arguments->data());
19 |
20 | $builder->whereNotIn(...$args);
21 | }
22 |
23 | /**
24 | * Throw a exception if can't build this clausule.
25 | *
26 | * @return void
27 | */
28 | protected function canBuild(): void
29 | {
30 | parent::throwIfMethodIsNotAllowed('whereNotIn');
31 | $this->throwIfArgumentIsMissing('whereNotIn');
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/Clausules/WithClausule.php:
--------------------------------------------------------------------------------
1 | with($this->arguments->data());
28 | }
29 |
30 | /**
31 | * Get a new instance of the clausule argument.
32 | *
33 | * @param array $values
34 | * @return \Restql\Arguments\WhereArgument
35 | */
36 | protected function createArgumentsInstance(array $values = []): Argument
37 | {
38 | return new WithArgument($this->executor->getModel(), $values);
39 | }
40 |
41 | /**
42 | * Throw a exception if can't build this clausule.
43 | *
44 | * @return void
45 | */
46 | protected function canBuild(): void
47 | {
48 | parent::throwIfMethodIsNotAllowed('where');
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/Console/AuthorizerMakeCommand.php:
--------------------------------------------------------------------------------
1 | call('vendor:publish', [
31 | '--tag' => 'restql-config'
32 | ]);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/Contracts/ArgumentContract.php:
--------------------------------------------------------------------------------
1 | model = $model;
26 | $this->values = $values;
27 | }
28 |
29 | /**
30 | * Get argument model.
31 | *
32 | * @return \Illuminate\Database\Eloquent\Model
33 | */
34 | public function getModel(): Model
35 | {
36 | return $this->model;
37 | }
38 |
39 | /**
40 | * Get the primary key for the model.
41 | *
42 | * @return string
43 | */
44 | public function getKeyName(): string
45 | {
46 | return $this->model->getKeyName();
47 | }
48 |
49 | /**
50 | * Get the hidden attributes for the model.
51 | *
52 | * @return array
53 | */
54 | public function getHidden(): array
55 | {
56 | return $this->model->getHidden();
57 | }
58 |
59 | /**
60 | * Determine if current model is using Restql\Traits\RestqlAttributes.
61 | *
62 | * @return bool
63 | */
64 | public function unsingRestqlTrait(): bool
65 | {
66 | return in_array(RestqlAttributes::class, class_uses($this->model));
67 | }
68 |
69 | /**
70 | * Exclude model hidden attributes.
71 | *
72 | * @return array
73 | */
74 | public function excludeHiddenAttributes(): array
75 | {
76 | $hidden = $this->getHidden();
77 |
78 | return array_filter(parent::values(), function ($value) use ($hidden) {
79 | return ! in_array($value, $hidden, true);
80 | });
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/Providers/RestqlServiceProvider.php:
--------------------------------------------------------------------------------
1 | mergeConfigFrom($this->configPath(), 'restql');
22 |
23 | if ($this->runningInConsole()) {
24 | $this->app->singleton(ConfigService::class, function ($app) {
25 | return new ConfigService($app['config']['restql']);
26 | });
27 | }
28 | }
29 |
30 | /**
31 | * Determine if the app is running in console and isn't running test.
32 | *
33 | * @return bool
34 | */
35 | protected function runningInConsole(): bool
36 | {
37 | return $this->app->runningInConsole() && ! $this->app->runningUnitTests();
38 | }
39 |
40 | /**
41 | * Determine if the app is running test.
42 | *
43 | * @return bool
44 | */
45 | protected function runningTests(): bool
46 | {
47 | return $this->app->runningInConsole() && $this->app->runningUnitTests();
48 | }
49 |
50 | /**
51 | * Set the config path.
52 | *
53 | * @return string
54 | */
55 | protected function configPath(): string
56 | {
57 | return __DIR__.'/../../config/restql.php';
58 | }
59 |
60 | /**
61 | * Register the config for publishing.
62 | *
63 | */
64 | public function boot(): void
65 | {
66 | if ($this->runningInConsole()) {
67 | /// Register the RestQL config.
68 | $this->publishes([
69 | $this->configPath() => config_path('restql.php')
70 | ], 'restql-config');
71 |
72 | /// Register the RestQL commands.
73 | $this->commands([
74 | ResolverMakeCommand::class,
75 | AuthorizerMakeCommand::class,
76 | ClausuleMakeCommand::class,
77 | SchemaRestqlCommand::class
78 | ]);
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/RequestParser.php:
--------------------------------------------------------------------------------
1 | request = $request;
29 | }
30 |
31 | /**
32 | * Static class instance.
33 | *
34 | * @param \Illuminate\Http\Request $request
35 | * @return \Illuminate\Support\Collection
36 | */
37 | public static function filter(Request $request): Collection
38 | {
39 | return (new RequestParser($request))->decode();
40 | }
41 |
42 | /**
43 | * Decode the parameter and return a collection with it.
44 | *
45 | * @return \Illuminate\Support\Collection
46 | */
47 | protected function decode(): Collection
48 | {
49 | $resources = $this->hasParam() ? $this->getQueryParamValue() : $this->request->all();
50 |
51 | return $this->getAllowedResources($resources);
52 | }
53 |
54 | /**
55 | * Determine if the parameter was sent in the request.
56 | *
57 | * @return boolean
58 | */
59 | protected function hasParam(): bool
60 | {
61 | $paramName = $this->getQueryParamName();
62 |
63 | return $this->request->has($paramName);
64 | }
65 |
66 | /**
67 | * Get the request param value.
68 | *
69 | * @return array
70 | */
71 | protected function getQueryParamValue(): array
72 | {
73 | $paramName = $this->getQueryParamName();
74 |
75 | $paramValue = $this->request->input($paramName);
76 |
77 | if (! is_array($paramValue)) {
78 | throw new Exception(sprintf('The value of param %s must be array', $paramName));
79 | }
80 |
81 | return $paramValue;
82 | }
83 |
84 | /**
85 | * Get the query param name defined in the configuration.
86 | *
87 | * @return string
88 | */
89 | protected function getQueryParamName(): string
90 | {
91 | return $this->getConfigService()->get('query_param', '');
92 | }
93 |
94 | /**
95 | * The accepted resources key names (models/resolvers).
96 | *
97 | * @return array
98 | */
99 | public function getAllowedResources(array $array): Collection
100 | {
101 | $keyNames = $this->getConfigService()->getFullSchemaKeyNames();
102 |
103 | return collect($array)->only($keyNames);
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/src/Resolver.php:
--------------------------------------------------------------------------------
1 | getModel($schema), $schema->collect());
25 |
26 | if (! $builder->getQuery()->limit) {
27 | // Set the "limit" value of the query by default.
28 | $builder->limit(15);
29 | }
30 |
31 | return $builder->get();
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/Resolvers/WhoamiResolver.php:
--------------------------------------------------------------------------------
1 | request = $request;
35 | }
36 |
37 | /**
38 | * Start data resolution from the eloquent models.
39 | *
40 | * @param \Illuminate\Http\Request $request
41 | * @return \Restql\Restql
42 | */
43 | public static function resolve(Request $request): Restql
44 | {
45 | return (new Restql($request))->build();
46 | }
47 |
48 | /**
49 | * Start data resolution from the eloquent models with array.
50 | *
51 | * @param array $array
52 | * @return \Restql\Restql
53 | */
54 | public static function resolveWithArr(array $array = []): Restql
55 | {
56 | return self::resolve(new Request($array));
57 | }
58 |
59 | /**
60 | * Dispatch the builder make method and save the response.
61 | *
62 | * @return \Restql\Restql
63 | */
64 | protected function build(): Restql
65 | {
66 | $filter = RequestParser::filter($this->request);
67 |
68 | $this->response = Builder::make($filter);
69 |
70 | return $this;
71 | }
72 |
73 | /**
74 | * Create a new Eloquent Collection instance by default.
75 | *
76 | * @param Closure $callback
77 | * @return Collection
78 | */
79 | public function get(Closure $callback = null): Collection
80 | {
81 | return $this->response->map(function (Collection $data) use ($callback) {
82 | /// You can pass a clousure with the eloquente query
83 | /// builder has argument. This allow you to add and
84 | /// resolve the data based on your logic.
85 | if ($callback instanceof Closure) {
86 | return $callback($data);
87 | }
88 |
89 | return $data;
90 | });
91 | }
92 |
93 | /**
94 | * Create an HTTP response that represents the object.
95 | *
96 | * @param \Illuminate\Http\Request $request
97 | * @return \Symfony\Component\HttpFoundation\Response
98 | */
99 | public function toResponse($request)
100 | {
101 | $data = $this->get();
102 |
103 | return new Response(compact('data'));
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/src/SchemaDefinition.php:
--------------------------------------------------------------------------------
1 | keyName = $keyName;
46 |
47 | $this->clausules = $clausules;
48 |
49 | $this->schema = $this->getConfigService()->getSchemaDefinitionOrFail($keyName);
50 | }
51 |
52 | /**
53 | * Get the schema definition key name.
54 | *
55 | * @return string
56 | */
57 | public function getKeyName(): string
58 | {
59 | return $this->keyName;
60 | }
61 |
62 | /**
63 | * Get schema definition class.
64 | *
65 | * @return string
66 | */
67 | public function getClass(): string
68 | {
69 | return $this->getAttributeOrFail('class');
70 | }
71 |
72 | /**
73 | * Get the schema definition clausules send by the client.
74 | *
75 | * @return array
76 | */
77 | public function getClausules(): array
78 | {
79 | return $this->clausules;
80 | }
81 |
82 | /**
83 | * Create a collection of clausules.
84 | *
85 | * @return \Illuminate\Support\Colection
86 | */
87 | public function collect(): Collection
88 | {
89 | $clausules = $this->clausules;
90 |
91 | return Collection::make($clausules);
92 | }
93 |
94 | /**
95 | * Return the schema definition middlewares.
96 | *
97 | * @return array
98 | */
99 | public function getMiddlewares(): array
100 | {
101 | return $this->schema['middlewares'] ?? [];
102 | }
103 |
104 | /**
105 | * Get the authorizer class name.
106 | *
107 | * @return string
108 | */
109 | public function getAuthorizer(): string
110 | {
111 | return $this->getAttribute('authorizer', Authorizer::class);
112 | }
113 |
114 | /**
115 | * Get the authorizer instance.
116 | *
117 | * @return \Restql\Authorizer
118 | */
119 | public function getAuthorizerInstance(): Authorizer
120 | {
121 | $authorizer = $this->getAuthorizer();
122 |
123 | return new $authorizer();
124 | }
125 |
126 | /**
127 | * Get schema definition type.
128 | *
129 | * @return string
130 | */
131 | public function getType(): string
132 | {
133 | $classname = $this->getClass();
134 |
135 | $classname = class_exists($classname) ? class_parents($classname) : [$classname];
136 |
137 | $parentClass = Arr::last($classname);
138 |
139 | return Str::lower(class_basename($parentClass));
140 | }
141 |
142 | /**
143 | * Determine if the schema definition is valid.
144 | *
145 | * @return bool
146 | */
147 | public function imValid(): bool
148 | {
149 | return class_exists($this->getClass()) && in_array($this->getType(), [
150 | 'model', 'resolver'
151 | ]);
152 | }
153 |
154 | /**
155 | * Create resolver instance.
156 | *
157 | * @return Restql\Resolver
158 | */
159 | protected function createResolverInstance(): Resolver
160 | {
161 | if ($this->getType() === 'model') {
162 | /// TODO: Document this.
163 | $classname = QueryBuilderResolver::class;
164 | } else {
165 | /// TODO: Document this
166 | $classname = $this->getClass();
167 | }
168 |
169 | return new $classname();
170 | }
171 |
172 | /**
173 | * Handle the resolver or model.
174 | *
175 | * @return \Illuminate\Support\Collection
176 | */
177 | public function handle(): Collection
178 | {
179 | return ($this->createResolverInstance())->handle($this);
180 | }
181 |
182 | /**
183 | * Get the schema attribute.
184 | *
185 | * @param string $attribute
186 | * @param string $default
187 | *
188 | * @return string
189 | */
190 | protected function getAttribute(string $attribute, string $default = ''): string
191 | {
192 | return $this->schema[$attribute] ?? $default;
193 | }
194 |
195 | /**
196 | * Get schema attribute definition or fail.
197 | *
198 | * @param string $attribute
199 | * @return string
200 | */
201 | protected function getAttributeOrFail(string $attribute): string
202 | {
203 | return $this->getAttribute($attribute) ?? new InvalidSchemaDefinitionException(
204 | $this->keyName,
205 | sprintf('The attribute [%s] is not defined.', $attribute)
206 | );
207 | }
208 | }
209 |
--------------------------------------------------------------------------------
/src/Services/ConfigService.php:
--------------------------------------------------------------------------------
1 | config = Collection::make($config);
28 | }
29 |
30 | /**
31 | * Get an item from the collection by key.
32 | *
33 | * @param string $key
34 | * @param mixed $default
35 | * @return mixed
36 | */
37 | public function get(string $key, $default = null)
38 | {
39 | return $this->config->get($key, $default);
40 | }
41 |
42 | /**
43 | * Get schema definition.
44 | *
45 | * @return array
46 | */
47 | public function getSchema(): array
48 | {
49 | return $this->get('schema', []);
50 | }
51 |
52 | /**
53 | * Get allowed resolvers.
54 | *
55 | * @return array
56 | */
57 | public function getResolvers(): array
58 | {
59 | return $this->get('resolvers', []);
60 | }
61 |
62 | /**
63 | * Get the allowed clausules.
64 | *
65 | * @return array
66 | */
67 | public function getClausules(): array
68 | {
69 | return $this->get('clausules', []);
70 | }
71 |
72 | /**
73 | * Determine if a key or className is registered in the config.
74 | *
75 | * @param string $keyOrClassName
76 | * @return boolean
77 | */
78 | public function hasClausule(string $keyOrClassName): bool
79 | {
80 | $clausules = $this->getClausules();
81 |
82 | return in_array($keyOrClassName, $clausules) || array_key_exists($keyOrClassName, $clausules);
83 | }
84 |
85 | /**
86 | * Create a instance of Clausule based on the key name.
87 | *
88 | * @param string $keyOrClassName
89 | * @param array $values
90 | * @return \Restql\Clausule
91 | */
92 | public function createClasuleInstance(ClausuleExecutor $executor, string $keyName, array $values = []): Clausule
93 | {
94 | $classname = $this->getClausules()[$keyName];
95 |
96 | return new $classname($executor, $values);
97 | }
98 |
99 | /**
100 | * Merge the schema and the resolver definition.
101 | *
102 | * @return array
103 | */
104 | public function getFullSchema(): array
105 | {
106 | return array_merge($this->getResolvers(), $this->getSchema());
107 | }
108 |
109 | /**
110 | * Determine if the key exists in full schema definition.
111 | *
112 | * @param string $keyName
113 | * @return bool
114 | */
115 | public function inSchema(string $keyName): bool
116 | {
117 | return in_array($keyName, $this->getFullSchemaKeyNames(), true);
118 | }
119 |
120 | /**
121 | * Get schema definition or fail.
122 | *
123 | * @param string $keyName
124 | * @return array
125 | */
126 | public function getSchemaDefinitionOrFail(string $keyName): array
127 | {
128 | if (! $this->inSchema($keyName)) {
129 | throw new InvalidSchemaDefinitionException(
130 | $keyName,
131 | sprintf('The key name [%s] is not defined.', $keyName)
132 | );
133 | }
134 |
135 | return $this->getSchemaDefinition($keyName);
136 | }
137 |
138 | /**
139 | * Get schema definition.
140 | *
141 | * @param string $keyName
142 | * @return array
143 | */
144 | public function getSchemaDefinition(string $keyName): array
145 | {
146 | return $this->getFullSchema()[$keyName];
147 | }
148 |
149 | /**
150 | * Get the schema keys names.
151 | *
152 | * @return array
153 | */
154 | public function getSchemaKeys(): array
155 | {
156 | return array_keys($this->getSchema());
157 | }
158 |
159 | /**
160 | * Get the resolvers keys names.
161 | *
162 | * @return array
163 | */
164 | public function getResolversKey(): array
165 | {
166 | return array_keys($this->getResolvers());
167 | }
168 |
169 | /**
170 | * Get the allowed key names merging the schema keys into resolvers key names.
171 | *
172 | * @return array
173 | */
174 | public function getFullSchemaKeyNames(): array
175 | {
176 | return array_keys($this->getFullSchema());
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/src/Support/ReflectionSupport.php:
--------------------------------------------------------------------------------
1 | getMethod($method)->getReturnType();
19 |
20 | return $type instanceof ReflectionType ? $type->getName() : '';
21 | }
22 |
23 | /**
24 | * Check if the method return type is equal to $type passed as argument.
25 | *
26 | * @param string $method
27 | * @param string $type
28 | * @return bool
29 | */
30 | public function methodIs(string $method, string $type): bool
31 | {
32 | return $this->getMethodReturnType($method) === $type;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/Traits/HasConfigService.php:
--------------------------------------------------------------------------------
1 | getClass();
19 |
20 | return new $classname();
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/Traits/RestqlAttributes.php:
--------------------------------------------------------------------------------
1 | getFillable();
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/stubs/authorizer.stub:
--------------------------------------------------------------------------------
1 |