├── LICENSE
├── README.md
├── api.php
├── api.xml
├── mashape
├── configuration
│ ├── helpers
│ │ ├── loadMethods.php
│ │ └── loadObjects.php
│ ├── restConfiguration.php
│ ├── restConfigurationLoader.php
│ ├── restField.php
│ ├── restMethod.php
│ └── restObject.php
├── exceptions
│ ├── exceptionMessages.php
│ └── mashapeException.php
├── init
│ ├── headers.php
│ ├── init.php
│ ├── json.php
│ └── session.php
├── json
│ ├── jsonImpl.php
│ └── jsonUtils.php
├── mashape.php
├── mashapeAPIError.php
├── methods
│ ├── IMethodHandler.php
│ ├── call
│ │ ├── call.php
│ │ └── helpers
│ │ │ ├── callHelper.php
│ │ │ ├── routeHelper.php
│ │ │ ├── serializeArray.php
│ │ │ ├── serializeMethodResult.php
│ │ │ ├── serializeObject.php
│ │ │ └── validateParameters.php
│ ├── discover
│ │ ├── discover.php
│ │ └── helpers
│ │ │ ├── discoverMethods.php
│ │ │ ├── discoverObjects.php
│ │ │ └── updateHtaccess.php
│ └── handler.php
├── net
│ └── httpUtils.php
├── settings.php
├── utils
│ ├── arrayUtils.php
│ └── routeUtils.php
└── xml
│ ├── xmlParser.php
│ └── xmlParserUtils.php
└── tests
├── bootstrap.php
├── configuration
├── restConfigurationLoaderTest.php
├── restConfigurationTest.php
└── restMethodTest.php
├── json
├── jsonImplTest.php
└── jsonUtilsTest.php
├── methods
├── call
│ └── helpers
│ │ ├── callHelperTest.php
│ │ ├── test.xml
│ │ ├── test2.xml
│ │ ├── test3.xml
│ │ ├── test4.xml
│ │ ├── test5.xml
│ │ ├── test6.xml
│ │ └── test7.xml
└── discover
│ └── discoverTest.php
├── net
└── httpUtilsTest.php
├── phpunit.CI.xml
├── phpunit.xml
└── utils
└── arrayUtilsTest.php
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
663 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Mashape PHP Server Library v0.8
2 |
3 | **[Deprecated]**: This project is not being maintained anymore.
4 |
5 | The Mashape PHP Library is:
6 | * it's a dead simple PHP framework for generating RESTful APIs
7 | * it supports everything from custom routes to custom errors, following the DRY (Don't Repeat Yourself) principle: reuse your existing code
8 | * it's fully integrated with Mashape: distribute your components, get traction and make money!
9 |
10 | For the complete documentation, please visit http://www.mashape.com/guide/publish/php
11 |
12 | Copyright (C) 2011 Mashape, Inc.
13 |
--------------------------------------------------------------------------------
/api.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/mashape/configuration/helpers/loadMethods.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../../xml/xmlParser.php");
28 | require_once(dirname(__FILE__) . "/../../xml/xmlParserUtils.php");
29 | require_once(dirname(__FILE__) . "/../../exceptions/mashapeException.php");
30 | require_once(dirname(__FILE__) . "/../restMethod.php");
31 |
32 | define("XML_METHOD", "method");
33 | define("XML_METHOD_NAME", "name");
34 | define("XML_METHOD_HTTP", "http");
35 | define("XML_METHOD_ROUTE", "route");
36 |
37 | define("XML_RESULT", "result");
38 | define("XML_RESULT_ARRAY", "array");
39 | define("XML_RESULT_TYPE", "type");
40 | define("XML_RESULT_NAME", "name");
41 |
42 | function loadMethodsFromXML($xmlParser) {
43 | $methods = array();
44 |
45 | $xmlMethods = XmlParserUtils::getChildren($xmlParser->document, XML_METHOD);
46 |
47 | foreach ($xmlMethods as $xmlMethod) {
48 | $name = (XmlParserUtils::existAttribute($xmlMethod, XML_METHOD_NAME)) ? $xmlMethod->tagAttrs[XML_METHOD_NAME] : null;
49 |
50 | if (empty($name)) {
51 | throw new MashapeException(EXCEPTION_METHOD_EMPTY_NAME, EXCEPTION_XML_CODE);
52 | } else if (existMethod($methods, $name)) {
53 | throw new MashapeException(sprintf(EXCEPTION_METHOD_DUPLICATE_NAME, $name), EXCEPTION_XML_CODE);
54 | }
55 |
56 | $http = (XmlParserUtils::existAttribute($xmlMethod, XML_METHOD_HTTP)) ? $xmlMethod->tagAttrs[XML_METHOD_HTTP] : null;
57 | if (empty($http)) {
58 | throw new MashapeException(EXCEPTION_METHOD_EMPTY_HTTP, EXCEPTION_XML_CODE);
59 | } else {
60 | $http = strtolower($http);
61 | if ($http != "get" && $http != "post" && $http != "put" && $http != "delete") {
62 | throw new MashapeException(sprintf(EXCEPTION_METHOD_INVALID_HTTP, $http),EXCEPTION_XML_CODE);
63 | }
64 | }
65 |
66 | $route = (XmlParserUtils::existAttribute($xmlMethod, XML_METHOD_ROUTE)) ? $xmlMethod->tagAttrs[XML_METHOD_ROUTE] : null;
67 | if (!empty($route)) {
68 | if (!validateRoute($route)) {
69 | throw new MashapeException(sprintf(EXCEPTION_METHOD_INVALID_ROUTE, $route),EXCEPTION_XML_CODE);
70 | } else {
71 | if (existRoute($methods, $route, $http)) {
72 | throw new MashapeException(sprintf(EXCEPTION_METHOD_DUPLICATE_ROUTE, $route), EXCEPTION_XML_CODE);
73 | }
74 | }
75 | }
76 |
77 | // Get the result
78 | $resultsNode = XmlParserUtils::getChildren($xmlMethod, "result"); //$xmlMethod->result;
79 |
80 | $resultNode = null;
81 | if (count($resultsNode) > 1) {
82 | throw new MashapeException(sprintf(EXCEPTION_RESULT_MULTIPLE, $name), EXCEPTION_XML_CODE);
83 | } elseif (count($resultsNode)==1) {
84 | $resultNode = $resultsNode[0];
85 | }
86 | // else {
87 | // throw new MashapeException(sprintf(EXCEPTION_RESULT_MISSING, $name), EXCEPTION_XML_CODE);
88 | // }
89 |
90 | $object = null;
91 | $array = null;
92 | $resultName = null;
93 |
94 | if ($resultNode != null) {
95 |
96 | $array = (XmlParserUtils::existAttribute($resultNode, XML_RESULT_ARRAY)) ? $resultNode->tagAttrs[XML_RESULT_ARRAY] : null;
97 | if ($array != null && strtolower($array) == "true") {
98 | $array = true;
99 | } else {
100 | $array = false;
101 | }
102 |
103 | $type = (XmlParserUtils::existAttribute($resultNode, XML_RESULT_TYPE)) ? $resultNode->tagAttrs[XML_RESULT_TYPE] : null;
104 | if (strtolower($type=="simple")) {
105 | $resultName = (XmlParserUtils::existAttribute($resultNode, XML_RESULT_NAME)) ? $resultNode->tagAttrs[XML_RESULT_NAME] : null;
106 | if (empty($resultName)) {
107 | throw new MashapeException(sprintf(EXCEPTION_RESULT_EMPTY_NAME_SIMPLE, $name), EXCEPTION_XML_CODE);
108 | }
109 | } else if (strtolower($type=="complex")) {
110 | $object = (XmlParserUtils::existAttribute($resultNode, XML_RESULT_NAME)) ? $resultNode->tagAttrs[XML_RESULT_NAME] : null;
111 | if (empty($object)) {
112 | throw new MashapeException(sprintf(EXCEPTION_RESULT_EMPTY_NAME_OBJECT, $name), EXCEPTION_XML_CODE);
113 | }
114 | } else if (empty($type)) {
115 | throw new MashapeException(sprintf(EXCEPTION_RESULT_EMPTY_TYPE, $name), EXCEPTION_XML_CODE);
116 | } else {
117 | throw new MashapeException(sprintf(EXCEPTION_RESULT_INVALID_TYPE, $type, $name), EXCEPTION_XML_CODE);
118 | }
119 | }
120 |
121 | $method = new RESTMethod();
122 | $method->setName($name);
123 | $method->setObject($object);
124 | $method->setResult($resultName);
125 | $method->setArray($array);
126 | $method->setHttp($http);
127 | $method->setRoute($route);
128 |
129 | //Save method
130 | array_push($methods, $method);
131 |
132 | }
133 | return $methods;
134 | }
135 |
136 | function validateRoute($route) {
137 | if (preg_match("/^(\/((\w+)|(\{\w+\})))+$/", $route)) {
138 | return true;
139 | } else {
140 | return false;
141 | }
142 | }
143 |
144 | function existRoute($methods, $route, $http) {
145 | foreach ($methods as $method) {
146 | if ($method->getRoute() == $route && $method->getHttp() == $http) {
147 | return true;
148 | }
149 | }
150 | return false;
151 | }
152 |
153 | function existMethod($methods, $name) {
154 | foreach ($methods as $method) {
155 | if ($method->getName() == $name) {
156 | return true;
157 | }
158 | }
159 | return false;
160 | }
161 |
--------------------------------------------------------------------------------
/mashape/configuration/helpers/loadObjects.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../../xml/xmlParser.php");
28 | require_once(dirname(__FILE__) . "/../../xml/xmlParserUtils.php");
29 | require_once(dirname(__FILE__) . "/../../exceptions/mashapeException.php");
30 | require_once(dirname(__FILE__) . "/../restField.php");
31 | require_once(dirname(__FILE__) . "/../restObject.php");
32 |
33 | define("XML_OBJECT", "object");
34 | define("XML_OBJECT_CLASS", "class");
35 |
36 | define("XML_FIELD", "field");
37 | define("XML_FIELD_OBJECT", "object");
38 | define("XML_FIELD_METHOD", "method");
39 | define("XML_FIELD_ARRAY", "array");
40 | define("XML_FIELD_OPTIONAL", "optional");
41 |
42 | function loadObjectsFromXML($xmlParser) {
43 | $objects = array();
44 |
45 | $xmlObjects = XmlParserUtils::getChildren($xmlParser->document, XML_OBJECT);
46 | foreach($xmlObjects as $xmlObject)
47 | {
48 | $className = (XmlParserUtils::existAttribute($xmlObject, XML_OBJECT_CLASS)) ? $xmlObject->tagAttrs[XML_OBJECT_CLASS] : null;
49 | if (empty($className)) {
50 | throw new MashapeException(EXCEPTION_OBJECT_EMPTY_CLASS, EXCEPTION_XML_CODE);
51 | } else if (existClassName($objects, $className)) {
52 | throw new MashapeException(sprintf(EXCEPTION_OBJECT_DUPLICATE_CLASS, $className), EXCEPTION_XML_CODE);
53 | }
54 |
55 | //Get fields
56 | $fields = array();
57 | $xmlFields = XmlParserUtils::getChildren($xmlObject, XML_FIELD);
58 | if (empty($xmlFields)) {
59 | throw new MashapeException(sprintf(EXCEPTION_EMPTY_FIELDS, $className), EXCEPTION_XML_CODE);
60 | }
61 | foreach($xmlFields as $xmlField)
62 | {
63 | $field_name = $xmlField->tagData;
64 | if (empty($field_name)) {
65 | throw new MashapeException(EXCEPTION_FIELD_EMPTY_NAME, EXCEPTION_XML_CODE);
66 | } else if (existFieldName($fields, $field_name)) {
67 | throw new MashapeException(sprintf(EXCEPTION_FIELD_NAME_DUPLICATE, $field_name, $className), EXCEPTION_XML_CODE);
68 | }
69 |
70 | $field_object = (XmlParserUtils::existAttribute($xmlField, XML_FIELD_OBJECT)) ? $xmlField->tagAttrs[XML_FIELD_OBJECT] : null;
71 | $field_method = (XmlParserUtils::existAttribute($xmlField, XML_FIELD_METHOD)) ? $xmlField->tagAttrs[XML_FIELD_METHOD] : null;
72 |
73 | $field_array = (XmlParserUtils::existAttribute($xmlField, XML_FIELD_ARRAY)) ? $xmlField->tagAttrs[XML_FIELD_ARRAY] : null;
74 | if ($field_array != null && strtolower($field_array) == "true") {
75 | $field_array = true;
76 | } else {
77 | $field_array = false;
78 | }
79 |
80 | $field_optional = (XmlParserUtils::existAttribute($xmlField, XML_FIELD_OPTIONAL)) ? $xmlField->tagAttrs[XML_FIELD_OPTIONAL] : null;
81 | if ($field_optional != null && strtolower($field_optional) == "true") {
82 | $field_optional = true;
83 | } else {
84 | $field_optional = false;
85 | }
86 |
87 | $field = new RESTField();
88 | $field->setName($field_name);
89 | $field->setObject($field_object);
90 | $field->setMethod($field_method);
91 | $field->setArray($field_array);
92 | $field->setOptional($field_optional);
93 | array_push($fields, $field);
94 | }
95 |
96 | $object = new RESTObject();
97 | $object->setClassName($className);
98 | $object->setFields($fields);
99 | array_push($objects, $object);
100 | }
101 | return $objects;
102 | }
103 |
104 | function existClassName($objects, $className) {
105 | foreach ($objects as $object) {
106 | if ($object->getClassName() == $className) {
107 | return true;
108 | }
109 | }
110 | return false;
111 | }
112 |
113 | function existFieldName($fields, $fieldName) {
114 | foreach ($fields as $field) {
115 | if ($field->getName() == $fieldName) {
116 | return true;
117 | }
118 | }
119 | return false;
120 | }
121 |
--------------------------------------------------------------------------------
/mashape/configuration/restConfiguration.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | class RESTConfiguration {
28 | private $methods;
29 | private $objects;
30 |
31 | public function getMethods() {
32 | return $this->methods;
33 | }
34 | public function getObjects() {
35 | return $this->objects;
36 | }
37 | public function setMethods($x) {
38 | $this->methods = $x;
39 | }
40 | public function setObjects($x) {
41 | $this->objects = $x;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/mashape/configuration/restConfigurationLoader.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../settings.php");
28 | require_once(dirname(__FILE__) . "/../init/init.php");
29 | require_once(dirname(__FILE__) . "/../xml/xmlParser.php");
30 | require_once(dirname(__FILE__) . "/../xml/xmlParserUtils.php");
31 | require_once(dirname(__FILE__) . "/helpers/loadMethods.php");
32 | require_once(dirname(__FILE__) . "/helpers/loadObjects.php");
33 | require_once(dirname(__FILE__) . "/restConfiguration.php");
34 |
35 | class RESTConfigurationLoader {
36 |
37 | private static function getSessionVarName($serverKey) {
38 | return SESSION_VARNAME . $serverKey;
39 | }
40 |
41 | public static function reloadConfiguration($serverKey, $path=CONFIGURATION_FILEPATH) {
42 | $sessionVarName = self::getSessionVarName($serverKey);
43 | $_SESSION[$sessionVarName] = null;
44 | return self::loadConfiguration($serverKey, $path);
45 | }
46 |
47 | public static function loadConfiguration($serverKey, $path=CONFIGURATION_FILEPATH) {
48 | $sessionVarName = self::getSessionVarName($serverKey);
49 | $configuration = null;
50 | if (isset($_SESSION[$sessionVarName]) && empty($_SESSION[$sessionVarName]) == false) {
51 | $configuration = unserialize($_SESSION[$sessionVarName]);
52 | } else {
53 | $configuration = self::init($path);
54 | $_SESSION[$sessionVarName] = serialize($configuration);
55 | }
56 | return $configuration;
57 | }
58 |
59 | public static function getMethod($methodName, $serverKey) {
60 | $methods = self::loadConfiguration($serverKey)->getMethods();
61 | foreach ($methods as $method) {
62 | if ($method->getName() == $methodName) {
63 | return $method;
64 | }
65 | }
66 | return null;
67 | }
68 |
69 | public static function getObject($className, $serverKey) {
70 | $objects = self::loadConfiguration($serverKey)->getObjects();
71 | foreach ($objects as $object) {
72 | if ($object->getClassName() == $className) {
73 | return $object;
74 | }
75 | }
76 | return null;
77 | }
78 |
79 | private static function init($path) {
80 | $xmlParser = self::getXmlDoc($path);
81 |
82 | // Load Methods
83 | $methods = loadMethodsFromXML($xmlParser);
84 |
85 | // Load Objects
86 | $objects = loadObjectsFromXML($xmlParser);
87 |
88 | $result = new RESTConfiguration();
89 | $result->setMethods($methods);
90 | $result->setObjects($objects);
91 | return $result;
92 | }
93 |
94 | private static function getXmlDoc($path) {
95 | if (file_exists($path)) {
96 | $xml = file_get_contents($path);
97 | $xmlParser = new XMLParser($xml);
98 | $xmlParser->Parse();
99 | return $xmlParser;
100 | } else {
101 | throw new MashapeException(sprintf(EXCEPTION_CONFIGURATION_FILE_NOTFOUND, $path), EXCEPTION_XML_CODE);
102 | }
103 | }
104 |
105 | }
106 |
--------------------------------------------------------------------------------
/mashape/configuration/restField.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | class RESTField {
28 | private $name;
29 | private $object;
30 | private $method;
31 | private $array;
32 | private $optional;
33 |
34 | public function getName() {
35 | return $this->name;
36 | }
37 | public function getObject() {
38 | return $this->object;
39 | }
40 | public function getMethod() {
41 | return $this->method;
42 | }
43 | public function isArray() {
44 | return $this->array;
45 | }
46 | public function isOptional() {
47 | return $this->optional;
48 | }
49 | public function setName($x) {
50 | $this->name = $x;
51 | }
52 | public function setObject($x) {
53 | $this->object = $x;
54 | }
55 | public function setMethod($x) {
56 | $this->method = $x;
57 | }
58 | public function setArray($x) {
59 | $this->array = $x;
60 | }
61 | public function setOptional($x) {
62 | $this->optional = $x;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/mashape/configuration/restMethod.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | class RESTMethod {
28 | private $object;
29 | private $result;
30 | private $name;
31 | private $array;
32 | private $http;
33 | private $route;
34 |
35 | public function getObject() {
36 | return $this->object;
37 | }
38 | public function getResult() {
39 | return $this->result;
40 | }
41 | public function getName() {
42 | return $this->name;
43 | }
44 | public function getHttp() {
45 | return $this->http;
46 | }
47 | public function getRoute() {
48 | return $this->route;
49 | }
50 | public function setObject($x) {
51 | $this->object = $x;
52 | }
53 | public function setRoute($x) {
54 | $this->route = $x;
55 | }
56 | public function setResult($x) {
57 | $this->result = $x;
58 | }
59 | public function setName($x) {
60 | $this->name = $x;
61 | }
62 | public function setHttp($x) {
63 | $this->http = $x;
64 | }
65 | public function setArray($x) {
66 | $this->array = $x;
67 | }
68 | public function isArray() {
69 | return $this->array;
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/mashape/configuration/restObject.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | class RESTObject {
28 | private $className;
29 | private $fields;
30 |
31 | public function getClassName() {
32 | return $this->className;
33 | }
34 | public function getFields() {
35 | return $this->fields;
36 | }
37 | public function setClassName($x) {
38 | $this->className = $x;
39 | }
40 | public function setFields($x) {
41 | $this->fields = $x;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/mashape/exceptions/exceptionMessages.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | define("EXCEPTION_GENERIC_LIBRARY_ERROR_CODE", 1000);
28 | define("EXCEPTION_EXPECTED_ARRAY_RESULT_SIMPLE", "The result value it's not an array although it's described it would have been an array, please check your XML file");
29 | define("EXCEPTION_EXPECTED_ARRAY_RESULT", "The result value of field \"%s\" in object \"%s\" it's not an array although it's described it would have been an array, please check your XML file");
30 | define("EXCEPTION_UNEXPECTED_ARRAY_RESULT_SIMPLE", "The result value it's an array although it was described it wouldn't have been an array, please check your XML file");
31 | define("EXCEPTION_UNEXPECTED_ARRAY_RESULT", "The result value of field \"%s\" in object \"%s\" it's an array although it was described it wouldn't have been an array, please check your XML file");
32 | define("EXCEPTION_UNKNOWN_OBJECT", "The result can't be serialized because it's of an unknown type \"%s\" not described in the XML file");
33 |
34 | define("EXCEPTION_XML_CODE", 1001);
35 | // Error messages for XML configuration
36 | define("EXCEPTION_CONFIGURATION_FILE_NOTFOUND", "Can't find the XML configuration file (path: \"%s\"). Please check that the path is valid and it exists");
37 | define("EXCEPTION_METHOD_EMPTY_NAME", "Methods can't have an empty \"name\" attribute");
38 | define("EXCEPTION_METHOD_DUPLICATE_NAME", "A method with name \"%s\" has already been described");
39 | define("EXCEPTION_METHOD_DUPLICATE_ROUTE", "A method with route \"%s\" has already been described");
40 | define("EXCEPTION_METHOD_EMPTY_HTTP", "Methods can't have an empty \"http\" attribute");
41 | define("EXCEPTION_METHOD_INVALID_HTTP", "Http method \"%s\" not supported");
42 | define("EXCEPTION_METHOD_INVALID_ROUTE", "Route \"%s\" is invalid");
43 | define("EXCEPTION_METHOD_INVALID_ROUTE_PARAM", "Can't find the route param \"%s\" in the method signature");
44 | define("EXCEPTION_METHOD_OPTIONAL_ROUTE_PARAM", "You can't set the optional parameter \"%s\" belonging to the method \"%s\" as a route parameter. Optional parameters should never been included in a route URL");
45 | define("EXCEPTION_RESULT_MULTIPLE", "The method \"%s\" has multiple result nodes. Only one is allowed");
46 | define("EXCEPTION_RESULT_MISSING", "The method \"%s\" requires a result child element");
47 | define("EXCEPTION_RESULT_EMPTY_TYPE", "Please enter a result \"type\" attribute for method \"%s\"");
48 | define("EXCEPTION_RESULT_EMPTY_NAME_SIMPLE", "Please enter a result \"name\" attribute for method \"%s\", that is the name of the field that will contain the result value");
49 | define("EXCEPTION_RESULT_EMPTY_NAME_OBJECT", "Please enter a result \"name\" attribute for method \"%s\", that is the class name belonging to the object that will represent the result value");
50 | define("EXCEPTION_RESULT_INVALID_TYPE", "Invalid result type \"%s\" for method \"%s\"");
51 | define("EXCEPTION_OBJECT_EMPTY_CLASS", "Objects can't have an empty \"class\" attribute");
52 | define("EXCEPTION_OBJECT_DUPLICATE_CLASS", "An object with class \"%s\" has already been described");
53 | define("EXCEPTION_EMPTY_FIELDS", "Please add at least one field to object: %s");
54 | define("EXCEPTION_FIELD_EMPTY_NAME", "Fields can't have an empty \"name\" attribute");
55 | define("EXCEPTION_FIELD_NAME_DUPLICATE", "A field with name \"%s\" has already been described for object \"%s\"");
56 | define("EXCEPTION_EMPTY_SERVERKEY", "The server-key is missing");
57 | define("EXCEPTION_MISSING_OBJECTS", "Missing XML description for objects: %s");
58 |
59 | define("EXCEPTION_INVALID_HTTPMETHOD_CODE", 1002);
60 | define("EXCEPTION_INVALID_HTTPMETHOD", "The requested method doesn't support this HTTP Method provided");
61 |
62 | define("EXCEPTION_NOTSUPPORTED_HTTPMETHOD_CODE", 1003);
63 | define("EXCEPTION_NOTSUPPORTED_HTTPMETHOD", "Http Method not supported. Only DELETE, GET, POST, PUT are supported");
64 |
65 | define("EXCEPTION_NOTSUPPORTED_OPERATION_CODE", 1004);
66 | define("EXCEPTION_NOTSUPPORTED_OPERATION", "Operation not supported");
67 |
68 | define("EXCEPTION_METHOD_NOTFOUND_CODE", 1006);
69 | define("EXCEPTION_METHOD_NOTFOUND", "The method requested was not found: \"%s\"");
70 |
71 | define("EXCEPTION_AUTH_INVALID_CODE", 1007);
72 | define("EXCEPTION_AUTH_INVALID", "The request has not been authorized");
73 |
74 | define("EXCEPTION_AUTH_INVALID_SERVERKEY_CODE", 1005);
75 | define("EXCEPTION_AUTH_INVALID_SERVERKEY", "The request can't be authenticated because the server key sent for the request, and the one set in your implementation, don't match");
76 |
77 | define("EXCEPTION_REQUIRED_PARAMETERS_CODE", 1008);
78 | define("EXCEPTION_REQUIRED_PARAMETERS", "Some parameters required by the method are missing");
79 |
80 | define("EXCEPTION_REQUIRED_PARAMETER", "Missing required parameter \"%s\"");
81 |
82 | // http://api.mashape.com Error codes
83 |
84 | define("EXCEPTION_FIELD_NOTFOUND", "Can't find the property \"%s\"");
85 | define("EXCEPTION_INSTANCE_NULL", "Please verify the class you're initializing with 'MashapeHandler::handleApi(..)' exists");
86 | define("EXCEPTION_EMPTY_REQUEST", "A request attempt was made to Mashape, but the response was empty. The firewall may be blocking outbound HTTP requests");
87 | define("EXCEPTION_JSONDECODE_REQUEST", "Can't deserialize the response JSON from Mashape. The json_decode function is missing on server");
88 | define("EXCEPTION_INVALID_CALLBACK", "Invalid function name set as a callback");
89 | define("EXCEPTION_INVALID_PERMISSION", "File permission denied: can't create and write to the file %s");
90 | define("EXCEPTION_AMBIGUOUS_ROUTE", "Some routes are ambiguous and very similar, please verify the methods: %s");
91 |
92 | define("EXCEPTION_INVALID_APIKEY_CODE", 2001);
93 | define("EXCEPTION_EXCEEDED_LIMIT_CODE", 2002);
94 | define("EXCEPTION_SYSTEM_ERROR_CODE", 2000);
95 |
--------------------------------------------------------------------------------
/mashape/exceptions/mashapeException.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/exceptionMessages.php");
28 |
29 | class MashapeException extends Exception {
30 |
31 | function __construct($message, $code) {
32 | parent::__construct($message, $code);
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/mashape/init/headers.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | if(!function_exists('apache_request_headers')) {
28 | function apache_request_headers() {
29 | $headers = array();
30 | foreach($_SERVER as $key => $value) {
31 | if(substr($key, 0, 5) == 'HTTP_') {
32 | $headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
33 | }
34 | }
35 | return $headers;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/mashape/init/init.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/headers.php");
28 | require_once(dirname(__FILE__) . "/session.php");
29 | require_once(dirname(__FILE__) . "/../settings.php");
30 | require_once(dirname(__FILE__) . "/json.php");
31 | require_once(dirname(__FILE__) . "/../exceptions/mashapeException.php");
32 |
33 | define("LIBRARY_LANGUAGE", "PHP");
34 | define("LIBRARY_VERSION", "V07");
35 |
--------------------------------------------------------------------------------
/mashape/init/json.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | if (!function_exists('json_decode')) {
28 | function json_decode($content, $assoc=false) {
29 | require_once(dirname(__FILE__) . "/../json/jsonImpl.php");
30 | if ($assoc) {
31 | $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
32 | }
33 | else {
34 | $json = new Services_JSON;
35 | }
36 | return $json->decode($content);
37 | }
38 | }
39 |
40 | if (!function_exists('json_encode')) {
41 | function json_encode($content, $assoc=false) {
42 | require_once(dirname(__FILE__) . "/../json/jsonImpl.php");
43 | if ($assoc) {
44 | $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
45 | }
46 | else {
47 | $json = new Services_JSON;
48 | }
49 | return $json->encode($content);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/mashape/init/session.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | // Start the session. If already started do nothing.
28 | if (!session_id()) session_start();
29 |
--------------------------------------------------------------------------------
/mashape/json/jsonImpl.php:
--------------------------------------------------------------------------------
1 |
51 | * @author Matt Knapp
52 | * @author Brett Stimmerman
53 | * @copyright 2005 Michal Migurski
54 | * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
55 | * @license http://www.opensource.org/licenses/bsd-license.php
56 | * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
57 | */
58 |
59 | /**
60 | * Marker constant for Services_JSON::decode(), used to flag stack state
61 | */
62 | define('SERVICES_JSON_SLICE', 1);
63 |
64 | /**
65 | * Marker constant for Services_JSON::decode(), used to flag stack state
66 | */
67 | define('SERVICES_JSON_IN_STR', 2);
68 |
69 | /**
70 | * Marker constant for Services_JSON::decode(), used to flag stack state
71 | */
72 | define('SERVICES_JSON_IN_ARR', 3);
73 |
74 | /**
75 | * Marker constant for Services_JSON::decode(), used to flag stack state
76 | */
77 | define('SERVICES_JSON_IN_OBJ', 4);
78 |
79 | /**
80 | * Marker constant for Services_JSON::decode(), used to flag stack state
81 | */
82 | define('SERVICES_JSON_IN_CMT', 5);
83 |
84 | /**
85 | * Behavior switch for Services_JSON::decode()
86 | */
87 | define('SERVICES_JSON_LOOSE_TYPE', 16);
88 |
89 | /**
90 | * Behavior switch for Services_JSON::decode()
91 | */
92 | define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
93 |
94 | /**
95 | * Converts to and from JSON format.
96 | *
97 | * Brief example of use:
98 | *
99 | *
100 | * // create a new instance of Services_JSON
101 | * $json = new Services_JSON();
102 | *
103 | * // convert a complexe value to JSON notation, and send it to the browser
104 | * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
105 | * $output = $json->encode($value);
106 | *
107 | * print($output);
108 | * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
109 | *
110 | * // accept incoming POST data, assumed to be in JSON notation
111 | * $input = file_get_contents('php://input', 1000000);
112 | * $value = $json->decode($input);
113 | *
114 | */
115 | class Services_JSON
116 | {
117 | /**
118 | * constructs a new JSON instance
119 | *
120 | * @param int $use object behavior flags; combine with boolean-OR
121 | *
122 | * possible values:
123 | * - SERVICES_JSON_LOOSE_TYPE: loose typing.
124 | * "{...}" syntax creates associative arrays
125 | * instead of objects in decode().
126 | * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
127 | * Values which can't be encoded (e.g. resources)
128 | * appear as NULL instead of throwing errors.
129 | * By default, a deeply-nested resource will
130 | * bubble up with an error, so all return values
131 | * from encode() should be checked with isError()
132 | */
133 | function Services_JSON($use = 0)
134 | {
135 | $this->use = $use;
136 | }
137 |
138 | /**
139 | * convert a string from one UTF-16 char to one UTF-8 char
140 | *
141 | * Normally should be handled by mb_convert_encoding, but
142 | * provides a slower PHP-only method for installations
143 | * that lack the multibye string extension.
144 | *
145 | * @param string $utf16 UTF-16 character
146 | * @return string UTF-8 character
147 | * @access private
148 | */
149 | function utf162utf8($utf16)
150 | {
151 | // oh please oh please oh please oh please oh please
152 | if(function_exists('mb_convert_encoding')) {
153 | return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
154 | }
155 |
156 | $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
157 |
158 | switch(true) {
159 | case ((0x7F & $bytes) == $bytes):
160 | // this case should never be reached, because we are in ASCII range
161 | // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
162 | return chr(0x7F & $bytes);
163 |
164 | case (0x07FF & $bytes) == $bytes:
165 | // return a 2-byte UTF-8 character
166 | // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
167 | return chr(0xC0 | (($bytes >> 6) & 0x1F))
168 | . chr(0x80 | ($bytes & 0x3F));
169 |
170 | case (0xFFFF & $bytes) == $bytes:
171 | // return a 3-byte UTF-8 character
172 | // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
173 | return chr(0xE0 | (($bytes >> 12) & 0x0F))
174 | . chr(0x80 | (($bytes >> 6) & 0x3F))
175 | . chr(0x80 | ($bytes & 0x3F));
176 | }
177 |
178 | // ignoring UTF-32 for now, sorry
179 | return '';
180 | }
181 |
182 | /**
183 | * convert a string from one UTF-8 char to one UTF-16 char
184 | *
185 | * Normally should be handled by mb_convert_encoding, but
186 | * provides a slower PHP-only method for installations
187 | * that lack the multibye string extension.
188 | *
189 | * @param string $utf8 UTF-8 character
190 | * @return string UTF-16 character
191 | * @access private
192 | */
193 | function utf82utf16($utf8)
194 | {
195 | // oh please oh please oh please oh please oh please
196 | if(function_exists('mb_convert_encoding')) {
197 | return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
198 | }
199 |
200 | switch(strlen($utf8)) {
201 | case 1:
202 | // this case should never be reached, because we are in ASCII range
203 | // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
204 | return $utf8;
205 |
206 | case 2:
207 | // return a UTF-16 character from a 2-byte UTF-8 char
208 | // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
209 | return chr(0x07 & (ord($utf8{0}) >> 2))
210 | . chr((0xC0 & (ord($utf8{0}) << 6))
211 | | (0x3F & ord($utf8{1})));
212 |
213 | case 3:
214 | // return a UTF-16 character from a 3-byte UTF-8 char
215 | // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
216 | return chr((0xF0 & (ord($utf8{0}) << 4))
217 | | (0x0F & (ord($utf8{1}) >> 2)))
218 | . chr((0xC0 & (ord($utf8{1}) << 6))
219 | | (0x7F & ord($utf8{2})));
220 | }
221 |
222 | // ignoring UTF-32 for now, sorry
223 | return '';
224 | }
225 |
226 | /**
227 | * encodes an arbitrary variable into JSON format
228 | *
229 | * @param mixed $var any number, boolean, string, array, or object to be encoded.
230 | * see argument 1 to Services_JSON() above for array-parsing behavior.
231 | * if var is a strng, note that encode() always expects it
232 | * to be in ASCII or UTF-8 format!
233 | *
234 | * @return mixed JSON string representation of input var or an error if a problem occurs
235 | * @access public
236 | */
237 | function encode($var)
238 | {
239 | switch (gettype($var)) {
240 | case 'boolean':
241 | return $var ? 'true' : 'false';
242 |
243 | case 'NULL':
244 | return 'null';
245 |
246 | case 'integer':
247 | return (int) $var;
248 |
249 | case 'double':
250 | case 'float':
251 | return (float) $var;
252 |
253 | case 'string':
254 | // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
255 | $ascii = '';
256 | $strlen_var = strlen($var);
257 |
258 | /*
259 | * Iterate over every character in the string,
260 | * escaping with a slash or encoding to UTF-8 where necessary
261 | */
262 | for ($c = 0; $c < $strlen_var; ++$c) {
263 |
264 | $ord_var_c = ord($var{$c});
265 |
266 | switch (true) {
267 | case $ord_var_c == 0x08:
268 | $ascii .= '\b';
269 | break;
270 | case $ord_var_c == 0x09:
271 | $ascii .= '\t';
272 | break;
273 | case $ord_var_c == 0x0A:
274 | $ascii .= '\n';
275 | break;
276 | case $ord_var_c == 0x0C:
277 | $ascii .= '\f';
278 | break;
279 | case $ord_var_c == 0x0D:
280 | $ascii .= '\r';
281 | break;
282 |
283 | case $ord_var_c == 0x22:
284 | case $ord_var_c == 0x2F:
285 | case $ord_var_c == 0x5C:
286 | // double quote, slash, slosh
287 | $ascii .= '\\'.$var{$c};
288 | break;
289 |
290 | case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
291 | // characters U-00000000 - U-0000007F (same as ASCII)
292 | $ascii .= $var{$c};
293 | break;
294 |
295 | case (($ord_var_c & 0xE0) == 0xC0):
296 | // characters U-00000080 - U-000007FF, mask 110XXXXX
297 | // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
298 | $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
299 | $c += 1;
300 | $utf16 = $this->utf82utf16($char);
301 | $ascii .= sprintf('\u%04s', bin2hex($utf16));
302 | break;
303 |
304 | case (($ord_var_c & 0xF0) == 0xE0):
305 | // characters U-00000800 - U-0000FFFF, mask 1110XXXX
306 | // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
307 | $char = pack('C*', $ord_var_c,
308 | ord($var{$c + 1}),
309 | ord($var{$c + 2}));
310 | $c += 2;
311 | $utf16 = $this->utf82utf16($char);
312 | $ascii .= sprintf('\u%04s', bin2hex($utf16));
313 | break;
314 |
315 | case (($ord_var_c & 0xF8) == 0xF0):
316 | // characters U-00010000 - U-001FFFFF, mask 11110XXX
317 | // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
318 | $char = pack('C*', $ord_var_c,
319 | ord($var{$c + 1}),
320 | ord($var{$c + 2}),
321 | ord($var{$c + 3}));
322 | $c += 3;
323 | $utf16 = $this->utf82utf16($char);
324 | $ascii .= sprintf('\u%04s', bin2hex($utf16));
325 | break;
326 |
327 | case (($ord_var_c & 0xFC) == 0xF8):
328 | // characters U-00200000 - U-03FFFFFF, mask 111110XX
329 | // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
330 | $char = pack('C*', $ord_var_c,
331 | ord($var{$c + 1}),
332 | ord($var{$c + 2}),
333 | ord($var{$c + 3}),
334 | ord($var{$c + 4}));
335 | $c += 4;
336 | $utf16 = $this->utf82utf16($char);
337 | $ascii .= sprintf('\u%04s', bin2hex($utf16));
338 | break;
339 |
340 | case (($ord_var_c & 0xFE) == 0xFC):
341 | // characters U-04000000 - U-7FFFFFFF, mask 1111110X
342 | // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
343 | $char = pack('C*', $ord_var_c,
344 | ord($var{$c + 1}),
345 | ord($var{$c + 2}),
346 | ord($var{$c + 3}),
347 | ord($var{$c + 4}),
348 | ord($var{$c + 5}));
349 | $c += 5;
350 | $utf16 = $this->utf82utf16($char);
351 | $ascii .= sprintf('\u%04s', bin2hex($utf16));
352 | break;
353 | }
354 | }
355 |
356 | return '"'.$ascii.'"';
357 |
358 | case 'array':
359 | /*
360 | * As per JSON spec if any array key is not an integer
361 | * we must treat the the whole array as an object. We
362 | * also try to catch a sparsely populated associative
363 | * array with numeric keys here because some JS engines
364 | * will create an array with empty indexes up to
365 | * max_index which can cause memory issues and because
366 | * the keys, which may be relevant, will be remapped
367 | * otherwise.
368 | *
369 | * As per the ECMA and JSON specification an object may
370 | * have any string as a property. Unfortunately due to
371 | * a hole in the ECMA specification if the key is a
372 | * ECMA reserved word or starts with a digit the
373 | * parameter is only accessible using ECMAScript's
374 | * bracket notation.
375 | */
376 |
377 | // treat as a JSON object
378 | if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
379 | $properties = array_map(array($this, 'name_value'),
380 | array_keys($var),
381 | array_values($var));
382 |
383 | foreach($properties as $property) {
384 | if(Services_JSON::isError($property)) {
385 | return $property;
386 | }
387 | }
388 |
389 | return '{' . join(',', $properties) . '}';
390 | }
391 |
392 | // treat it like a regular array
393 | $elements = array_map(array($this, 'encode'), $var);
394 |
395 | foreach($elements as $element) {
396 | if(Services_JSON::isError($element)) {
397 | return $element;
398 | }
399 | }
400 |
401 | return '[' . join(',', $elements) . ']';
402 |
403 | case 'object':
404 | $vars = get_object_vars($var);
405 |
406 | $properties = array_map(array($this, 'name_value'),
407 | array_keys($vars),
408 | array_values($vars));
409 |
410 | foreach($properties as $property) {
411 | if(Services_JSON::isError($property)) {
412 | return $property;
413 | }
414 | }
415 |
416 | return '{' . join(',', $properties) . '}';
417 |
418 | default:
419 | return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
420 | ? 'null'
421 | : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
422 | }
423 | }
424 |
425 | /**
426 | * array-walking function for use in generating JSON-formatted name-value pairs
427 | *
428 | * @param string $name name of key to use
429 | * @param mixed $value reference to an array element to be encoded
430 | *
431 | * @return string JSON-formatted name-value pair, like '"name":value'
432 | * @access private
433 | */
434 | function name_value($name, $value)
435 | {
436 | $encoded_value = $this->encode($value);
437 |
438 | if(Services_JSON::isError($encoded_value)) {
439 | return $encoded_value;
440 | }
441 |
442 | return $this->encode(strval($name)) . ':' . $encoded_value;
443 | }
444 |
445 | /**
446 | * reduce a string by removing leading and trailing comments and whitespace
447 | *
448 | * @param $str string string value to strip of comments and whitespace
449 | *
450 | * @return string string value stripped of comments and whitespace
451 | * @access private
452 | */
453 | function reduce_string($str)
454 | {
455 | $str = preg_replace(array(
456 |
457 | // eliminate single line comments in '// ...' form
458 | '#^\s*//(.+)$#m',
459 |
460 | // eliminate multi-line comments in '/* ... */' form, at start of string
461 | '#^\s*/\*(.+)\*/#Us',
462 |
463 | // eliminate multi-line comments in '/* ... */' form, at end of string
464 | '#/\*(.+)\*/\s*$#Us'
465 |
466 | ), '', $str);
467 |
468 | // eliminate extraneous space
469 | return trim($str);
470 | }
471 |
472 | /**
473 | * decodes a JSON string into appropriate variable
474 | *
475 | * @param string $str JSON-formatted string
476 | *
477 | * @return mixed number, boolean, string, array, or object
478 | * corresponding to given JSON input string.
479 | * See argument 1 to Services_JSON() above for object-output behavior.
480 | * Note that decode() always returns strings
481 | * in ASCII or UTF-8 format!
482 | * @access public
483 | */
484 | function decode($str)
485 | {
486 | $str = $this->reduce_string($str);
487 |
488 | switch (strtolower($str)) {
489 | case 'true':
490 | return true;
491 |
492 | case 'false':
493 | return false;
494 |
495 | case 'null':
496 | return null;
497 |
498 | default:
499 | $m = array();
500 |
501 | if (is_numeric($str)) {
502 | // Lookie-loo, it's a number
503 |
504 | // This would work on its own, but I'm trying to be
505 | // good about returning integers where appropriate:
506 | // return (float)$str;
507 |
508 | // Return float or int, as appropriate
509 | return ((float)$str == (integer)$str)
510 | ? (integer)$str
511 | : (float)$str;
512 |
513 | } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
514 | // STRINGS RETURNED IN UTF-8 FORMAT
515 | $delim = substr($str, 0, 1);
516 | $chrs = substr($str, 1, -1);
517 | $utf8 = '';
518 | $strlen_chrs = strlen($chrs);
519 |
520 | for ($c = 0; $c < $strlen_chrs; ++$c) {
521 |
522 | $substr_chrs_c_2 = substr($chrs, $c, 2);
523 | $ord_chrs_c = ord($chrs{$c});
524 |
525 | switch (true) {
526 | case $substr_chrs_c_2 == '\b':
527 | $utf8 .= chr(0x08);
528 | ++$c;
529 | break;
530 | case $substr_chrs_c_2 == '\t':
531 | $utf8 .= chr(0x09);
532 | ++$c;
533 | break;
534 | case $substr_chrs_c_2 == '\n':
535 | $utf8 .= chr(0x0A);
536 | ++$c;
537 | break;
538 | case $substr_chrs_c_2 == '\f':
539 | $utf8 .= chr(0x0C);
540 | ++$c;
541 | break;
542 | case $substr_chrs_c_2 == '\r':
543 | $utf8 .= chr(0x0D);
544 | ++$c;
545 | break;
546 |
547 | case $substr_chrs_c_2 == '\\"':
548 | case $substr_chrs_c_2 == '\\\'':
549 | case $substr_chrs_c_2 == '\\\\':
550 | case $substr_chrs_c_2 == '\\/':
551 | if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
552 | ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
553 | $utf8 .= $chrs{++$c};
554 | }
555 | break;
556 |
557 | case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
558 | // single, escaped unicode character
559 | $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
560 | . chr(hexdec(substr($chrs, ($c + 4), 2)));
561 | $utf8 .= $this->utf162utf8($utf16);
562 | $c += 5;
563 | break;
564 |
565 | case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
566 | $utf8 .= $chrs{$c};
567 | break;
568 |
569 | case ($ord_chrs_c & 0xE0) == 0xC0:
570 | // characters U-00000080 - U-000007FF, mask 110XXXXX
571 | //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
572 | $utf8 .= substr($chrs, $c, 2);
573 | ++$c;
574 | break;
575 |
576 | case ($ord_chrs_c & 0xF0) == 0xE0:
577 | // characters U-00000800 - U-0000FFFF, mask 1110XXXX
578 | // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
579 | $utf8 .= substr($chrs, $c, 3);
580 | $c += 2;
581 | break;
582 |
583 | case ($ord_chrs_c & 0xF8) == 0xF0:
584 | // characters U-00010000 - U-001FFFFF, mask 11110XXX
585 | // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
586 | $utf8 .= substr($chrs, $c, 4);
587 | $c += 3;
588 | break;
589 |
590 | case ($ord_chrs_c & 0xFC) == 0xF8:
591 | // characters U-00200000 - U-03FFFFFF, mask 111110XX
592 | // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
593 | $utf8 .= substr($chrs, $c, 5);
594 | $c += 4;
595 | break;
596 |
597 | case ($ord_chrs_c & 0xFE) == 0xFC:
598 | // characters U-04000000 - U-7FFFFFFF, mask 1111110X
599 | // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
600 | $utf8 .= substr($chrs, $c, 6);
601 | $c += 5;
602 | break;
603 |
604 | }
605 |
606 | }
607 |
608 | return $utf8;
609 |
610 | } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
611 | // array, or object notation
612 |
613 | if ($str{0} == '[') {
614 | $stk = array(SERVICES_JSON_IN_ARR);
615 | $arr = array();
616 | } else {
617 | if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
618 | $stk = array(SERVICES_JSON_IN_OBJ);
619 | $obj = array();
620 | } else {
621 | $stk = array(SERVICES_JSON_IN_OBJ);
622 | $obj = new stdClass();
623 | }
624 | }
625 |
626 | array_push($stk, array('what' => SERVICES_JSON_SLICE,
627 | 'where' => 0,
628 | 'delim' => false));
629 |
630 | $chrs = substr($str, 1, -1);
631 | $chrs = $this->reduce_string($chrs);
632 |
633 | if ($chrs == '') {
634 | if (reset($stk) == SERVICES_JSON_IN_ARR) {
635 | return $arr;
636 |
637 | } else {
638 | return $obj;
639 |
640 | }
641 | }
642 |
643 | //print("\nparsing {$chrs}\n");
644 |
645 | $strlen_chrs = strlen($chrs);
646 |
647 | for ($c = 0; $c <= $strlen_chrs; ++$c) {
648 |
649 | $top = end($stk);
650 | $substr_chrs_c_2 = substr($chrs, $c, 2);
651 |
652 | if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
653 | // found a comma that is not inside a string, array, etc.,
654 | // OR we've reached the end of the character list
655 | $slice = substr($chrs, $top['where'], ($c - $top['where']));
656 | array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
657 | //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
658 |
659 | if (reset($stk) == SERVICES_JSON_IN_ARR) {
660 | // we are in an array, so just push an element onto the stack
661 | array_push($arr, $this->decode($slice));
662 |
663 | } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
664 | // we are in an object, so figure
665 | // out the property name and set an
666 | // element in an associative array,
667 | // for now
668 | $parts = array();
669 |
670 | if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
671 | // "name":value pair
672 | $key = $this->decode($parts[1]);
673 | $val = $this->decode($parts[2]);
674 |
675 | if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
676 | $obj[$key] = $val;
677 | } else {
678 | $obj->$key = $val;
679 | }
680 | } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
681 | // name:value pair, where name is unquoted
682 | $key = $parts[1];
683 | $val = $this->decode($parts[2]);
684 |
685 | if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
686 | $obj[$key] = $val;
687 | } else {
688 | $obj->$key = $val;
689 | }
690 | }
691 |
692 | }
693 |
694 | } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
695 | // found a quote, and we are not inside a string
696 | array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
697 | //print("Found start of string at {$c}\n");
698 |
699 | } elseif (($chrs{$c} == $top['delim']) &&
700 | ($top['what'] == SERVICES_JSON_IN_STR) &&
701 | ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
702 | // found a quote, we're in a string, and it's not escaped
703 | // we know that it's not escaped becase there is _not_ an
704 | // odd number of backslashes at the end of the string so far
705 | array_pop($stk);
706 | //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
707 |
708 | } elseif (($chrs{$c} == '[') &&
709 | in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
710 | // found a left-bracket, and we are in an array, object, or slice
711 | array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
712 | //print("Found start of array at {$c}\n");
713 |
714 | } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
715 | // found a right-bracket, and we're in an array
716 | array_pop($stk);
717 | //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
718 |
719 | } elseif (($chrs{$c} == '{') &&
720 | in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
721 | // found a left-brace, and we are in an array, object, or slice
722 | array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
723 | //print("Found start of object at {$c}\n");
724 |
725 | } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
726 | // found a right-brace, and we're in an object
727 | array_pop($stk);
728 | //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
729 |
730 | } elseif (($substr_chrs_c_2 == '/*') &&
731 | in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
732 | // found a comment start, and we are in an array, object, or slice
733 | array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
734 | $c++;
735 | //print("Found start of comment at {$c}\n");
736 |
737 | } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
738 | // found a comment end, and we're in one now
739 | array_pop($stk);
740 | $c++;
741 |
742 | for ($i = $top['where']; $i <= $c; ++$i)
743 | $chrs = substr_replace($chrs, ' ', $i, 1);
744 |
745 | //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
746 |
747 | }
748 |
749 | }
750 |
751 | if (reset($stk) == SERVICES_JSON_IN_ARR) {
752 | return $arr;
753 |
754 | } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
755 | return $obj;
756 |
757 | }
758 |
759 | }
760 | }
761 | }
762 |
763 | /**
764 | * @todo Ultimately, this should just call PEAR::isError()
765 | */
766 | function isError($data, $code = null)
767 | {
768 | if (class_exists('pear')) {
769 | return PEAR::isError($data, $code);
770 | } elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
771 | is_subclass_of($data, 'services_json_error'))) {
772 | return true;
773 | }
774 |
775 | return false;
776 | }
777 | }
778 |
779 | if (class_exists('PEAR_Error')) {
780 |
781 | class Services_JSON_Error extends PEAR_Error
782 | {
783 | function Services_JSON_Error($message = 'unknown error', $code = null,
784 | $mode = null, $options = null, $userinfo = null)
785 | {
786 | parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
787 | }
788 | }
789 |
790 | } else {
791 |
792 | /**
793 | * @todo Ultimately, this class shall be descended from PEAR_Error
794 | */
795 | class Services_JSON_Error
796 | {
797 | function Services_JSON_Error($message = 'unknown error', $code = null,
798 | $mode = null, $options = null, $userinfo = null)
799 | {
800 |
801 | }
802 | }
803 | }
804 |
--------------------------------------------------------------------------------
/mashape/json/jsonUtils.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | class JsonUtils {
28 |
29 | public static function serializeError($message, $code) {
30 | return '[{"message":' . self::encodeToJson($message) . ',"code":' . self::encodeToJson($code) . '}]';
31 | }
32 |
33 | public static function encodeToJson($text) {
34 | if (is_string($text)) {
35 | return json_encode($text);
36 | } else if (is_bool($text)) {
37 | if ($text) {
38 | return "true";
39 | } else {
40 | return "false";
41 | }
42 | } else if (is_numeric($text)) {
43 | return $text;
44 | } else if ($text == null) {
45 | return "null";
46 | }
47 | }
48 |
49 | public static function removeLastChar($array, $object) {
50 | $result = $object;
51 | if (count($array) > 0) {
52 | $result = substr($result, 0, strlen($result) - 1);
53 | }
54 | return $result;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/mashape/mashape.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once (dirname(__FILE__) . "/mashapeAPIError.php");
28 | require_once (dirname(__FILE__) . "/init/init.php");
29 | require_once (dirname(__FILE__) . "/methods/handler.php");
30 |
31 | abstract class MashapeRestAPI {
32 | private static $errors;
33 | public $dirPath;
34 |
35 | protected function __construct($dirPath) {
36 | $this->dirPath = $dirPath;
37 | }
38 |
39 | protected static function addError($code, $message, $statusCode = null) {
40 | if (empty(self::$errors)) {
41 | self::$errors = array();
42 | }
43 | $e = new MashapeAPIError($code, $message);
44 | array_push(self::$errors, $e);
45 | if (!empty($statusCode)) {
46 | self::setHTTPStatusCode($statusCode);
47 | }
48 | }
49 |
50 | public static function setHTTPStatusCode($statusCode) {
51 | if (!empty($statusCode)) {
52 | header("HTTP/1.0 " . $statusCode);
53 | }
54 | }
55 |
56 | public static function parseBoolean($value) {
57 | if ($value == "1" || strtolower($value) === "true") {
58 | return true;
59 | }
60 | return false;
61 | }
62 |
63 | public static function clearErrors() {
64 | self::$errors = array();
65 | }
66 |
67 | public static function hasErrors() {
68 | if (empty(self::$errors)) {
69 | return false;
70 | } else {
71 | return true;
72 | }
73 | }
74 |
75 | public static function getErrors() {
76 | return self::$errors;
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/mashape/mashapeAPIError.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | class MashapeAPIError {
28 | private $code;
29 | private $message;
30 |
31 | function __construct($code, $message) {
32 | $this->code = $code;
33 | $this->message = $message;
34 | }
35 |
36 | public function getCode() {
37 | return $this->code;
38 | }
39 | public function getMessage() {
40 | return $this->message;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/mashape/methods/IMethodHandler.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | interface IMethodHandler {
28 | public function handle($instance, $serverKey, $parameters, $httpRequestMethod);
29 | }
30 |
--------------------------------------------------------------------------------
/mashape/methods/call/call.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../IMethodHandler.php");
28 | require_once(dirname(__FILE__) . "/../../net/httpUtils.php");
29 | require_once(dirname(__FILE__) . "/../../init/init.php");
30 | require_once(dirname(__FILE__) . "/../../configuration/restConfigurationLoader.php");
31 | require_once(dirname(__FILE__) . "/helpers/callHelper.php");
32 | require_once(dirname(__FILE__) . "/helpers/routeHelper.php");
33 | require_once(dirname(__FILE__) . "/../discover/helpers/updateHtaccess.php");
34 |
35 | define("METHOD", "_method");
36 |
37 | class Call implements IMethodHandler {
38 |
39 | public function handle($instance, $serverKey, $parameters, $httpRequestMethod) {
40 | // If the request comes from local, reload the configuration
41 | $this->reloadConfiguration($instance, $serverKey);
42 |
43 | $methodName = null;
44 | $method = null;
45 |
46 | $this->findMethod($parameters, $methodName, $method, $serverKey, $httpRequestMethod);
47 |
48 | if (strtolower($method->getHttp()) != strtolower($httpRequestMethod)) {
49 | throw new MashapeException(EXCEPTION_INVALID_HTTPMETHOD, EXCEPTION_INVALID_HTTPMETHOD_CODE);
50 | }
51 |
52 | unset($parameters[METHOD]); // Remove the method name from the params
53 |
54 | return doCall($method, $parameters, $instance, $serverKey);
55 | }
56 |
57 | private function findMethod(&$parameters, &$methodName, &$method, $serverKey, $httpRequestMethod) {
58 | $methodName = (isset($parameters[METHOD])) ? $parameters[METHOD] : null;
59 | $method = null;
60 | if (empty($methodName)) {
61 | // Find route
62 | $requestUri = (isset($_SERVER["REQUEST_URI"])) ? $_SERVER["REQUEST_URI"] : null;
63 |
64 | $method = findRoute($requestUri, $parameters, $httpRequestMethod, $serverKey);
65 | if (!empty($method)) {
66 | $methodName = $method->getName();
67 | }
68 | } else {
69 | $method = RESTConfigurationLoader::getMethod($methodName, $serverKey);
70 | }
71 | if (empty($method)) {
72 | throw new MashapeException(sprintf(EXCEPTION_METHOD_NOTFOUND, $methodName), EXCEPTION_METHOD_NOTFOUND_CODE);
73 | }
74 | }
75 |
76 | private function reloadConfiguration($instance, $serverKey) {
77 | if (HttpUtils::isLocal()) {
78 | // Update the .htaccess file with the new route settings
79 | updateHtaccess($instance);
80 |
81 | // Update the configuration
82 | RESTConfigurationLoader::reloadConfiguration($serverKey);
83 | }
84 | }
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/mashape/methods/call/helpers/callHelper.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../../../json/jsonUtils.php");
28 | require_once(dirname(__FILE__) . "/validateParameters.php");
29 | require_once(dirname(__FILE__) . "/serializeMethodResult.php");
30 |
31 | function doCall($method, $parameters, $instance, $serverKey) {
32 | $callParameters = validateCallParameters($method, $parameters, $instance);
33 |
34 | $reflectedClass = new ReflectionClass(get_class($instance));
35 | $reflectedMethod = $reflectedClass->getMethod($method->getName());
36 | $result;
37 |
38 | $result = $reflectedMethod->invokeArgs($instance, $callParameters);
39 |
40 | $resultJson = "";
41 |
42 | //Print custom errors
43 | $reflectedErrorMethod = $reflectedClass->getMethod("getErrors");
44 | $reflectedErrors = $reflectedErrorMethod->invoke($instance);
45 |
46 | if (!empty($reflectedErrors)) {
47 | $resultJson .= "[";
48 | foreach ($reflectedErrors as $reflectedError) {
49 | $reflectedErrorClass = new ReflectionClass(get_class($reflectedError));
50 | $code = $reflectedErrorClass->getMethod("getCode")->invoke($reflectedError);
51 | $message = $reflectedErrorClass->getMethod("getMessage")->invoke($reflectedError);
52 | $resultJson .= '{"code":' . JsonUtils::encodeToJson($code) . ',"message":' . JsonUtils::encodeToJson($message) . '},';
53 | }
54 | $resultJson = JsonUtils::removeLastChar($reflectedErrors, $resultJson);
55 | $resultJson .= "]";
56 | } else {
57 | $resultJson .= serializeMethodResult($method, $result, $instance, $serverKey);
58 | }
59 | return $resultJson;
60 | }
61 |
--------------------------------------------------------------------------------
/mashape/methods/call/helpers/routeHelper.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../../../configuration/restConfigurationLoader.php");
28 | require_once(dirname(__FILE__) . "/../../../exceptions/mashapeException.php");
29 | require_once(dirname(__FILE__) . "/../../../utils/routeUtils.php");
30 | require_once(dirname(__FILE__) . "/../../../utils/arrayUtils.php");
31 |
32 | function findRoute($requestUri, &$routeParameters, $httpRequestMethod, $serverKey) {
33 | $routeMethod = null;
34 |
35 | $configuration = RESTConfigurationLoader::loadConfiguration($serverKey);
36 | $methods = $configuration->getMethods();
37 |
38 | for ($i=0;$igetHttp() != $httpRequestMethod) {
40 | unset($methods[$i]);
41 | }
42 | }
43 |
44 | $requestUri = Explode("?", substr($requestUri, 1));
45 | $requestUriParts = Explode("/", $requestUri[0]);
46 |
47 | $likelyMethods = array();
48 | $excludedMethods = array();
49 | // Backward loop
50 | for ($i=count($requestUriParts) - 1; $i>=0;$i--) {
51 | // Find if there's a path like that, otherwise check for placeholders
52 | foreach ($methods as $method) {
53 | $methodName = $method->getName();
54 | if (in_array($methodName, $excludedMethods)) {
55 | continue;
56 | }
57 | $route = $method->getRoute();
58 | if (!empty($route)) {
59 | $routeParts = Explode("/", substr($route, 1));
60 | if (count($routeParts) <= count($requestUriParts)) {
61 | $backwardIndex = count($routeParts) - (count($requestUriParts) - $i);
62 | if ($backwardIndex >= 0) {
63 | if ($routeParts[$backwardIndex] == $requestUriParts[$i]) {
64 | if (!ArrayUtils::existKey($methodName, $likelyMethods)) {
65 | $likelyMethods[$methodName] = array();
66 | }
67 | } else if (RouteUtils::isRoutePlaceholder($routeParts[$backwardIndex])) {
68 | $foundParameters;
69 | $placeHolder = RouteUtils::getRoutePlaceholder($routeParts[$backwardIndex]);
70 | if (!ArrayUtils::existKey($methodName, $likelyMethods)) {
71 | $foundParameters = array();
72 | } else {
73 | $foundParameters = $likelyMethods[$methodName];
74 | }
75 | $foundParameters[$placeHolder] = $requestUriParts[$i];
76 | $likelyMethods[$methodName] = $foundParameters;
77 | } else {
78 | array_push($excludedMethods, $methodName);
79 | unset($likelyMethods[$methodName]);
80 | }
81 | }
82 | }
83 | }
84 | }
85 | }
86 |
87 | if (count($likelyMethods) > 1) {
88 | // Get the route with the highest matches
89 | $maxRouteSize = 0;
90 | foreach ($likelyMethods as $key => $value) {
91 | $route = RESTConfigurationLoader::getMethod($key, $serverKey)->getRoute();
92 | $routeSize = count(Explode("/", substr($route, 1)));
93 | if ($routeSize > $maxRouteSize) {
94 | $maxRouteSize = $routeSize;
95 | }
96 | }
97 | foreach ($likelyMethods as $key => $value) {
98 | $route = RESTConfigurationLoader::getMethod($key, $serverKey)->getRoute();
99 | $routeSize = count(Explode("/", substr($route, 1)));
100 | if ($routeSize < $maxRouteSize) {
101 | unset($likelyMethods[$key]);
102 | }
103 | }
104 | }
105 |
106 | if (count($likelyMethods) > 1) {
107 | $ambiguousMethods = "";
108 | foreach ($likelyMethods as $key => $value) {
109 | $ambiguousMethods .= "\"" . $key . "\", ";
110 | }
111 | $ambiguousMethods = substr($ambiguousMethods, 0, strlen($ambiguousMethods) - 2);
112 | throw new MashapeException(sprintf(EXCEPTION_AMBIGUOUS_ROUTE, $ambiguousMethods), EXCEPTION_SYSTEM_ERROR_CODE);
113 | }
114 |
115 | // Get the first item (just one or none item can exist)
116 | foreach ($likelyMethods as $key => $value) {
117 | $routeMethod = RESTConfigurationLoader::getMethod($key, $serverKey);
118 | $routeParameters = array_merge($routeParameters, $value);
119 | break;
120 | }
121 |
122 | return $routeMethod;
123 | }
124 |
--------------------------------------------------------------------------------
/mashape/methods/call/helpers/serializeArray.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../../../configuration/restConfigurationLoader.php");
28 | require_once(dirname(__FILE__) . "/../../../json/jsonUtils.php");
29 | require_once(dirname(__FILE__) . "/../../../utils/arrayUtils.php");
30 | require_once(dirname(__FILE__) . "/serializeObject.php");
31 |
32 | function serializeArray($result, $instance, $isSimpleResult, $serverKey) {
33 | $json = "";
34 | if (is_array($result)) {
35 | if (ArrayUtils::isAssociative($result)) {
36 | $json .= "{";
37 | foreach ($result as $key => $value) {
38 | $json .= '"' . $key . '":';
39 | if (is_object($value)) {
40 | $json .= serializeObject($value, $instance, false, $serverKey);
41 | } else {
42 | if (is_array($value)) {
43 | $json .= serializeArray($value, $instance, $isSimpleResult, $serverKey);
44 | } else {
45 | $json .= serializeObject($value, $instance, !is_object($value), $serverKey);
46 | }
47 | }
48 | $json .= ",";
49 | }
50 | } else {
51 | $json .= "[";
52 | for ($i=0;$i.
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../../../exceptions/mashapeException.php");
28 | require_once(dirname(__FILE__) . "/../../../configuration/restConfigurationLoader.php");
29 | require_once(dirname(__FILE__) . "/../../../json/jsonUtils.php");
30 | require_once(dirname(__FILE__) . "/../../../utils/arrayUtils.php");
31 | require_once(dirname(__FILE__) . "/serializeObject.php");
32 | require_once(dirname(__FILE__) . "/serializeArray.php");
33 |
34 | function serializeMethodResult($method, $result, $instance, $serverKey) {
35 | $json = "";
36 |
37 | if (isNoResult($method)) {
38 | return "{}";
39 | }
40 |
41 | $isSimpleResult = isSimpleResult($method);
42 |
43 | if ($result === null) {
44 | if($isSimpleResult) {
45 | $json .= '{"' . $method->getResult() . '":null}';
46 | } else {
47 | $json .= "{}";
48 | }
49 | } else {
50 | if ($isSimpleResult) {
51 | $json .= '{"' . $method->getResult() . '":';
52 | }
53 | if ($method->isArray()) {
54 | if (is_array($result)) {
55 | $json .= serializeArray($result, $instance, $isSimpleResult, $serverKey);
56 | } else {
57 | // The result it's not an array although it was described IT WAS an array
58 | throw new MashapeException(EXCEPTION_EXPECTED_ARRAY_RESULT_SIMPLE, EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
59 | }
60 | } else {
61 | if (is_array($result)) {
62 | // The result it's an array although it was described IT WAS NOT an array
63 | throw new MashapeException(EXCEPTION_UNEXPECTED_ARRAY_RESULT_SIMPLE, EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
64 | } else {
65 | $json .= serializeObject($result, $instance, $isSimpleResult, $serverKey);
66 | }
67 | }
68 | if ($isSimpleResult) {
69 | $json .= '}';
70 | }
71 | }
72 | return $json;
73 | }
74 |
75 | function isNoResult($method) {
76 | $resultName = $method->getResult();
77 | $objectName = $method->getObject();
78 | if (empty($resultName) && empty($objectName)) {
79 | return true;
80 | }
81 | return false;
82 | }
83 | function isSimpleResult($method) {
84 | $resultName = $method->getResult();
85 | $objectName = $method->getObject();
86 | if (empty($resultName) && !empty($objectName)) {
87 | return false;
88 | }
89 | return true;
90 | }
91 |
--------------------------------------------------------------------------------
/mashape/methods/call/helpers/serializeObject.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../../../exceptions/mashapeException.php");
28 | require_once(dirname(__FILE__) . "/../../../configuration/restConfigurationLoader.php");
29 | require_once(dirname(__FILE__) . "/../../../json/jsonUtils.php");
30 | require_once(dirname(__FILE__) . "/serializeArray.php");
31 |
32 | function serializeObject($result, $instance, $isSimpleResult, $serverKey) {
33 | $json = "";
34 | if ($isSimpleResult) {
35 | // It's a simple result, just serialize it
36 | $json = JsonUtils::encodeToJson($result);
37 | } else {
38 | // It's a custom object, let's serialize recursively every field
39 | $className = get_class($result);
40 |
41 | $reflectedClass = new ReflectionClass($className);
42 |
43 | $xmlObject = RESTConfigurationLoader::getObject($className, $serverKey);
44 |
45 | if (empty($xmlObject)) {
46 | throw new MashapeException(sprintf(EXCEPTION_UNKNOWN_OBJECT, $className), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
47 | }
48 |
49 | // Start element
50 | $json .= "{";
51 |
52 | // Serialize fields
53 | $fields = $xmlObject->getFields();
54 |
55 | for ($i=0;$igetName();
59 | $fieldMethod = $field->getMethod();
60 | $fieldValue = null;
61 | if (empty($fieldMethod)) {
62 | if ($reflectedClass->hasProperty($fieldName)) {
63 | $reflectedProperty = $reflectedClass->getProperty($fieldName);
64 | if ($reflectedProperty->isPublic()) {
65 | $fieldValue = $reflectedProperty->getValue($result);
66 | } else {
67 | // Try using the __get magic method
68 | $fieldValue = $reflectedClass->getMethod("__get")->invokeArgs($result, array($fieldName));
69 | }
70 | } else if (ArrayUtils::existKey($fieldName, get_object_vars($result))) {
71 | $fieldValue = $result->$fieldName;
72 |
73 | } else {
74 | throw new MashapeException(sprintf(EXCEPTION_FIELD_NOTFOUND, $fieldName), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
75 | }
76 | } else {
77 | $fieldValue = $reflectedClass->getMethod($fieldMethod)->invoke($result);
78 | }
79 |
80 | if ($fieldValue === null && $field->isOptional()) {
81 | // Don't serialize the field
82 | continue;
83 | }
84 |
85 | $json .= '"' . $fieldName . '":';
86 | if ($fieldValue === null) {
87 | $json .= JsonUtils::encodeToJson($fieldValue);
88 | } else {
89 |
90 | $isSimpleField = isSimpleField($field);
91 |
92 | if ($field->isArray()) {
93 | if (is_array($fieldValue)) {
94 | $json .= serializeArray($fieldValue, $instance, isSimpleField($field), $serverKey);
95 | } else {
96 | // The result it's not an array although it was described IT WAS an array
97 | throw new MashapeException(sprintf(EXCEPTION_EXPECTED_ARRAY_RESULT, $fieldName, $className), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
98 | }
99 | } else {
100 | if (is_array($fieldValue)) {
101 | // The result it's an array although it was described IT WAS NOT an array
102 | throw new MashapeException(sprintf(EXCEPTION_UNEXPECTED_ARRAY_RESULT, $fieldName, $className), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
103 | } else {
104 | $json .= serializeObject($fieldValue, $instance, $isSimpleField, $serverKey);
105 | }
106 | }
107 | }
108 | $json .= ",";
109 | }
110 | if (substr($json, strlen($json) - 1, 1) != "{") {
111 | $json = JsonUtils::removeLastChar($fields, $json);
112 | }
113 | // Close element
114 | $json .= "}";
115 | }
116 | return $json;
117 | }
118 |
119 | function isSimpleField($field) {
120 | $object = $field->getObject();
121 | return empty($object);
122 | }
123 |
--------------------------------------------------------------------------------
/mashape/methods/call/helpers/validateParameters.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../../../exceptions/mashapeException.php");
28 | require_once(dirname(__FILE__) . "/../../../configuration/restConfigurationLoader.php");
29 | require_once(dirname(__FILE__) . "/../../../utils/arrayUtils.php");
30 |
31 | function validateCallParameters($method, $parameters, $instance) {
32 | $reflectedClass = new ReflectionClass(get_class($instance));
33 | $reflectedMethod = $reflectedClass->getMethod($method->getName());
34 | $reflectedParameters = $reflectedMethod->getParameters();
35 |
36 | $hasRequiredParams = false;
37 | foreach ($reflectedParameters as $reflectedParameter) {
38 | if (!$reflectedParameter->isOptional()) {
39 | $hasRequiredParams = true;
40 | break;
41 | }
42 | }
43 |
44 | if ($hasRequiredParams && (empty($parameters) || !is_array($parameters) || count($parameters) == 0)) {
45 | throw new MashapeException(EXCEPTION_REQUIRED_PARAMETERS, EXCEPTION_REQUIRED_PARAMETERS_CODE);
46 | }
47 |
48 | if (!empty($parameters)) {
49 | $keys = array_keys($parameters);
50 | for ($i = 0;$iname;
52 | if (($i + 1) > count($parameters)) {
53 | if (!$reflectedParameters[$i]->isOptional()) {
54 | throw new MashapeException(sprintf(EXCEPTION_REQUIRED_PARAMETER, $parameterName), EXCEPTION_REQUIRED_PARAMETERS_CODE);
55 | }
56 | } else {
57 | if (in_array($parameterName, $keys) == false && $reflectedParameters[$i]->isOptional() == false) {
58 | throw new MashapeException(sprintf(EXCEPTION_REQUIRED_PARAMETER, $parameterName), EXCEPTION_REQUIRED_PARAMETERS_CODE);
59 | }
60 | }
61 | }
62 | }
63 |
64 | $callParameters = array();
65 |
66 | // Sort parameters
67 | if (!empty($reflectedParameters)) {
68 | $sorted = array();
69 |
70 | foreach ($reflectedParameters as $reflectedParameter) {
71 | $reflectedParameterName = $reflectedParameter->name;
72 |
73 | if (isset($parameters[$reflectedParameterName])) {
74 | $sorted[$reflectedParameterName] = $parameters[$reflectedParameterName];
75 | } else {
76 | $sorted[$reflectedParameterName] = $reflectedParameter->getDefaultValue();
77 | }
78 | }
79 |
80 | $callParameters = $sorted;
81 | }
82 |
83 | return $callParameters;
84 | }
85 |
--------------------------------------------------------------------------------
/mashape/methods/discover/discover.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../IMethodHandler.php");
28 | require_once(dirname(__FILE__) . "/../../configuration/restConfigurationLoader.php");
29 | require_once(dirname(__FILE__) . "/../../net/httpUtils.php");
30 | require_once(dirname(__FILE__) . "/../../init/init.php");
31 | require_once(dirname(__FILE__) . "/helpers/discoverMethods.php");
32 | require_once(dirname(__FILE__) . "/helpers/discoverObjects.php");
33 | require_once(dirname(__FILE__) . "/helpers/updateHtaccess.php");
34 |
35 | define("HEADER_SERVER_KEY", "X-Mashape-Server-Key");
36 |
37 | define("MODE", "_mode");
38 | define("SIMPLE_MODE", "simple");
39 |
40 | class Discover implements IMethodHandler {
41 |
42 | public function handle($instance, $serverKey, $parameters, $httpRequestMethod) {
43 | // Validate HTTP Verb
44 | if (strtolower($httpRequestMethod) != "get") {
45 | throw new MashapeException(EXCEPTION_INVALID_HTTPMETHOD, EXCEPTION_INVALID_HTTPMETHOD_CODE);
46 | }
47 |
48 | // Validate request
49 | if ($this->validateRequest($serverKey) == false) {
50 | throw new MashapeException(EXCEPTION_AUTH_INVALID_SERVERKEY, EXCEPTION_AUTH_INVALID_SERVERKEY_CODE);
51 | }
52 |
53 | $resultXml = "\n";
54 |
55 | $fileParts = Explode('/', $_SERVER["PHP_SELF"]);
56 | $scriptName = $fileParts[count($fileParts) - 1];
57 |
58 | $baseUrl = Explode("/" . $scriptName, $this->curPageURL());
59 | $resultXml .= "getSimpleInfo() . ">\n";
60 |
61 | $mode = (isset($parameters[MODE])) ? $parameters[MODE] : null;
62 |
63 | $configuration = RESTConfigurationLoader::reloadConfiguration($serverKey);
64 | if ($mode == null || $mode != SIMPLE_MODE) {
65 | $objectsFound = array();
66 | $objectsToCreate = array();
67 |
68 | $methods = discoverMethods($instance, $configuration, $objectsFound, $objectsToCreate, $scriptName);
69 | $objects = discoverObjects($configuration, $objectsFound);
70 | $resultXml .= $methods . $objects . generateObjects($objectsToCreate);
71 |
72 | // Update the .htaccess file with the new route settings
73 | updateHtaccess($instance);
74 |
75 | }
76 | $resultXml .= "";
77 |
78 | return $resultXml;
79 | }
80 |
81 | private function getSimpleInfo() {
82 | $libraryLanguage = "language=\"" . LIBRARY_LANGUAGE . "\"";
83 | $libraryVersion = " version=\"" . LIBRARY_VERSION . "\"";
84 |
85 | return $libraryLanguage . $libraryVersion;
86 | }
87 |
88 | private function curPageURL() {
89 | $pageURL = 'http';
90 | if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
91 | $pageURL .= "://";
92 | if (isset($_SERVER["SERVER_PORT"]) && $_SERVER["SERVER_PORT"] != "80") {
93 | $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
94 | } else {
95 | $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
96 | }
97 | return $pageURL;
98 | }
99 |
100 | private function validateRequest($serverKey) {
101 | // If the request comes from the local computer, then don't require authorization,
102 | // otherwise check the headers
103 | if (HttpUtils::isLocal()) {
104 | return true;
105 | } else {
106 | $providedServerkey = HttpUtils::getHeader(HEADER_SERVER_KEY);
107 | if (empty($serverKey)) {
108 | throw new MashapeException(EXCEPTION_EMPTY_SERVERKEY, EXCEPTION_XML_CODE);
109 | }
110 | if ($providedServerkey != null && md5($serverKey) == $providedServerkey) {
111 | return true;
112 | }
113 | return false;
114 | }
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/mashape/methods/discover/helpers/discoverMethods.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../../../json/jsonUtils.php");
28 | require_once(dirname(__FILE__) . "/../../../utils/routeUtils.php");
29 |
30 | function discoverMethods($instance, $configuration, &$objectsFound, &$objectsToCreate, $scriptName) {
31 | // Serialize methods
32 | $result = "";
33 | $methods = $configuration->getMethods();
34 | foreach($methods as $method) {
35 | $result .= "\tgetName();
37 | $result .= 'name="' . $name . '"';
38 | $http = $method->getHttp();
39 | $result .= " http=\"" . strtoupper($http) . "\">\n";
40 | $route = $method->getRoute();
41 |
42 | $result .= "\t\t\n";
59 | $result .= serializeParameters($method, $instance);
60 |
61 | $object = $method->getObject();
62 | $resultName = $method->getResult();
63 |
64 | if (!empty($object)) {
65 | $result .= "\t\tisArray();
76 | $result .= " array=\"" . ($array ? "true" : "false") . "\" />\n";
77 |
78 | $result .= "\t\t\n";
79 |
80 | $result .= "\t\n";
81 | }
82 | return $result;
83 | }
84 |
85 | function findUniqueObjectName($objects, $name, $index) {
86 | $numeratedName = $name;
87 | if ($index > 0) {
88 | $numeratedName .= $index;
89 | }
90 | $keys = array_keys($objects);
91 | foreach ($keys as $key) {
92 | if ($key == $numeratedName) {
93 | return findUniqueObjectName($objects, $name, $index + 1);
94 | }
95 | }
96 | return $numeratedName;
97 | }
98 |
99 | function serializeParametersQueryString($method, $instance, $routeParameters = null) {
100 | $reflectedClass = new ReflectionClass(get_class($instance));
101 | $reflectedMethod = $reflectedClass->getMethod($method->getName());
102 | $reflectedParameters = $reflectedMethod->getParameters();
103 | $result = "";
104 | for ($i=0;$iname, $routeParameters)) {
108 | continue;
109 | }
110 | }
111 | if ($i == 0) {
112 | $result .= "&";
113 | }
114 | $result .= $param->name . "={" . $param->name . "}&";
115 | }
116 |
117 | $result = JsonUtils::removeLastChar($reflectedParameters, $result);
118 | return $result;
119 | }
120 |
121 | function serializeParameters($method, $instance) {
122 | $reflectedClass = new ReflectionClass(get_class($instance));
123 | $reflectedMethod = $reflectedClass->getMethod($method->getName());
124 | $reflectedParameters = $reflectedMethod->getParameters();
125 | $result = "\t\t\n";
126 | for ($i=0;$iisDefaultValueAvailable() ? "true" : "false") . "\">" . $param->name . "\n";
129 | }
130 |
131 | $result .= "\t\t\n";
132 |
133 | // Check route parameters
134 | $route = $method->getRoute();
135 | if (!empty($route)) {
136 | $routeParts = Explode("/", substr($route, 1));
137 | foreach ($routeParts as $routePart) {
138 | if (RouteUtils::isRoutePlaceholder($routePart)) {
139 | $placeHolder = RouteUtils::getRoutePlaceholder($routePart);
140 | $exist = false;
141 | for ($i=0;$iname) {
144 | if ($param->isDefaultValueAvailable()) {
145 | throw new MashapeException(sprintf(EXCEPTION_METHOD_OPTIONAL_ROUTE_PARAM, $param->name, $method->getName()),EXCEPTION_XML_CODE);
146 | }
147 | $exist = true;
148 | break;
149 | }
150 | }
151 | if ($exist == false) {
152 | throw new MashapeException(sprintf(EXCEPTION_METHOD_INVALID_ROUTE_PARAM, $placeHolder),EXCEPTION_XML_CODE);
153 | }
154 | }
155 | }
156 | }
157 |
158 | return $result;
159 | }
160 |
--------------------------------------------------------------------------------
/mashape/methods/discover/helpers/discoverObjects.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../../../json/jsonUtils.php");
28 | require_once(dirname(__FILE__) . "/../../../exceptions/mashapeException.php");
29 |
30 | function generateObjects($objectsToCreate) {
31 | $result = "";
32 |
33 | $keys = array_keys($objectsToCreate);
34 |
35 | foreach ($keys as $key) {
36 | $result .= "\t\n";
40 | }
41 |
42 | return $result;
43 | }
44 |
45 |
46 | function discoverObjects($configuration, $objectsFound) {
47 | $result = "";
48 | $objects = $configuration->getObjects();
49 |
50 | $objectsDone = array();
51 |
52 | foreach ($objects as $object) {
53 | $result .= "\t\n";
76 |
77 | array_push($objectsDone, $className);
78 |
79 | $objectsFound = array_diff($objectsFound, array($className));
80 | }
81 |
82 | $result .= "\t\n";
83 |
84 | // Check that all objects exist
85 | if (!empty($objectsFound)) {
86 | $missingObjects = "";
87 | foreach($objectsFound as $requiredObject) {
88 | $missingObjects .= $requiredObject . ",";
89 | }
90 | $missingObjects = JsonUtils::removeLastChar($objectsFound, $missingObjects);
91 | throw new MashapeException(sprintf(EXCEPTION_MISSING_OBJECTS, $missingObjects), EXCEPTION_XML_CODE);
92 | }
93 |
94 | return $result;
95 | }
96 |
--------------------------------------------------------------------------------
/mashape/methods/discover/helpers/updateHtaccess.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | function updateHtaccess($instance) {
28 | $reflectedClass = new ReflectionClass(get_class($instance));
29 | $implPath = $reflectedClass->getParentClass()->getProperty("dirPath")->getValue($instance);
30 |
31 | $fileParts = Explode('/', $_SERVER["PHP_SELF"]);
32 | $scriptName = $fileParts[count($fileParts) - 1];
33 |
34 | $fhandle = @fopen($implPath . "/.htaccess", "w");
35 | if ($fhandle == null) {
36 | throw new MashapeException(sprintf(EXCEPTION_INVALID_PERMISSION, $implPath . "/.htaccess"), EXCEPTION_SYSTEM_ERROR_CODE);
37 | }
38 | fwrite($fhandle, "RewriteEngine On\n");
39 | unset($fileParts[count($fileParts) - 1]);
40 | $basePath = (count($fileParts) == 1 && empty($fileParts[0])) ? "/" : implode("/", $fileParts);
41 | fwrite($fhandle, "RewriteBase " . $basePath . "\n");
42 | fwrite($fhandle, "RewriteRule ^(.*)$ " . $scriptName . " [QSA,L]");
43 | fclose($fhandle);
44 | }
45 |
46 | function emptyMatches($matches) {
47 | if (empty($matches)) {
48 | return true;
49 | } else {
50 | foreach ($matches as $match) {
51 | if (!empty($match)) {
52 | return false;
53 | }
54 | }
55 | }
56 | return true;
57 | }
58 |
59 | function parseRoute($route) {
60 | $pattern = '/\{(\w+)\}/';
61 | preg_match_all($pattern, $route, $matches, PREG_OFFSET_CAPTURE);
62 | return $matches;
63 | }
64 |
--------------------------------------------------------------------------------
/mashape/methods/handler.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../init/init.php");
28 | require_once(dirname(__FILE__) . "/../json/jsonUtils.php");
29 | require_once(dirname(__FILE__) . "/../net/httpUtils.php");
30 | require_once(dirname(__FILE__) . "/discover/discover.php");
31 | require_once(dirname(__FILE__) . "/call/call.php");
32 |
33 | define("OPERATION", "_op");
34 | define("CALLBACK", "callback");
35 |
36 | class MashapeHandler {
37 |
38 | private static function setUnauthorizedResponse() {
39 | header("HTTP/1.0 401 Unauthorized");
40 | header('WWW-Authenticate: Mashape realm="Mashape API authentication"');
41 | }
42 |
43 | private static function getAllParams($source) {
44 | $keys = array_keys($source);
45 | $result = array();
46 | foreach ($keys as $key) {
47 | $result[$key] = $source[$key];
48 | }
49 | return $result;
50 | }
51 |
52 | private static function validateCallback($callback) {
53 | if (preg_match("/^(\w\.?_?)+$/", $callback)) {
54 | return true;
55 | } else {
56 | return false;
57 | }
58 | }
59 |
60 | public static function handleAPI($instance, $serverKey) {
61 | header("Content-type: application/json");
62 | try {
63 | if ($instance == null) {
64 | throw new MashapeException(EXCEPTION_INSTANCE_NULL, EXCEPTION_SYSTEM_ERROR_CODE);
65 | }
66 | $requestMethod = (isset($_SERVER['REQUEST_METHOD'])) ? strtolower($_SERVER['REQUEST_METHOD']) : null;
67 | $params;
68 | if ($requestMethod == 'post') {
69 | $params = array_merge(self::getAllParams($_GET), self::getAllParams($_POST));
70 | } else if ($requestMethod == 'get') {
71 | $params = self::getAllParams($_GET);
72 | } else if ($requestMethod == 'put' || $requestMethod == 'delete') {
73 | $params = HttpUtils::parseQueryString(file_get_contents("php://input"));
74 | } else {
75 | throw new MashapeException(EXCEPTION_NOTSUPPORTED_HTTPMETHOD, EXCEPTION_NOTSUPPORTED_HTTPMETHOD_CODE);
76 | }
77 |
78 | $operation = (isset($params[OPERATION])) ? $params[OPERATION] : null;
79 | unset($params[OPERATION]); // remove the operation parameter
80 |
81 | if (empty($operation)) {
82 | $operation = "call";
83 | }
84 | if ($operation != null) {
85 | $result;
86 | switch (strtolower($operation)) {
87 | case "discover":
88 | header("Content-type: application/xml");
89 | $discover = new Discover();
90 | $result = $discover->handle($instance, $serverKey, $params, $requestMethod);
91 | break;
92 | case "call":
93 | $call = new Call();
94 | $result = $call->handle($instance, $serverKey, $params, $requestMethod);
95 | break;
96 | default:
97 | throw new MashapeException(EXCEPTION_NOTSUPPORTED_OPERATION, EXCEPTION_NOTSUPPORTED_OPERATION_CODE);
98 | }
99 |
100 | $jsonpCallback = (isset($params[CALLBACK])) ? $params[CALLBACK] : null;
101 | if (empty($jsonpCallback)) {
102 | // Print the output
103 | echo $result;
104 | } else {
105 | if (self::validateCallback($jsonpCallback)) {
106 | echo $jsonpCallback . '(' . $result . ')';
107 | } else {
108 | throw new MashapeException(EXCEPTION_INVALID_CALLBACK, EXCEPTION_SYSTEM_ERROR_CODE);
109 | }
110 | }
111 |
112 | } else {
113 | // Operation not supported
114 | throw new MashapeException(EXCEPTION_NOTSUPPORTED_OPERATION, EXCEPTION_NOTSUPPORTED_OPERATION_CODE);
115 | }
116 |
117 | } catch (Exception $e) {
118 | //If it's an ApizatorException then print the specific code
119 | if ($e instanceof MashapeException) {
120 | header("Content-type: application/json");
121 | $code = $e->getCode();
122 | switch ($code) {
123 | case EXCEPTION_XML_CODE:
124 | header("HTTP/1.0 500 Internal Server Error");
125 | break;
126 | case EXCEPTION_INVALID_HTTPMETHOD_CODE:
127 | header("HTTP/1.0 405 Method Not Allowed");
128 | break;
129 | case EXCEPTION_NOTSUPPORTED_HTTPMETHOD_CODE:
130 | header("HTTP/1.0 405 Method Not Allowed");
131 | break;
132 | case EXCEPTION_NOTSUPPORTED_OPERATION_CODE:
133 | header("HTTP/1.0 501 Not Implemented");
134 | break;
135 | case EXCEPTION_METHOD_NOTFOUND_CODE:
136 | header("HTTP/1.0 404 Not Found");
137 | break;
138 | case EXCEPTION_AUTH_INVALID_CODE:
139 | self::setUnauthorizedResponse();
140 | break;
141 | case EXCEPTION_AUTH_INVALID_SERVERKEY_CODE:
142 | self::setUnauthorizedResponse();
143 | break;
144 | case EXCEPTION_REQUIRED_PARAMETERS_CODE:
145 | header("HTTP/1.0 200 OK");
146 | break;
147 | case EXCEPTION_GENERIC_LIBRARY_ERROR_CODE:
148 | header("HTTP/1.0 500 Internal Server Error");
149 | break;
150 | case EXCEPTION_INVALID_APIKEY_CODE:
151 | self::setUnauthorizedResponse();
152 | break;
153 | case EXCEPTION_EXCEEDED_LIMIT_CODE:
154 | self::setUnauthorizedResponse();
155 | break;
156 | case EXCEPTION_SYSTEM_ERROR_CODE:
157 | header("HTTP/1.0 500 Internal Server Error");
158 | break;
159 | }
160 | echo JsonUtils::serializeError($e->getMessage(), $code);
161 | } else {
162 | //Otherwise print a "generic exception" code
163 | header("HTTP/1.0 500 Internal Server Error");
164 | echo JsonUtils::serializeError($e->getMessage(), EXCEPTION_GENERIC_LIBRARY_ERROR_CODE);
165 | }
166 | }
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/mashape/net/httpUtils.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(dirname(__FILE__) . "/../init/init.php");
28 |
29 | class HttpUtils {
30 |
31 | public static function parseQueryString($str) {
32 | $op = array();
33 | $pairs = explode("&", $str);
34 | foreach ($pairs as $pair) {
35 | list($k, $v) = array_map("urldecode", explode("=", $pair));
36 | $op[$k] = $v;
37 | }
38 | return $op;
39 | }
40 |
41 | public static function isLocal() {
42 | $ip = self::getRealIpAddr();
43 | return $ip == "127.0.0.1" || $ip == "::1";
44 | }
45 |
46 | public static function getHeader($name) {
47 | $headers = apache_request_headers();
48 | foreach ($headers as $key => $value) {
49 | if ($key == $name) {
50 | return $value;
51 | }
52 | }
53 | }
54 |
55 | public static function makeHttpRequest($url) {
56 | $response = @file_get_contents($url);
57 | return $response;
58 | }
59 |
60 | private static function getRealIpAddr()
61 | {
62 | if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
63 | {
64 | $ip=$_SERVER['HTTP_CLIENT_IP'];
65 | }
66 | elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
67 | {
68 | $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
69 | }
70 | else
71 | {
72 | $ip=$_SERVER['REMOTE_ADDR'];
73 | }
74 | return $ip;
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/mashape/settings.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | // The variable name where Mashape will cache the configuration file.
28 | // By default it's "mashape_api_configuration"
29 | define("SESSION_VARNAME", "mashape_api_configuration");
30 | define("UID", "mashape_uid");
31 |
--------------------------------------------------------------------------------
/mashape/utils/arrayUtils.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | class ArrayUtils {
28 |
29 | public static function existKey($key, $array) {
30 | if (empty($array) == false) {
31 | return array_key_exists($key, $array);
32 | }
33 | return false;
34 | }
35 |
36 | public static function isAssociative($array) {
37 | if ( !is_array($array) || empty($array) ) {
38 | return false;
39 | }
40 | return array_keys($array) !== range(0, count($array) - 1);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/mashape/utils/routeUtils.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | class RouteUtils {
28 |
29 | public static function findPlaceHolders($url) {
30 | $placeholders = array();
31 |
32 | for($i=0;$i < strlen($url);$i++) {
33 | $curchar = substr($url, $i, 1);
34 |
35 | if ($curchar == "{") {
36 | // It may be a placeholder
37 |
38 | $pos = strpos($url, "}", $i);
39 | if ($pos !== false) {
40 | // It's a placeholder
41 |
42 | $placeHolder = substr($url, $i + 1, $pos - 1 - $i); // Get the placeholder name without {..}
43 | if (in_array($placeHolder, $placeholders) === false) {
44 | array_push($placeholders, $placeHolder);
45 |
46 | $i = $pos;
47 | continue;
48 |
49 | }
50 | }
51 | }
52 | }
53 |
54 | return $placeholders;
55 | }
56 |
57 |
58 | public static function getRoutePlaceholder($val) {
59 | return substr($val, 1, strlen($val) - 2);
60 | }
61 |
62 | public static function isRoutePlaceholder($val) {
63 | if (!empty($val)) {
64 | if (strlen($val) >= 2) {
65 | if (substr($val, 0, 1) == "{" && substr($val, strlen($val) - 1, 1) == "}") {
66 | return true;
67 | }
68 | }
69 | }
70 | return false;
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/mashape/xml/xmlParser.php:
--------------------------------------------------------------------------------
1 |
22 | * @copyright Copyright (c) 2005-2007, Adam A. Flynn
23 | *
24 | * @version 1.3.0
25 | */
26 | class XMLParser
27 | {
28 | /**
29 | * The XML parser
30 | *
31 | * @var resource
32 | */
33 | var $parser;
34 |
35 | /**
36 | * The XML document
37 | *
38 | * @var string
39 | */
40 | var $xml;
41 |
42 | /**
43 | * Document tag
44 | *
45 | * @var object
46 | */
47 | var $document;
48 |
49 | /**
50 | * Current object depth
51 | *
52 | * @var array
53 | */
54 | var $stack;
55 | /**
56 | * Whether or not to replace dashes and colons in tag
57 | * names with underscores.
58 | *
59 | * @var bool
60 | */
61 | var $cleanTagNames;
62 |
63 |
64 | /**
65 | * Constructor. Loads XML document.
66 | *
67 | * @param string $xml The string of the XML document
68 | * @return XMLParser
69 | */
70 | function XMLParser($xml = '', $cleanTagNames = true)
71 | {
72 | //Load XML document
73 | $this->xml = $xml;
74 |
75 | // Set stack to an array
76 | $this->stack = array();
77 |
78 | //Set whether or not to clean tag names
79 | $this->cleanTagNames = $cleanTagNames;
80 | }
81 |
82 | /**
83 | * Initiates and runs PHP's XML parser
84 | */
85 | function Parse()
86 | {
87 | //Create the parser resource
88 | $this->parser = xml_parser_create();
89 |
90 | //Set the handlers
91 | xml_set_object($this->parser, $this);
92 | xml_set_element_handler($this->parser, 'StartElement', 'EndElement');
93 | xml_set_character_data_handler($this->parser, 'CharacterData');
94 |
95 | //Error handling
96 | if (!xml_parse($this->parser, $this->xml))
97 | $this->HandleError(xml_get_error_code($this->parser), xml_get_current_line_number($this->parser), xml_get_current_column_number($this->parser));
98 |
99 | //Free the parser
100 | xml_parser_free($this->parser);
101 | }
102 |
103 | /**
104 | * Handles an XML parsing error
105 | *
106 | * @param int $code XML Error Code
107 | * @param int $line Line on which the error happened
108 | * @param int $col Column on which the error happened
109 | */
110 | function HandleError($code, $line, $col)
111 | {
112 | throw new Exception('XML Parsing Error at '.$line.':'.$col.'. Error '.$code.': '.xml_error_string($code));
113 | }
114 |
115 |
116 | /**
117 | * Gets the XML output of the PHP structure within $this->document
118 | *
119 | * @return string
120 | */
121 | function GenerateXML()
122 | {
123 | return $this->document->GetXML();
124 | }
125 |
126 | /**
127 | * Gets the reference to the current direct parent
128 | *
129 | * @return object
130 | */
131 | function GetStackLocation()
132 | {
133 | $return = '';
134 |
135 | foreach($this->stack as $stack)
136 | $return .= $stack.'->';
137 |
138 | return rtrim($return, '->');
139 | }
140 |
141 | /**
142 | * Handler function for the start of a tag
143 | *
144 | * @param resource $parser
145 | * @param string $name
146 | * @param array $attrs
147 | */
148 | function StartElement($parser, $name, $attrs = array())
149 | {
150 | //Make the name of the tag lower case
151 | $name = strtolower($name);
152 |
153 | //Check to see if tag is root-level
154 | if (count($this->stack) == 0)
155 | {
156 | //If so, set the document as the current tag
157 | $this->document = new XMLTag($name, $attrs);
158 |
159 | //And start out the stack with the document tag
160 | $this->stack = array('document');
161 | }
162 | //If it isn't root level, use the stack to find the parent
163 | else
164 | {
165 | //Get the name which points to the current direct parent, relative to $this
166 | $parent = $this->GetStackLocation();
167 |
168 | //Add the child
169 | eval('$this->'.$parent.'->AddChild($name, $attrs, '.count($this->stack).', $this->cleanTagNames);');
170 |
171 | //If the cleanTagName feature is on, replace colons and dashes with underscores
172 | if($this->cleanTagNames)
173 | $name = str_replace(array(':', '-'), '_', $name);
174 |
175 |
176 | //Update the stack
177 | eval('$this->stack[] = $name.\'[\'.(count($this->'.$parent.'->'.$name.') - 1).\']\';');
178 | }
179 | }
180 |
181 | /**
182 | * Handler function for the end of a tag
183 | *
184 | * @param resource $parser
185 | * @param string $name
186 | */
187 | function EndElement($parser, $name)
188 | {
189 | //Update stack by removing the end value from it as the parent
190 | array_pop($this->stack);
191 | }
192 |
193 | /**
194 | * Handler function for the character data within a tag
195 | *
196 | * @param resource $parser
197 | * @param string $data
198 | */
199 | function CharacterData($parser, $data)
200 | {
201 | //Get the reference to the current parent object
202 | $tag = $this->GetStackLocation();
203 |
204 | //Assign data to it
205 | eval('$this->'.$tag.'->tagData .= trim($data);');
206 | }
207 | }
208 |
209 |
210 | /**
211 | * XML Tag Object (php4)
212 | *
213 | * This object stores all of the direct children of itself in the $children array. They are also stored by
214 | * type as arrays. So, if, for example, this tag had 2 tags as children, there would be a class member
215 | * called $font created as an array. $font[0] would be the first font tag, and $font[1] would be the second.
216 | *
217 | * To loop through all of the direct children of this object, the $children member should be used.
218 | *
219 | * To loop through all of the direct children of a specific tag for this object, it is probably easier
220 | * to use the arrays of the specific tag names, as explained above.
221 | *
222 | * @author Adam A. Flynn
223 | * @copyright Copyright (c) 2005-2007, Adam A. Flynn
224 | *
225 | * @version 1.3.0
226 | */
227 | class XMLTag
228 | {
229 | /**
230 | * Array with the attributes of this XML tag
231 | *
232 | * @var array
233 | */
234 | var $tagAttrs;
235 |
236 | /**
237 | * The name of the tag
238 | *
239 | * @var string
240 | */
241 | var $tagName;
242 |
243 | /**
244 | * The data the tag contains
245 | *
246 | * So, if the tag doesn't contain child tags, and just contains a string, it would go here
247 | *
248 | * @var string
249 | */
250 | var $tagData;
251 |
252 | /**
253 | * Array of references to the objects of all direct children of this XML object
254 | *
255 | * @var array
256 | */
257 | var $tagChildren;
258 |
259 | /**
260 | * The number of parents this XML object has (number of levels from this tag to the root tag)
261 | *
262 | * Used presently only to set the number of tabs when outputting XML
263 | *
264 | * @var int
265 | */
266 | var $tagParents;
267 |
268 | /**
269 | * Constructor, sets up all the default values
270 | *
271 | * @param string $name
272 | * @param array $attrs
273 | * @param int $parents
274 | * @return XMLTag
275 | */
276 | function XMLTag($name, $attrs = array(), $parents = 0)
277 | {
278 | //Make the keys of the attr array lower case, and store the value
279 | $this->tagAttrs = array_change_key_case($attrs, CASE_LOWER);
280 |
281 | //Make the name lower case and store the value
282 | $this->tagName = strtolower($name);
283 |
284 | //Set the number of parents
285 | $this->tagParents = $parents;
286 |
287 | //Set the types for children and data
288 | $this->tagChildren = array();
289 | $this->tagData = '';
290 | }
291 |
292 | /**
293 | * Adds a direct child to this object
294 | *
295 | * @param string $name
296 | * @param array $attrs
297 | * @param int $parents
298 | * @param bool $cleanTagName
299 | */
300 | function AddChild($name, $attrs, $parents, $cleanTagName = true)
301 | {
302 | //If the tag is a reserved name, output an error
303 | if(in_array($name, array('tagChildren', 'tagAttrs', 'tagParents', 'tagData', 'tagName')))
304 | {
305 | trigger_error('You have used a reserved name as the name of an XML tag. Please consult the documentation (http://www.criticaldevelopment.net/xml/) and rename the tag named "'.$name.'" to something other than a reserved name.', E_USER_ERROR);
306 |
307 | return;
308 | }
309 |
310 | //Create the child object itself
311 | $child = new XMLTag($name, $attrs, $parents);
312 |
313 | //If the cleanTagName feature is on, replace colons and dashes with underscores
314 | if($cleanTagName)
315 | $name = str_replace(array(':', '-'), '_', $name);
316 |
317 | //Toss up a notice if someone's trying to to use a colon or dash in a tag name
318 | elseif(strstr($name, ':') || strstr($name, '-'))
319 | trigger_error('Your tag named "'.$name.'" contains either a dash or a colon. Neither of these characters are friendly with PHP variable names, and, as such, they cannot be accessed and will cause the parser to not work. You must enable the cleanTagName feature (pass true as the second argument of the XMLParser constructor). For more details, see http://www.criticaldevelopment.net/xml/', E_USER_ERROR);
320 |
321 | //If there is no array already set for the tag name being added,
322 | //create an empty array for it
323 | if(!isset($this->$name))
324 | $this->$name = array();
325 |
326 | //Add the reference of it to the end of an array member named for the tag's name
327 | $this->{$name}[] =& $child;
328 |
329 | //Add the reference to the children array member
330 | $this->tagChildren[] =& $child;
331 | }
332 |
333 | /**
334 | * Returns the string of the XML document which would be generated from this object
335 | *
336 | * This function works recursively, so it gets the XML of itself and all of its children, which
337 | * in turn gets the XML of all their children, which in turn gets the XML of all thier children,
338 | * and so on. So, if you call GetXML from the document root object, it will return a string for
339 | * the XML of the entire document.
340 | *
341 | * This function does not, however, return a DTD or an XML version/encoding tag. That should be
342 | * handled by XMLParser::GetXML()
343 | *
344 | * @return string
345 | */
346 | function GetXML()
347 | {
348 | //Start a new line, indent by the number indicated in $this->parents, add a <, and add the name of the tag
349 | $out = "\n".str_repeat("\t", $this->tagParents).'<'.$this->tagName;
350 |
351 | //For each attribute, add attr="value"
352 | foreach($this->tagAttrs as $attr => $value)
353 | $out .= ' '.$attr.'="'.$value.'"';
354 |
355 | //If there are no children and it contains no data, end it off with a />
356 | if(empty($this->tagChildren) && empty($this->tagData))
357 | $out .= " />";
358 |
359 | //Otherwise...
360 | else
361 | {
362 | //If there are children
363 | if(!empty($this->tagChildren))
364 | {
365 | //Close off the start tag
366 | $out .= '>';
367 |
368 | //For each child, call the GetXML function (this will ensure that all children are added recursively)
369 | foreach($this->tagChildren as $child)
370 | {
371 | if(is_object($child))
372 | $out .= $child->GetXML();
373 | }
374 |
375 | //Add the newline and indentation to go along with the close tag
376 | $out .= "\n".str_repeat("\t", $this->tagParents);
377 | }
378 |
379 | //If there is data, close off the start tag and add the data
380 | elseif(!empty($this->tagData))
381 | $out .= '>'.$this->tagData;
382 |
383 | //Add the end tag
384 | $out .= ''.$this->tagName.'>';
385 | }
386 |
387 | //Return the final output
388 | return $out;
389 | }
390 |
391 | /**
392 | * Deletes this tag's child with a name of $childName and an index
393 | * of $childIndex
394 | *
395 | * @param string $childName
396 | * @param int $childIndex
397 | */
398 | function Delete($childName, $childIndex = 0)
399 | {
400 | //Delete all of the children of that child
401 | $this->{$childName}[$childIndex]->DeleteChildren();
402 |
403 | //Destroy the child's value
404 | $this->{$childName}[$childIndex] = null;
405 |
406 | //Remove the child's name from the named array
407 | unset($this->{$childName}[$childIndex]);
408 |
409 | //Loop through the tagChildren array and remove any null
410 | //values left behind from the above operation
411 | for($x = 0; $x < count($this->tagChildren); $x ++)
412 | {
413 | if(is_null($this->tagChildren[$x]))
414 | unset($this->tagChildren[$x]);
415 | }
416 | }
417 |
418 | /**
419 | * Removes all of the children of this tag in both name and value
420 | */
421 | function DeleteChildren()
422 | {
423 | //Loop through all child tags
424 | for($x = 0; $x < count($this->tagChildren); $x ++)
425 | {
426 | //Do this recursively
427 | $this->tagChildren[$x]->DeleteChildren();
428 |
429 | //Delete the name and value
430 | $this->tagChildren[$x] = null;
431 | unset($this->tagChildren[$x]);
432 | }
433 | }
434 | }
435 |
--------------------------------------------------------------------------------
/mashape/xml/xmlParserUtils.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | class XmlParserUtils {
28 |
29 | public static function existAttribute($obj, $attribute) {
30 | return array_key_exists($attribute, $obj->tagAttrs);
31 | }
32 |
33 | public static function getChildren($document, $tagName) {
34 | $result = array();
35 | foreach ($document->tagChildren as $child) {
36 | if ($child->tagName == $tagName) {
37 | array_push($result, $child);
38 | }
39 | }
40 | return $result;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/tests/bootstrap.php:
--------------------------------------------------------------------------------
1 |
7 | */
8 |
9 | define('CONFIGURATION_FILEPATH', dirname(dirname(__FILE__)) . '/api.xml');
10 | define('MASHAPE_LIBRAY_PATH', dirname(dirname(__FILE__)) . '/mashape');
11 |
12 | ?>
--------------------------------------------------------------------------------
/tests/configuration/restConfigurationLoaderTest.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(MASHAPE_LIBRAY_PATH . "/configuration/restConfigurationLoader.php");
28 |
29 | class RESTConfigurationLoaderTest extends PHPUnit_Framework_TestCase
30 | {
31 | function testLoadConfiguration() {
32 | $serverKey = "the-server-key";
33 | $configuration = RESTConfigurationLoader::loadConfiguration($serverKey);
34 | $this->assertFalse($configuration == null);
35 | $this->assertEquals(1, count($configuration->getMethods()));
36 | $this->assertEquals(0, count($configuration->getObjects()));
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/tests/configuration/restConfigurationTest.php:
--------------------------------------------------------------------------------
1 |
7 | */
8 |
9 | require_once(MASHAPE_LIBRAY_PATH . "/configuration/restConfiguration.php");
10 |
11 | class RESTConfigurationTest extends PHPUnit_Framework_TestCase
12 | {
13 | protected $_instance;
14 |
15 | public function setUp()
16 | {
17 | $this->_instance = new RESTConfiguration();
18 | }
19 |
20 | /**
21 | * @covers RESTConfiguration::setMethods
22 | * @covers RESTConfiguration::getMethods
23 | */
24 | public function test_setMethods_and_getMethods()
25 | {
26 | $value = __METHOD__ . time();
27 | $this->_instance->setMethods($value);
28 | $this->assertEquals($value, $this->_instance->getMethods());
29 | }
30 |
31 | /**
32 | * @covers RESTConfiguration::setObjects
33 | * @covers RESTConfiguration::getObjects
34 | */
35 | public function test_setObjects_and_getObjects()
36 | {
37 | $value = __METHOD__ . time();
38 | $this->_instance->setObjects($value);
39 | $this->assertEquals($value, $this->_instance->getObjects());
40 | }
41 | }
--------------------------------------------------------------------------------
/tests/configuration/restMethodTest.php:
--------------------------------------------------------------------------------
1 |
7 | */
8 |
9 | require_once(MASHAPE_LIBRAY_PATH . "/configuration/restMethod.php");
10 |
11 | class RESTMethodTest extends PHPUnit_Framework_TestCase
12 | {
13 | protected $_instance;
14 |
15 | public function setUp()
16 | {
17 | $this->_instance = new RESTMethod();
18 | }
19 |
20 | /**
21 | * @covers RESTMethod::setResult
22 | * @covers RESTMethod::getResult
23 | */
24 | public function test_setResult_and_getResult()
25 | {
26 | $value = __METHOD__ . time();
27 | $this->_instance->setResult($value);
28 | $this->assertEquals($value, $this->_instance->getResult());
29 | }
30 |
31 | /**
32 | * @covers RESTMethod::setObject
33 | * @covers RESTMethod::getObject
34 | */
35 | public function test_setObject_and_getObject()
36 | {
37 | $value = __METHOD__ . time();
38 | $this->_instance->setObject($value);
39 | $this->assertEquals($value, $this->_instance->getObject());
40 | }
41 |
42 | /**
43 | * @covers RESTMethod::setName
44 | * @covers RESTMethod::getName
45 | */
46 | public function test_setName_and_getName()
47 | {
48 | $value = __METHOD__ . time();
49 | $this->_instance->setName($value);
50 | $this->assertEquals($value, $this->_instance->getName());
51 | }
52 |
53 | /**
54 | * @covers RESTMethod::setHttp
55 | * @covers RESTMethod::getHttp
56 | */
57 | public function test_setHttp_and_getHttp()
58 | {
59 | $value = __METHOD__ . time();
60 | $this->_instance->setHttp($value);
61 | $this->assertEquals($value, $this->_instance->getHttp());
62 | }
63 |
64 | /**
65 | * @covers RESTMethod::setRoute
66 | * @covers RESTMethod::getRoute
67 | */
68 | public function test_setRoute_and_getRoute()
69 | {
70 | $value = __METHOD__ . time();
71 | $this->_instance->setRoute($value);
72 | $this->assertEquals($value, $this->_instance->getRoute());
73 | }
74 |
75 | /**
76 | * @covers RESTMethod::setArray
77 | * @covers RESTMethod::isArray
78 | */
79 | public function test_setArray_and_isArray()
80 | {
81 | $this->markTestSkipped('isArray() implementation does not verify if the value is an array');
82 | $value = __METHOD__ . time();
83 | $this->_instance->setArray($value);
84 | $this->assertEquals($value, $this->_instance->isArray());
85 | }
86 | }
--------------------------------------------------------------------------------
/tests/json/jsonImplTest.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(MASHAPE_LIBRAY_PATH . "/json/jsonImpl.php");
28 |
29 | class JsonImplTest extends PHPUnit_Framework_TestCase
30 | {
31 | function testSerializeError() {
32 | $json = new Services_JSON;
33 | $result = $json->decode('{"error":{"message":"this is an error","code":2}}');
34 | $this->assertFalse(empty($result));
35 | $obj = $result->error;
36 | $this->assertFalse(empty($obj));
37 |
38 |
39 | $this->assertEquals($obj->message, "this is an error");
40 | $this->assertEquals($obj->code, 2);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/tests/json/jsonUtilsTest.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(MASHAPE_LIBRAY_PATH . "/json/jsonUtils.php");
28 |
29 | class JsonUtilsTest extends PHPUnit_Framework_TestCase
30 | {
31 | function testSerializeError() {
32 | $this->assertEquals('[{"message":"this is an error","code":2}]', JsonUtils::serializeError("this is an error", 2));
33 | $this->assertEquals('[{"message":"this is an error","code":null}]', JsonUtils::serializeError("this is an error", null));
34 | $this->assertEquals('[{"message":null,"code":null}]', JsonUtils::serializeError(null, null));
35 | $this->assertEquals('[{"message":"this is a \"great\" error","code":2}]', JsonUtils::serializeError('this is a "great" error', 2));
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/tests/methods/call/helpers/callHelperTest.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(MASHAPE_LIBRAY_PATH . "/configuration/restMethod.php");
28 | require_once(MASHAPE_LIBRAY_PATH . "/mashape.php");
29 | require_once(MASHAPE_LIBRAY_PATH . "/methods/call/helpers/callHelper.php");
30 |
31 | define("SERVER_KEY", "serverkey");
32 |
33 | class CallTest extends PHPUnit_Framework_TestCase
34 | {
35 | function testNull() {
36 | // Test NULL Simple result
37 | $method = new RESTMethod();
38 | $method->setName("touchNull");
39 | $method->setResult("message");
40 | $this->assertEquals('{"message":null}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
41 |
42 | // Test NULL Object
43 | $method = new RESTMethod();
44 | $method->setName("touchNull");
45 | $method->setObject("Ret");
46 | $this->assertEquals('{}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
47 | }
48 |
49 | function testSimple() {
50 | $method = new RESTMethod();
51 | $method->setName("touchSimple");
52 | $method->setResult("message");
53 | $this->assertEquals('{"message":"simpleValue"}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
54 |
55 | $method = new RESTMethod();
56 | $method->setName("touchSimpleArray");
57 | $method->setResult("message");
58 | $method->setArray(true);
59 | $this->assertEquals('{"message":["value1",3,"value3"]}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
60 | }
61 |
62 | function testComplex() {
63 | RESTConfigurationLoader::reloadConfiguration(SERVER_KEY, dirname(__FILE__) . "/test.xml");
64 | $method = new RESTMethod();
65 | $method->setName("touchComplex");
66 | $method->setObject("ClassOne");
67 | $this->assertEquals('{"field1":"value1","field2":"value2"}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
68 |
69 | RESTConfigurationLoader::reloadConfiguration(SERVER_KEY, dirname(__FILE__) . "/test2.xml");
70 | $method = new RESTMethod();
71 | $method->setName("touchComplex2");
72 | $method->setObject("ClassOne");
73 | $this->assertEquals('{"field2":"value2"}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
74 |
75 | RESTConfigurationLoader::reloadConfiguration(SERVER_KEY, dirname(__FILE__) . "/test3.xml");
76 | $method = new RESTMethod();
77 | $method->setName("touchComplex3");
78 | $method->setObject("ClassOne");
79 | $this->assertEquals('{"field1":"value1","field2":{"childField1":"child value 1","childField2":"child value 2"}}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
80 |
81 | RESTConfigurationLoader::reloadConfiguration(SERVER_KEY, dirname(__FILE__) . "/test3.xml");
82 | $method = new RESTMethod();
83 | $method->setName("touchComplex4");
84 | $method->setObject("ClassOne");
85 | $this->assertEquals('{"field1":"value1","field2":null}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
86 |
87 | RESTConfigurationLoader::reloadConfiguration(SERVER_KEY, dirname(__FILE__) . "/test4.xml");
88 | $method = new RESTMethod();
89 | $method->setName("touchComplex5");
90 | $method->setObject("ClassOne");
91 | $this->assertEquals('{"field1":["value1",3,"value3"]}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
92 |
93 | RESTConfigurationLoader::reloadConfiguration(SERVER_KEY, dirname(__FILE__) . "/test5.xml");
94 | $method = new RESTMethod();
95 | $method->setName("touchComplex6");
96 | $method->setObject("ClassOne");
97 | $this->assertEquals('{"field1":[{"childField1":"child value 1","childField2":"child value 2"},{"childField1":"second child value 1","childField2":"second child value 2"}]}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
98 |
99 | RESTConfigurationLoader::reloadConfiguration(SERVER_KEY, dirname(__FILE__) . "/test6.xml");
100 | $method = new RESTMethod();
101 | $method->setName("touchComplex7");
102 | $method->setObject("ClassThree");
103 | $this->assertEquals('{"field1":"this is field1","field2":["this","is","field",2,true],"field4":[{"field1":"child value 1","field2":"child value 2"},{"field1":"second child value 1","field2":"second child value 2"}]}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
104 |
105 | RESTConfigurationLoader::reloadConfiguration(SERVER_KEY, dirname(__FILE__) . "/test.xml");
106 | $method = new RESTMethod();
107 | $method->setName("touchComplex8");
108 | $method->setObject("ClassOne");
109 | $method->setArray(true);
110 | $this->assertEquals('[{"field1":"value1","field2":"value2"},{"field1":"second value1","field2":"second value2"},{"field1":"third value1","field2":"third value2"}]', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
111 |
112 | $method = new RESTMethod();
113 | $method->setName("touchComplex9");
114 | $method->setArray(true);
115 | $method->setResult("val");
116 | $this->assertEquals('{"val":["ciao","marco",false]}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
117 |
118 | $method = new RESTMethod();
119 | $method->setName("touchComplex10");
120 | $method->setArray(true);
121 | $method->setResult("val");
122 | $this->assertEquals('{"val":{"key1":"value1","key2":"value2","key3":{"nested1":"nv1","nested2":"nv2"}}}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
123 |
124 | $method = new RESTMethod();
125 | $method->setName("touchComplex11");
126 | $method->setArray(true);
127 | $method->setResult("val");
128 | $this->assertEquals('{"val":{"key1":"value1","key2":"value2","key3":{"nested1":"nv1","nested2":{"yo1":"vyo1","yo2":[1,2,3]}}}}', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
129 | }
130 |
131 | function testError() {
132 | RESTConfigurationLoader::reloadConfiguration(SERVER_KEY, dirname(__FILE__) . "/test7.xml");
133 | $method = new RESTMethod();
134 | $method->setName("touchError");
135 | $method->setObject("ClassOne");
136 | $method->setArray(true);
137 | $this->assertEquals('[{"code":1,"message":"custom message"}]', doCall($method, null, new NewSampleAPI(), SERVER_KEY));
138 | }
139 | }
140 |
141 |
142 | class ClassOne {
143 | public $field1;
144 | public $field2;
145 | }
146 |
147 | class ClassTwo {
148 | public $childField1;
149 | public $childField2;
150 | }
151 |
152 | class ClassThree {
153 | public $f1;
154 | public $f2;
155 | public $f3;
156 | public $f4;
157 |
158 | public function getField1() {
159 | return $this->f1;
160 | }
161 |
162 | public function getField2() {
163 | return $this->f2;
164 | }
165 |
166 | public function getField3() {
167 | return $this->f3;
168 | }
169 |
170 | public function getField4() {
171 | return $this->f4;
172 | }
173 | }
174 |
175 | class NewSampleAPI extends MashapeRestAPI {
176 |
177 | // Don't edit the constructor code
178 | public function __construct() {
179 | parent::__construct(dirname(__FILE__));
180 | }
181 |
182 | public function touchNull() {
183 | return null;
184 | }
185 |
186 | public function touchSimple() {
187 | return "simpleValue";
188 | }
189 |
190 | public function touchSimpleArray() {
191 | $result = array("value1", 3, "value3");
192 | return $result;
193 | }
194 |
195 | public function touchComplex() {
196 | $result = new ClassOne();
197 | $result->field1 = "value1";
198 | $result->field2 = "value2";
199 | return $result;
200 | }
201 |
202 | public function touchComplex2() {
203 | $result = new ClassOne();
204 | $result->field1 = null;
205 | $result->field2 = "value2";
206 | return $result;
207 | }
208 |
209 | public function touchComplex3() {
210 | $result = new ClassOne();
211 | $result->field1 = "value1";
212 | $child = new ClassTwo();
213 | $child->childField1 = "child value 1";
214 | $child->childField2 = "child value 2";
215 | $result->field2 = $child;
216 | return $result;
217 | }
218 |
219 | public function touchComplex4() {
220 | $result = new ClassOne();
221 | $result->field1 = "value1";
222 | $result->field2 = null;
223 | return $result;
224 | }
225 |
226 | public function touchComplex5() {
227 | $result = new ClassOne();
228 | $result->field1 = array("value1", 3, "value3");
229 | $result->field2 = null;
230 | return $result;
231 | }
232 |
233 | public function touchComplex6() {
234 | $result = new ClassOne();
235 | $childs = array();
236 |
237 | $child = new ClassTwo();
238 | $child->childField1 = "child value 1";
239 | $child->childField2 = "child value 2";
240 | array_push($childs, $child);
241 | $child = new ClassTwo();
242 | $child->childField1 = "second child value 1";
243 | $child->childField2 = "second child value 2";
244 | array_push($childs, $child);
245 |
246 | $result->field1 = $childs;
247 | $result->field2 = null;
248 | return $result;
249 | }
250 |
251 | public function touchComplex7() {
252 | $result = new ClassThree();
253 | $result->f1 = "this is field1";
254 | $result->f2 = array("this", "is", "field", 2, true);
255 | $result->f3 = null;
256 |
257 | $childs = array();
258 |
259 | $child = new ClassOne();
260 | $child->field1 = "child value 1";
261 | $child->field2 = "child value 2";
262 | array_push($childs, $child);
263 |
264 | $child = new ClassOne();
265 | $child->field1 = "second child value 1";
266 | $child->field2 = "second child value 2";
267 | array_push($childs, $child);
268 |
269 | $result->f4 = $childs;
270 | return $result;
271 | }
272 |
273 | public function touchComplex8() {
274 | $result = array();
275 | $obj = new ClassOne();
276 | $obj->field1 = "value1";
277 | $obj->field2 = "value2";
278 | array_push($result, $obj);
279 | $obj = new ClassOne();
280 | $obj->field1 = "second value1";
281 | $obj->field2 = "second value2";
282 | array_push($result, $obj);
283 |
284 | $obj = new ClassOne();
285 | $obj->field1 = "third value1";
286 | $obj->field2 = "third value2";
287 | array_push($result, $obj);
288 |
289 | return $result;
290 | }
291 |
292 | public function touchComplex9() {
293 | return array("ciao", "marco", false);
294 | }
295 |
296 | public function touchComplex10() {
297 | return array("key1"=>"value1", "key2"=>"value2", "key3"=>array("nested1"=>"nv1", "nested2"=>"nv2"));
298 | }
299 |
300 | public function touchComplex11() {
301 | return array("key1"=>"value1", "key2"=>"value2", "key3"=>array("nested1"=>"nv1", "nested2"=>array("yo1"=>"vyo1", "yo2"=>array(1,2,3))));
302 | }
303 |
304 | public function touchError() {
305 | parent::addError(1, "custom message");
306 | return null;
307 | }
308 | }
309 |
--------------------------------------------------------------------------------
/tests/methods/call/helpers/test.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/tests/methods/call/helpers/test2.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/tests/methods/call/helpers/test3.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/tests/methods/call/helpers/test4.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/tests/methods/call/helpers/test5.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/tests/methods/call/helpers/test6.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
9 |
10 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/tests/methods/call/helpers/test7.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/tests/methods/discover/discoverTest.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(MASHAPE_LIBRAY_PATH . "/mashape.php");
28 | require_once(MASHAPE_LIBRAY_PATH . "/methods/discover/discover.php");
29 |
30 | class DiscoverTest extends PHPUnit_Framework_TestCase
31 | {
32 | function testDiscover() {
33 | $discover = new Discover();
34 | try {
35 | $result = $discover->handle(new SampleAPI(), "serverkey", null, "post");
36 | $this->assertTrue(false);
37 | } catch (Exception $e) {
38 | if ($e instanceof MashapeException) {
39 | $this->assertTrue(true);
40 | } else {
41 | $this->assertTrue(false);
42 | }
43 | }
44 | }
45 | }
46 |
47 | class SampleAPI extends MashapeRestAPI {
48 |
49 | // Don't edit the constructor code
50 | public function __construct() {
51 | parent::__construct(dirname(__FILE__));
52 | }
53 |
54 | public function sayHello($name) {
55 | return "Hi, " . $name;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/tests/net/httpUtilsTest.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(MASHAPE_LIBRAY_PATH . "/net/httpUtils.php");
28 |
29 | class HttpUtilsTest extends PHPUnit_Framework_TestCase
30 | {
31 | /**
32 | * @TODO: This is an integration test with www.mashape.com
33 | * This test could fail if the site is unreachable (maintenance, dns, proxy, firewall etc.)
34 | * The external resource should be mocked
35 | * ~ dluc
36 | */
37 | function testMakeHttpRequest() {
38 | $response = HttpUtils::makeHttpRequest("http://www.mashape.com");
39 | $this->assertFalse(empty($response));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/tests/phpunit.CI.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | ./configuration
10 | ./json
11 | ./methods
12 | ./net
13 | ./utils
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/tests/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 | ./configuration
10 | ./json
11 | ./methods
12 | ./net
13 | ./utils
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/tests/utils/arrayUtilsTest.php:
--------------------------------------------------------------------------------
1 | .
20 | *
21 | *
22 | * The author of this software is Mashape, Inc.
23 | * For any question or feedback please contact us at: support@mashape.com
24 | *
25 | */
26 |
27 | require_once(MASHAPE_LIBRAY_PATH . "/utils/arrayUtils.php");
28 |
29 | class ArrayUtilsTest extends PHPUnit_Framework_TestCase
30 | {
31 | function testIsAssociative() {
32 | $this->assertFalse(ArrayUtils::isAssociative(null));
33 | $this->assertFalse(ArrayUtils::isAssociative(array()));
34 | $this->assertFalse(ArrayUtils::isAssociative(array(1,2,3)));
35 | $this->assertFalse(ArrayUtils::isAssociative(array("value",2,false)));
36 | $this->assertTrue(ArrayUtils::isAssociative(array("key1"=>"value1", "key2"=>"value2")));
37 | }
38 | }
39 |
--------------------------------------------------------------------------------