├── .codeclimate.yml
├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── codeception.yml
├── composer.json
├── jetrouter.php
├── readme.txt
├── src
├── DynamicRouteParser.php
├── Exception
│ ├── InvalidHttpMethodException.php
│ ├── InvalidNamespaceException.php
│ ├── InvalidOutputFormatException.php
│ ├── InvalidRouteException.php
│ ├── InvalidRouteHandlerException.php
│ └── MissingRouteException.php
├── RequestDispatcher.php
├── ReverseRouter.php
├── RouteParser.php
├── RouteStore.php
├── Router.php
└── StaticRouteParser.php
└── tests
├── _bootstrap.php
├── _data
└── dump.sql
├── _support
├── AcceptanceTester.php
├── FunctionalTester.php
├── Helper
│ ├── Acceptance.php
│ ├── Functional.php
│ └── Unit.php
├── UnitTester.php
└── _generated
│ ├── AcceptanceTesterActions.php
│ ├── FunctionalTesterActions.php
│ └── UnitTesterActions.php
├── acceptance.suite.yml
├── acceptance
└── _bootstrap.php
├── functional.suite.yml
├── functional
└── _bootstrap.php
├── unit.suite.yml
└── unit
├── RouterTest.php
└── _bootstrap.php
/.codeclimate.yml:
--------------------------------------------------------------------------------
1 | ---
2 | engines:
3 | duplication:
4 | enabled: true
5 | config:
6 | languages:
7 | - ruby
8 | - javascript
9 | - python
10 | - php
11 | fixme:
12 | enabled: true
13 | phpmd:
14 | enabled: true
15 | Controversial/Superglobals:
16 | enabled: false
17 | exclude_fingerprints:
18 | - 04184a89cc95d4de27194c1bfae58468
19 | - 113dfe251ce1988d4de94f4141f41267
20 | - c994a1b3b901807afd4128bef6310a69
21 | - d3f4156691d2262bda1a34326a6a2786
22 | - 481ad10f1f811b709de0c99951196766
23 | - 672a2e1ab76ccbf5bdc4fd80e17c21e1
24 | ratings:
25 | paths:
26 | - "**.inc"
27 | - "**.js"
28 | - "**.jsx"
29 | - "**.module"
30 | - "**.php"
31 | - "**.py"
32 | - "**.rb"
33 | exclude_paths:
34 | - tests/
35 | - vendor/
36 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | /vendor
3 | /tests/_output/*
4 | composer.lock
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | dist: trusty
2 | language: php
3 | php:
4 | - 7.0
5 | before_script:
6 | - composer self-update
7 | - composer install --prefer-source --no-interaction
8 | script: vendor/bin/codecept run
9 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # JetRouter - WordPress Routing, Fast & Easy
2 | [](https://travis-ci.org/sformisano/jetrouter)
3 | [](https://codeclimate.com/github/sformisano/jetrouter)
4 |
5 | This WordPress plugin adds a regular expression based router on top of the WordPress standard routing system. Any route declared through this router will take priority over standard WordPress URLs.
6 |
7 | - [Installation](#installation)
8 | - [Usage](#usage)
9 | - [Initialization & Configuration](#initialization--configuration)
10 | - [Configuration properties](#available-router-configuration-properties)
11 | - [Adding Routes](#adding-routes)
12 | - [The basics](#the-basics)
13 | - [Dynamic routes](#dynamic-routes)
14 | - [Parameters regular expressions](#parameters-regular-expressions)
15 | - [Optional parameters](#optional-parameters)
16 | - [Reverse Routing](#reverse-routing)
17 | - [Dynamic routes reverse routing](#dynamic-routes-reverse-routing)
18 | - [Handler's respond_to Feature](#handlers-respond_to-feature)
19 | - [Why I built it](#why-i-built-the-jetrouter)
20 | - [Credits](#credits)
21 |
22 |
23 | ## Installation
24 |
25 | #### Download zip
26 |
27 | ##### Download via WordPress plugin page
28 |
29 | You can visit the [WordPress plugin page](https://wordpress.org/plugins/jetrouter/) and download the latest plugin version there.
30 |
31 | ##### Download via GitHub repo release page
32 |
33 | You can also grab the latest release from this repository's [releases page](https://github.com/sformisano/jetrouter/releases).
34 |
35 | #### Composer
36 |
37 | If your setup uses [Composer](https://getcomposer.org/) for proper dependency management (check out the awesome [Bedrock project](https://roots.io/bedrock/) if you are interested in running WordPress as a 12 factor app) installing the JetRouter is quite easy.
38 |
39 | ##### Composer via WordPress Packagist (simpler & better)
40 |
41 | [WordPress Packagist](https://wpackagist.org/) is a site that scans the WordPress Subversion repository every hour for plugins and themes and then mirrors them as Composer repositories.
42 |
43 | Search for "jetrouter" (here's the [search results for that](https://wpackagist.org/search?q=jetrouter) ), click on the latest version in the "Versions" column of the record and you will be given the code to paste in your `composer.json` file in the `require` property.
44 |
45 | It should look something like this:
46 |
47 | ```
48 | "wpackagist-plugin/jetrouter": "0.1.2.1"
49 | ```
50 |
51 | **Please note:** I have had no time to verify this, but even without using the [Bedrock](https://roots.io/bedrock/) WordPress boilerplate, wpackagist packages should automatically install in the plugins directory (which is what you would want) rather than the default composer vendor directory. If that is not the case, reference the *Composer via GitHub releases* section below to learn how to tell composer where to install your WordPress plugins.
52 |
53 | ##### Composer via GitHub releases
54 |
55 | Add this package to the "repositories" property of your composer json definition (make sure the release version is the one you want to install):
56 |
57 | ```json
58 | {
59 | "repositories": [
60 | {
61 | "type": "package",
62 | "package": {
63 | "name": "jetrouter",
64 | "type": "wordpress-plugin",
65 | "version": "0.1.2.1",
66 | "dist": {
67 | "type": "zip",
68 | "url": "https://github.com/sformisano/jetrouter/releases/download/v0.1.2/jetrouter-v0.1.2.1.zip",
69 | "reference": "v0.1.2.1"
70 | },
71 | "autoload": {
72 | "classmap": ["."]
73 | }
74 | }
75 | }
76 | ]
77 | }
78 | ```
79 |
80 | Once that's done, add the JetRouter in the composer require property (the version has to match the package version):
81 |
82 | ```json
83 | {
84 | "require":{
85 | "jetrouter": "0.1.2.1"
86 | }
87 | }
88 | ```
89 |
90 | Finally, make sure to specify the correct path for the "wordpress-plugin" type we assigned
91 | to the JetRouter package in the definition above (note: if you are using
92 | [Bedrock](https://roots.io/bedrock/) this is already taken care of).
93 |
94 | ```json
95 | {
96 | "extra": {
97 | "installer-paths": {
98 | "path/to/your/wordpress/plugins-directory/{$name}/": ["type:wordpress-plugin"],
99 | }
100 | }
101 | }
102 | ```
103 | Run `composer update` from your composer directory and you're good to go!
104 |
105 | ## Usage
106 |
107 | ### Initialization & Configuration
108 | In your theme’s `functions.php` file or somewhere in your plugin:
109 |
110 | ```php
111 | // Import the JetRouter
112 | use JetRouter\Router;
113 |
114 | // Router config
115 | $config = [];
116 |
117 | // Create the router instance
118 | $r = Router::create($config);
119 | ```
120 |
121 | #### Available router configuration properties:
122 |
123 | * `namespace`: if defined, the namespace prefixes all routes, e.g. if you set the namespace to “my-api” and then define a route as “comments/published”, the actual endpoint will be “/my-api/comments/published/“.
124 | * `outputFormat`: determines the routes handlers output format. Available values: `auto`, `json`, `html`.
125 |
126 | The router automatically hooks itself to WordPress, so once you’ve created the router instance with the configuration that suits your needs, all that is left to do is adding routes. After that, the router is ready to dispatch requests.
127 |
128 | ##### Pro tip on the namespace
129 |
130 | If you use the JetRouter to build a json/data api, or if you simply don’t mind having a namespace before your urls, having one will speed up standard WordPress requests, especially if you have many dynamic routes.
131 |
132 | This is because, if the router has a namespace, but the http request’s path does not begin with that namespace (like it would be the case with all WordPress urls), the router won’t even try to dispatch the request.
133 |
134 | Without a namespace, on the other hand, the router will try to dispatch all requests, building the dynamic routes array every time. *(Note: caching the generated dynamic routes is on my todo list.)*
135 |
136 | ### Adding Routes
137 |
138 | #### The basics
139 |
140 | The basic method to add routes is `addMethod`. Example:
141 |
142 | ```php
143 | $r->addRoute('GET', 'some/resource/path', 'the_route_name', function(){
144 | // the callback fired when a request matches this route
145 | });
146 | ```
147 |
148 | The `addRoute` method has aliases for each http method (get, post, put, patch, delete, head, options). Example:
149 |
150 | ```php
151 | $r->get(‘users/new’, ‘route_name’, function(){
152 | // new user form view
153 | });
154 |
155 | $r->post('users', 'create_user', function(){
156 | // create user in database
157 | });
158 | ```
159 |
160 | #### Dynamic routes
161 |
162 | Use curly braces to outline parameters, then declare them as arguments of the callback function and the router will take care of everything else. Example:
163 |
164 | ```php
165 | $r->get('users/{username}', 'get_user_by_username', function($username){
166 | echo "Welcome back, $username!";
167 | });
168 |
169 | $->get('schools/{school}/students/{year}', 'get_school_students_by_year', function($school, $year){
170 | echo "Welcome, $school students of $year!";
171 | });
172 | ```
173 |
174 | #### Parameters regular expressions
175 | By default, all parameters are matched against a very permissive regular expression:
176 |
177 | ```php
178 | /**
179 | * One or more characters that is not a '/'
180 | */
181 | const DEFAULT_PARAM_VALUE_REGEX = '[^/]+';
182 | ```
183 |
184 | You can use your own regular expressions by adding a colon after the parameter name and the regex right after it. Example:
185 |
186 | ```php
187 | $r->get('schools/{school}/students/{year:[0-9]+}', 'get_school_students_by_year', function($school, $year){
188 | // If $year is not an integer an exception will be thrown
189 | });
190 | ```
191 |
192 | You can also use one of these regex shortcuts for convenience:
193 |
194 | ```php
195 | private $regexShortcuts = [
196 | ':i}' => ':[0-9]+}', // integer
197 | ':a}' => ':[a-zA-Z0-9]+}', // alphanumeric
198 | ':s}' => ':[a-zA-Z0-9_\-\.]+}' // alphanumeric, "_", "-" and ".""
199 | ];
200 | ```
201 |
202 | If, for example, we wanted to write the same `get_school_students_by_year` route by using the `:i` shortcut, this is how we would do it:
203 |
204 | ```php
205 | $r->get('schools/{school}/students/{year:i}', 'get_school_students_by_year', function($school, $year){
206 | // If $year is not an integer an exception will be thrown
207 | });
208 | ```
209 |
210 | #### Optional parameters
211 |
212 | You can make a parameter optional by adding a question mark after the closing curly brace. Example:
213 |
214 | ```php
215 | $r->get('schools/{school}/students/{year}?’, 'get_school_students_by_year', function($school, $year){
216 | // $year can be empty!
217 | });
218 | ```
219 |
220 | You can make all parameters optionals, even when they are not the last segment in a route. Example:
221 |
222 | ```php
223 | $r->get('files/{filter_name}?/{filter_value}?/latest', 'get_latest_files', function($filter_name, $filter_value){
224 | // get files and work with filters if they have a value
225 | });
226 | ```
227 |
228 | All the example requests below would match the route defined above:
229 |
230 | ```php
231 | '/files/latest'
232 | '/files/type/pdf/latest'
233 | '/files/author/sformisano/latest'
234 | ```
235 |
236 | This is not necessarily the best use of optional parameters. The examples here are just to show that, if you have a valid use case, the JetRouter will allow you to setup your routes this way.
237 |
238 | ### Reverse Routing
239 |
240 | Reverse routing is done through the same router object for simplicity’s sake.
241 |
242 | Given this simple example route:
243 |
244 | ```php
245 | $r->addRoute('GET', 'posts/popular', 'popular_posts', function(){});
246 | ```
247 |
248 | To print out the full path you use the `thePath` method:
249 |
250 | ```php
251 | $r->thePath('popular_posts'); // prints /posts/popular/
252 | ```
253 |
254 | You can also get the value returned, rather than printed out, by using the `getThePath` method (trying to follow some WordPress conventions with this):
255 |
256 | ```php
257 | $r->getThePath('popular_posts'); // returns /posts/popular/
258 | ```
259 |
260 | #### Dynamic routes reverse routing
261 |
262 | Dynamic routes work in the exact same way, you just pass the values of the parameters after the route name in the same order they are defined in when you created the route.
263 |
264 | For example, given this route:
265 |
266 | ```php
267 | $r->get('schools/{school}/students/{year}?’, 'get_school_students_by_year', function($school, $year){
268 | });
269 | ```
270 |
271 | This is how you would print out a full path to this route:
272 |
273 | ```php
274 | $r->thePath('get_school_students_by_year', 'caltech', 2005); // prints /schools/caltech/students/2005/
275 | ```
276 |
277 | As the last parameter is optional you can simply omit it:
278 |
279 | ```php
280 | $r->thePath('get_school_students_by_year', 'mit'); // prints /schools/mit/students/
281 | ```
282 |
283 | If the optional parameter you need to omit is not the last parameter, you can simply pass `null` as a value and it will be ignored. Example:
284 |
285 | ```php
286 | $r->get('{school}?/students/{year}’, 'get_students', function($school, $year){
287 | });
288 |
289 | $r->thePath('get_students', null, 1999); // prints /students/1999/
290 | ```
291 |
292 | I prefer this approach to the more common associative array for arguments as it makes everything simpler (less typing in the vast majority of scenarios) and more explicit (a missing optional parameter is still defined as null, so there’s a 1:1 match between formal parameters and arguments).
293 |
294 | ### Handler's respond_to Feature
295 |
296 | If you ever played around with Ruby on Rails, you're probably familiar with the [respond_to and respond_with blocks](http://www.davidwparker.com/2010/03/09/api-in-rails-respond-to-and-respond-with/). This respond_to feature is a basic, simplistic imitation of that clever way to handle different request types with different behaviours.
297 |
298 | If you never tried out Rails, let me make this simple with an example:
299 |
300 | You created a public signup form that posts to a `create_user` endpoint created with the JetRouter. You definitely want that form to work with ajax, but you're one of those few developers left who still cares about graceful degradation, so you don't just want to set the `outputFormat` config parameter to `json` and do a `return $data;` of sorts. You need to be able to receive json data with ajax requests, while doing something else (redirects, loading views in error mode etc.) for standard, synchronous requests.
301 |
302 | Technically, you *could* manually check for `$_SERVER['HTTP_X_REQUESTED_WITH']` and write some conditional code that works with that, but who wants to do that kind of manual labour for every single endpoint?
303 |
304 | JetRouter's respond_to to the rescue! All you have to do is leave the `outputFormat` config parameter to `auto` and have your route handler return an array following this format:
305 |
306 | ```php
307 |
308 | // endpoint doing stuff up here
309 |
310 | return [ 'respond_to' => [
311 | 'json' => $output // this is whatever came out of this endpoint, to be returned as json!,
312 | 'html' => function(){
313 | // this callback will run if this the route handler is dispatching a standard, synchronous request
314 | // do something here, then maybe redirect with wp_redirect or whatever else!
315 | }
316 | ] ];
317 | ```
318 |
319 | **Pro tip:** appending ?json to a request path will force the json output.
320 |
321 | ## Why I built the JetRouter
322 |
323 | * I wanted something fast, easy to setup and with a minimal API. The JetRouter is setup with one line of code (`$r = Router::create();`) and all functionality is readily available through that object.
324 |
325 | * I needed extra features not offered by any other small footprint php router I am familiar with, including the ones I credited below.
326 |
327 | * The routers I am aware of, even the ones I credited below, are conceived to be used as the core routing system of a website/webapp. This does not make them the best fit for the use case of a WordPress extra routing layer, e.g. they will throw an exception if a route is not found or if there’s a path match but the http method of the request is different. Because this router is an extra layer on top of WordPress, it needs to fail silently in most of these scenarios and give control back to WordPress. WordPress can then dispatch those requests matching, return a 404 or do whatever else it’s supposed to do.
328 |
329 | * Finally, building this looked like a fun way to revisit PCRE, which are something I have not worked with in many years.
330 |
331 | ## Credits
332 |
333 | * This router implements [Nikita Popov](https://github.com/nikic)’s group position based, non-chunked approach to regex matching for lightning fast routing. Learn more about it by reading [this great post](http://nikic.github.io/2014/02/18/Fast-request-routing-using-regular-expressions.html) by Nikita himself.
334 |
335 | * [Joe Green](https://github.com/mrjgreen) and his [phroute](https://github.com/mrjgreen/phroute) project (also loosely based on Nikita’s work) are to be thanked for:
336 | * the regex used to capture dynamic routes parameters
337 | * the regex shortcuts (a simple yet very elegant idea)
338 | * the basics of the optional parameters and reverse routing implementation
339 |
340 | Go check both these authors and their projects, they are awesome.
341 |
--------------------------------------------------------------------------------
/codeception.yml:
--------------------------------------------------------------------------------
1 | actor: Tester
2 | paths:
3 | tests: tests
4 | log: tests/_output
5 | data: tests/_data
6 | support: tests/_support
7 | envs: tests/_envs
8 | settings:
9 | bootstrap: _bootstrap.php
10 | colors: true
11 | memory_limit: 1024M
12 | extensions:
13 | enabled:
14 | - Codeception\Extension\RunFailed
15 | modules:
16 | config:
17 | Db:
18 | dsn: ''
19 | user: ''
20 | password: ''
21 | dump: tests/_data/dump.sql
22 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "sformisano/jetrouter",
3 | "description": "An intuitive WordPress router.",
4 | "type": "library",
5 | "authors": [
6 | {
7 | "name": "Salvatore Formisano",
8 | "email": "hello@salvatoreformisano.com"
9 | }
10 | ],
11 | "require-dev": {
12 | "codeception/codeception": "*",
13 | "10up/wp_mock": "dev-master"
14 | },
15 | "autoload": {
16 | "psr-4": {
17 | "JetRouter\\": "src"
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/jetrouter.php:
--------------------------------------------------------------------------------
1 | comments/param/popular
72 | *
73 | * @param string $path The dynamic route path
74 | */
75 | private static function validateStaticPathParts($path)
76 | {
77 | StaticRouteParser::validateStaticPath(
78 | preg_replace(
79 | self::LOOSE_PARAMS_REGEX, 'param',
80 | str_replace('}?', '}', $path) // accounts for optional parameters
81 | )
82 | );
83 | }
84 |
85 | /**
86 | * Captures data about the dynamic route path parameter
87 | *
88 | * Uses a regex to capture params data (name, position in path, regex)
89 | *
90 | * @param string $path The dynamic route path
91 | *
92 | * @return array The array with the params data
93 | */
94 | private static function captureParamsData($path)
95 | {
96 | preg_match_all(
97 | self::CAPTURE_PARAMS_REGEX,
98 | $path,
99 | $paramsData,
100 | PREG_OFFSET_CAPTURE | PREG_SET_ORDER
101 | );
102 |
103 | return $paramsData;
104 | }
105 |
106 | /**
107 | * Validates the params in the dynamic route path parameter
108 | *
109 | * Compares the number of {} pairs found with the loose params regex, with the
110 | * number of parameters captured with the full capture params regex. If there
111 | * is a delta then one of the {} pairs is wrapping an invalid param definition
112 | * that the capture params regex failed to parse correctly.
113 | *
114 | * @param integer $looseParamsN The number of loose params
115 | * @param integer $paramsDataN The number of captured params
116 | * @param string $path The dynamic route path
117 | *
118 | * @throws Exception\InvalidRouteException If there are more loose params than params data items
119 | */
120 | private static function validateParamsN($looseParamsN, $paramsDataN, $path)
121 | {
122 | $invalidParamsN = abs( $looseParamsN - $paramsDataN );
123 |
124 | if( $invalidParamsN ){
125 | throw new Exception\InvalidRouteException(
126 | sprintf(
127 | _n(
128 | '%s invalid parameter',
129 | '%s invalid parameters',
130 | $invalidParamsN
131 | ),
132 | $invalidParamsN
133 | ) . " found in '$path' route.",
134 | 1
135 | );
136 | }
137 | }
138 |
139 | /**
140 | * Validates a regex
141 | *
142 | * Simply tests a regex with @preg_match (@ to avoid warnings) against null.
143 | * If === false then the regex is broken.
144 | *
145 | * @param string $regex The regular expression
146 | *
147 | * @throws Exception\InvalidRouteException If the regex is invalid
148 | */
149 | private static function validateRegex($regex)
150 | {
151 | if( @preg_match($regex, null) === false ){
152 | throw new Exception\InvalidRouteException("'$regex' is not a valid regex.");
153 | }
154 | }
155 |
156 |
157 | /*** PROPERTIES ***/
158 |
159 | private $paramsNames = [];
160 | private $regex;
161 | private $regexParts = [];
162 | private $regexShortcuts = [
163 | ':i}' => ':[0-9]+}', // integer
164 | ':a}' => ':[a-zA-Z0-9]+}', // alphanumeric
165 | ':s}' => ':[a-zA-Z0-9_\-\.]+}' // alphanumeric, "_", "-" and ".""
166 | ];
167 | private $segments = [];
168 | private $segmentsCounter = 0;
169 | private $regexPartsCounter = 0;
170 |
171 |
172 | /*** PUBLIC METHODS ***/
173 |
174 | /**
175 | * Gets the regular expression.
176 | *
177 | * @return string The full dynamic route regex.
178 | */
179 | public function getRegex()
180 | {
181 | return $this->regex;
182 | }
183 |
184 | /**
185 | * Gets the dynamic route params names.
186 | *
187 | * @return array The dynamic route params names.
188 | */
189 | public function getParamsNames()
190 | {
191 | return $this->paramsNames;
192 | }
193 |
194 | /**
195 | * Gets the segments.
196 | *
197 | * @return array The dynamic route segments.
198 | */
199 | public function getSegments()
200 | {
201 | return $this->segments;
202 | }
203 |
204 |
205 | /*** PRIVATE METHODS ***/
206 |
207 | /**
208 | * Parses the dynamic route path param and collects params data.
209 | *
210 | * @param string $path The dynamic route path
211 | */
212 | protected function setPath($path)
213 | {
214 | // replace regex shortcuts with regex
215 | $this->path = $path = strtr($path, $this->regexShortcuts);
216 |
217 | self::validateStaticPathParts($path);
218 | self::validateParamsCurlyBraces($path);
219 |
220 | $paramsData = self::captureParamsData($path);
221 | $looseParamsN = preg_match_all(self::LOOSE_PARAMS_REGEX, $path);
222 |
223 | self::validateParamsN($looseParamsN, count($paramsData), $path);
224 |
225 | $this->parseParamsData($paramsData);
226 | }
227 |
228 | /**
229 | * Parses the dynamic route params data
230 | *
231 | * Uses the params data obtained from the dynamic route path to build a
232 | * full route regex, which will be used to match requests to routes, and a
233 | * route path segments array, which will be used for reverse routing.
234 | *
235 | * @param array $paramsData The dynamic route params data
236 | */
237 | private function parseParamsData($paramsData)
238 | {
239 | $this->setParamsNames($paramsData);
240 |
241 | $prevParamEndPos = 0;
242 |
243 | foreach($paramsData as $paramData){
244 | $param = $paramData[0][0]; // e.g. "{foo:[0-9]+}" (regex shortcut translated into regex)
245 | $paramStartPosInRoute = $paramData[0][1]; // strpos of {foobar} in route string
246 | $paramName = $paramData[1][0]; // e.g. "foobar"
247 |
248 | // e.g. "[0-9]+"
249 | $paramRegex = (isset($paramData[2]) ? $paramData[2][0] : self::DEFAULT_PARAM_VALUE_REGEX);
250 |
251 | $optional = substr($param, -1) === '?'; // e.g. "test/{foo}?"
252 |
253 | // Find static segments between current and previous param in route
254 | $this->maybeAddStaticSegments(
255 | $prevParamEndPos,
256 | $paramStartPosInRoute - $prevParamEndPos
257 | );
258 |
259 | $this->addParamSegment($paramName, $paramRegex, $optional);
260 |
261 | /*
262 | * These are imploded into the full route regex (i.e. used to match route
263 | * to request path), whereas $paramRegex is used to match the single param
264 | */
265 | $this->addRoutePathRegexPart($paramRegex, $optional);
266 |
267 | $prevParamEndPos = $paramStartPosInRoute + strlen($param);
268 |
269 | /*
270 | * Note on why the segments and regex parts require separate counters.
271 | *
272 | * The regex parts array is used to build the full regex path used to match
273 | * requests to routes, whereas the segments array is used for reverse routing.
274 | *
275 | * In the full route regex, optional parameters replace the previous "/"
276 | * symbol and include it in the optional param regex, so if the parameter
277 | * does not exist there won't be an extra unneeded "/" symbol in the regex.
278 | *
279 | * None of this happens for the segments array, which means that for every
280 | * optional parameter added to the dynamic route path the regex parts array
281 | * will have one less element than the segments array.
282 | *
283 | * Example: the route "/users/{username}/comments/{filter}?"
284 | * creates a segments array with 7 elements:
285 | * ["users", "/", username param data array, "/", "comments", "/", "filter param data array"]
286 | *
287 | * That same route will create a regex parts array with one less element,
288 | * because the "/" symbol before the optional filter parameter will be
289 | * removed as separate array element and added in the filter param regex
290 | */
291 | $this->segmentsCounter++;
292 | $this->regexPartsCounter++;
293 | }
294 |
295 | // Find any static segments after the final param
296 | $this->maybeAddStaticSegments(
297 | $prevParamEndPos,
298 | strlen($this->path) - $prevParamEndPos
299 | );
300 |
301 | $this->regex = implode('', $this->regexParts);
302 | }
303 |
304 | /**
305 | * Sets the params names array as a property of the object.
306 | *
307 | * @param array $paramsData The dynamice route params data
308 | *
309 | * @throws Exception\InvalidRouteException If the same param name is used more than once
310 | */
311 | private function setParamsNames($paramsData)
312 | {
313 | foreach($paramsData as $paramData){
314 | $paramName = $paramData[1][0];
315 |
316 | if( array_key_exists($paramName, $this->paramsNames) ){
317 | throw new Exception\InvalidRouteException(
318 | "Parameter '$paramName' found more than once in route.",
319 | 1
320 | );
321 | }
322 |
323 | $this->paramsNames[$paramName] = null;
324 | }
325 | }
326 |
327 | /**
328 | * Adds a param segment to the segments array property of the object.
329 | *
330 | * @param string $paramName The param name
331 | * @param string $paramRegex The param regex the argument will have to match
332 | * @param boolean $optional Is the param optional?
333 | */
334 | private function addParamSegment($paramName, $paramRegex, $optional)
335 | {
336 | $this->segments[$this->segmentsCounter] = [
337 | 'paramName' => $paramName,
338 | 'paramRegex' => '~^(' . $paramRegex . ')$~',
339 | 'optional' => $optional
340 | ];
341 | }
342 |
343 | /**
344 | * Adds the param regex to the regexParts property of the object.
345 | *
346 | * If the param is optional and there's a previous "/" symbol before this new
347 | * param regex, this new param regex will replace that "/" symbol in the array
348 | * (the regex array index counter, i.e. the regexPartsCounter object property,
349 | * is reduced by 1 so this param regex will be placed at the array index where
350 | * the previous "/" symbol was) and the param regex will be changed
351 | * to incorporate the "/" symbol. This is to avoid having an extra "/" symbol
352 | * if the argument for this optional parameter does not exist (either in
353 | * request matching or reverse routing).
354 | *
355 | * @param string $paramRegex The param regex the argument will have to match
356 | * @param boolean $optional Is the param optional?
357 | */
358 | private function addRoutePathRegexPart($paramRegex, $optional)
359 | {
360 | $routeRegexPart = '(' . $paramRegex . ')';
361 | self::validateRegex($routeRegexPart);
362 |
363 | if($optional){
364 | $prevSegmentPos = $this->regexPartsCounter - 1;
365 |
366 | if(
367 | isset($this->regexParts[$prevSegmentPos]) &&
368 | $this->regexParts[$prevSegmentPos] === '/'
369 | ){
370 | $this->regexPartsCounter--;
371 | $routeRegexPart = '(?:/' . $routeRegexPart . ')';
372 | }
373 |
374 | $routeRegexPart .= '?';
375 | }
376 |
377 | $this->regexParts[$this->regexPartsCounter] = $routeRegexPart;
378 | }
379 |
380 | /**
381 | * Adds static segments in the specified dynamic route path substr if there's any
382 | *
383 | * Looks for any static segments in the dynamic route path substring specified
384 | * with the $start and $end params. If it finds any it adds them to the segments
385 | * and the regexParts properties of the object.
386 | *
387 | * @param integer $start The start position of the dynamic route path substring
388 | * @param integer $end The end position of the dynamic route path substring
389 | */
390 | private function maybeAddStaticSegments($start, $end)
391 | {
392 | $staticSegments = preg_split(
393 | '~(/)~u',
394 | substr($this->path, $start, $end),
395 | 0,
396 | PREG_SPLIT_DELIM_CAPTURE
397 | );
398 |
399 | foreach($staticSegments as $segment){
400 | if($segment){
401 | // static, i.e. just the string
402 | $this->segments[$this->segmentsCounter] = $segment;
403 |
404 | $this->regexParts[] = preg_quote($segment, '~');
405 |
406 | $this->segmentsCounter++;
407 | $this->regexPartsCounter++;
408 | }
409 | }
410 | }
411 |
412 | }
--------------------------------------------------------------------------------
/src/Exception/InvalidHttpMethodException.php:
--------------------------------------------------------------------------------
1 | $output The output
43 | *
44 | * @return boolean True if respond to, False otherwise.
45 | */
46 | private static function isRespondTo($output)
47 | {
48 | return (
49 | is_array($output) &&
50 | array_key_exists('respond_to', $output)
51 | );
52 | }
53 |
54 |
55 | /*** PROPERTIES ***/
56 |
57 | private $outputFormat;
58 |
59 |
60 | /*** PUBLIC METHODS ***/
61 |
62 | /**
63 | * Initializes the object and sets the output format
64 | *
65 | * @param string $outputFormat The output format
66 | */
67 | public function __construct($outputFormat)
68 | {
69 | $this->outputFormat = $this->parseOutputFormat($outputFormat);
70 | }
71 |
72 | /**
73 | * Dispatches the HTTP request or returns a status code if no routes matches
74 | *
75 | * Tries to find a route in the route store by http method and request path.
76 | * Returns a NOT_DISPATCHED status code if no route matches.
77 | *
78 | * If a match is found, the route handler is called and the appropriate output
79 | * is printed/returned depending on request type and config.
80 | *
81 | * @param RouteStore $routeStore The route store object
82 | * @param string $requestHttpMethod The request http method
83 | * @param string $requestPath The request path
84 | *
85 | * @return integer|mixed|string|mixed Returns the RouteStore::NOT_FOUND status code (int), mixed if it prints json or returning $output, and finally if $output is a callback returns its returned value
86 | */
87 | public function dispatch($routeStore, $requestHttpMethod, $requestPath)
88 | {
89 | $route = $routeStore->findRouteByRequestMethodAndPath($requestHttpMethod, $requestPath);
90 |
91 | if($route === RouteStore::NOT_FOUND){
92 | // route does not exist, fallback to WordPress routing
93 | return self::NOT_DISPATCHED;
94 | }
95 |
96 | $output = $this->parseHandlerOutput(
97 | call_user_func_array($route['routeHandler'], $route['routeArgs'])
98 | );
99 |
100 | if( $this->shouldReturnJson() ){
101 | return wp_send_json($output);
102 | }
103 |
104 | if( is_callable($output) ){
105 | return call_user_func($output);
106 | }
107 |
108 | return $output;
109 | }
110 |
111 |
112 | /*** PRIVATE METHODS ***/
113 |
114 | /**
115 | * Parses the output format parameter.
116 | *
117 | * Makes sure the output format parameter has one of the predefined values set
118 | * in the $outputFormats static property set in this class.
119 | *
120 | * @param string $outputFormat The output format
121 | *
122 | * @throws Exception\InvalidOutputFormatException If the output format is invalid
123 | *
124 | * @return string The output format value
125 | */
126 | private function parseOutputFormat($outputFormat)
127 | {
128 | if( ! in_array($outputFormat, self::$outputFormats, true) ){
129 | throw new Exception\InvalidOutputFormatException(
130 | "'$outputFormat' is not a valid output format.",
131 | 1
132 | );
133 | }
134 |
135 | return $outputFormat;
136 | }
137 |
138 | /**
139 | * Parses and returns the route handler output.
140 | *
141 | * Checks that the output is a respond_to array. If it's not it simply returns
142 | * the output as it was passed in.
143 | *
144 | * If it is, it validates it and then it returns the appropriate output format
145 | * depending on config or request type.
146 | *
147 | * @param mixed $output The output of the route handler
148 | *
149 | * @return mixed The parsed output of the route handler
150 | */
151 | private function parseHandlerOutput($output)
152 | {
153 | if( ! self::isRespondTo($output) ){
154 | return $output;
155 | }
156 |
157 | $this->validateRespondTo($output['respond_to']);
158 | $type = $this->shouldReturnJson() ? 'json' : 'html';
159 |
160 | return $output['respond_to'][$type];
161 | }
162 |
163 | /**
164 | * Determines if the route handler respond_to block should return the json data
165 | *
166 | * Looks for a "json" get parameter, if it's missing it checks for conditions
167 | * that indicate the request we're handling is an ajax request, or finally it
168 | * simply looks for the output format not being set to html.
169 | *
170 | * If any of these condition is met it returns true
171 | *
172 | * @return boolean The should return json boolean
173 | */
174 | private function shouldReturnJson()
175 | {
176 | return (
177 | isset($_GET['json']) ||
178 | $this->outputFormat === 'json' ||
179 | (
180 | ! empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) &&
181 | strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' &&
182 | $this->outputFormat !== 'html'
183 | )
184 | );
185 | }
186 |
187 | /**
188 | * Validates the respond_to array
189 | *
190 | * @param array $respondTo The respond_to array
191 | *
192 | * @throws Exception\InvalidRouteHandlerException If the respond_to is not an array, or missing the 'json' or 'html' keys, or if 'html' property is not callable
193 | */
194 | private function validateRespondTo($respondTo)
195 | {
196 | if( ! is_array($respondTo) ){
197 | throw new Exception\InvalidRouteHandlerException(
198 | 'The "respond_to" handler output property must be an array.'
199 | );
200 | }
201 |
202 | if( ! array_key_exists('json', $respondTo) ){
203 | throw new Exception\InvalidRouteHandlerException(
204 | 'Missing json output from respond_to route handler.'
205 | );
206 | }
207 |
208 | if( ! array_key_exists('html', $respondTo) ){
209 | throw new Exception\InvalidRouteHandlerException(
210 | 'Missing html callback from respond_to route handler.'
211 | );
212 | }
213 |
214 | if( ! is_callable($respondTo['html']) ){
215 | throw new Exception\InvalidRouteHandlerException(
216 | "The html property of the respond_to route handler needs to be callable."
217 | );
218 | }
219 | }
220 |
221 | }
--------------------------------------------------------------------------------
/src/ReverseRouter.php:
--------------------------------------------------------------------------------
1 | routeStore = $routeStore;
30 | }
31 |
32 | /**
33 | * Looks for a route with the name passed as argument. If the route exists, it returns the absolute route path.
34 | *
35 | * Looks for a static route first. If no static route exists, it looks for a
36 | * dynamic one. If no dynamic route is found either, an exception is thrown.
37 | *
38 | * @param string $routeName The name of the route
39 | *
40 | * @throws Exception\MissingRouteException If there is no route with the name we passed as argument.
41 | *
42 | * @return string The route path
43 | */
44 | public function getThePath($routeName)
45 | {
46 | $routePath = $this->getStaticRoutePath($routeName);
47 |
48 | if( $routePath === RouteStore::NOT_FOUND ){
49 | $routePath = call_user_func_array(
50 | [$this, 'getDynamicRoutePath'],
51 | func_get_args()
52 | );
53 |
54 | if( $routePath === RouteStore::NOT_FOUND ){
55 | throw new Exception\MissingRouteException("There is no route named '$routeName'.");
56 | }
57 | }
58 |
59 | return '/' . $routePath . '/';
60 | }
61 |
62 |
63 | /*** PRIVATE METHODS ***/
64 |
65 | /**
66 | * Tries to find a static route by name in the RouteStore object.
67 | * Returns the full route path if the static route is found.
68 | *
69 | * @param string $routeName The static route name
70 | *
71 | * @return integer|string Returns the RouteStore::NOT_FOUND status code (int) if no static route is found, or the full route path (string) if the route is found.
72 | */
73 | private function getStaticRoutePath($routeName)
74 | {
75 | $matchingStaticRoute = $this->routeStore->getStaticRouteByName($routeName);
76 |
77 | if( $matchingStaticRoute === RouteStore::NOT_FOUND ){
78 | return RouteStore::NOT_FOUND;
79 | }
80 |
81 | return $matchingStaticRoute['routePath'];
82 | }
83 |
84 | /**
85 | * Tries to find a dynamic route by name in the RouteStore object.
86 | * Returns the full route path if the dynamic route is found.
87 | *
88 | * When the dynamic route is found, this method iterates on the route segments.
89 | * The static segments are simply added to the path array, whereas the params
90 | * are then matched against the arguments passed to this method, so if the regex
91 | * defined on the param matches the argument, the argument is added as next segment
92 | * to the path array. This process leads to an array with all the required path
93 | * segments which are then imploded to form the returned url path.
94 | *
95 | * @param string $routeName The route name
96 | *
97 | * @throws Exception\InvalidRouteException If there are missing required parameters, invalid parameters, too many parameters or invalid segments in the route data
98 | *
99 | * @return integer|string Returns the RouteStore::NOT_FOUND status code (int) if the route is not found, or the full dynamic route path (string) if the route is found.
100 | */
101 | private function getDynamicRoutePath($routeName)
102 | {
103 | $argsValues = func_get_args();
104 | array_splice($argsValues, 0, 1);
105 |
106 | $matchingDynamicRoute = $this->routeStore->getDynamicRouteByName($routeName, $argsValues);
107 |
108 | if( $matchingDynamicRoute === RouteStore::NOT_FOUND ){
109 | return RouteStore::NOT_FOUND;
110 | }
111 |
112 | $pathArr = [];
113 | $pathArrIndex = -1; // to start at index 0 since ++ is at loop top
114 | $argIndex = -1; // to start at index 0 since ++ is at dynamic block top
115 |
116 | foreach($matchingDynamicRoute['routeSegments'] as $segment){
117 | $pathArrIndex++;
118 |
119 | // static part
120 | if( is_string($segment) ){
121 | $pathArr[$pathArrIndex] = $segment;
122 | continue;
123 | }
124 |
125 | // dynamic part
126 | if( is_array($segment) ){
127 | $argIndex++;
128 |
129 | if( ! isset( $argsValues[$argIndex] ) ){
130 | if( $segment['optional'] ){
131 | $n = 1;
132 |
133 | // optional param does not exist, remove previous '/'
134 | unset($pathArr[$pathArrIndex - 1]);
135 |
136 | // optional param is not the last param, remove next '/'
137 | if( isset($matchingDynamicRoute['routeSegments'][$pathArrIndex + 1]) ){
138 | $n++;
139 | unset($matchingDynamicRoute['routeSegments'][$pathArrIndex + 1]);
140 | }
141 |
142 | $pathArrIndex = $pathArrIndex - $n;
143 | continue;
144 | }
145 |
146 | throw new Exception\InvalidRouteException(
147 | "Missing required parameter '{$segment['paramName']}' for '{$matchingDynamicRoute['routeName']}' route."
148 | );
149 | }
150 |
151 | if( ! preg_match($segment['paramRegex'], $argsValues[$argIndex]) ){
152 | throw new Exception\InvalidRouteException(
153 | "Invalid parameter '{$segment['paramName']}' for '{$matchingDynamicRoute['routeName']}' route."
154 | );
155 | }
156 |
157 | $pathArr[$pathArrIndex] = $argsValues[$argIndex];
158 | continue;
159 | }
160 |
161 | throw new Exception\InvalidRouteException("Invalid route segment.");
162 | }
163 |
164 | $argsPassed = count($argsValues);
165 | $argsNeeded = $argIndex + 1;
166 |
167 | if( $argsPassed > $argsNeeded ){
168 | throw new Exception\InvalidRouteException("Too many parameters for route $routeName");
169 | }
170 |
171 | return implode('', $pathArr);
172 | }
173 |
174 | }
--------------------------------------------------------------------------------
/src/RouteParser.php:
--------------------------------------------------------------------------------
1 | name . "' route."
78 | );
79 | }
80 | }
81 |
82 |
83 | /*** PROPERTIES ***/
84 |
85 | protected $httpMethod;
86 | protected $path;
87 | protected $name;
88 | protected $handler;
89 |
90 |
91 | /*** PUBLIC METHODS ***/
92 |
93 | /**
94 | * Initializes the object by setting the http method, path, name and handler properties
95 | *
96 | * @param string $httpMethod The route http method
97 | * @param string $path The route path
98 | * @param string $name The route name
99 | * @param callback $handler The route handler
100 | */
101 | public function __construct($httpMethod, $path, $name, $handler)
102 | {
103 | $this->setHttpMethod($httpMethod);
104 | $this->setPath($path);
105 | $this->setName($name);
106 | $this->setHandler($handler);
107 | }
108 |
109 | /**
110 | * Returns the route http method
111 | *
112 | * @return string The object's $httpMethod property
113 | */
114 | public function getHttpMethod()
115 | {
116 | return $this->httpMethod;
117 | }
118 |
119 | /**
120 | * Returns the route's path
121 | *
122 | * @return string The object's $path property
123 | */
124 | public function getPath()
125 | {
126 | return $this->path;
127 | }
128 |
129 | /**
130 | * Returns the route's name
131 | *
132 | * @return string The object's $name property
133 | */
134 | public function getName()
135 | {
136 | return $this->name;
137 | }
138 |
139 | /**
140 | * Returns the route's handler
141 | *
142 | * @return callback The object's $handler property
143 | */
144 | public function getHandler()
145 | {
146 | return $this->handler;
147 | }
148 |
149 |
150 | /*** PROTECTED METHODS ***/
151 |
152 | /**
153 | * Validates the route's http method and then sets it as an object property
154 | *
155 | * @param string $httpMethod The route's http method
156 | */
157 | protected function setHttpMethod($httpMethod)
158 | {
159 | self::validateHttpMethod($httpMethod);
160 | $this->httpMethod = $httpMethod;
161 | }
162 |
163 | /**
164 | * Validates the route's name and then sets it as an object property
165 | *
166 | * @param string $name The route's name
167 | */
168 | protected function setName($name)
169 | {
170 | self::validateName($name);
171 | $this->name = $name;
172 | }
173 |
174 | /**
175 | * Validates the route's handler and then sets it as an object property
176 | *
177 | * @param callback $handler The route's handler
178 | */
179 | protected function setHandler($handler)
180 | {
181 | self::validateHandler($handler);
182 | $this->handler = $handler;
183 | }
184 |
185 | }
--------------------------------------------------------------------------------
/src/RouteStore.php:
--------------------------------------------------------------------------------
1 | namespace = $this->parseNamespace($namespace);
61 | }
62 |
63 | /**
64 | * Adds a route to this object.
65 | *
66 | * Makes sure the route name is unique, then prepends the router namespace
67 | * to the route path and finally it calls the appropriate add route method
68 | * depending on route type (static/dynamic).
69 | *
70 | * @param string $httpMethod The route's http method
71 | * @param string $routePath The route's path
72 | * @param string $routeName The route's name
73 | * @param callback $handler The handler
74 | */
75 | public function addRoute($httpMethod, $routePath, $routeName, $handler)
76 | {
77 | $this->validateRouteNameUniqueness($routeName);
78 | $routePath = $this->preparePath($routePath);
79 |
80 | $add = self::isStaticRoutePath($routePath) ? 'addStaticRoute' : 'addDynamicRoute';
81 |
82 | $this->$add($httpMethod, $routePath, $routeName, $handler);
83 | }
84 |
85 | /**
86 | * Looks for a route by request http method and request path.
87 | *
88 | * Tries to establish if it should look for the route at all. If it should, it
89 | * looks for a static route first, then for a dynamic one if no static route was
90 | * found. If a static or dynamic route is found, that route is returned, otherwise
91 | * the RouteStore::NOT_FOUND status code is returned.
92 | *
93 | * @param string $requestHttpMethod The request http method
94 | * @param string $requestPath The request path
95 | *
96 | * @return integer|array Returns the RouteStore::NOT_FOUND status code (int) if not found, The route array if a route is found
97 | */
98 | public function findRouteByRequestMethodAndPath($requestHttpMethod, $requestPath)
99 | {
100 | $requestPath = trim($requestPath, ' /');
101 |
102 | if( ! $this->shouldLookForRoute($requestPath) ){
103 | return self::NOT_FOUND;
104 | }
105 |
106 | $route = $this->findStaticRoute($requestHttpMethod, $requestPath);
107 |
108 | if( ! $route ){
109 | $route = $this->findDynamicRoute($requestHttpMethod, $requestPath);
110 |
111 | if( ! $route ){
112 | $route = self::NOT_FOUND;
113 | }
114 | }
115 |
116 | return $route;
117 | }
118 |
119 | /**
120 | * Looks for a static route by name.
121 | *
122 | * Alias method for getRouteByName method specifying static routes as the
123 | * routes to be searched.
124 | *
125 | * @param string $routeName The route name
126 | *
127 | * @return integer|array Returns the RouteStore::NOT_FOUND status code (int) if not found, The route array if a route is found
128 | */
129 | public function getStaticRouteByName($routeName)
130 | {
131 | return $this->getRouteByName(
132 | $this->staticRoutes,
133 | $routeName
134 | );
135 | }
136 |
137 | /**
138 | * Looks for a dynamc route by name.
139 | *
140 | * Alias method for getRouteByName method specifying dynamc routes as the
141 | * routes to be searched.
142 | *
143 | * @param string $routeName The route name
144 | *
145 | * @return integer|array Returns the RouteStore::NOT_FOUND status code (int) if not found, The route array if a route is found
146 | */
147 | public function getDynamicRouteByName($routeName, $args = [])
148 | {
149 | return $this->getRouteByName(
150 | $this->dynamicRoutesData,
151 | $routeName,
152 | $args
153 | );
154 | }
155 |
156 |
157 | /*** PRIVATE METHODS ***/
158 |
159 | /**
160 | * Parses the router namespace.
161 | *
162 | * Makes sure that if the namespace is not empty it matches the regex
163 | * specified in the NAMESPACE_REGEX constant of this class. Trims whitespace
164 | * and leading/trailing forward slashes.
165 | *
166 | * @param string $namespace The namespace
167 | *
168 | * @throws Exception\InvalidNamespaceException If the namespace is not empty and does not match the namespace regex
169 | *
170 | * @return string The parsed router namespace
171 | */
172 | private function parseNamespace($namespace)
173 | {
174 | if(
175 | ! empty($namespace) &&
176 | ! preg_match(self::NAMESPACE_REGEX, $namespace)
177 | ){
178 | throw new Exception\InvalidNamespaceException(
179 | "'$namespace' is not a valid namespace",
180 | 1
181 | );
182 | }
183 |
184 | return trim($namespace, ' /');
185 | }
186 |
187 | /**
188 | * Makes sure the route name passed as argument is not used for another route already.
189 | *
190 | * Looks for static and dynamic routes already using the route name passed as
191 | * argument, throws an Exception if it finds one. Returns not found status code otherwise.
192 | *
193 | * @param $routeName The route's name
194 | *
195 | * @throws Exception\InvalidRouteException If a route with the route name passed as argument is found
196 | *
197 | * @return integer|void Returns the RouteStore::NOT_FOUND status code (int) if no route is found, void otherwise
198 | */
199 | private function validateRouteNameUniqueness($routeName)
200 | {
201 | $route = $this->getStaticRouteByName($routeName);
202 |
203 | if($route === self::NOT_FOUND){
204 | $route = $this->getDynamicRouteByName($routeName);
205 |
206 | if($route === self::NOT_FOUND){
207 | return self::NOT_FOUND;
208 | }
209 | }
210 |
211 | throw new Exception\InvalidRouteException(
212 | "A route named '$routeName' already exists."
213 | );
214 | }
215 |
216 | /**
217 | * Adds a static route to this object.
218 | *
219 | * Parses the route data passed to this method as arguments through the
220 | * StaticRouteParser class, then makes sure no conflicting route already exists
221 | * and finally it adds the route data to the staticRoutes property of this object.
222 | *
223 | * @param string $httpMethod The route's http method
224 | * @param string $routePath The route's path
225 | * @param string $routeName The route's name
226 | * @param callback $handler The route's handler
227 | *
228 | * @throws Exception\InvalidRouteException If a route with the same http method and path already exists
229 | */
230 | private function addStaticRoute($httpMethod, $routePath, $routeName, $handler)
231 | {
232 | $route = new StaticRouteParser($httpMethod, $routePath, $routeName, $handler);
233 | $httpMethod = $route->getHttpMethod();
234 | $routePath = $route->getPath();
235 | $routeName = $route->getName();
236 | $handler = $route->getHandler();
237 |
238 | if ( isset( $this->staticRoutes[$routePath][$httpMethod]) ){
239 | throw new Exception\InvalidRouteException(
240 | "Cannot register two routes matching '$routePath' for method '$httpMethod'"
241 | );
242 | }
243 |
244 | $this->staticRoutes[$routePath][$httpMethod] = [
245 | 'routeName' => $routeName,
246 | 'routeHandler' => $handler,
247 | 'routeArgs' => []
248 | ];
249 | }
250 |
251 | /**
252 | * Adds a dynamic route.
253 | *
254 | * @param $httpMethod The http method
255 | * @param $routePath The route path
256 | * @param $routeName The route name
257 | * @param $handler The handler
258 | *
259 | * @throws Exception\InvalidRouteException (description)
260 | */
261 | private function addDynamicRoute($httpMethod, $routePath, $routeName, $handler)
262 | {
263 | $route = new DynamicRouteParser($httpMethod, $routePath, $routeName, $handler);
264 |
265 | $regex = $route->getRegex();
266 | $paramsNames = $route->getParamsNames();
267 | $segments = $route->getSegments();
268 |
269 | if( isset( $this->dynamicRoutesData[$regex][$httpMethod] ) ){
270 | throw new Exception\InvalidRouteException("Cannot register two routes matching '$regex' for method '$httpMethod'");
271 | }
272 |
273 | $this->dynamicRoutesData[$regex][$httpMethod] = [
274 | 'routeName' => $routeName,
275 | 'routeHandler' => $handler,
276 | 'routeArgs' => $paramsNames,
277 | 'routeSegments' => $segments
278 | ];
279 | }
280 |
281 | /**
282 | * Parses the dynamic route data and generates the dynamic routes.
283 | *
284 | * Explanation of the group position based, non chunked dispatching
285 | * implementation adopted by this router:
286 | *
287 | * The router splits the dynamic routes data array in chunks whose size is
288 | * defined in the CHUNK_SIZE constant of this class. It then iterates
289 | * over the chunks to merge all the regexes in the chunk into a single
290 | * regex containing the regex expressions in a single OR group.
291 | *
292 | * The PCRE regex "?|" non-capturing group type is used to avoid ending
293 | * up with a massive amount of unneeded capturing groups (bad performance).
294 | * However, doing this also means losing separate group numbers which would
295 | * have allowed us to know which of the regexes in the OR group matched.
296 | *
297 | * This is solved by adding dummy groups to each individual route, making the
298 | * matches size of each regex unique.
299 | *
300 | * This unique number is also then used to map each of the regexes in the
301 | * OR group to its route data (handlers) in the routeMap array, i.e. the
302 | * unique number is used as index in the routeMap array.
303 | *
304 | * This regexes OR merge and the subsequent procedure outline above
305 | * is repeated for each chunk of routes.
306 | *
307 | * @return boolean Returns False if the dynamic route data array is empty
308 | */
309 | private function generateDynamicRoutes()
310 | {
311 | $dynamicRoutesN = count($this->dynamicRoutesData);
312 |
313 | if( ! $dynamicRoutesN ){
314 | return false;
315 | }
316 |
317 | $partsN = max(1, round( $dynamicRoutesN / self::CHUNK_SIZE ) );
318 | $chunkSize = ceil($dynamicRoutesN / $partsN);
319 | $chunks = array_chunk( $this->dynamicRoutesData, $chunkSize, true);
320 | $dynamicRoutes = [];
321 |
322 | foreach($chunks as $chunk){
323 | $routeMap = [];
324 | $regexes = [];
325 | $groupsN = 0;
326 |
327 | foreach($chunk as $regex => $routes){
328 | $firstRoute = reset($routes);
329 | $variablesN = count($firstRoute['routeArgs']);
330 | $groupsN = max($groupsN, $variablesN);
331 |
332 | $regexes[] = $regex . str_repeat('()', $groupsN - $variablesN);
333 |
334 | foreach ($routes as $httpMethod => $route) {
335 | $routeMap[$groupsN + 1][$httpMethod] = $route;
336 | }
337 |
338 | $groupsN++;
339 | }
340 |
341 | $regex = '~^(?|' . implode('|', $regexes) . ')$~';
342 |
343 | $dynamicRoutes[] = [ 'routeRegex' => $regex, 'routeMap' => $routeMap ];
344 | }
345 |
346 | $this->dynamicRoutes = $dynamicRoutes;
347 | }
348 |
349 | /**
350 | * Looks for a static route by http method and request path
351 | *
352 | * @param string $httpMethod The http method
353 | * @param string $requestPath The request path
354 | *
355 | * @return array|boolean Returns the route array if the route is found, False otherwise
356 | */
357 | private function findStaticRoute($httpMethod, $requestPath)
358 | {
359 | if( ! isset($this->staticRoutes[$requestPath][$httpMethod]) ){
360 | return false;
361 | }
362 |
363 | return $this->staticRoutes[$requestPath][$httpMethod];
364 | }
365 |
366 | /**
367 | * Looks for a dynamic route by http method and request path.
368 | *
369 | * Generates the dynamic routes chunks from the dynamic routes data. This is
370 | * done only at "find" time to avoid doing this work if a static route matched
371 | * the request we are trying to route.
372 | *
373 | * If both route regex match and http method handler are found, arguments are
374 | * extracted from the route path, added to the route array, and the route array
375 | * is then returned.
376 | *
377 | * @param string $httpMethod The http method
378 | * @param string $requestPath The request path
379 | *
380 | * @return array|boolean Returns the route array if the route is found, False otherwise
381 | */
382 | private function findDynamicRoute($httpMethod, $requestPath)
383 | {
384 | $this->generateDynamicRoutes();
385 |
386 | foreach($this->dynamicRoutes as $data){
387 | if ( ! preg_match( $data['routeRegex'], $requestPath, $matches ) ){
388 | continue;
389 | }
390 |
391 | $matchesN = count($matches);
392 |
393 | while( ! isset( $data['routeMap'][$matchesN++] ) );
394 |
395 | $routes = $data['routeMap'][$matchesN - 1];
396 |
397 | foreach(array_keys($routes[$httpMethod]['routeArgs']) as $i => $varName){
398 | if( ! isset($matches[$i + 1]) || $matches[$i + 1] === '' ){
399 | unset($routes[$httpMethod]['routeArgs'][$i]);
400 | continue;
401 | }
402 |
403 | $routes[$httpMethod]['routeArgs'][$varName] = $matches[$i + 1];
404 | }
405 |
406 | return $routes[$httpMethod];
407 | }
408 |
409 | return false;
410 | }
411 |
412 | /**
413 | * Looks for a route by name.
414 | *
415 | * Loops over the routes passed as argument and if one with the same name is
416 | * found, it does some parsing and it returnes the route data array.
417 | *
418 | * @param array $routes The routes array
419 | * @param string $routeName The name of the route to find
420 | * @param array $args The arguments to pass to the route data array (dynamic routes only)
421 | *
422 | * @return array|integer The route data array if a route is found, RouteStore::NOT_FOUND status code (int) otherwise
423 | */
424 | private function getRouteByName($routes, $routeName, $args = null)
425 | {
426 | foreach($routes as $routePath => $httpHandlers){
427 | foreach($httpHandlers as $httpHandler){
428 | if( $httpHandler['routeName'] === $routeName ){
429 | $route = [
430 | 'routeName' => $routeName,
431 | 'routePath' => $routePath,
432 | 'routeArgs' => $args
433 | ];
434 |
435 | // only defined in dynamic routes
436 | if( isset($httpHandler['routeSegments']) ){
437 | $routeSegments = $httpHandler['routeSegments'];
438 | $route['routeSegments'] = $routeSegments;
439 | }
440 |
441 | return $route;
442 | }
443 | }
444 | }
445 |
446 | return self::NOT_FOUND;
447 | }
448 |
449 | /**
450 | * Determines if the RouteStore object needs to look for a route matching
451 | * the request path passed as argument.
452 | *
453 | * @param string $requestPath The request path
454 | *
455 | * @return boolean The boolean result
456 | */
457 | private function shouldLookForRoute($requestPath)
458 | {
459 | return ! $this->namespace || 0 === strpos($requestPath, $this->namespace);
460 | }
461 |
462 | /**
463 | * Returns the route path passed as argument with the router namespace prepended to it
464 | *
465 | * @param string $routePath The route path
466 | *
467 | * @return string The route path with the prepended router namespace
468 | */
469 | private function preparePath($routePath)
470 | {
471 | $routePath = trim($routePath, ' /');
472 |
473 | if( ! $this->namespace ){
474 | return $routePath;
475 | }
476 |
477 | return $this->namespace . '/' . $routePath;
478 | }
479 |
480 | }
--------------------------------------------------------------------------------
/src/Router.php:
--------------------------------------------------------------------------------
1 | '',
19 | 'outputFormat' => 'auto'
20 | ];
21 |
22 | private $routeStore;
23 | private $reverseRouter;
24 | private $requestDispatcher;
25 |
26 | /*** STATIC METHODS ***/
27 |
28 | public static function create($args = [])
29 | {
30 | $config = array_merge(self::$defaults, $args);
31 | $router = new self();
32 | $router->init($config);
33 |
34 | return $router;
35 | }
36 |
37 | /*** PUBLIC METHODS ***/
38 |
39 | /**
40 | * Merges passed arguments with router defaults, initializes the other
41 | * classes adding them as object properties, and finally hooks into WordPress
42 | * so request can pass through this router before being handed back over.
43 | *
44 | * @param array $args The router arguments
45 | *
46 | * @return string The object's $httpMethod property
47 | */
48 | public function init($args = [])
49 | {
50 | $config = array_merge(self::$defaults, $args);
51 |
52 | $this->routeStore = new RouteStore($config['namespace']);
53 | $this->reverseRouter = new ReverseRouter($this->routeStore);
54 | $this->requestDispatcher = new RequestDispatcher($config['outputFormat']);
55 |
56 | add_action('wp_loaded', [$this, 'run'], 1, 0);
57 | }
58 |
59 | // Dispatcher
60 |
61 | /**
62 | * Tries to dispatch the current http request. If the request cannot be dispatched
63 | * it returns false. When the request matches a route and is successfully dispatched
64 | * it exists to avoid WordPress also attempting to dispatch the current http request.
65 | *
66 | * @return boolean|void Returns false if the request is not dispatched, exits if the request is dispatched
67 | */
68 | public function run()
69 | {
70 | $httpMethod = $_SERVER['REQUEST_METHOD'];
71 | $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
72 |
73 | $result = $this->dispatch($httpMethod, $path);
74 |
75 | if($result === RequestDispatcher::NOT_DISPATCHED){
76 | return false;
77 | }
78 |
79 | exit;
80 | }
81 |
82 | /**
83 | * Dispatches the HTTP request or returns a status code if no routes matches.
84 | * Look at the RequestDispatcher 'dispatch' method for details as this is
85 | * just a wrapper for that method.
86 | *
87 | * @param string $httpMethod The http method
88 | * @param string $path The path
89 | *
90 | * @return mixed ( description_of_the_return_value )
91 | */
92 | public function dispatch($httpMethod, $path)
93 | {
94 | return $this->requestDispatcher->dispatch(
95 | $this->routeStore,
96 | $httpMethod,
97 | $path
98 | );
99 | }
100 |
101 | // Route store
102 |
103 |
104 | /**
105 | * Adds a route in the RouteStore object.
106 | *
107 | * Look at the RouteStore 'addRoute' method for details as this is just
108 | * a wrapper for that method.
109 | *
110 | * @param string $httpMethod The route's http method
111 | * @param string $routePath The route's route path
112 | * @param string $routeName The route's route name
113 | * @param callback $handler The route's handler
114 | */
115 | public function addRoute($httpMethod, $routePath, $routeName, $handler)
116 | {
117 | $this->routeStore->addRoute($httpMethod, $routePath, $routeName, $handler);
118 | }
119 |
120 |
121 | /**
122 | * Alias method for addRoute method specifying 'GET' as http method
123 | *
124 | * @param string $routePath The route's path
125 | * @param string $routeName The route's name
126 | * @param callback $handler The route's handler
127 | */
128 | public function get($routePath, $routeName, $handler)
129 | {
130 | $this->addRoute('GET', $routePath, $routeName, $handler);
131 | }
132 |
133 | /**
134 | * Alias method for addRoute method specifying 'HEAD' as http method
135 | *
136 | * @param string $routePath The route's path
137 | * @param string $routeName The route's name
138 | * @param callback $handler The route's handler
139 | */
140 | public function head($routePath, $routeName, $handler)
141 | {
142 | $this->addRoute('HEAD', $routePath, $routeName, $handler);
143 | }
144 |
145 | /**
146 | * Alias method for addRoute method specifying 'POST' as http method
147 | *
148 | * @param string $routePath The route's path
149 | * @param string $routeName The route's name
150 | * @param callback $handler The route's handler
151 | */
152 | public function post($routePath, $routeName, $handler)
153 | {
154 | $this->addRoute('POST', $routePath, $routeName, $handler);
155 | }
156 |
157 | /**
158 | * Alias method for addRoute method specifying 'PUT' as http method
159 | *
160 | * @param string $routePath The route's path
161 | * @param string $routeName The route's name
162 | * @param callback $handler The route's handler
163 | */
164 | public function put($routePath, $routeName, $handler)
165 | {
166 | $this->addRoute('PUT', $routePath, $routeName, $handler);
167 | }
168 |
169 | /**
170 | * Alias method for addRoute method specifying 'PATCH' as http method
171 | *
172 | * @param string $routePath The route's path
173 | * @param string $routeName The route's name
174 | * @param callback $handler The route's handler
175 | */
176 | public function patch($routePath, $routeName, $handler)
177 | {
178 | $this->addRoute('PATCH', $routePath, $routeName, $handler);
179 | }
180 |
181 | /**
182 | * Alias method for addRoute method specifying 'DELETE' as http method
183 | *
184 | * @param string $routePath The route's path
185 | * @param string $routeName The route's name
186 | * @param callback $handler The route's handler
187 | */
188 | public function delete($routePath, $routeName, $handler)
189 | {
190 | $this->addRoute('DELETE', $routePath, $routeName, $handler);
191 | }
192 |
193 | /**
194 | * Alias method for addRoute method specifying 'OPTIONS' as http method
195 | *
196 | * @param string $routePath The route's path
197 | * @param string $routeName The route's name
198 | * @param callback $handler The route's handler
199 | */
200 | public function options($routePath, $routeName, $handler)
201 | {
202 | $this->addRoute('OPTIONS', $routePath, $routeName, $handler);
203 | }
204 |
205 | // Reverse router
206 |
207 | /**
208 | * Returns a full route path by pulling the route data from the RouteStore object
209 | * and then (for dynamic routes) passing this method's parameters as route params.
210 | *
211 | * @return string The full route path
212 | */
213 | public function getThePath()
214 | {
215 | return call_user_func_array( [$this->reverseRouter, 'getThePath'], func_get_args() );
216 | }
217 |
218 | /**
219 | * Prints a full route path by pulling the route data from the RouteStore object
220 | * and then (for dynamic routes) passing this method's parameters as route params.
221 | */
222 | public function thePath()
223 | {
224 | echo call_user_func_array( [$this, 'getThePath'], func_get_args() );
225 | }
226 |
227 | }
--------------------------------------------------------------------------------
/src/StaticRouteParser.php:
--------------------------------------------------------------------------------
1 | validateStaticPath($path);
53 | $this->path = $path;
54 | }
55 |
56 | }
--------------------------------------------------------------------------------
/tests/_bootstrap.php:
--------------------------------------------------------------------------------
1 | assertEquals($element->getChildrenCount(), 5);
30 | * ```
31 | *
32 | * Floating-point example:
33 | * ```php
34 | * assertEquals($calculator->add(0.1, 0.2), 0.3, 'Calculator should add the two numbers correctly.', 0.01);
36 | * ```
37 | *
38 | * @param $expected
39 | * @param $actual
40 | * @param string $message
41 | * @param float $delta
42 | * @see \Codeception\Module\Asserts::assertEquals()
43 | */
44 | public function assertEquals($expected, $actual, $message = null, $delta = null) {
45 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertEquals', func_get_args()));
46 | }
47 |
48 |
49 | /**
50 | * [!] Method is generated. Documentation taken from corresponding module.
51 | *
52 | * Checks that two variables are not equal. If you're comparing floating-point values,
53 | * you can specify the optional "delta" parameter which dictates how great of a precision
54 | * error are you willing to tolerate in order to consider the two values not equal.
55 | *
56 | * Regular example:
57 | * ```php
58 | * assertNotEquals($element->getChildrenCount(), 0);
60 | * ```
61 | *
62 | * Floating-point example:
63 | * ```php
64 | * assertNotEquals($calculator->add(0.1, 0.2), 0.4, 'Calculator should add the two numbers correctly.', 0.01);
66 | * ```
67 | *
68 | * @param $expected
69 | * @param $actual
70 | * @param string $message
71 | * @param float $delta
72 | * @see \Codeception\Module\Asserts::assertNotEquals()
73 | */
74 | public function assertNotEquals($expected, $actual, $message = null, $delta = null) {
75 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotEquals', func_get_args()));
76 | }
77 |
78 |
79 | /**
80 | * [!] Method is generated. Documentation taken from corresponding module.
81 | *
82 | * Checks that two variables are same
83 | *
84 | * @param $expected
85 | * @param $actual
86 | * @param string $message
87 | * @see \Codeception\Module\Asserts::assertSame()
88 | */
89 | public function assertSame($expected, $actual, $message = null) {
90 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertSame', func_get_args()));
91 | }
92 |
93 |
94 | /**
95 | * [!] Method is generated. Documentation taken from corresponding module.
96 | *
97 | * Checks that two variables are not same
98 | *
99 | * @param $expected
100 | * @param $actual
101 | * @param string $message
102 | * @see \Codeception\Module\Asserts::assertNotSame()
103 | */
104 | public function assertNotSame($expected, $actual, $message = null) {
105 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotSame', func_get_args()));
106 | }
107 |
108 |
109 | /**
110 | * [!] Method is generated. Documentation taken from corresponding module.
111 | *
112 | * Checks that actual is greater than expected
113 | *
114 | * @param $expected
115 | * @param $actual
116 | * @param string $message
117 | * @see \Codeception\Module\Asserts::assertGreaterThan()
118 | */
119 | public function assertGreaterThan($expected, $actual, $message = null) {
120 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertGreaterThan', func_get_args()));
121 | }
122 |
123 |
124 | /**
125 | * [!] Method is generated. Documentation taken from corresponding module.
126 | *
127 | * Checks that actual is greater or equal than expected
128 | *
129 | * @param $expected
130 | * @param $actual
131 | * @param string $message
132 | * @see \Codeception\Module\Asserts::assertGreaterThanOrEqual()
133 | */
134 | public function assertGreaterThanOrEqual($expected, $actual, $message = null) {
135 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertGreaterThanOrEqual', func_get_args()));
136 | }
137 |
138 |
139 | /**
140 | * [!] Method is generated. Documentation taken from corresponding module.
141 | *
142 | * Checks that actual is less than expected
143 | *
144 | * @param $expected
145 | * @param $actual
146 | * @param string $message
147 | * @see \Codeception\Module\Asserts::assertLessThan()
148 | */
149 | public function assertLessThan($expected, $actual, $message = null) {
150 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertLessThan', func_get_args()));
151 | }
152 |
153 |
154 | /**
155 | * [!] Method is generated. Documentation taken from corresponding module.
156 | *
157 | * Checks that actual is less or equal than expected
158 | *
159 | * @param $expected
160 | * @param $actual
161 | * @param string $message
162 | * @see \Codeception\Module\Asserts::assertLessThanOrEqual()
163 | */
164 | public function assertLessThanOrEqual($expected, $actual, $message = null) {
165 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertLessThanOrEqual', func_get_args()));
166 | }
167 |
168 |
169 | /**
170 | * [!] Method is generated. Documentation taken from corresponding module.
171 | *
172 | * Checks that haystack contains needle
173 | *
174 | * @param $needle
175 | * @param $haystack
176 | * @param string $message
177 | * @see \Codeception\Module\Asserts::assertContains()
178 | */
179 | public function assertContains($needle, $haystack, $message = null) {
180 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertContains', func_get_args()));
181 | }
182 |
183 |
184 | /**
185 | * [!] Method is generated. Documentation taken from corresponding module.
186 | *
187 | * Checks that haystack doesn't contain needle.
188 | *
189 | * @param $needle
190 | * @param $haystack
191 | * @param string $message
192 | * @see \Codeception\Module\Asserts::assertNotContains()
193 | */
194 | public function assertNotContains($needle, $haystack, $message = null) {
195 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotContains', func_get_args()));
196 | }
197 |
198 |
199 | /**
200 | * [!] Method is generated. Documentation taken from corresponding module.
201 | *
202 | * Checks that string match with pattern
203 | *
204 | * @param string $pattern
205 | * @param string $string
206 | * @param string $message
207 | * @see \Codeception\Module\Asserts::assertRegExp()
208 | */
209 | public function assertRegExp($pattern, $string, $message = null) {
210 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertRegExp', func_get_args()));
211 | }
212 |
213 |
214 | /**
215 | * [!] Method is generated. Documentation taken from corresponding module.
216 | *
217 | * Checks that string not match with pattern
218 | *
219 | * @param string $pattern
220 | * @param string $string
221 | * @param string $message
222 | * @see \Codeception\Module\Asserts::assertNotRegExp()
223 | */
224 | public function assertNotRegExp($pattern, $string, $message = null) {
225 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotRegExp', func_get_args()));
226 | }
227 |
228 |
229 | /**
230 | * [!] Method is generated. Documentation taken from corresponding module.
231 | *
232 | * Checks that a string starts with the given prefix.
233 | *
234 | * @param string $prefix
235 | * @param string $string
236 | * @param string $message
237 | * @see \Codeception\Module\Asserts::assertStringStartsWith()
238 | */
239 | public function assertStringStartsWith($prefix, $string, $message = null) {
240 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertStringStartsWith', func_get_args()));
241 | }
242 |
243 |
244 | /**
245 | * [!] Method is generated. Documentation taken from corresponding module.
246 | *
247 | * Checks that a string doesn't start with the given prefix.
248 | *
249 | * @param string $prefix
250 | * @param string $string
251 | * @param string $message
252 | * @see \Codeception\Module\Asserts::assertStringStartsNotWith()
253 | */
254 | public function assertStringStartsNotWith($prefix, $string, $message = null) {
255 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertStringStartsNotWith', func_get_args()));
256 | }
257 |
258 |
259 | /**
260 | * [!] Method is generated. Documentation taken from corresponding module.
261 | *
262 | * Checks that variable is empty.
263 | *
264 | * @param $actual
265 | * @param string $message
266 | * @see \Codeception\Module\Asserts::assertEmpty()
267 | */
268 | public function assertEmpty($actual, $message = null) {
269 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertEmpty', func_get_args()));
270 | }
271 |
272 |
273 | /**
274 | * [!] Method is generated. Documentation taken from corresponding module.
275 | *
276 | * Checks that variable is not empty.
277 | *
278 | * @param $actual
279 | * @param string $message
280 | * @see \Codeception\Module\Asserts::assertNotEmpty()
281 | */
282 | public function assertNotEmpty($actual, $message = null) {
283 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotEmpty', func_get_args()));
284 | }
285 |
286 |
287 | /**
288 | * [!] Method is generated. Documentation taken from corresponding module.
289 | *
290 | * Checks that variable is NULL
291 | *
292 | * @param $actual
293 | * @param string $message
294 | * @see \Codeception\Module\Asserts::assertNull()
295 | */
296 | public function assertNull($actual, $message = null) {
297 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNull', func_get_args()));
298 | }
299 |
300 |
301 | /**
302 | * [!] Method is generated. Documentation taken from corresponding module.
303 | *
304 | * Checks that variable is not NULL
305 | *
306 | * @param $actual
307 | * @param string $message
308 | * @see \Codeception\Module\Asserts::assertNotNull()
309 | */
310 | public function assertNotNull($actual, $message = null) {
311 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotNull', func_get_args()));
312 | }
313 |
314 |
315 | /**
316 | * [!] Method is generated. Documentation taken from corresponding module.
317 | *
318 | * Checks that condition is positive.
319 | *
320 | * @param $condition
321 | * @param string $message
322 | * @see \Codeception\Module\Asserts::assertTrue()
323 | */
324 | public function assertTrue($condition, $message = null) {
325 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertTrue', func_get_args()));
326 | }
327 |
328 |
329 | /**
330 | * [!] Method is generated. Documentation taken from corresponding module.
331 | *
332 | * Checks that condition is negative.
333 | *
334 | * @param $condition
335 | * @param string $message
336 | * @see \Codeception\Module\Asserts::assertFalse()
337 | */
338 | public function assertFalse($condition, $message = null) {
339 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertFalse', func_get_args()));
340 | }
341 |
342 |
343 | /**
344 | * [!] Method is generated. Documentation taken from corresponding module.
345 | *
346 | * Checks if file exists
347 | *
348 | * @param string $filename
349 | * @param string $message
350 | * @see \Codeception\Module\Asserts::assertFileExists()
351 | */
352 | public function assertFileExists($filename, $message = null) {
353 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertFileExists', func_get_args()));
354 | }
355 |
356 |
357 | /**
358 | * [!] Method is generated. Documentation taken from corresponding module.
359 | *
360 | * Checks if file doesn't exist
361 | *
362 | * @param string $filename
363 | * @param string $message
364 | * @see \Codeception\Module\Asserts::assertFileNotExists()
365 | */
366 | public function assertFileNotExists($filename, $message = null) {
367 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertFileNotExists', func_get_args()));
368 | }
369 |
370 |
371 | /**
372 | * [!] Method is generated. Documentation taken from corresponding module.
373 | *
374 | * @param $expected
375 | * @param $actual
376 | * @param $description
377 | * @see \Codeception\Module\Asserts::assertGreaterOrEquals()
378 | */
379 | public function assertGreaterOrEquals($expected, $actual, $description = null) {
380 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertGreaterOrEquals', func_get_args()));
381 | }
382 |
383 |
384 | /**
385 | * [!] Method is generated. Documentation taken from corresponding module.
386 | *
387 | * @param $expected
388 | * @param $actual
389 | * @param $description
390 | * @see \Codeception\Module\Asserts::assertLessOrEquals()
391 | */
392 | public function assertLessOrEquals($expected, $actual, $description = null) {
393 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertLessOrEquals', func_get_args()));
394 | }
395 |
396 |
397 | /**
398 | * [!] Method is generated. Documentation taken from corresponding module.
399 | *
400 | * @param $actual
401 | * @param $description
402 | * @see \Codeception\Module\Asserts::assertIsEmpty()
403 | */
404 | public function assertIsEmpty($actual, $description = null) {
405 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertIsEmpty', func_get_args()));
406 | }
407 |
408 |
409 | /**
410 | * [!] Method is generated. Documentation taken from corresponding module.
411 | *
412 | * @param $key
413 | * @param $actual
414 | * @param $description
415 | * @see \Codeception\Module\Asserts::assertArrayHasKey()
416 | */
417 | public function assertArrayHasKey($key, $actual, $description = null) {
418 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertArrayHasKey', func_get_args()));
419 | }
420 |
421 |
422 | /**
423 | * [!] Method is generated. Documentation taken from corresponding module.
424 | *
425 | * @param $key
426 | * @param $actual
427 | * @param $description
428 | * @see \Codeception\Module\Asserts::assertArrayNotHasKey()
429 | */
430 | public function assertArrayNotHasKey($key, $actual, $description = null) {
431 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertArrayNotHasKey', func_get_args()));
432 | }
433 |
434 |
435 | /**
436 | * [!] Method is generated. Documentation taken from corresponding module.
437 | *
438 | * Checks that array contains subset.
439 | *
440 | * @param array $subset
441 | * @param array $array
442 | * @param bool $strict
443 | * @param string $message
444 | * @see \Codeception\Module\Asserts::assertArraySubset()
445 | */
446 | public function assertArraySubset($subset, $array, $strict = null, $message = null) {
447 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertArraySubset', func_get_args()));
448 | }
449 |
450 |
451 | /**
452 | * [!] Method is generated. Documentation taken from corresponding module.
453 | *
454 | * @param $expectedCount
455 | * @param $actual
456 | * @param $description
457 | * @see \Codeception\Module\Asserts::assertCount()
458 | */
459 | public function assertCount($expectedCount, $actual, $description = null) {
460 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertCount', func_get_args()));
461 | }
462 |
463 |
464 | /**
465 | * [!] Method is generated. Documentation taken from corresponding module.
466 | *
467 | * @param $class
468 | * @param $actual
469 | * @param $description
470 | * @see \Codeception\Module\Asserts::assertInstanceOf()
471 | */
472 | public function assertInstanceOf($class, $actual, $description = null) {
473 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertInstanceOf', func_get_args()));
474 | }
475 |
476 |
477 | /**
478 | * [!] Method is generated. Documentation taken from corresponding module.
479 | *
480 | * @param $class
481 | * @param $actual
482 | * @param $description
483 | * @see \Codeception\Module\Asserts::assertNotInstanceOf()
484 | */
485 | public function assertNotInstanceOf($class, $actual, $description = null) {
486 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotInstanceOf', func_get_args()));
487 | }
488 |
489 |
490 | /**
491 | * [!] Method is generated. Documentation taken from corresponding module.
492 | *
493 | * @param $type
494 | * @param $actual
495 | * @param $description
496 | * @see \Codeception\Module\Asserts::assertInternalType()
497 | */
498 | public function assertInternalType($type, $actual, $description = null) {
499 | return $this->getScenario()->runStep(new \Codeception\Step\Action('assertInternalType', func_get_args()));
500 | }
501 |
502 |
503 | /**
504 | * [!] Method is generated. Documentation taken from corresponding module.
505 | *
506 | * Fails the test with message.
507 | *
508 | * @param $message
509 | * @see \Codeception\Module\Asserts::fail()
510 | */
511 | public function fail($message) {
512 | return $this->getScenario()->runStep(new \Codeception\Step\Action('fail', func_get_args()));
513 | }
514 |
515 |
516 | /**
517 | * [!] Method is generated. Documentation taken from corresponding module.
518 | *
519 | * Handles and checks exception called inside callback function.
520 | * Either exception class name or exception instance should be provided.
521 | *
522 | * ```php
523 | * expectException(MyException::class, function() {
525 | * $this->doSomethingBad();
526 | * });
527 | *
528 | * $I->expectException(new MyException(), function() {
529 | * $this->doSomethingBad();
530 | * });
531 | * ```
532 | * If you want to check message or exception code, you can pass them with exception instance:
533 | * ```php
534 | * expectException(new MyException("Don't do bad things"), function() {
537 | * $this->doSomethingBad();
538 | * });
539 | * ```
540 | *
541 | * @param $exception string or \Exception
542 | * @param $callback
543 | * @see \Codeception\Module\Asserts::expectException()
544 | */
545 | public function expectException($exception, $callback) {
546 | return $this->getScenario()->runStep(new \Codeception\Step\Action('expectException', func_get_args()));
547 | }
548 | }
549 |
--------------------------------------------------------------------------------
/tests/acceptance.suite.yml:
--------------------------------------------------------------------------------
1 | # Codeception Test Suite Configuration
2 | #
3 | # Suite for acceptance tests.
4 | # Perform tests in browser using the WebDriver or PhpBrowser.
5 | # If you need both WebDriver and PHPBrowser tests - create a separate suite.
6 |
7 | class_name: AcceptanceTester
8 | modules:
9 | enabled:
10 | - PhpBrowser:
11 | url: http://wp.dev
12 | - \Helper\Acceptance
--------------------------------------------------------------------------------
/tests/acceptance/_bootstrap.php:
--------------------------------------------------------------------------------
1 | addRoute(
28 | $route['routeHttpMethod'],
29 | $route['routePath'],
30 | $route['routeName'],
31 | $route['routeHandler']
32 | );
33 | }
34 |
35 | return $router;
36 | }
37 |
38 |
39 | /****************************************************************************/
40 | /* DATA PROVIDERS */
41 | /****************************************************************************/
42 |
43 | // Namespaces ________________________________________________________________
44 |
45 | function validNamespacesProvider()
46 | {
47 | return [
48 | 'with slash on the left' => [ '/cool-namespace' ],
49 | 'with slash on the right' => [ 'your_api/' ],
50 | 'with slashes on both sides' => [ '/another-project/' ],
51 | 'many slashes and symbols' => [ 'abc/def/ghi/jlm/nop/qrs/tuv/wxy/z_-/.' ],
52 | ];
53 | }
54 |
55 | function invalidNamespacesProvider()
56 | {
57 | return [
58 | 'just spaces' => [ ' ' ],
59 | 'with spaces' => [ 'has spaces inside it' ],
60 | 'with whitespace' => [ ' simple-string ' ],
61 | 'with whitespace on left' => [ ' simple-string' ],
62 | 'with whitespace on right' => [ 'the/namespace ' ],
63 | 'with whitespace on both sides' => [ ' another_string ' ],
64 | 'with illegal symbols' => [ 'namespace!@£$%^' ]
65 | ];
66 | }
67 |
68 | // Output Formats ____________________________________________________________
69 |
70 | function validOutputFormatsProvider()
71 | {
72 | $outputFormats = [];
73 |
74 | foreach( RequestDispatcher::$outputFormats as $format ){
75 | $outputFormats[$format] = [$format];
76 | }
77 |
78 | return $outputFormats;
79 | }
80 |
81 | function invalidOutputFormatsProvider()
82 | {
83 | return [
84 | 'simple string' => ['simple_string'],
85 | 'another example of random string' => ['ANOTHER_RANDOM_STRING']
86 | ];
87 | }
88 |
89 | // Add Route Methods _________________________________________________________
90 |
91 | function addRouteMethodAliasesProvider()
92 | {
93 | return [
94 | 'get' => ['get', 'GET'],
95 | 'head' => ['head', 'HEAD'],
96 | 'post' => ['post', 'POST'],
97 | 'put' => ['put', 'PUT'],
98 | 'patch' => ['patch', 'PATCH'],
99 | 'delete' => ['delete', 'DELETE'],
100 | 'options' => ['options', 'OPTIONS']
101 | ];
102 | }
103 |
104 | // HTTP Methods ______________________________________________________________
105 |
106 | function validHttpMethodsProvider()
107 | {
108 | $validHttpMethods = [];
109 |
110 | foreach(RouteParser::$allowedHttpMethods as $httpMethod){
111 | $validHttpMethods[$httpMethod] = [$httpMethod];
112 | }
113 |
114 | return $validHttpMethods;
115 | }
116 |
117 | function invalidHttpMethodsProvider()
118 | {
119 | return [
120 | 'test string' => ['TEST'],
121 | 'integer' => [ 29 ],
122 | 'boolean' => [ true ]
123 | ];
124 | }
125 |
126 | function unallowedHttpMethodsProviders()
127 | {
128 | $data = [];
129 |
130 | foreach( RouteParser::$allowedHttpMethods as $httpMethod ){
131 | $unallowedMethods = [ $httpMethod ];
132 |
133 | $data['unallowed ' . $httpMethod] = [
134 | 'allowedHttpMethods' => array_diff( RouteParser::$allowedHttpMethods, $unallowedMethods ),
135 | 'unallowedHttpMethod' => $httpMethod
136 | ];
137 | }
138 |
139 | return $data;
140 | }
141 |
142 | // Route Names _______________________________________________________________
143 |
144 | function validRouteNamesProvider()
145 | {
146 | return [
147 | 'simple' => ['someroute'],
148 | 'uppercase' => ['FINALROUTE'],
149 | 'with underscore' => ['casual_route'],
150 | 'with numbers' => ['route66']
151 | ];
152 | }
153 |
154 | function invalidRouteNamesProvider()
155 | {
156 | return [
157 | 'with spaces' => ['used route'],
158 | 'with hyphens' => ['get-users'],
159 | 'with random symbols' => ['get!@£$']
160 | ];
161 | }
162 |
163 | function duplicateRoutesNamesProvider()
164 | {
165 | $handler = function(){};
166 |
167 | return [
168 | 'two static routes, no namespace, different methods' => [
169 | 'routerArgs' => [],
170 | 'routes' => [
171 | [
172 | 'routeHttpMethod' => 'GET',
173 | 'routePath' => 'cool/rainbow',
174 | 'routeName' => 'get_rainbow',
175 | 'routeHandler' => $handler
176 | ],
177 | [
178 | 'routeHttpMethod' => 'PATCH',
179 | 'routePath' => 'somewhere/over/the/rainbow',
180 | 'routeName' => 'get_rainbow',
181 | 'routeHandler' => $handler
182 | ]
183 | ]
184 | ],
185 | 'two static routes, with namespace, same methods' => [
186 | 'routerArgs' => ['namespace' => 'clouds'],
187 | 'routes' => [
188 | [
189 | 'routeHttpMethod' => 'POST',
190 | 'routePath' => 'clouds',
191 | 'routeName' => 'create_cloud',
192 | 'routeHandler' => $handler
193 | ],
194 | [
195 | 'routeHttpMethod' => 'POST',
196 | 'routePath' => 'sky/clouds',
197 | 'routeName' => 'create_cloud',
198 | 'routeHandler' => $handler
199 | ]
200 | ]
201 | ],
202 | 'two dynamic routes, same param name, same methods' => [
203 | 'routerArgs' => [],
204 | 'routes' => [
205 | [
206 | 'routeHttpMethod' => 'PUT',
207 | 'routePath' => 'apps/{id}',
208 | 'routeName' => 'update_app',
209 | 'routeHandler' => $handler
210 | ],
211 | [
212 | 'routeHttpMethod' => 'PUT',
213 | 'routePath' => '/system/apps/{id}/',
214 | 'routeName' => 'update_app',
215 | 'routeHandler' => $handler
216 | ]
217 | ]
218 | ],
219 | 'two dynamic routes, different params names' => [
220 | 'routerArgs' => [],
221 | 'routes' => [
222 | [
223 | 'routeHttpMethod' => 'PUT',
224 | 'routePath' => 'profile/{id}',
225 | 'routeName' => 'update_profile',
226 | 'routeHandler' => $handler
227 | ],
228 | [
229 | 'routeHttpMethod' => 'PATCH',
230 | 'routePath' => 'user-profile/{username}',
231 | 'routeName' => 'update_profile',
232 | 'routeHandler' => $handler
233 | ]
234 | ]
235 | ],
236 | ];
237 | }
238 |
239 | // Route Paths _______________________________________________________________
240 |
241 | function invalidRoutePathsProvider()
242 | {
243 | $handler = function(){};
244 |
245 | return [
246 | 'route with spaces' => [
247 | 'routerArgs' => [],
248 | 'routes' => [
249 | [
250 | 'routeHttpMethod' => 'GET',
251 | 'routePath' => 'a route/with spaces',
252 | 'routeName' => 'delete_alphabet_letter',
253 | 'routeHandler' => $handler
254 | ]
255 | ]
256 | ]
257 | ];
258 | }
259 |
260 | function routesWithDuplicatePathsProvider()
261 | {
262 | $handler = function(){};
263 |
264 | return [
265 | 'two static routes, no namespace' => [
266 | 'routerArgs' => [],
267 | 'routes' => [
268 | [
269 | 'routeHttpMethod' => 'GET',
270 | 'routePath' => 'netflix/movies/featured',
271 | 'routeName' => 'featured_netflix_movies',
272 | 'routeHandler' => $handler
273 | ],
274 | [
275 | 'routeHttpMethod' => 'GET',
276 | 'routePath' => 'netflix/movies/featured',
277 | 'routeName' => 'featured_netflix_movies_again',
278 | 'routeHandler' => $handler
279 | ]
280 | ]
281 | ],
282 | 'two static routes, with namespace' => [
283 | 'routerArgs' => ['namespace' => 'rotten-tomatoes-api'],
284 | 'routes' => [
285 | [
286 | 'routeHttpMethod' => 'GET',
287 | 'routePath' => 'reviews',
288 | 'routeName' => 'rotten_movies_reviews',
289 | 'routeHandler' => $handler
290 | ],
291 | [
292 | 'routeHttpMethod' => 'GET',
293 | 'routePath' => 'reviews',
294 | 'routeName' => 'rotten_movies_reviews_one_more_time',
295 | 'routeHandler' => $handler
296 | ]
297 | ]
298 | ],
299 | 'two dynamic routes, same param name' => [
300 | 'routerArgs' => [],
301 | 'routes' => [
302 | [
303 | 'routeHttpMethod' => 'DELETE',
304 | 'routePath' => 'raspberrypi-projects/{slug}',
305 | 'routeName' => 'delete_raspberrypi_project',
306 | 'routeHandler' => $handler
307 | ],
308 | [
309 | 'routeHttpMethod' => 'DELETE',
310 | 'routePath' => 'raspberrypi-projects/{slug}',
311 | 'routeName' => 'delete_bad_raspberrypi_project',
312 | 'routeHandler' => $handler
313 | ]
314 | ]
315 | ],
316 | 'two dynamic routes, different params names' => [
317 | 'routerArgs' => [],
318 | 'routes' => [
319 | [
320 | 'routeHttpMethod' => 'PUT',
321 | 'routePath' => 'chips/{slug}',
322 | 'routeName' => 'update_chip_project',
323 | 'routeHandler' => $handler
324 | ],
325 | [
326 | 'routeHttpMethod' => 'PUT',
327 | 'routePath' => 'chips/{name}',
328 | 'routeName' => 'update_the_chip_project',
329 | 'routeHandler' => $handler
330 | ]
331 | ]
332 | ],
333 | ];
334 | }
335 |
336 | function dynamicRoutesWithDuplicatePathsWithDiffRegexProvider()
337 | {
338 | $handler = function(){};
339 |
340 | return [
341 | 'two dynamic routes, integer and default regex' => [
342 | 'routerArgs' => [],
343 | 'routes' => [
344 | [
345 | 'routeHttpMethod' => 'GET',
346 | 'routePath' => 'users/{id:i}',
347 | 'routeName' => 'get_user_by_id',
348 | 'routeHandler' => $handler
349 | ],
350 | [
351 | 'routeHttpMethod' => 'GET',
352 | 'routePath' => 'users/{email}',
353 | 'routeName' => 'get_user_by_email',
354 | 'routeHandler' => $handler
355 | ]
356 | ]
357 | ]
358 | ];
359 | }
360 |
361 | function dynamicRoutesWithDuplicateParamsNamesProvider()
362 | {
363 | $handler = function(){};
364 |
365 | return [
366 | 'same param name, same default regex' => [
367 | 'routerArgs' => [],
368 | 'routes' => [
369 | [
370 | 'routeHttpMethod' => 'GET',
371 | 'routePath' => 'users/{username}/{username}',
372 | 'routeName' => 'get_user_by_id',
373 | 'routeHandler' => $handler
374 | ]
375 | ]
376 | ],
377 | 'same param name, same integer regex' => [
378 | 'routerArgs' => [],
379 | 'routes' => [
380 | [
381 | 'routeHttpMethod' => 'GET',
382 | 'routePath' => 'books/{id:i}/{id:i}',
383 | 'routeName' => 'get_user_by_id',
384 | 'routeHandler' => $handler
385 | ]
386 | ]
387 | ],
388 | 'same param name, different regexes' => [
389 | 'routerArgs' => [],
390 | 'routes' => [
391 | [
392 | 'routeHttpMethod' => 'GET',
393 | 'routePath' => 'movies/{title:a}/{title:c}',
394 | 'routeName' => 'get_user_by_id',
395 | 'routeHandler' => $handler
396 | ]
397 | ]
398 | ]
399 | ];
400 | }
401 |
402 |
403 | // Dispatcher ________________________________________________________________
404 |
405 | function requestsToDispatchProvider()
406 | {
407 | return [
408 | 'simple static route' => [
409 | 'routerArgs' => [],
410 | 'routes' => [
411 | [
412 | 'routeHttpMethod' => 'POST',
413 | 'routePath' => 'comments',
414 | 'routeName' => 'create_comment',
415 | 'routeHandler' => function(){
416 | return 'comment created';
417 | }
418 | ]
419 | ],
420 | 'request' => ['routeHttpMethod' => 'POST', 'routePath' => '/comments/'],
421 | 'output' => 'comment created'
422 | ],
423 | 'simple static route with namespace' => [
424 | 'routerArgs' => ['namespace' => 'awesome/api/v3/'],
425 | 'routes' => [
426 | [
427 | 'routeHttpMethod' => 'GET',
428 | 'routePath' => 'photos/latest',
429 | 'routeName' => 'get_latest_photos',
430 | 'routeHandler' => function(){
431 | return 'so many photos';
432 | }
433 | ]
434 | ],
435 | 'request' => ['routeHttpMethod' => 'GET', 'routePath' => '/awesome/api/v3/photos/latest'],
436 | 'output' => 'so many photos'
437 | ],
438 | 'dynamic route with namespace and default param regex' => [
439 | 'routerArgs' => ['namespace' => 'social-api'],
440 | 'routes' => [
441 | [
442 | 'routeHttpMethod' => 'GET',
443 | 'routePath' => 'friends/{username}/details',
444 | 'routeName' => 'get_friend_details',
445 | 'routeHandler' => function(){
446 | return 'friend details output';
447 | }
448 | ]
449 | ],
450 | 'request' => ['routeHttpMethod' => 'GET', 'routePath' => '/social-api/friends/m@tt!/details/'],
451 | 'output' => 'friend details output'
452 | ],
453 | 'dynamic route with :i integer regex shortcut param' => [
454 | 'routerArgs' => [],
455 | 'routes' => [
456 | [
457 | 'routeHttpMethod' => 'GET',
458 | 'routePath' => 'comments/{id:i}',
459 | 'routeName' => 'get_comment',
460 | 'routeHandler' => function(){
461 | return 'get comment by id output';
462 | }
463 | ]
464 | ],
465 | 'request' => ['routeHttpMethod' => 'GET', 'routePath' => 'comments/2'],
466 | 'output' => 'get comment by id output'
467 | ],
468 | 'dynamic route with :a alphanumeric regex shortcut param' => [
469 | 'routerArgs' => [],
470 | 'routes' => [
471 | [
472 | 'routeHttpMethod' => 'PATCH',
473 | 'routePath' => 'users/{name:a}',
474 | 'routeName' => 'update_user',
475 | 'routeHandler' => function(){
476 | return 'user updated';
477 | }
478 | ]
479 | ],
480 | 'request' => ['routeHttpMethod' => 'PATCH', 'routePath' => 'users/salvatore'],
481 | 'output' => 'user updated'
482 | ],
483 | 'dynamic route with :s slug regex shortcut param' => [
484 | 'routerArgs' => [],
485 | 'routes' => [
486 | [
487 | 'routeHttpMethod' => 'DELETE',
488 | 'routePath' => 'news/{slug:s}',
489 | 'routeName' => 'delete_news',
490 | 'routeHandler' => function(){
491 | return 'news deleted';
492 | }
493 | ]
494 | ],
495 | 'request' => ['routeHttpMethod' => 'DELETE', 'routePath' => 'news/new-wordpress-version-released'],
496 | 'output' => 'news deleted'
497 | ],
498 | 'dynamic route with specific words custom regex param' => [
499 | 'routerArgs' => [],
500 | 'routes' => [
501 | [
502 | 'routeHttpMethod' => 'GET',
503 | 'routePath' => 'languages/{language:english|italian|french|spanish}',
504 | 'routeName' => 'get_language',
505 | 'routeHandler' => function(){
506 | return 'lang output';
507 | }
508 | ]
509 | ],
510 | 'request' => ['routeHttpMethod' => 'GET', 'routePath' => 'languages/italian'],
511 | 'output' => 'lang output'
512 | ],
513 | 'dynamic route with integer custom regex param' => [
514 | 'routerArgs' => [],
515 | 'routes' => [
516 | [
517 | 'routeHttpMethod' => 'GET',
518 | 'routePath' => 'posts/{id:[0-9]+}',
519 | 'routeName' => 'get_post',
520 | 'routeHandler' => function(){
521 | return 'get post by id output';
522 | }
523 | ]
524 | ],
525 | 'request' => ['routeHttpMethod' => 'GET', 'routePath' => 'posts/25'],
526 | 'output' => 'get post by id output'
527 | ],
528 | 'dynamic route with lowercase letters and _ - symbols custom regex param' => [
529 | 'routerArgs' => [],
530 | 'routes' => [
531 | [
532 | 'routeHttpMethod' => 'PUT',
533 | 'routePath' => 'articles/{slug:[a-z_-]+}',
534 | 'routeName' => 'update_article',
535 | 'routeHandler' => function(){
536 | return 'get article by slug output';
537 | }
538 | ]
539 | ],
540 | 'request' => ['routeHttpMethod' => 'PUT', 'routePath' => 'articles/why-jetrouter_router-is-a-great-tool'],
541 | 'output' => 'get article by slug output'
542 | ],
543 | 'dynamic route with uppercase character custom regex param' => [
544 | 'routerArgs' => [],
545 | 'routes' => [
546 | [
547 | 'routeHttpMethod' => 'DELETE',
548 | 'routePath' => 'letters/{char:[A-Z]}',
549 | 'routeName' => 'delete_alphabet_letter',
550 | 'routeHandler' => function(){
551 | return 'delete alphabet letter output';
552 | }
553 | ]
554 | ],
555 | 'request' => ['routeHttpMethod' => 'DELETE', 'routePath' => 'letters/A'],
556 | 'output' => 'delete alphabet letter output'
557 | ]
558 | ];
559 | }
560 |
561 | function requestsToNotDispatchProvider()
562 | {
563 | $handler = function(){ return 'request is being dispatched!'; };
564 |
565 | return [
566 | 'router with namespace, same request path without namespace' => [
567 | 'routerArgs' => ['namespace' => 'awesome_project/api'],
568 | 'routes' => [
569 | [
570 | 'routeHttpMethod' => 'PUT',
571 | 'routePath' => 'cool-resource',
572 | 'routeName' => 'some_cool_resource_path',
573 | 'routeHandler' => $handler
574 | ]
575 | ],
576 | 'request' => ['routeHttpMethod' => 'PUT', 'routePath' => 'cool-resource']
577 | ],
578 |
579 | 'router with namespace, request path more specific than route path' => [
580 | 'routerArgs' => ['namespace' => 'photoapp/api'],
581 | 'routes' => [
582 | [
583 | 'routeHttpMethod' => 'GET',
584 | 'routePath' => 'comments',
585 | 'routeName' => 'app_comments',
586 | 'routeHandler' => $handler
587 | ]
588 | ],
589 | 'request' => ['routeHttpMethod' => 'GET', 'routePath' => 'photoapp/api/comments/published']
590 | ],
591 |
592 | 'fully matching static route, different HTTP method' => [
593 | 'routerArgs' => [],
594 | 'routes' => [
595 | [
596 | 'routeHttpMethod' => 'GET',
597 | 'routePath' => 'calendar/sformisano',
598 | 'routeName' => 'get_user_calendar',
599 | 'routeHandler' => $handler
600 | ]
601 | ],
602 | 'request' => ['routeHttpMethod' => 'PATCH', 'routePath' => 'calendar/sformisano']
603 | ],
604 |
605 | 'same request path as route, regex not matching' => [
606 | 'routerArgs' => [],
607 | 'routes' => [
608 | [
609 | 'routeHttpMethod' => 'PUT',
610 | 'routePath' => 'posts/{id:i}',
611 | 'routeName' => 'update_post',
612 | 'routeHandler' => $handler
613 | ]
614 | ],
615 | 'request' => ['routeHttpMethod' => 'PUT', 'routePath' => 'posts/post-title']
616 | ]
617 | ];
618 | }
619 |
620 | function staticRoutesOverridingDynamicRoutesProvider()
621 | {
622 | return [
623 | 'GET posts/popular overriding GET posts/{id} (routes added in this order)' => [
624 | 'routerArgs' => [],
625 | 'routes' => [
626 | [
627 | 'routeHttpMethod' => 'GET',
628 | 'routePath' => 'posts/popular',
629 | 'routeName' => 'popular_posts',
630 | 'routeHandler' => function(){
631 | return 'get popular posts handler';
632 | }
633 | ],
634 | [
635 | 'routeHttpMethod' => 'GET',
636 | 'routePath' => 'posts/{id}',
637 | 'routeName' => 'get_post',
638 | 'routeHandler' => function($id){
639 | return 'get post handler';
640 | }
641 | ]
642 | ],
643 | 'request' => ['routeHttpMethod' => 'GET', 'routePath' => 'posts/popular'],
644 | 'output' => 'get popular posts handler'
645 | ],
646 | 'with namespace, PUT users/{username}/pages/{slug} being overridden by PUT users/salvatore/pages/about (routes added in this order)' => [
647 | 'routerArgs' => [ 'namespace' => 'some/namespace/' ],
648 | 'routes' => [
649 | [
650 | 'routeHttpMethod' => 'PUT',
651 | 'routePath' => 'users/{username}/articles/{id}',
652 | 'routeName' => 'update_user_page',
653 | 'routeHandler' => function(){
654 | return 'get popular posts handler';
655 | }
656 | ],
657 | [
658 | 'routeHttpMethod' => 'PUT',
659 | 'routePath' => 'users/salvatore/pages/about',
660 | 'routeName' => 'update_salvatore_about_page',
661 | 'routeHandler' => function(){
662 | return 'about page updated';
663 | }
664 | ]
665 | ],
666 | 'request' => ['routeHttpMethod' => 'PUT', 'routePath' => 'some/namespace/users/salvatore/pages/about'],
667 | 'output' => 'about page updated'
668 | ]
669 | ];
670 | }
671 |
672 | function optionalParamsRequestsToDispatchProvider()
673 | {
674 | return [
675 | 'Single optional param as last segment' => [
676 | 'routerArgs' => [],
677 | 'routes' => [
678 | [
679 | 'routeHttpMethod' => 'GET',
680 | 'routePath' => '/comments/{filter}?',
681 | 'routeName' => 'get_comments',
682 | 'routeHandler' => function($filter){
683 | return "get $filter comments handler output";
684 | }
685 | ]
686 | ],
687 | 'requests' => [
688 | ['routeHttpMethod' => 'GET', 'routePath' => 'comments'],
689 | ['routeHttpMethod' => 'GET', 'routePath' => 'comments/deleted'],
690 | ],
691 | 'outputs' => [
692 | 'get comments handler output',
693 | 'get deleted comments handler output'
694 | ]
695 | ],
696 | 'Single optional param between static segments' => [
697 | 'routerArgs' => [],
698 | 'routes' => [
699 | [
700 | 'routeHttpMethod' => 'GET',
701 | 'routePath' => 'attachments/{type}?/alphabetical/',
702 | 'routeName' => 'get_attachments',
703 | 'routeHandler' => function($type){
704 | return "get $type attachments handler output";
705 | }
706 | ]
707 | ],
708 | 'requests' => [
709 | ['routeHttpMethod' => 'GET', 'routePath' => '/attachments/alphabetical'],
710 | ['routeHttpMethod' => 'GET', 'routePath' => '/attachments/PDF/alphabetical']
711 | ],
712 | 'outputs' => [
713 | 'get attachments handler output',
714 | 'get PDF attachments handler output'
715 | ]
716 | ],
717 | 'Multiple optional/non-optional params between static segments' => [
718 | 'routerArgs' => [],
719 | 'routes' => [
720 | [
721 | 'routeHttpMethod' => 'GET',
722 | 'routePath' => 'college/{college_name}/{teacher_name}?/students/{class_year}?',
723 | 'routeName' => 'get_students',
724 | 'routeHandler' => function($college_name, $teacher_name, $class_year){
725 | $output = '';
726 |
727 | if( $college_name ){
728 | $output .= "college $college_name > ";
729 | }
730 |
731 | if( $teacher_name ){
732 | $output .= "teacher $teacher_name > ";
733 | }
734 |
735 | if( $class_year ){
736 | $output .= "class year $class_year";
737 | }
738 | else{
739 | $output .= 'all students';
740 | }
741 |
742 | return $output;
743 | }
744 | ]
745 | ],
746 | 'requests' => [
747 | ['routeHttpMethod' => 'GET', 'routePath' => 'college/CalTech/students'],
748 | ['routeHttpMethod' => 'GET', 'routePath' => 'college/Oxford/Stephen-Hawking/students/1980'],
749 | ['routeHttpMethod' => 'GET', 'routePath' => 'college/MIT/students/2010'],
750 | ['routeHttpMethod' => 'GET', 'routePath' => 'college/MarvelUniversity/BruceBanner/students/'],
751 | ],
752 | 'outputs' => [
753 | 'college CalTech > all students',
754 | 'college Oxford > teacher Stephen-Hawking > class year 1980',
755 | 'college MIT > class year 2010',
756 | 'college MarvelUniversity > teacher BruceBanner > all students',
757 | ]
758 | ]
759 | ];
760 | }
761 |
762 | function optionalParamsRequestsToNotDispatchProvider()
763 | {
764 | $handler = function(){
765 | return 'request has a match and is being dispatched';
766 | };
767 |
768 | return [
769 | 'Single optional integer param, request not matching integer regex' => [
770 | 'routerArgs' => [],
771 | 'routes' => [
772 | [
773 | 'routeHttpMethod' => 'GET',
774 | 'routePath' => '/circles/{circle:i}?/activities',
775 | 'routeName' => 'circles_activities',
776 | 'routeHandler' => $handler
777 | ]
778 | ],
779 | 'requests' => [
780 | ['routeHttpMethod' => 'GET', 'routePath' => 'circles/close-friends/activities'],
781 | ]
782 | ]
783 | ];
784 | }
785 |
786 | function respondToInvalidTypesProvider(){
787 | return [
788 | ['not an array'],
789 | [ true ],
790 | [ false ],
791 | [ 100 ],
792 | [ new Router() ]
793 | ];
794 | }
795 |
796 | function respondToInvalidHtmlElementTypesProvider(){
797 | return [
798 | ['not a callable function'],
799 | [ true ],
800 | [ false ],
801 | [ 88 ],
802 | [ new Router() ]
803 | ];
804 | }
805 |
806 | function validReverseRoutesProvider()
807 | {
808 | $handler = function(){};
809 |
810 | return [
811 | 'Valid entries' => [
812 | 'routerArgs' => [],
813 | 'routes' => [
814 | [
815 | 'routeHttpMethod' => 'POST',
816 | 'routePath' => 'users',
817 | 'routeName' => 'create_user',
818 | 'routeHandler' => $handler
819 | ],
820 | [
821 | 'routeHttpMethod' => 'GET',
822 | 'routePath' => '/users/{username}',
823 | 'routeName' => 'get_user_by_username',
824 | 'routeHandler' => $handler
825 | ],
826 | [
827 | 'routeHttpMethod' => 'GET',
828 | 'routePath' => '/users/{username}/comments/{filter}?/',
829 | 'routeName' => 'get_user_comments',
830 | 'routeHandler' => $handler
831 | ],
832 | [
833 | 'routeHttpMethod' => 'GET',
834 | 'routePath' => '/users/{username}/comments/{filter}?/{page}/',
835 | 'routeName' => 'get_paged_comments',
836 | 'routeHandler' => $handler
837 | ],
838 | [
839 | 'routeHttpMethod' => 'GET',
840 | 'routePath' => '/schools/{school_name:s}?/teachers/{teacher_name:s}?/students/{year:i}?',
841 | 'routeName' => 'get_students',
842 | 'routeHandler' => $handler
843 | ],
844 | [
845 | 'routeHttpMethod' => 'GET',
846 | 'routePath' => '{model:a}/{filter_type:s}/{filter_value:a}',
847 | 'routeName' => 'get_model_by_filter',
848 | 'routeHandler' => $handler
849 | ]
850 | ],
851 |
852 | 'reverseRoutes' => [
853 | ['create_user'],
854 | ['get_user_by_username', 'sformisano'],
855 | ['get_user_comments', 'matt'],
856 | ['get_user_comments', 'james', 'published'],
857 | ['get_paged_comments', 'kris', 'rejected', '3'],
858 | ['get_paged_comments', 'kris', null, '2'],
859 | ['get_students', 'mit', 'tony-stark', '2000'],
860 | ['get_students', 'caltech', null, 1990],
861 | ['get_students', 'politecnico-milano'],
862 | ['get_model_by_filter', 'taxonomy', 'type', 'tag'],
863 | ],
864 | 'reverseRoutesOutputs' => [
865 | '/users/',
866 | '/users/sformisano/',
867 | '/users/matt/comments/',
868 | '/users/james/comments/published/',
869 | '/users/kris/comments/rejected/3/',
870 | '/users/kris/comments/2/',
871 | '/schools/mit/teachers/tony-stark/students/2000/',
872 | '/schools/caltech/teachers/students/1990/',
873 | '/schools/politecnico-milano/teachers/students/',
874 | '/taxonomy/type/tag/'
875 | ]
876 | ]
877 | ];
878 | }
879 |
880 | function validReverseRoutesProviderWithNamespace()
881 | {
882 | $handler = function(){};
883 |
884 | return [
885 | 'Valid entries' => [
886 | 'routerArgs' => [ 'namespace' => '/jetrouter-api/v3' ],
887 | 'routes' => [
888 | [
889 | 'routeHttpMethod' => 'POST',
890 | 'routePath' => 'users',
891 | 'routeName' => 'create_user',
892 | 'routeHandler' => $handler
893 | ],
894 | [
895 | 'routeHttpMethod' => 'GET',
896 | 'routePath' => '/users/{username}',
897 | 'routeName' => 'get_user_by_username',
898 | 'routeHandler' => $handler
899 | ],
900 | [
901 | 'routeHttpMethod' => 'GET',
902 | 'routePath' => '/users/{username}/comments/{filter}?/',
903 | 'routeName' => 'get_user_comments',
904 | 'routeHandler' => $handler
905 | ],
906 | [
907 | 'routeHttpMethod' => 'GET',
908 | 'routePath' => '/users/{username}/comments/{filter}?/{page}',
909 | 'routeName' => 'get_paged_comments',
910 | 'routeHandler' => $handler
911 | ],
912 | [
913 | 'routeHttpMethod' => 'GET',
914 | 'routePath' => '/schools/{school_name:s}?/teachers/{teacher_name:s}?/students/{year:i}?',
915 | 'routeName' => 'get_students',
916 | 'routeHandler' => $handler
917 | ],
918 | [
919 | 'routeHttpMethod' => 'GET',
920 | 'routePath' => '{model:a}/{filter_type:s}/{filter_value:a}',
921 | 'routeName' => 'get_model_by_filter',
922 | 'routeHandler' => $handler
923 | ]
924 | ],
925 |
926 | 'reverseRoutes' => [
927 | ['create_user'],
928 | ['get_user_by_username', 'sformisano'],
929 | ['get_user_comments', 'matt'],
930 | ['get_user_comments', 'james', 'published'],
931 | ['get_paged_comments', 'kris', 'rejected', '3'],
932 | ['get_paged_comments', 'kris', null, '2'],
933 | ['get_students', 'mit', 'tony-stark', '2000'],
934 | ['get_students', 'caltech', null, 1990],
935 | ['get_students', 'politecnico-milano'],
936 | ['get_model_by_filter', 'taxonomy', 'type', 'tag'],
937 | ],
938 | 'reverseRoutesOutputs' => [
939 | '/jetrouter-api/v3/users/',
940 | '/jetrouter-api/v3/users/sformisano/',
941 | '/jetrouter-api/v3/users/matt/comments/',
942 | '/jetrouter-api/v3/users/james/comments/published/',
943 | '/jetrouter-api/v3/users/kris/comments/rejected/3/',
944 | '/jetrouter-api/v3/users/kris/comments/2/',
945 | '/jetrouter-api/v3/schools/mit/teachers/tony-stark/students/2000/',
946 | '/jetrouter-api/v3/schools/caltech/teachers/students/1990/',
947 | '/jetrouter-api/v3/schools/politecnico-milano/teachers/students/',
948 | '/jetrouter-api/v3/taxonomy/type/tag/'
949 | ]
950 | ]
951 | ];
952 | }
953 |
954 |
955 | /****************************************************************************/
956 | /* ROUTER INITIALIZATION TESTS */
957 | /****************************************************************************/
958 |
959 | // WP Integration ____________________________________________________________
960 |
961 | function testWpAddAction()
962 | {
963 | $router = new Router();
964 | \WP_Mock::expectActionAdded('wp_loaded', [ $router, 'run' ], 1, 0);
965 | $router->init();
966 | }
967 |
968 | // Namespaces ________________________________________________________________
969 |
970 | /**
971 | * @dataProvider validNamespacesProvider
972 | */
973 | function testValidNamespaces($namespace)
974 | {
975 | $router = Router::create(['namespace' => $namespace]);
976 | }
977 |
978 | /**
979 | * @dataProvider invalidNamespacesProvider
980 | * @expectedException JetRouter\Exception\InvalidNamespaceException
981 | * @expectedExceptionMessage is not a valid namespace
982 | */
983 | function testInvalidNamespaces($namespace)
984 | {
985 | $router = Router::create(['namespace' => $namespace]);
986 | }
987 |
988 | // Output Formats ____________________________________________________________
989 |
990 | /**
991 | * @dataProvider validOutputFormatsProvider
992 | */
993 | function testValidOutputFormats($outputFormat)
994 | {
995 | $router = Router::create(['outputFormat' => $outputFormat]);
996 | }
997 |
998 | /**
999 | * @dataProvider invalidOutputFormatsProvider
1000 | * @expectedException JetRouter\Exception\InvalidOutputFormatException
1001 | * @expectedExceptionMessage is not a valid output format
1002 | */
1003 | function testInvalidOutputFormats($outputFormat)
1004 | {
1005 | $router = Router::create(['outputFormat' => $outputFormat]);
1006 | }
1007 |
1008 |
1009 | /****************************************************************************/
1010 | /* ADDING ROUTES TESTS */
1011 | /****************************************************************************/
1012 |
1013 | // HTTP Methods ______________________________________________________________
1014 |
1015 | /**
1016 | * @dataProvider validHttpMethodsProvider
1017 | */
1018 | function testValidHttpMethods($httpMethod)
1019 | {
1020 | $router = Router::create();
1021 |
1022 | $router->addRoute($httpMethod, 'test', 'test_route', function(){
1023 | return 'valid http method!';
1024 | });
1025 |
1026 | $this->assertEquals('valid http method!', $router->dispatch($httpMethod, 'test'));
1027 | }
1028 |
1029 | /**
1030 | * @dataProvider invalidHttpMethodsProvider
1031 | * @expectedException JetRouter\Exception\InvalidHttpMethodException
1032 | * @expectedExceptionMessage is not a valid HTTP method
1033 | */
1034 | function testInvalidHttpMethods($httpMethod)
1035 | {
1036 | $router = Router::create();
1037 | $router->addRoute($httpMethod, 'somewhere', 'sw_route', function(){});
1038 | }
1039 |
1040 | /**
1041 | * @dataProvider addRouteMethodAliasesProvider
1042 | */
1043 | function testAddRouteMethodAliases($httpMethodAlias, $httpMethod)
1044 | {
1045 | $router = Router::create();
1046 |
1047 | $router->$httpMethodAlias('best/resource', 'best_resource', function(){
1048 | return 'best resource return';
1049 | });
1050 |
1051 | $this->assertEquals(
1052 | 'best resource return',
1053 | $router->dispatch($httpMethod, 'best/resource')
1054 | );
1055 | }
1056 |
1057 | // Route Names _______________________________________________________________
1058 |
1059 | /**
1060 | * @dataProvider validRouteNamesProvider
1061 | */
1062 | function testValidRouteNames($routeName)
1063 | {
1064 | $router = Router::create();
1065 |
1066 | $router->addRoute( 'GET', '/something', $routeName, function(){
1067 | return 'valid route name!';
1068 | });
1069 |
1070 | $this->assertEquals(
1071 | 'valid route name!',
1072 | $router->dispatch('GET', '/something')
1073 | );
1074 | }
1075 |
1076 | /**
1077 | * @dataProvider invalidRouteNamesProvider
1078 | * @expectedException JetRouter\Exception\InvalidRouteException
1079 | * @expectedExceptionMessage is not a valid route name
1080 | */
1081 | function testInvalidRouteNames($routeName)
1082 | {
1083 | $router = Router::create();
1084 |
1085 | $router->addRoute('GET', '/something', $routeName, function(){});
1086 | }
1087 |
1088 | /**
1089 | * @dataProvider duplicateRoutesNamesProvider
1090 | * @expectedException JetRouter\Exception\InvalidRouteException
1091 | * @expectedExceptionMessage A route named
1092 | */
1093 | function testDuplicateRouteNames($routerArgs, $routes){
1094 | $router = $this->getRouter($routerArgs, $routes);
1095 | }
1096 |
1097 | // Route Paths _______________________________________________________________
1098 |
1099 | /**
1100 | * @dataProvider invalidRoutePathsProvider
1101 | * @expectedException JetRouter\Exception\InvalidRouteException
1102 | * @expectedExceptionMessage is not a valid route path
1103 | */
1104 | function testInvalidRoutePaths($routerArgs, $routes){
1105 | $router = $this->getRouter($routerArgs, $routes);
1106 | }
1107 |
1108 | /**
1109 | * @dataProvider routesWithDuplicatePathsProvider
1110 | * @expectedException JetRouter\Exception\InvalidRouteException
1111 | * @expectedExceptionMessage Cannot register two routes matching
1112 | */
1113 | function testDuplicateRoutePaths($routerArgs, $routes){
1114 | $router = Router::create($routerArgs);
1115 |
1116 | foreach($routes as $route){
1117 | $router->addRoute(
1118 | $route['routeHttpMethod'],
1119 | $route['routePath'],
1120 | $route['routeName'],
1121 | $route['routeHandler']
1122 | );
1123 | }
1124 | }
1125 |
1126 | /**
1127 | * @dataProvider dynamicRoutesWithDuplicatePathsWithDiffRegexProvider
1128 | */
1129 | function testDuplicateRoutePathsWithDiffRegex($routerArgs, $routes)
1130 | {
1131 | $router = $this->getRouter($routerArgs, $routes);
1132 | }
1133 |
1134 | /**
1135 | * @dataProvider dynamicRoutesWithDuplicateParamsNamesProvider
1136 | * @expectedException JetRouter\Exception\InvalidRouteException
1137 | * @expectedExceptionMessage found more than once in route
1138 | */
1139 | function testDynamicRoutesWithDuplicateParamsNames($routerArgs, $routes)
1140 | {
1141 | $router = $this->getRouter($routerArgs, $routes);
1142 | }
1143 |
1144 |
1145 | /****************************************************************************/
1146 | /* DISPATCHER TESTS */
1147 | /****************************************************************************/
1148 |
1149 | /**
1150 | * @dataProvider requestsToDispatchProvider
1151 | */
1152 | function testRequestsToDispatch($routerArgs, $routes, $request, $output)
1153 | {
1154 | $router = $this->getRouter($routerArgs, $routes);
1155 |
1156 | $this->assertEquals(
1157 | $output,
1158 | $router->dispatch($request['routeHttpMethod'], $request['routePath'])
1159 | );
1160 | }
1161 |
1162 | /**
1163 | * @dataProvider requestsToNotDispatchProvider
1164 | */
1165 | function testRequestsToNotDispatch($routerArgs, $routes, $request)
1166 | {
1167 | $router = Router::create($routerArgs);
1168 |
1169 | foreach($routes as $route){
1170 | $router->addRoute(
1171 | $route['routeHttpMethod'],
1172 | $route['routePath'],
1173 | $route['routeName'],
1174 | $route['routeHandler']
1175 | );
1176 | }
1177 |
1178 | $this->assertEquals(
1179 | RequestDispatcher::NOT_DISPATCHED,
1180 | $router->dispatch($request['routeHttpMethod'], $request['routePath'])
1181 | );
1182 | }
1183 |
1184 | /**
1185 | * @dataProvider unallowedHttpMethodsProviders
1186 | */
1187 | function testRequestWithUnallowedHttpMethods($allowedHttpMethods, $unallowedHttpMethod)
1188 | {
1189 | $router = Router::create();
1190 |
1191 | $path = '/somewhere/over/the/rainbow/';
1192 | $handler = function(){};
1193 |
1194 | foreach($allowedHttpMethods as $httpMethod){
1195 | $name = 'test_' . $httpMethod;
1196 | $router->addRoute($httpMethod, $path, $name, $handler);
1197 | }
1198 |
1199 | $this->assertEquals(
1200 | RouteStore::NOT_FOUND,
1201 | $router->dispatch($unallowedHttpMethod, $path)
1202 | );
1203 | }
1204 |
1205 | /**
1206 | * @dataProvider staticRoutesOverridingDynamicRoutesProvider
1207 | */
1208 | function testStaticRouteOverridingDynamicRoute($routerArgs, $routes, $request, $output)
1209 | {
1210 | $router = $this->getRouter($routerArgs, $routes);
1211 |
1212 | $this->assertEquals(
1213 | $output,
1214 | $router->dispatch($request['routeHttpMethod'], $request['routePath'])
1215 | );
1216 | }
1217 |
1218 | /**
1219 | * @dataProvider optionalParamsRequestsToDispatchProvider
1220 | */
1221 | function testOptionalParamsRequestsToDispatch($routerArgs, $routes, $requests, $outputs)
1222 | {
1223 | $router = $this->getRouter($routerArgs, $routes);
1224 |
1225 | $i = 0;
1226 |
1227 | foreach($requests as $request){
1228 | $this->assertEquals(
1229 | $outputs[$i],
1230 | $router->dispatch($request['routeHttpMethod'], $request['routePath'])
1231 | );
1232 |
1233 | $i++;
1234 | }
1235 | }
1236 |
1237 | /**
1238 | * @dataProvider optionalParamsRequestsToNotDispatchProvider
1239 | */
1240 | function testOptionalParamsRequestsToNotDispatch($routerArgs, $routes, $requests)
1241 | {
1242 | $router = $this->getRouter($routerArgs, $routes);
1243 |
1244 | foreach($requests as $request){
1245 | $this->assertEquals(
1246 | RouteStore::NOT_FOUND,
1247 | $router->dispatch($request['routeHttpMethod'], $request['routePath'])
1248 | );
1249 | }
1250 | }
1251 |
1252 | /**
1253 | * @dataProvider respondToInvalidTypesProvider
1254 | * @expectedException JetRouter\Exception\InvalidRouteHandlerException
1255 | * @expectedExceptionMessage handler output property must be an array.
1256 | */
1257 | function testInvalidHandlerRespondToTypes($respondToValue)
1258 | {
1259 | $router = Router::create();
1260 |
1261 | $router->get('foo', 'get_foo', function() use($respondToValue){
1262 | return ['respond_to' => $respondToValue];
1263 | });
1264 |
1265 | $router->dispatch('GET', 'foo');
1266 | }
1267 |
1268 | /**
1269 | * @expectedException JetRouter\Exception\InvalidRouteHandlerException
1270 | * @expectedExceptionMessage Missing json output from respond_to route handler.
1271 | */
1272 | function testHandlerRespondToWithoutJsonKey()
1273 | {
1274 | $router = Router::create();
1275 |
1276 | $router->get('foo', 'get_foo', function(){
1277 | return ['respond_to' => [ 'html' => '', 'something-else' => '', 'but-no-json!' => true ] ];
1278 | });
1279 |
1280 | $router->dispatch('GET', 'foo');
1281 | }
1282 |
1283 | /**
1284 | * @expectedException JetRouter\Exception\InvalidRouteHandlerException
1285 | * @expectedExceptionMessage Missing html callback from respond_to route handler.
1286 | */
1287 | function testHandlerRespondToWithoutHtmlKey()
1288 | {
1289 | $router = Router::create();
1290 |
1291 | $router->get('foo', 'get_foo', function(){
1292 | return ['respond_to' => [ 'json' => '', 'something-else' => '', 'but-no-html!' => true ] ];
1293 | });
1294 |
1295 | $router->dispatch('GET', 'foo');
1296 | }
1297 |
1298 | /**
1299 | * @dataProvider respondToInvalidHtmlElementTypesProvider
1300 | * @expectedException JetRouter\Exception\InvalidRouteHandlerException
1301 | * @expectedExceptionMessage The html property of the respond_to route handler needs to be callable.
1302 | */
1303 | function testHandlerRespondToWithInvalidHtmlTypes($htmlValue)
1304 | {
1305 | $router = Router::create();
1306 |
1307 | $router->get('foo', 'get_foo', function() use($htmlValue){
1308 | return ['respond_to' => [ 'json' => 'can be anything really', 'html' => $htmlValue ] ];
1309 | });
1310 |
1311 | $router->dispatch('GET', 'foo');
1312 | }
1313 |
1314 | function testValidHandlerRespondToOutput()
1315 | {
1316 | $router = Router::create();
1317 |
1318 | $router->get('foo', 'get_foo', function(){
1319 | return ['respond_to' => [
1320 | 'json' => 'can be anything really',
1321 | 'html' => function(){
1322 | return 'works fine';
1323 | }
1324 | ]];
1325 | });
1326 |
1327 | $this->assertEquals(
1328 | 'works fine',
1329 | $router->dispatch('GET', 'foo')
1330 | );
1331 | }
1332 |
1333 | function testHandlerReturningRespondToJsonBasedOnOutputFormatConfigValue()
1334 | {
1335 | $router = Router::create(['outputFormat' => 'json']);
1336 |
1337 | \WP_Mock::wpFunction( 'wp_send_json', array(
1338 | 'times' => 1,
1339 | 'return' => 'wp_send_json output',
1340 | ) );
1341 |
1342 | $router->get('movies', 'get_movies', function(){
1343 | return ['respond_to' => [
1344 | 'json' => null,
1345 | 'html' => function(){
1346 | return 'movies list view loaded';
1347 | }
1348 | ]];
1349 | });
1350 |
1351 | $this->assertEquals(
1352 | 'wp_send_json output',
1353 | $router->dispatch('GET', 'movies')
1354 | );
1355 | }
1356 |
1357 | function testHandlerReturningRespondToJsonToXmlHttpRequest()
1358 | {
1359 | $_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';
1360 |
1361 | \WP_Mock::wpFunction( 'wp_send_json', array(
1362 | 'times' => 1,
1363 | 'return' => 'json data output',
1364 | ) );
1365 |
1366 | $router = Router::create();
1367 |
1368 | $router->get('users', 'get_users', function(){
1369 | return ['respond_to' => [
1370 | 'json' => 'irrelevant data as wp_send_json return data is mocked above',
1371 | 'html' => function(){
1372 | return 'users view loaded';
1373 | }
1374 | ]];
1375 | });
1376 |
1377 | $this->assertEquals(
1378 | 'json data output',
1379 | $router->dispatch('GET', 'users')
1380 | );
1381 | }
1382 |
1383 | function testHandlerReturningRespondToJsonToRequestWithJsonGetParam()
1384 | {
1385 | \WP_Mock::wpFunction( 'wp_send_json', array(
1386 | 'times' => 1,
1387 | 'return' => 'here are your files in json format',
1388 | ) );
1389 |
1390 | // we're testing against definition itself, no need for truthy values
1391 | $_GET['json'] = '';
1392 |
1393 | $router = Router::create();
1394 |
1395 | $router->get('files', 'get_files', function(){
1396 | return ['respond_to' => [
1397 | 'json' => 'irrelevant data as wp_send_json return data is mocked above',
1398 | 'html' => function(){
1399 | return 'files list view';
1400 | }
1401 | ]];
1402 | });
1403 |
1404 | $this->assertEquals(
1405 | 'here are your files in json format',
1406 | $router->dispatch('GET', 'files')
1407 | );
1408 | }
1409 |
1410 | function testHandlerReturningRespondToHtmlByDefault()
1411 | {
1412 | $router = Router::create();
1413 |
1414 | $router->get('laptops', 'get_laptops', function(){
1415 | return ['respond_to' => [
1416 | 'json' => 'json data',
1417 | 'html' => function(){
1418 | return 'laptops list view';
1419 | }
1420 | ]];
1421 | });
1422 |
1423 | $this->assertEquals(
1424 | 'laptops list view',
1425 | $router->dispatch('GET', 'laptops')
1426 | );
1427 | }
1428 |
1429 | function testHandlerReturningRespondToHtmlWithOutputFormatOverridingXmlHttpRequest()
1430 | {
1431 | $_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';
1432 |
1433 | $router = Router::create(['outputFormat' => 'html']);
1434 |
1435 | $router->get('laptops', 'get_laptops', function(){
1436 | return ['respond_to' => [
1437 | 'json' => 'json respond to data',
1438 | 'html' => function(){
1439 | return 'laptops list view';
1440 | }
1441 | ]];
1442 | });
1443 |
1444 | $this->assertEquals(
1445 | 'laptops list view',
1446 | $router->dispatch('GET', 'laptops')
1447 | );
1448 | }
1449 |
1450 |
1451 | /****************************************************************************/
1452 | /* REVERSE ROUTER TESTS */
1453 | /****************************************************************************/
1454 |
1455 | /**
1456 | * @dataProvider validReverseRoutesProvider
1457 | */
1458 | function testValidReverseRoutes($routerArgs, $routes, $reverseRoutes, $reverseRoutesOutputs)
1459 | {
1460 | $router = $this->getRouter($routerArgs, $routes);
1461 |
1462 | $i = 0;
1463 |
1464 | foreach($reverseRoutes as $reverseRoute){
1465 | $this->assertEquals(
1466 | $reverseRoutesOutputs[$i],
1467 | call_user_func_array( [$router, 'getThePath'], $reverseRoute )
1468 | );
1469 |
1470 | $i++;
1471 | }
1472 | }
1473 |
1474 | /**
1475 | * @dataProvider validReverseRoutesProviderWithNamespace
1476 | */
1477 | function testValidReverseRoutesWithNamespace($routerArgs, $routes, $reverseRoutes, $reverseRoutesOutputs)
1478 | {
1479 | $router = $this->getRouter($routerArgs, $routes);
1480 |
1481 | $i = 0;
1482 |
1483 | foreach($reverseRoutes as $reverseRoute){
1484 | $this->assertEquals(
1485 | $reverseRoutesOutputs[$i],
1486 | call_user_func_array( [$router, 'getThePath'], $reverseRoute )
1487 | );
1488 |
1489 | $i++;
1490 | }
1491 | }
1492 |
1493 | /**
1494 | * @expectedException JetRouter\Exception\InvalidRouteException
1495 | * @expectedExceptionMessage Missing required parameter
1496 | */
1497 | function testMissingRequiredParameterInReverseRouter()
1498 | {
1499 | $router = Router::create();
1500 |
1501 | $router->delete('movies/{movie_name:s}', 'delete_movie', function(){});
1502 | $router->thePath('delete_movie');
1503 | }
1504 |
1505 | /**
1506 | * @expectedException JetRouter\Exception\InvalidRouteException
1507 | * @expectedExceptionMessage Invalid parameter
1508 | */
1509 | function testInvalidParameterInReverseRouter()
1510 | {
1511 | $router = Router::create();
1512 |
1513 | $router->get('guitarists/{id:i}', 'get_guitarist', function(){});
1514 | $router->thePath('get_guitarist', 'yngwie-malmsteen');
1515 | }
1516 |
1517 | /**
1518 | * @expectedException JetRouter\Exception\InvalidRouteException
1519 | * @expectedExceptionMessage Too many parameters for route
1520 | */
1521 | function testTooManyParametersReverseRouterException()
1522 | {
1523 | $router = Router::create();
1524 |
1525 | $router->put('tv-shows/{show_name:s}', 'update_tv_show', function(){});
1526 | $router->thePath('update_tv_show', 'game-of-thrones', 'season-2');
1527 | }
1528 |
1529 |
1530 | // test namespace is in the output
1531 | // test no route with name
1532 | // test missing parameter/s
1533 |
1534 | // fixme test with routes with same path existing (static and dynamic) the
1535 | // right handler is selected depending on the method
1536 |
1537 | // check if param custom regex is valid at addRoute time
1538 |
1539 |
1540 | // fixme we may wanna look into same dynamic routes with optional and non optional param but equal in everything else,
1541 | // and how they work / how the routes behaves with this case
1542 | //
1543 | // fixme test default param value in dynamic routes with optional params (right now it does not seem to work if you set a default in the param definition in the callback, e.g. function($foo = 'bar'){
1544 | // foo is null!
1545 | // })
1546 | //
1547 | // fixme maybe we should have all router instances add their routes to a class static property so one can know if different router instances have conflicting routes
1548 | }
--------------------------------------------------------------------------------
/tests/unit/_bootstrap.php:
--------------------------------------------------------------------------------
1 |