├── .github
├── FUNDING.yml
└── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── PluboRoutes
├── Endpoint
│ ├── DeleteEndpoint.php
│ ├── Endpoint.php
│ ├── EndpointInterface.php
│ ├── GetEndpoint.php
│ ├── PostEndpoint.php
│ └── PutEndpoint.php
├── Helpers
│ ├── RegexHelper.php
│ ├── RegexHelperEndpoints.php
│ └── RegexHelperRoutes.php
├── Middleware
│ ├── Cache.php
│ ├── Cors.php
│ ├── JwtValidation.php
│ ├── MiddlewareInterface.php
│ ├── Permissions.php
│ ├── RateLimit.php
│ └── SchemaValidator.php
├── PermissionChecker.php
├── Route
│ ├── ActionRoute.php
│ ├── PageRoute.php
│ ├── RedirectRoute.php
│ ├── Route.php
│ ├── RouteInterface.php
│ └── RouteTrait.php
├── Router.php
└── RoutesProcessor.php
├── README.md
├── SECURITY.md
├── composer.json
├── composer.lock
├── plubo-routes.php
├── pull_request_template.md
├── renovate.json
└── test.json
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: #
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: joanrodas
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
14 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | vendor/
2 | node_modules/
3 | *.log
4 | *.env
5 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## 0.3
4 |
5 | ### 0.3.2
6 |
7 | * [Fix] Fix body class error
8 |
9 | ### 0.3.1
10 |
11 | * [Feature] Allow callable for roles and capabilities
12 |
13 | ### 0.3.0
14 |
15 | * [Feature] Private routes: Logged only + role & capabilities filter with custom redirect and status code
16 |
17 | ## 0.2
18 |
19 | ### 0.2.0
20 |
21 | * [Feature] Endpoints
22 |
23 | ## 0.1
24 |
25 | ### 0.1.4
26 |
27 | * [Refactor] Added Traits + Regex helper class
28 |
29 | ### 0.1.3
30 |
31 | * [Fix] Serializable + Auto flush
32 |
33 | ### 0.1.2
34 |
35 | * [Feature] Redirect routes
36 | * [Feature] Action routes
37 | * [Feature] IP format
38 |
39 | ### 0.1.1
40 |
41 | * [Feature] JWT and digit formats
42 |
43 | ### 0.1.0
44 |
45 | * [Initial release] Basic routing system
46 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | joan@sirvelia.com.
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to Plubo Routes
2 | Contributions to this projects are more than welcome, whether it's:
3 |
4 | - Reporting a bug 🐛
5 | - Submitting a fix or improvement of the code 🩹
6 | - Proposing new features 💡
7 | - Becoming a maintainer 🧑💼
8 |
9 | *All code is hosted on github.*
10 |
11 | ## All Code Changes Happen Through Pull Requests. [Github Flow](https://guides.github.com/introduction/flow/index.html)
12 | Pull requests are the best way to propose changes to the codebase.
13 |
14 | To make a pull request:
15 |
16 | 1. Fork the repo and create your branch from `main`.
17 | 2. Make your changes.
18 | 3. Make sure everything is OK and your code lints.
19 | 4. Issue a pull request
20 | 5. Update the documentation if necessary.
21 |
22 | ## Report bugs using Github's [issues](https://github.com/joanrodas/plubo-routes/issues)
23 | GitHub issues are great to track public bugs. Report a bug by [opening a new issue](https://github.com/joanrodas/plubo-routes/issues/new/choose); it's that easy!
24 |
25 | ## Write bug reports with detail, background, and sample code
26 |
27 | **Great Bug Reports** tend to have:
28 |
29 | - A quick summary and/or background
30 | - Specific steps to reproduce, preferably with sample code
31 | - What you expected to happen
32 | - What actually happens
33 | - Notes. Anything you think could be helpful. Things you've tried, what you think could be the cause or even suggesting possible solutions
34 |
35 |
36 | ## Use a Consistent Coding Style
37 |
38 | * Tabs for indentation
39 | * You can try running `npm run lint` for style unification
40 |
41 | ## License
42 |
43 | Any contributions you make will be under GNU GPLv3 Software License. By contributing, you agree that your code will be licensed under the GNU GPLv3 License.
44 | Feel free to contact the author if that's a concern.
45 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/PluboRoutes/Endpoint/DeleteEndpoint.php:
--------------------------------------------------------------------------------
1 | method = \WP_REST_Server::DELETABLE;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/PluboRoutes/Endpoint/Endpoint.php:
--------------------------------------------------------------------------------
1 | namespace = $namespace;
64 | $this->path = $path;
65 | $this->config = $config;
66 | $this->permission_callback = $permission_callback ?? '__return_true';
67 | }
68 |
69 | /**
70 | * Get the namespace of the endpoint.
71 | *
72 | * @return string
73 | */
74 | public function getNamespace()
75 | {
76 | return $this->namespace;
77 | }
78 |
79 | /**
80 | * Get the path to be matched.
81 | *
82 | * @return string
83 | */
84 | public function getPath()
85 | {
86 | return $this->path;
87 | }
88 |
89 | /**
90 | * Get the config parameters of the endpoint.
91 | *
92 | * @return array
93 | */
94 | public function getConfig()
95 | {
96 | return $this->config;
97 | }
98 |
99 | /**
100 | * Get the method of the endpoint.
101 | *
102 | * @return string
103 | */
104 | public function getMethod()
105 | {
106 | return $this->method;
107 | }
108 |
109 | /**
110 | * Get the endpoint permission callback.
111 | *
112 | * @return callable
113 | */
114 | public function getPermissionCallback()
115 | {
116 | return $this->permission_callback;
117 | }
118 |
119 | /**
120 | * Add middleware to this endpoint.
121 | *
122 | * @param callable $middleware
123 | */
124 | public function useMiddleware($middleware)
125 | {
126 | $this->middlewareStack[] = $middleware;
127 | }
128 |
129 | /**
130 | * Get the middleware stack for this endpoint.
131 | *
132 | * @return array
133 | */
134 | public function getMiddlewareStack()
135 | {
136 | return $this->middlewareStack;
137 | }
138 |
139 | /**
140 | * Serialize the endpoint.
141 | *
142 | * @return string
143 | */
144 | public function __serialize()
145 | {
146 | return [
147 | 'namespace' => $this->namespace,
148 | 'path' => $this->path,
149 | 'method' => $this->method
150 | ];
151 | }
152 |
153 | /**
154 | * Unserialize the endpoint.
155 | *
156 | * @param array
157 | */
158 | public function __unserialize($data)
159 | {
160 | $this->namespace = $data['namespace'];
161 | $this->path = $data['path'];
162 | $this->method = $data['method'];
163 | }
164 | }
165 |
--------------------------------------------------------------------------------
/PluboRoutes/Endpoint/EndpointInterface.php:
--------------------------------------------------------------------------------
1 | method = \WP_REST_Server::READABLE;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/PluboRoutes/Endpoint/PostEndpoint.php:
--------------------------------------------------------------------------------
1 | method = \WP_REST_Server::CREATABLE;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/PluboRoutes/Endpoint/PutEndpoint.php:
--------------------------------------------------------------------------------
1 | method = 'PUT';
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/PluboRoutes/Helpers/RegexHelper.php:
--------------------------------------------------------------------------------
1 | self::DIGIT,
25 | 'number' => self::NUMBER,
26 | 'word' => self::WORD,
27 | 'text' => self::TEXT,
28 | 'alphanumeric' => self::ALPHANUMERIC,
29 | 'hex' => self::HEXADECIMAL,
30 | 'uuid' => self::UUID,
31 | 'file' => self::FILE_PATH,
32 | 'date' => self::DATE,
33 | 'year' => self::YEAR,
34 | 'month' => self::MONTH,
35 | 'day' => self::DAY,
36 | 'ip' => self::IP,
37 | 'jwt' => self::JWT,
38 | 'slug' => self::SLUG,
39 | ];
40 |
41 | /**
42 | * Get translated Regex path for an endpoint route.
43 | *
44 | * @param string $path
45 | */
46 | public function getRegexMatches(string $regex_path)
47 | {
48 | preg_match_all('#\{(.+?)\}#', $regex_path, $matches);
49 | return $matches;
50 | }
51 |
52 | /**
53 | * Return trimmed path.
54 | *
55 | * @param string $path
56 | * @return string
57 | */
58 | public function cleanPath(string $path)
59 | {
60 | return ltrim(trim($path), '/');
61 | }
62 |
63 | /**
64 | * Return regex of path.
65 | *
66 | * @param mixed $type
67 | * @return string
68 | */
69 | abstract public function getRegex($type): string;
70 | }
71 |
--------------------------------------------------------------------------------
/PluboRoutes/Helpers/RegexHelperEndpoints.php:
--------------------------------------------------------------------------------
1 | $regex_code)";
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/PluboRoutes/Helpers/RegexHelperRoutes.php:
--------------------------------------------------------------------------------
1 | cacheTime = $cacheTime;
14 | }
15 |
16 | public function handle(WP_REST_Request $request, callable $next)
17 | {
18 | $cacheKey = 'route_cache_' . md5($_SERVER['REQUEST_URI']);
19 | $cachedResponse = get_transient($cacheKey);
20 |
21 | if ($cachedResponse) {
22 | return $cachedResponse;
23 | }
24 |
25 | $response = $next($request);
26 | set_transient($cacheKey, $response, $this->cacheTime);
27 |
28 | return $response;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/PluboRoutes/Middleware/Cors.php:
--------------------------------------------------------------------------------
1 | allowedOrigins = is_array($allowedOrigins) ? $allowedOrigins : [$allowedOrigins];
17 | $this->allowedMethods = array_map('strtoupper', $allowedMethods);
18 | $this->allowedHeaders = array_map('strtolower', $allowedHeaders);
19 | }
20 |
21 | public function handle(WP_REST_Request $request, callable $next)
22 | {
23 | $origin = $request->get_header('origin');
24 |
25 | if ($this->isAllowedOrigin($origin)) {
26 | header("Access-Control-Allow-Origin: {$origin}");
27 | header('Access-Control-Allow-Credentials: true');
28 | header("Access-Control-Allow-Methods: " . implode(', ', $this->allowedMethods));
29 | header("Access-Control-Allow-Headers: " . implode(', ', $this->allowedHeaders));
30 | header("Access-Control-Max-Age: {$this->maxAge}");
31 | }
32 |
33 | if ($request->get_method() === 'OPTIONS') {
34 | return new \WP_REST_Response(null, 204);
35 | }
36 |
37 | if (!in_array($request->get_method(), $this->allowedMethods)) {
38 | return new \WP_REST_Response(['error' => 'Method not allowed'], 405);
39 | }
40 |
41 | return $next($request);
42 | }
43 |
44 | protected function isAllowedOrigin($origin)
45 | {
46 | if (in_array('*', $this->allowedOrigins)) {
47 | return true;
48 | }
49 | return in_array($origin, $this->allowedOrigins);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/PluboRoutes/Middleware/JwtValidation.php:
--------------------------------------------------------------------------------
1 | secret_key = $secret_key;
36 | $this->expected_issuer = $expected_issuer;
37 | $this->expected_audience = $expected_audience;
38 | $this->leeway = $leeway;
39 | }
40 |
41 | /**
42 | * Handles the incoming request and validates the JWT token.
43 | *
44 | * @param mixed $request The incoming request object.
45 | * @param callable $next The next middleware to execute.
46 | *
47 | * @return WP_REST_Response|WP_Error The response after validation.
48 | */
49 | public function handle(WP_REST_Request $request, callable $next)
50 | {
51 | $authHeader = $this->get_authorization_header();
52 |
53 | if (!$authHeader) {
54 | return $this->error_response('Authorization token missing', 401);
55 | }
56 |
57 | if (preg_match('/Bearer\s(\S+)/i', $authHeader, $matches)) {
58 | $token = sanitize_text_field($matches[1]);
59 |
60 | // Validate the token
61 | $validationResult = $this->validateToken($token);
62 |
63 | if (is_wp_error($validationResult)) {
64 | return $validationResult;
65 | }
66 |
67 | // Token is valid; proceed to the next middleware or request handler
68 | return $next($request);
69 | } else {
70 | return $this->error_response('Invalid Authorization header format', 400);
71 | }
72 | }
73 |
74 | /**
75 | * Retrieves the Authorization header from the request.
76 | *
77 | * @return string|null The Authorization header if present, null otherwise.
78 | */
79 | private function get_authorization_header(): ?string
80 | {
81 | // Check $_SERVER superglobal.
82 | if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
83 | return sanitize_text_field(wp_unslash($_SERVER['HTTP_AUTHORIZATION']));
84 | }
85 |
86 | // Some servers use REDIRECT_HTTP_AUTHORIZATION.
87 | if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
88 | return sanitize_text_field(wp_unslash($_SERVER['REDIRECT_HTTP_AUTHORIZATION']));
89 | }
90 |
91 | return null;
92 | }
93 |
94 | /**
95 | * Validates the JWT token.
96 | *
97 | * @param string $token The JWT token to validate.
98 | * @return true|WP_Error Returns true if valid, WP_Error otherwise.
99 | */
100 | private function validateToken(string $token)
101 | {
102 | $parts = explode('.', $token);
103 |
104 | if (count($parts) !== 3) {
105 | return $this->error_response('Invalid token format', 400);
106 | }
107 |
108 | list($header, $payload, $signature) = $parts;
109 |
110 | // Decode the JWT segments safely
111 | $decodedHeader = $this->base64UrlDecode($header);
112 | $decodedPayload = $this->base64UrlDecode($payload);
113 |
114 | if (!$decodedHeader || !$decodedPayload) {
115 | return $this->error_response('Invalid token encoding', 400);
116 | }
117 |
118 | $headerArray = json_decode($decodedHeader, true);
119 | $payloadArray = json_decode($decodedPayload, true);
120 |
121 | if (json_last_error() !== JSON_ERROR_NONE) {
122 | return $this->error_response('Invalid JSON in token', 400);
123 | }
124 |
125 | // Validate the algorithm
126 | if (empty($headerArray['alg']) || $headerArray['alg'] !== 'HS256') {
127 | return $this->error_response('Unsupported token algorithm', 400);
128 | }
129 |
130 | // Recreate the signature
131 | $dataToSign = "$header.$payload";
132 | $expectedSignature = $this->base64UrlEncode(hash_hmac('sha256', $dataToSign, $this->secret_key, true));
133 |
134 | if (!hash_equals($expectedSignature, $signature)) {
135 | return $this->error_response('Signature verification failed', 403);
136 | }
137 |
138 | // 1. Expiration time (exp)
139 | if (isset($payloadArray['exp'])) {
140 | if (!is_numeric($payloadArray['exp'])) {
141 | return $this->error_response('Invalid expiration claim', 400);
142 | }
143 | if (($payloadArray['exp'] + $this->leeway) < time()) {
144 | return $this->error_response('Token has expired', 401);
145 | }
146 | }
147 |
148 | // 2. Not Before (nbf)
149 | if (isset($payloadArray['nbf'])) {
150 | if (!is_numeric($payloadArray['nbf'])) {
151 | return $this->error_response('Invalid not before claim', 400);
152 | }
153 | if (($payloadArray['nbf'] - $this->leeway) > time()) {
154 | return $this->error_response('Token is not yet valid', 401);
155 | }
156 | }
157 |
158 | // 3. Issued At (iat)
159 | if (isset($payloadArray['iat'])) {
160 | if (!is_numeric($payloadArray['iat'])) {
161 | return $this->error_response('Invalid issued at claim', 400);
162 | }
163 | if (($payloadArray['iat'] - $this->leeway) > time()) {
164 | return $this->error_response('Token was issued in the future', 400);
165 | }
166 | }
167 |
168 | // 4. Issuer (iss)
169 | if ($this->expected_issuer !== null) {
170 | if (!isset($payloadArray['iss']) || !is_string($payloadArray['iss'])) {
171 | return $this->error_response('Issuer claim missing or invalid', 403);
172 | }
173 | if ($payloadArray['iss'] !== $this->expected_issuer) {
174 | return $this->error_response('Invalid issuer', 403);
175 | }
176 | }
177 |
178 | // 5. Audience (aud)
179 | if ($this->expected_audience !== null) {
180 | if (!isset($payloadArray['aud'])) {
181 | return $this->error_response('Audience claim missing', 403);
182 | }
183 |
184 | // 'aud' can be a string or an array of strings
185 | $audience = $payloadArray['aud'];
186 | $isValidAudience = false;
187 |
188 | if (is_string($audience) && $audience === $this->expected_audience) {
189 | $isValidAudience = true;
190 | } elseif (is_array($audience) && in_array($this->expected_audience, $audience, true)) {
191 | $isValidAudience = true;
192 | }
193 |
194 | if (!$isValidAudience) {
195 | return $this->error_response('Invalid audience', 403);
196 | }
197 | }
198 |
199 | return true;
200 | }
201 |
202 | /**
203 | * Creates a standardized WP_Error response.
204 | *
205 | * @param string $message The error message.
206 | * @param int $status The HTTP status code.
207 | *
208 | * @return WP_Error The WP_Error object.
209 | */
210 | private function error_response(string $message, int $status): WP_Error
211 | {
212 | $this->log_error($message);
213 | return new WP_Error('jwt_validation_error', esc_html($message), ['status' => $status]);
214 | }
215 |
216 | private function log_error(string $message): void
217 | {
218 | if (defined('WP_DEBUG') && WP_DEBUG) {
219 | error_log('[JWT Validation Error] ' . $message);
220 | }
221 | }
222 |
223 | /**
224 | * Encodes data using Base64 URL encoding.
225 | *
226 | * @param string $data The data to encode.
227 | *
228 | * @return string The Base64 URL encoded data.
229 | */
230 | private function base64UrlEncode(string $data): string
231 | {
232 | return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
233 | }
234 |
235 | /**
236 | * Decodes Base64 URL encoded data.
237 | *
238 | * @param string $data The Base64 URL encoded data.
239 | *
240 | * @return string|false The decoded data or false on failure.
241 | */
242 | private function base64UrlDecode(string $data)
243 | {
244 | $padding = 4 - (strlen($data) % 4);
245 | if ($padding < 4) {
246 | $data .= str_repeat('=', $padding);
247 | }
248 | $decoded = base64_decode(strtr($data, '-_', '+/'), true);
249 | return $decoded;
250 | }
251 | }
252 |
--------------------------------------------------------------------------------
/PluboRoutes/Middleware/MiddlewareInterface.php:
--------------------------------------------------------------------------------
1 | type = $type;
24 | $this->allowed_roles = $allowed_roles;
25 | $this->allowed_capabilities = $allowed_capabilities;
26 | $this->disallowed_roles = $disallowed_roles;
27 | $this->disallowed_capabilities = $disallowed_capabilities;
28 | }
29 |
30 | public function handle(WP_REST_Request $request, callable $next)
31 | {
32 | $user = wp_get_current_user();
33 |
34 | // Check guest, registered, or open
35 | if ($this->type) {
36 | $is_guest = !$user->exists();
37 | if (($this->type === 'registered' && $is_guest) || ($this->type === 'guest' && !$is_guest)) {
38 | return $this->forbiddenResponse('Access restricted');
39 | }
40 | }
41 |
42 | // Check disallowed roles
43 | if (!empty($this->disallowed_roles) && array_intersect($user->roles, $this->disallowed_roles)) {
44 | return $this->forbiddenResponse('User role not allowed');
45 | }
46 |
47 | // Check disallowed capabilities
48 | if (!empty($this->disallowed_capabilities)) {
49 | foreach ($this->disallowed_capabilities as $capability) {
50 | if ($user->has_cap($capability)) {
51 | return $this->forbiddenResponse('User capability not allowed');
52 | }
53 | }
54 | }
55 |
56 | // Check allowed roles if disallowed checks passed
57 | if (!empty($this->allowed_roles) && !array_intersect($user->roles, $this->allowed_roles)) {
58 | return $this->forbiddenResponse('User role not allowed');
59 | }
60 |
61 | // Check allowed capabilities if disallowed checks passed
62 | if (!empty($this->allowed_capabilities)) {
63 | $has_cap = false;
64 | foreach ($this->allowed_capabilities as $capability) {
65 | if ($user->has_cap($capability)) {
66 | $has_cap = true;
67 | break;
68 | }
69 | }
70 | if (!$has_cap) {
71 | return $this->forbiddenResponse('User lacks required capabilities');
72 | }
73 | }
74 |
75 | return $next($request);
76 | }
77 |
78 | private function forbiddenResponse(string $message)
79 | {
80 | return new WP_Error('permission_denied', $message, ['status' => 403]);
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/PluboRoutes/Middleware/RateLimit.php:
--------------------------------------------------------------------------------
1 | maxRequests = max(1, intval($maxRequests));
45 | $this->windowTime = max(1, intval($windowTime));
46 | $this->type = in_array($type, ['ip', 'user', 'endpoint']) ? $type : 'ip';
47 | }
48 |
49 | /**
50 | * Handles the incoming request and enforces rate limiting.
51 | *
52 | * @param mixed $request The incoming request object.
53 | * @param callable $next The next middleware to execute.
54 | *
55 | * @return WP_REST_Response|WP_Error The response after rate limiting.
56 | */
57 | public function handle(WP_REST_Request $request, callable $next)
58 | {
59 | $key = $this->getRateLimitKey($request);
60 | $requestCount = get_transient($key);
61 |
62 | if ($requestCount === false) {
63 | set_transient($key, 1, $this->windowTime);
64 | } else {
65 | if ($requestCount >= $this->maxRequests) {
66 | do_action('plubo/rate_limit_exceeded', $request, $this->type);
67 | return new \WP_REST_Response(['error' => 'Too many requests'], 429);
68 | }
69 | set_transient($key, $requestCount + 1, $this->windowTime);
70 | }
71 |
72 | $response = $next($request);
73 |
74 | // Add rate limit headers
75 | if ($response instanceof WP_REST_Response) {
76 | $response->set_headers([
77 | 'X-RateLimit-Limit' => $this->maxRequests,
78 | 'X-RateLimit-Remaining' => max(0, $this->maxRequests - ($requestCount + 1)),
79 | 'X-RateLimit-Reset' => time() + $this->windowTime,
80 | ]);
81 | }
82 |
83 | return $response;
84 | }
85 |
86 | protected function getRateLimitKey($request)
87 | {
88 | switch ($this->type) {
89 | case 'user':
90 | $identifier = get_current_user_id() ?: $this->getClientIp();
91 | break;
92 | case 'endpoint':
93 | $identifier = $request->get_route();
94 | break;
95 | case 'ip':
96 | default:
97 | $identifier = $this->getClientIp();
98 | }
99 | return $this->prefix . md5($identifier . $this->type);
100 | }
101 |
102 | /**
103 | * Retrieves the client's IP address securely.
104 | *
105 | * @return string The sanitized client IP or 'unknown'.
106 | */
107 | protected function getClientIp(): string
108 | {
109 | $ipKeys = [
110 | 'HTTP_CLIENT_IP',
111 | 'HTTP_X_FORWARDED_FOR',
112 | 'HTTP_X_FORWARDED',
113 | 'HTTP_X_CLUSTER_CLIENT_IP',
114 | 'HTTP_FORWARDED_FOR',
115 | 'HTTP_FORWARDED',
116 | 'REMOTE_ADDR',
117 | ];
118 |
119 | foreach ($ipKeys as $key) {
120 | if (!empty($_SERVER[$key])) {
121 | // Handle multiple IPs (e.g., X-Forwarded-For: client, proxy1, proxy2)
122 | $ips = explode(',', wp_unslash($_SERVER[$key]));
123 | foreach ($ips as $ip) {
124 | $ip = trim($ip);
125 | if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
126 | return sanitize_text_field($ip);
127 | }
128 | }
129 | }
130 | }
131 |
132 | return 'unknown';
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/PluboRoutes/Middleware/SchemaValidator.php:
--------------------------------------------------------------------------------
1 | schema = $schema;
16 | }
17 |
18 | public function handle(WP_REST_Request $request, callable $next)
19 | {
20 | $params = $request->get_params();
21 | $paramsObject = json_decode(json_encode($params));
22 |
23 | // Validate against the schema
24 | $validator = new Validator();
25 | $validator->validate($paramsObject, $this->schema, Constraint::CHECK_MODE_APPLY_DEFAULTS);
26 |
27 | if (!$validator->isValid()) {
28 | $errors = array_map(function ($error) {
29 | return sprintf("[%s] %s", $error['property'], $error['message']);
30 | }, $validator->getErrors());
31 |
32 | return new \WP_REST_Response(['error' => 'Input validation failed', 'details' => $errors], 400);
33 | }
34 |
35 | // Sanitize data
36 | $sanitizedData = $this->sanitize($paramsObject, $this->schema);
37 |
38 | // Replace request parameters with sanitized and validated data
39 | foreach ($sanitizedData as $key => $value) {
40 | $request->set_param($key, $value);
41 | }
42 |
43 | return $next($request);
44 | }
45 |
46 | private function sanitize($data, $schema)
47 | {
48 | if (!is_object($schema)) {
49 | $schema = json_decode(json_encode($schema));
50 | }
51 |
52 | $sanitizedData = [];
53 |
54 | foreach ($schema->properties as $key => $property) {
55 | if (isset($data->$key)) {
56 | $sanitizedData[$key] = $this->sanitizeValue($data->$key, $property);
57 | }
58 | }
59 |
60 | return (object)$sanitizedData;
61 | }
62 |
63 | private function sanitizeValue($value, $propertySchema)
64 | {
65 | $type = $propertySchema->type ?? 'string';
66 |
67 | switch ($type) {
68 | case 'string':
69 | if (isset($propertySchema->format)) {
70 | switch ($propertySchema->format) {
71 | case 'email':
72 | return filter_var($value, FILTER_VALIDATE_EMAIL) ? sanitize_email($value) : null;
73 | case 'uri':
74 | return filter_var($value, FILTER_VALIDATE_URL) ? esc_url($value) : null;
75 | case 'date-time':
76 | try {
77 | $dateTime = new \DateTime($value);
78 | return $dateTime->format(\DateTime::ATOM); // Sanitized ISO 8601 date-time string
79 | } catch (\Exception $e) {
80 | return null; // Invalid date-time
81 | }
82 | default:
83 | return sanitize_text_field($value); // Default sanitization for unknown formats
84 | }
85 | }
86 | return sanitize_text_field($value);
87 | case 'integer':
88 | return intval($value);
89 | case 'number':
90 | return floatval($value);
91 | case 'boolean':
92 | return filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
93 | case 'array':
94 | if (is_array($value) && isset($propertySchema->items)) {
95 | return array_map(function ($item) use ($propertySchema) {
96 | return $this->sanitizeValue($item, $propertySchema->items);
97 | }, $value);
98 | }
99 | return [];
100 | case 'object':
101 | if (is_object($value) && isset($propertySchema->properties)) {
102 | $sanitizedObject = [];
103 | foreach ($propertySchema->properties as $subKey => $subSchema) {
104 | if (isset($value->$subKey)) {
105 | $sanitizedObject[$subKey] = $this->sanitizeValue($value->$subKey, $subSchema);
106 | }
107 | }
108 | return (object)$sanitizedObject;
109 | }
110 | return new \stdClass();
111 | case 'null':
112 | return null;
113 | default:
114 | if (is_array($type)) { // Handle multiple types
115 | foreach ($type as $t) {
116 | $sanitized = $this->sanitizeValue($value, $t);
117 | if ($sanitized !== null) {
118 | return $sanitized;
119 | }
120 | }
121 | }
122 | return sanitize_text_field($value);
123 | }
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/PluboRoutes/PermissionChecker.php:
--------------------------------------------------------------------------------
1 | matched_route = $route;
45 | $this->matched_args = $args;
46 | $this->current_user = wp_get_current_user();
47 | }
48 |
49 | /**
50 | * Check permissions for the matched route.
51 | */
52 | public function checkPermissions()
53 | {
54 | $permission_callback = $this->matched_route->getPermissionCallback();
55 | if (!$permission_callback || !is_callable($permission_callback)) {
56 | return;
57 | }
58 | $has_access = $permission_callback($this->matched_args);
59 | if (!$has_access) {
60 | $this->forbidAccess();
61 | }
62 |
63 | if ($this->checkLoggedIn()) {
64 | $this->checkRoles();
65 | $this->checkCapabilities();
66 | }
67 | }
68 |
69 | /**
70 | * Check if the user is logged in and has access based on route settings.
71 | *
72 | * @return bool Whether the user is logged in.
73 | */
74 | private function checkLoggedIn()
75 | {
76 | $is_logged_in = $this->current_user->exists();
77 |
78 | if (
79 | !$this->matched_route->guestHasAccess() && !$is_logged_in
80 | || !$this->matched_route->memberHasAccess() && $is_logged_in
81 | ) {
82 | $this->forbidAccess();
83 | }
84 |
85 | return $is_logged_in;
86 | }
87 |
88 | /**
89 | * Check if the user has the required roles for the matched route.
90 | */
91 | private function checkRoles()
92 | {
93 | $allowed_roles = $this->matched_route->getRoles();
94 | if ($this->matched_route->hasRolesCallback()) {
95 | $allowed_roles = $allowed_roles($this->matched_args);
96 | }
97 | if ($allowed_roles !== false && !array_intersect((array)$this->current_user->roles, (array)$allowed_roles)) {
98 | $this->forbidAccess();
99 | }
100 | }
101 |
102 | /**
103 | * Check if the user has the required capabilities for the matched route.
104 | */
105 | private function checkCapabilities()
106 | {
107 | $allowed_caps = $this->getAllowedCapabilities();
108 | if ($allowed_caps === false) {
109 | return;
110 | }
111 |
112 | $is_allowed = false;
113 | foreach ((array)$allowed_caps as $allowed_cap) {
114 | if ($this->current_user->has_cap($allowed_cap)) {
115 | $is_allowed = true;
116 | break;
117 | }
118 | }
119 | if (!$is_allowed) {
120 | $this->forbidAccess();
121 | }
122 | }
123 |
124 | /**
125 | * Get the allowed capabilities for the matched route.
126 | *
127 | * @return mixed
128 | */
129 | private function getAllowedCapabilities()
130 | {
131 | $allowed_caps = $this->matched_route->getCapabilities();
132 | if ($this->matched_route->hasCapabilitiesCallback()) {
133 | $allowed_caps = $allowed_caps($this->matched_args);
134 | }
135 | return $allowed_caps;
136 | }
137 |
138 | /**
139 | * Forbid access based on route settings.
140 | */
141 | private function forbidAccess()
142 | {
143 | if ($this->matched_route->hasRedirect()) {
144 | wp_redirect(esc_url_raw($this->matched_route->getRedirect()), $this->matched_route->getNotAllowedStatus());
145 | exit;
146 | }
147 | status_header($this->matched_route->getNotAllowedStatus());
148 | exit();
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/PluboRoutes/Route/ActionRoute.php:
--------------------------------------------------------------------------------
1 | path = $path;
30 | $this->action = $action;
31 | $this->config = $config;
32 | $this->args = [];
33 | }
34 |
35 | /**
36 | * Get the action to be called when this route is matched.
37 | *
38 | * @return string|callable
39 | */
40 | public function getAction()
41 | {
42 | return $this->action;
43 | }
44 |
45 | /**
46 | * Check if the action is a callable.
47 | *
48 | * @return boolean
49 | */
50 | public function hasCallback()
51 | {
52 | return is_callable($this->action);
53 | }
54 |
55 | /**
56 | * Get the status.
57 | *
58 | * @return int
59 | */
60 | public function getStatus()
61 | {
62 | $status = $this->config['status'] ?? 200;
63 | return (int)$status;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/PluboRoutes/Route/PageRoute.php:
--------------------------------------------------------------------------------
1 | path = $path;
30 | $this->page_id = $page_id;
31 | $this->config = $config;
32 | $this->args = [];
33 | }
34 |
35 | /**
36 | * Get the action to be called when this route is matched.
37 | *
38 | * @return string|callable
39 | */
40 | public function getAction()
41 | {
42 | return "plubo/route_{$this->getName()}";
43 | }
44 |
45 | /**
46 | * Check if the action is a callable.
47 | *
48 | * @return boolean
49 | */
50 | public function hasCallback()
51 | {
52 | return false;
53 | }
54 |
55 | /**
56 | * Returns the page URI.
57 | *
58 | * @return string
59 | */
60 | public function getPageUri()
61 | {
62 | return get_page_uri($this->page_id);
63 | }
64 |
65 | /**
66 | * Returns the page ID.
67 | *
68 | * @return string
69 | */
70 | public function getPageId()
71 | {
72 | return $this->page_id;
73 | }
74 |
75 | /**
76 | * Get the status.
77 | *
78 | * @return int
79 | */
80 | public function getStatus()
81 | {
82 | $status = $this->config['status'] ?? 200;
83 | return (int)$status;
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/PluboRoutes/Route/RedirectRoute.php:
--------------------------------------------------------------------------------
1 | path = $path;
30 | $this->action = $action;
31 | $this->config = $config;
32 | $this->args = [];
33 | }
34 |
35 | /**
36 | * Get the action to be called when this route is matched.
37 | *
38 | * @return string|callable
39 | */
40 | public function getAction()
41 | {
42 | return $this->action;
43 | }
44 |
45 | /**
46 | * Check if the action is a callable.
47 | *
48 | * @return boolean
49 | */
50 | public function hasCallback()
51 | {
52 | return is_callable($this->action);
53 | }
54 |
55 | /**
56 | * Check if the action is a callable.
57 | *
58 | * @return boolean
59 | */
60 | public function isExternal()
61 | {
62 | $is_external = $this->config['external'] ?? false;
63 | return filter_var($is_external, FILTER_VALIDATE_BOOLEAN);
64 | }
65 |
66 | /**
67 | * Get the status.
68 | *
69 | * @return int
70 | */
71 | public function getStatus()
72 | {
73 | $status = $this->config['status'] ?? 301;
74 | in_array((int)$status, range(300, 308), true) or $status = 301;
75 | return $status;
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/PluboRoutes/Route/Route.php:
--------------------------------------------------------------------------------
1 | path = $path;
30 | $this->template = $template;
31 | $this->config = $config;
32 | $this->args = [];
33 | }
34 |
35 | /**
36 | * Get the action to be executed when this route is matched.
37 | *
38 | * @return string
39 | */
40 | public function getAction()
41 | {
42 | return "plubo/route_{$this->getName()}";
43 | }
44 |
45 | /**
46 | * Check if the action is a callable.
47 | *
48 | * @return boolean
49 | */
50 | public function hasCallback()
51 | {
52 | return false;
53 | }
54 |
55 | /**
56 | * Check if the template is a callable.
57 | *
58 | * @return boolean
59 | */
60 | public function hasTemplateCallback()
61 | {
62 | return is_callable($this->template);
63 | }
64 |
65 | /**
66 | * Get the template to be loaded when this route is matched.
67 | *
68 | * @return string
69 | */
70 | public function getTemplate()
71 | {
72 | $template_name = $this->template;
73 | if($this->hasTemplateCallback()) return $template_name;
74 |
75 | $custom_directory = $this->config['template_path'] ?? '';
76 |
77 | // Check if a custom directory is provided
78 | if ($custom_directory) {
79 | $customTemplate = trailingslashit($custom_directory) . $template_name;
80 | if (is_readable($customTemplate)) {
81 | return $customTemplate;
82 | }
83 | }
84 |
85 | // Check if the template exists in the theme
86 | $themeTemplate = locate_template(apply_filters('plubo/template', $template_name));
87 |
88 | return $themeTemplate ?: $template_name;
89 | }
90 |
91 | /**
92 | * Check if route has basic auth.
93 | *
94 | * @return boolean
95 | */
96 | public function hasBasicAuth()
97 | {
98 | $basic_auth = $this->config['basic_auth'] ?? [];
99 | return is_array($basic_auth) && !empty($basic_auth);
100 | }
101 |
102 | /**
103 | * Get basic auth.
104 | *
105 | * @return array
106 | */
107 | public function getBasicAuth()
108 | {
109 | $basic_auth = $this->config['basic_auth'] ?? [];
110 | return $basic_auth;
111 | }
112 |
113 | /**
114 | * Renders the html.
115 | *
116 | * @return boolean
117 | */
118 | public function isRender()
119 | {
120 | $render = $this->config['render'] ?? false;
121 | return filter_var(($render != false), FILTER_VALIDATE_BOOLEAN);
122 | }
123 |
124 | /**
125 | * Get the status.
126 | *
127 | * @return int
128 | */
129 | public function getStatus()
130 | {
131 | $status = $this->config['status'] ?? 200;
132 | return (int)$status;
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/PluboRoutes/Route/RouteInterface.php:
--------------------------------------------------------------------------------
1 | config['name'] ?? md5($this->path);
48 | }
49 |
50 | /**
51 | * Get the title of the route.
52 | *
53 | * @return string
54 | */
55 | public function getTitle()
56 | {
57 | return $this->config['title'] ?? '';
58 | }
59 |
60 | /**
61 | * Get the path to be matched.
62 | *
63 | * @return string
64 | */
65 | public function getPath()
66 | {
67 | return $this->path;
68 | }
69 |
70 | /**
71 | * Get the config parameters of the route.
72 | *
73 | * @return array
74 | */
75 | public function getConfig()
76 | {
77 | return $this->config;
78 | }
79 |
80 | /**
81 | * Set the matches of the route.
82 | *
83 | * @param array
84 | */
85 | public function addArg($arg)
86 | {
87 | $this->args[] = $arg;
88 | }
89 |
90 | /**
91 | * Get the matches of the route.
92 | *
93 | * @return array
94 | */
95 | public function getArgs()
96 | {
97 | return $this->args;
98 | }
99 |
100 | /**
101 | * Get extra query vars.
102 | *
103 | * @return array
104 | */
105 | public function getExtraVars()
106 | {
107 | $query_vars = $this->config['extra_vars'] ?? [];
108 | return $query_vars;
109 | }
110 |
111 | /**
112 | * Check if guests have access.
113 | *
114 | * @return boolean
115 | */
116 | public function guestHasAccess()
117 | {
118 | $guest_has_access = $this->config['guest'] ?? true;
119 | return filter_var($guest_has_access, FILTER_VALIDATE_BOOLEAN);
120 | }
121 |
122 | /**
123 | * Check if a logged in user has access.
124 | *
125 | * @return boolean
126 | */
127 | public function memberHasAccess()
128 | {
129 | $member_has_access = $this->config['logged_in'] ?? true;
130 | return filter_var($member_has_access, FILTER_VALIDATE_BOOLEAN);
131 | }
132 |
133 | /**
134 | * Check if the route has a redirect if access not allowed.
135 | *
136 | * @return boolean
137 | */
138 | public function hasRedirect()
139 | {
140 | $redirect = $this->config['redirect'] ?? false;
141 | return filter_var(($redirect != false), FILTER_VALIDATE_BOOLEAN);
142 | }
143 |
144 | /**
145 | * Get the http status if access not allowed.
146 | *
147 | * @return int
148 | */
149 | public function getNotAllowedStatus()
150 | {
151 | $status = $this->hasRedirect() ? 302 : 403;
152 | return $this->config['forbidden_status'] ?? $status;
153 | }
154 |
155 | /**
156 | * Get the redirect URL.
157 | *
158 | * @return int
159 | */
160 | public function getRedirect()
161 | {
162 | $redirect = $this->config['redirect'] ?? home_url();
163 | return $redirect;
164 | }
165 |
166 | /**
167 | * Check if the roles option is a callable.
168 | *
169 | * @return boolean
170 | */
171 | public function hasRolesCallback()
172 | {
173 | $roles = $this->config['allowed_roles'] ?? [];
174 | return is_callable($roles);
175 | }
176 |
177 | /**
178 | * Get the allowed roles.
179 | *
180 | * @return array|string
181 | */
182 | public function getRoles()
183 | {
184 | $roles = $this->config['allowed_roles'] ?? false;
185 | return $roles;
186 | }
187 |
188 | /**
189 | * Check if the capabilities option is a callable.
190 | *
191 | * @return boolean
192 | */
193 | public function hasCapabilitiesCallback()
194 | {
195 | $capabilities = $this->config['allowed_caps'] ?? [];
196 | return is_callable($capabilities);
197 | }
198 |
199 | /**
200 | * Get the allowed capabilities.
201 | *
202 | * @return array|string
203 | */
204 | public function getCapabilities()
205 | {
206 | $capabilities = $this->config['allowed_caps'] ?? false;
207 | return $capabilities;
208 | }
209 |
210 | /**
211 | * Get the permission callback.
212 | *
213 | * @return callable
214 | */
215 | public function getPermissionCallback()
216 | {
217 | $permission_callback = $this->config['permission_callback'] ?? '__return_true';
218 | return $permission_callback;
219 | }
220 |
221 | /**
222 | * Add middleware to this route.
223 | *
224 | * @param callable $middleware
225 | */
226 | public function useMiddleware(callable $middleware)
227 | {
228 | $this->middlewareStack[] = $middleware;
229 | }
230 |
231 | /**
232 | * Get the middleware stack for this route.
233 | *
234 | * @return array
235 | */
236 | public function getMiddlewareStack()
237 | {
238 | return $this->middlewareStack;
239 | }
240 |
241 | /**
242 | * Serialize the route.
243 | *
244 | * @return string
245 | */
246 | public function __serialize()
247 | {
248 | return [
249 | 'path' => $this->path,
250 | 'extra_vars' => $this->getExtraVars(),
251 | 'name' => $this->getName()
252 | ];
253 | }
254 |
255 | /**
256 | * Unserialize the route.
257 | *
258 | * @param array
259 | */
260 | public function __unserialize($data)
261 | {
262 | $this->path = $data['path'];
263 | $this->config['extra_vars'] = $data['extra_vars'];
264 | $this->config['name'] = $data['name'];
265 | }
266 | }
267 |
--------------------------------------------------------------------------------
/PluboRoutes/Router.php:
--------------------------------------------------------------------------------
1 | routes = [];
61 | $this->endpoints = [];
62 | $this->route_variable = apply_filters('plubo/route_variable', 'route_name');
63 | $this->regex_routes = new RegexHelperRoutes();
64 | $this->regex_endpoints = new RegexHelperEndpoints();
65 | }
66 |
67 | /**
68 | * Add a route to the router.
69 | *
70 | * @param RouteInterface $route
71 | */
72 | public function addRoute(RouteInterface $route)
73 | {
74 | $this->routes[] = $route;
75 | }
76 |
77 | /**
78 | * Add an endpoint to the router.
79 | *
80 | * @param EndpointInterface $route
81 | */
82 | public function addEndpoint(EndpointInterface $endpoint)
83 | {
84 | $this->endpoints[] = $endpoint;
85 | }
86 |
87 | /**
88 | * Compiles the router into WordPress rewrite rules.
89 | */
90 | public function compileRoutes()
91 | {
92 | add_rewrite_tag('%' . $this->route_variable . '%', '(.+)');
93 |
94 | $rules = [];
95 |
96 | foreach ($this->routes as $route) {
97 | if ($route instanceof PageRoute) {
98 | $this->addPageRule($route);
99 | continue;
100 | }
101 |
102 | $rules = array_merge($rules, $this->addRule($route));
103 | }
104 |
105 | // Apply custom filter for Polylang
106 | $rules = apply_filters('plubo_routes_rewrite_rules', $rules);
107 |
108 | // Add the rules to Polylang's filter
109 | add_filter('pll_rewrite_rules', function ($pll_rules) use ($rules) {
110 | return array_merge($pll_rules, $rules);
111 | });
112 | }
113 |
114 | /**
115 | * Compiles the router into WordPress endpoints.
116 | */
117 | public function compileEndpoints()
118 | {
119 | foreach ($this->endpoints as $endpoint) {
120 | $path = $this->getEndpointPath($endpoint->getPath());
121 | $namespace = $endpoint->getNamespace();
122 | $method = $endpoint->getMethod();
123 |
124 | // Wrap the main callback with middleware processing
125 | $callback = function ($request) use ($endpoint) {
126 | return $this->runEndpointMiddlewareStack($endpoint, $request);
127 | };
128 |
129 | register_rest_route($namespace, $path, [
130 | 'methods' => $method,
131 | 'callback' => $callback,
132 | 'permission_callback' => $endpoint->getPermissionCallback()
133 | ]);
134 | }
135 | }
136 |
137 | /**
138 | * Run the middleware stack for the endpoint and then call the endpoint's config callback.
139 | *
140 | * @param EndpointInterface $endpoint
141 | * @param \WP_REST_Request $request
142 | * @return mixed
143 | */
144 | private function runEndpointMiddlewareStack(EndpointInterface $endpoint, \WP_REST_Request $request)
145 | {
146 | $middlewareStack = $endpoint->getMiddlewareStack();
147 | $index = 0;
148 |
149 | $runNext = function () use (&$index, $middlewareStack, $endpoint, $request, &$runNext) {
150 | if ($index < count($middlewareStack)) {
151 | $middleware = $middlewareStack[$index];
152 | $index++;
153 |
154 | return is_object($middleware) && $middleware instanceof MiddlewareInterface
155 | ? $middleware->handle($request, $runNext)
156 | : $middleware($request, $runNext); // For function-based middleware
157 |
158 |
159 | } else {
160 | // Call the main callback if all middleware passed
161 | $configCallback = $endpoint->getConfig();
162 | $response = $configCallback($request);
163 | return $response instanceof \WP_REST_Response ? $response : new \WP_REST_Response($response);
164 | }
165 | };
166 |
167 | return $runNext();
168 | }
169 |
170 | /**
171 | * Tries to find a matching route using the given query variables. Returns the matching route
172 | * or a WP_Error.
173 | *
174 | * @param array $query_variables
175 | *
176 | * @return RouteInterface|\WP_Error
177 | */
178 | public function match(array $query_variables)
179 | {
180 | if (empty($query_variables[$this->route_variable])) {
181 | return new \WP_Error('missing_route_variable');
182 | }
183 |
184 | $route_name = $query_variables[$this->route_variable];
185 | foreach ($this->routes as $route) {
186 | if ($route->getName() === $route_name) {
187 | return $route;
188 | }
189 | }
190 |
191 | return new \WP_Error('route_not_found');
192 | }
193 |
194 | /**
195 | * Adds a new WordPress rewrite rule for the given Route.
196 | *
197 | * @param RouteInterface $route
198 | * @param string $position
199 | */
200 | private function addRule(RouteInterface $route, $position = 'top')
201 | {
202 | $regex_path = $this->regex_routes->cleanPath($route->getPath());
203 | $matches = $this->regex_routes->getRegexMatches($regex_path);
204 | $index_string = 'index.php?' . $this->route_variable . '=' . $route->getName();
205 | $rules = [];
206 |
207 | if (!$matches) {
208 | return $rules;
209 | }
210 |
211 |
212 | // Add language param if Polylang is active
213 | if (function_exists('pll_current_language')) {
214 | $languages = \pll_languages_list();
215 | $language_regex = implode('|', $languages);
216 | // Use non-capturing group for the slash and capture only the language code
217 | $regex_path = "(?:($language_regex)/)?" . $regex_path;
218 | $index_string .= "&lang=\$matches[1]";
219 | }
220 |
221 | foreach ($matches[1] as $key => $pattern) {
222 | $pattern = explode(':', $pattern);
223 | if (count($pattern) > 1) {
224 | $name = $pattern[0];
225 | $num_arg = function_exists('pll_current_language') ? $key + 2 : $key + 1;
226 | $regex_code = $this->regex_routes->getRegex($pattern[1]);
227 | $regex_path = str_replace($matches[0][$key], $regex_code, $regex_path);
228 | add_rewrite_tag("%$name%", $regex_code);
229 | $index_string .= "&$name=\$matches[$num_arg]";
230 | $route->addArg($name);
231 | }
232 | }
233 | if ($route instanceof Route) {
234 | $index_string = $this->addExtraVars($route, $index_string);
235 | }
236 |
237 | add_rewrite_rule("^$regex_path$", $index_string, $position);
238 |
239 | $rules["^$regex_path$"] = $index_string;
240 | return $rules;
241 | }
242 |
243 | /**
244 | * Adds a new WordPress rewrite rule for the given PageRoute.
245 | *
246 | * @param PageRoute $route
247 | * @param string $position
248 | */
249 | private function addPageRule(PageRoute $route, $position = 'top')
250 | {
251 | $index_string = 'index.php?pagename=' . $route->getPageUri();
252 | $page_path = $route->getPath();
253 |
254 | add_rewrite_rule("^$page_path$", $index_string, $position);
255 | add_filter('page_link', function ($link, $post_id) use ($route) {
256 | if ($post_id === $route->getPageId()) {
257 | $link = home_url($route->getPath());
258 | }
259 | return $link;
260 | }, 10, 2);
261 | }
262 |
263 | /**
264 | * Get translated Regex path for an endpoint route.
265 | *
266 | * @param string $path
267 | *
268 | * @return string
269 | */
270 | private function getEndpointPath(string $path)
271 | {
272 | $regex_path = $this->regex_endpoints->cleanPath($path);
273 | $matches = $this->regex_endpoints->getRegexMatches($regex_path);
274 |
275 | if ($matches) {
276 | foreach ($matches[1] as $key => $pattern) {
277 | $regex_path = $this->getEndpointPatternPath($regex_path, $key, $pattern, $matches);
278 | }
279 | }
280 |
281 | return $regex_path;
282 | }
283 |
284 | /**
285 | * Get translated Regex path for an endpoint pattern.
286 | *
287 | * @param string $path
288 | * @param int $key
289 | * @param string $pattern
290 | * @param array $matches
291 | *
292 | * @return string
293 | */
294 | private function getEndpointPatternPath(string $path, int $key, string $pattern, array $matches)
295 | {
296 | $pattern = explode(':', $pattern);
297 |
298 | if (count($pattern) > 1) {
299 | $regex_code = $this->regex_endpoints->getRegex($pattern);
300 | $path = str_replace($matches[0][$key], $regex_code, $path);
301 | }
302 |
303 | return $path;
304 | }
305 |
306 | /**
307 | * Add extra query vars.
308 | *
309 | * @param Route $route
310 | * @param string $index_string
311 | *
312 | * @return string
313 | */
314 | private function addExtraVars(Route $route, string $index_string)
315 | {
316 | $extra_vars = $route->getExtraVars();
317 |
318 | foreach ($extra_vars as $var_name => $var_value) {
319 | $index_string .= "&$var_name=$var_value";
320 | $route->addArg($var_name);
321 | add_rewrite_tag("%$var_name%", '([a-z0-9-]+)');
322 | }
323 |
324 | return $index_string;
325 | }
326 | }
327 |
--------------------------------------------------------------------------------
/PluboRoutes/RoutesProcessor.php:
--------------------------------------------------------------------------------
1 |
15 | *
16 | */
17 | class RoutesProcessor
18 | {
19 | /**
20 | * The matched route found by the router.
21 | *
22 | * @var Route|RedirectRote|ActionRoute|null
23 | */
24 | private $matched_route;
25 |
26 | /**
27 | * The matched args found by the router.
28 | *
29 | * @var array
30 | */
31 | private $matched_args;
32 |
33 | /**
34 | * The router.
35 | *
36 | * @var Router
37 | */
38 | private $router;
39 |
40 | /**
41 | * The router instance.
42 | *
43 | * @var RoutesProcessor|null
44 | */
45 | private static $instance = NULL;
46 |
47 | /**
48 | * Constructor.
49 | *
50 | * @param Router $router
51 | */
52 | public function __construct(Router $router)
53 | {
54 | $this->router = $router;
55 | $this->initHooks();
56 | }
57 |
58 | /**
59 | * Initialize hooks with WordPress.
60 | */
61 | private function initHooks()
62 | {
63 | add_action('init', [$this, 'addRoutes']);
64 | add_action('parse_request', [$this, 'matchRouteRequest']);
65 | add_action('send_headers', [$this, 'basicAuth']);
66 | add_action('rest_api_init', [$this, 'addEndpoints']);
67 | add_action('template_redirect', [$this, 'doRouteActions']);
68 | add_filter('template_include', [$this, 'includeRouteTemplate']);
69 | add_filter('body_class', [$this, 'addBodyClasses']);
70 | add_filter('document_title_parts', [$this, 'modifyTitle']);
71 | }
72 |
73 | /**
74 | * Clone not allowed.
75 | *
76 | */
77 | private function __clone() {}
78 |
79 | /**
80 | * Initialize processor with WordPress.
81 | *
82 | */
83 | public static function init($plugin_dir_path = '', $namespace = '')
84 | {
85 | if (self::$instance === null) {
86 | self::$instance = new self(new Router());
87 | }
88 |
89 | if (!empty($plugin_dir_path) && !empty($namespace)) {
90 | $dynamic_routes = self::$instance->getDynamicRoutes($plugin_dir_path, $namespace);
91 |
92 | foreach($dynamic_routes as $dynamic_route) {
93 | self::$instance->router->addRoute($dynamic_route);
94 | }
95 |
96 | self::$instance->maybeFlushRewriteRules($dynamic_routes, 'plubo-dynamic-' . strtolower($namespace));
97 | }
98 |
99 | // Custom action for router initialization
100 | do_action('plubo/router_init');
101 | return self::$instance;
102 | }
103 |
104 | public function getDynamicRoutes($plugin_dir_path = '', $namespace = '')
105 | {
106 | global $wp_filesystem;
107 |
108 | require_once(ABSPATH . '/wp-admin/includes/file.php');
109 | WP_Filesystem();
110 |
111 | $routes_json_path = $plugin_dir_path . 'dist/routes.json';
112 |
113 | $routes_content = $wp_filesystem->get_contents($routes_json_path);
114 | $routes_info = json_decode($routes_content, true);
115 |
116 | foreach ($routes_info as $route) {
117 | $route_path = $route['route'];
118 | unset($route['route']);
119 |
120 | $template_name = str_replace('/', '.', $route_path);
121 | $controller = function ($matches) use ($wp_filesystem, $template_name, $route, $plugin_dir_path) {
122 |
123 | $file_path = $plugin_dir_path . $route['path'];
124 | $html = $wp_filesystem->get_contents($file_path);
125 | $html = preg_replace('/@configRoute\s*\(\s*(\{[\s\S]*?\})\s*\)/s', '', $html);
126 |
127 | return apply_filters('plubo/get_route_html', $html, $template_name, $matches);
128 | };
129 |
130 | // Parse controller
131 | $route_controller = ($route['controller'] ?? false) ? str_replace('.', '::', $route['controller']) : false;
132 | if ($route_controller && is_callable("\\$namespace\\Controllers\\$route_controller")) {
133 | $controller = "\\$namespace\\Controllers\\$route_controller";
134 | }
135 |
136 | // Parse roles callback
137 | if (isset($route['allowed_roles']) && is_string($route['allowed_roles']) && str_contains($route['allowed_roles'], '.')) {
138 | $roles_controller = str_replace('.', '::', $route['allowed_roles']);
139 | if (is_callable($roles_controller)) {
140 | $route['allowed_roles'] = "\\$namespace\\Controllers\\$roles_controller";
141 | }
142 | }
143 |
144 | // Parse capabilities callback
145 | if (isset($route['allowed_capabilities']) && is_string($route['allowed_capabilities']) && str_contains($route['allowed_capabilities'], '.')) {
146 | $capabilities_controller = str_replace('.', '::', $route['allowed_capabilities']);
147 | if (is_callable($capabilities_controller)) {
148 | $route['allowed_capabilities'] = "\\$namespace\\Controllers\\$capabilities_controller";
149 | }
150 | }
151 |
152 | $routes[] = new Route($route_path, $controller, wp_parse_args($route, ['render' => true]));
153 | }
154 |
155 | return $routes;
156 | }
157 |
158 | /**
159 | * Step 1: Register all our routes into WordPress. Flush rewrite rules if the routes changed.
160 | */
161 | public function addRoutes()
162 | {
163 | $routes = apply_filters('plubo/routes', []);
164 | $routes = is_array($routes) ? $routes : [];
165 |
166 | foreach ($routes as $route) {
167 | $this->router->addRoute($route);
168 | }
169 |
170 | $this->router->compileRoutes();
171 | $this->maybeFlushRewriteRules($routes, 'plubo-routes-hash');
172 | }
173 |
174 | /**
175 | * Step 1 alt: Register all our endpoints into WordPress. Flush rewrite rules if the endpoints changed.
176 | */
177 | public function addEndpoints()
178 | {
179 | $endpoints = apply_filters('plubo/endpoints', []);
180 | $endpoints = is_array($endpoints) ? $endpoints : [];
181 |
182 | foreach ($endpoints as $endpoint) {
183 | $this->router->addEndpoint($endpoint);
184 | }
185 |
186 | $this->router->compileEndpoints();
187 | $this->maybeFlushRewriteRules($endpoints, 'plubo-endpoints-hash');
188 | }
189 |
190 | /**
191 | * Flush if needed.
192 | */
193 | public function maybeFlushRewriteRules(array $values, string $option_name)
194 | {
195 | if (!is_array($values)) {
196 | return;
197 | }
198 |
199 | $hash = md5(serialize($values));
200 | if ($hash != get_option($option_name)) {
201 | flush_rewrite_rules();
202 | update_option($option_name, $hash);
203 | }
204 | }
205 |
206 | /**
207 | * Step 2: Attempts to match the current request to an added route.
208 | *
209 | * @param \WP $env
210 | */
211 | public function matchRouteRequest(\WP $env)
212 | {
213 | // Ensure the language is set in query variables if Polylang is active
214 | if (function_exists('pll_current_language') && !isset($env->query_vars['lang'])) {
215 | $env->query_vars['lang'] = \pll_current_language();
216 | }
217 |
218 | $found_route = $this->router->match($env->query_vars);
219 |
220 | if ($found_route instanceof RouteInterface) {
221 | $this->processMatchedRoute($found_route, $env);
222 | }
223 |
224 | if ($found_route instanceof \WP_Error && in_array('route_not_found', $found_route->get_error_codes())) {
225 | $this->handleRouteNotFound();
226 | }
227 | }
228 |
229 | /**
230 | * Process matched route and set matched route and args.
231 | *
232 | * @param RouteInterface $found_route
233 | * @param \WP $env
234 | */
235 | private function processMatchedRoute(RouteInterface $found_route, \WP $env)
236 | {
237 | $this->matched_route = $found_route;
238 | $this->matched_args = $this->extractArgs($found_route, $env);
239 |
240 | // Action hook after matching route request
241 | do_action('plubo/after_matching_route_request', $this->matched_route, $this->matched_args, $env);
242 | }
243 |
244 |
245 | /**
246 | * Handle route not found error.
247 | */
248 | private function extractArgs(RouteInterface $route, \WP $env)
249 | {
250 | $args = [];
251 | $extra_args = $route->getExtraVars();
252 |
253 | foreach ($route->getArgs() as $arg_name) {
254 | $query_value = $env->query_vars[$arg_name] ?? ($extra_args[$arg_name] ?? false);
255 | $args[$arg_name] = $query_value;
256 | }
257 |
258 | return $args;
259 | }
260 |
261 | /**
262 | * Handle route not found error.
263 | */
264 | private function handleRouteNotFound()
265 | {
266 | wp_die(esc_html('Route Not Found'), esc_html('Route Not Found'), ['response' => 404]);
267 | }
268 |
269 | /**
270 | * Step 3: Check if route has basic Auth enabled.
271 | */
272 | public function basicAuth()
273 | {
274 | if ($this->matched_route instanceof Route && $this->matched_route->hasBasicAuth()) {
275 | $this->checkBasicAuth();
276 | }
277 | }
278 |
279 | /**
280 | * Check basic authentication for the matched route.
281 | */
282 | private function checkBasicAuth()
283 | {
284 | header('Cache-Control: no-cache, must-revalidate, max-age=0');
285 | $basic_auth = $this->matched_route->getBasicAuth();
286 | $auth_user = isset($_SERVER['PHP_AUTH_USER']) ? wp_unslash(sanitize_text_field($_SERVER['PHP_AUTH_USER'])) : '';
287 | $auth_pass = isset($_SERVER['PHP_AUTH_PW']) ? wp_unslash(sanitize_text_field($_SERVER['PHP_AUTH_PW'])) : '';
288 |
289 | if (
290 | empty($auth_user) || empty($auth_pass)
291 | || !array_key_exists($auth_user, $basic_auth)
292 | || $auth_pass != $basic_auth[$auth_user]
293 | ) {
294 | $this->unauthorized();
295 | }
296 | }
297 |
298 | /**
299 | * Handle unauthorized access.
300 | */
301 | private function unauthorized()
302 | {
303 | wp_die(esc_html('Unauthorized Access'), esc_html('Unauthorized Access'), ['response' => 401]);
304 | }
305 |
306 | /**
307 | * Step 4: If a route was found, execute the route's action. Or redirect if RedirectRoute.
308 | */
309 | public function doRouteActions()
310 | {
311 | if ($this->matched_route instanceof Route || $this->matched_route instanceof ActionRoute || $this->matched_route instanceof RedirectRoute) {
312 | if ($this->matched_route->getMiddlewareStack()) {
313 | $this->runMiddlewareStack($this->matched_route);
314 | } else {
315 | $this->executeRouteActions();
316 | }
317 | }
318 | }
319 |
320 | /**
321 | * Execute middleware before route actions.
322 | */
323 | private function runMiddlewareStack(RouteInterface $route)
324 | {
325 | $middlewareStack = $route->getMiddlewareStack();
326 | $index = 0;
327 |
328 | $runNext = function () use (&$index, $middlewareStack, $route, &$runNext) {
329 | if ($index < count($middlewareStack)) {
330 | $middleware = $middlewareStack[$index];
331 | $index++;
332 |
333 | return is_object($middleware) && $middleware instanceof MiddlewareInterface
334 | ? $middleware->handle($this->matched_args, $runNext)
335 | : $middleware($this->matched_args, $runNext); // For function-based middleware
336 | } else {
337 | $this->executeRouteActions(); // All middleware passed, execute route
338 | }
339 | };
340 |
341 | $runNext();
342 | }
343 |
344 | /**
345 | * Execute actions based on the type of matched route.
346 | */
347 | private function executeRouteActions()
348 | {
349 | // Action hook before executing route actions
350 | do_action('plubo/before_executing_route_actions', $this->matched_route, $this->matched_args);
351 |
352 | $permission_checker = new PermissionChecker($this->matched_route, $this->matched_args);
353 | $permission_checker->checkPermissions();
354 |
355 | if ($this->matched_route instanceof Route) {
356 | $this->executeRouteHook();
357 | } elseif ($this->matched_route instanceof ActionRoute) {
358 | $this->executeRouteFunction();
359 | } elseif ($this->matched_route instanceof RedirectRoute) {
360 | $this->executeRedirect();
361 | }
362 | }
363 |
364 | /**
365 | * Execute route hook action.
366 | */
367 | private function executeRouteHook()
368 | {
369 | status_header($this->matched_route->getStatus());
370 | do_action($this->matched_route->getAction(), $this->matched_args);
371 | }
372 |
373 | /**
374 | * Execute route function action.
375 | */
376 | private function executeRouteFunction()
377 | {
378 | status_header($this->matched_route->getStatus());
379 | $action = $this->matched_route->getAction();
380 | if ($this->matched_route->hasCallback()) {
381 | $action = $action($this->matched_args);
382 | }
383 | }
384 |
385 | /**
386 | * Execute redirect action.
387 | */
388 | private function executeRedirect()
389 | {
390 | if (!$this->matched_route instanceof RedirectRoute) {
391 | exit;
392 | }
393 |
394 | $redirect_to = $this->matched_route->getAction();
395 | if ($this->matched_route->hasCallback()) {
396 | $redirect_to = $redirect_to($this->matched_args);
397 | }
398 | nocache_headers();
399 | if ($this->matched_route->isExternal()) {
400 | wp_redirect(esc_url_raw($redirect_to), $this->matched_route->getStatus());
401 | exit;
402 | }
403 | wp_safe_redirect(home_url($redirect_to), $this->matched_route->getStatus());
404 | exit;
405 | }
406 |
407 | /**
408 | * Step 5: If a route of type Route was found, load the route template.
409 | *
410 | * @param string $template
411 | *
412 | * @return string
413 | */
414 | public function includeRouteTemplate($template)
415 | {
416 | if (!$this->matched_route instanceof Route) {
417 | return $template;
418 | }
419 |
420 | $matched_template = $this->matched_route->getTemplate();
421 | if ($this->matched_route->isRender()) {
422 | $template = $this->createTempFile(sys_get_temp_dir(), $this->matched_route->getName(), '.blade.php');
423 | if ($this->matched_route->hasTemplateCallback()) {
424 | $matched_template = $matched_template($this->matched_args);
425 | }
426 | file_put_contents($template, $matched_template);
427 | return $template;
428 | }
429 | if ($this->matched_route->hasTemplateCallback()) {
430 | $template_func = $this->matched_route->getTemplate();
431 | return $template_func($this->matched_args);
432 | }
433 |
434 | return $matched_template;
435 | }
436 |
437 | /**
438 | * Create a temporary file.
439 | *
440 | * @param string $dir
441 | * @param string $prefix
442 | * @param string $postfix
443 | *
444 | * @return string|false
445 | */
446 | private function createTempFile(string $dir, string $prefix, string $postfix)
447 | {
448 | // Trim trailing slashes from $dir.
449 | $dir = rtrim($dir, DIRECTORY_SEPARATOR);
450 |
451 | // If we don't have permission to create a directory, fail, otherwise we will be stuck in an endless loop.
452 | if (!is_dir($dir) || !is_writable($dir)) {
453 | return false;
454 | }
455 |
456 | // Make sure characters in prefix and postfix are safe.
457 | if ((strpbrk($prefix, '\\/:*?"<>|') !== false) || (strpbrk($postfix, '\\/:*?"<>|') !== false)) {
458 | return false;
459 | }
460 |
461 | $path = $dir . DIRECTORY_SEPARATOR . $prefix . $postfix;
462 | $tmp_file = @fopen($path, 'x+');
463 |
464 | if ($tmp_file) {
465 | fclose($tmp_file);
466 | }
467 |
468 | return $path;
469 | }
470 |
471 | /**
472 | * Filter: If a route was found, add name as body tag.
473 | *
474 | * @param array $classes
475 | *
476 | * @return array
477 | */
478 | public function addBodyClasses($classes)
479 | {
480 | if ($this->matched_route instanceof Route) {
481 | $route_name = $this->matched_route->getName();
482 | $classes[] = "route-$route_name";
483 | foreach ($this->matched_args as $arg_name => $arg_value) {
484 | $classes[] = sanitize_title("$arg_name-$arg_value");
485 | }
486 | $classes = apply_filters('plubo/body_classes', $classes, $route_name, $this->matched_args);
487 | }
488 | return $classes;
489 | }
490 |
491 | /**
492 | * Filter: If a route was found, modify the title.
493 | *
494 | * @param array $title_parts
495 | *
496 | * @return array
497 | */
498 | public function modifyTitle($title_parts)
499 | {
500 | if ($this->matched_route instanceof Route) {
501 | $route_title = $this->matched_route->getTitle();
502 | $route_title = is_callable($route_title) ? $route_title($this->matched_args) : $route_title;
503 | $title_parts['title'] = $route_title ?? get_bloginfo('name');
504 | $title_parts = apply_filters('plubo/title_parts', $title_parts, $route_title, $this->matched_args);
505 | }
506 |
507 | return $title_parts;
508 | }
509 | }
510 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | [](https://github.com/joanrodas/plubo-routes/stargazers)
6 | 
7 |
8 | WordPress routes made simple.
9 |
10 |
11 | ✔️ No need to write rewrite rules and tags manually\
12 | ✔️ Automatically flush rewrite rules when the routes change\
13 | ✔️ Custom redirects and action routes\
14 | ✔️ Easily extendable with hooks\
15 | ✔️ Easy to use with Sage 10
16 |
17 |
18 |
19 |
20 | ## Getting started
21 |
22 | `composer require joanrodas/plubo-routes`
23 |
24 | > You can also install Plubo Routes as a standalone WordPress plugin, simply downloading the zip and placing it in the plugins folder.
25 |
26 |
27 |
28 | [Read the Docs](https://www.plubo.dev/docs/routing/)
29 |
30 |
31 |
32 | ## Adding new routes
33 |
34 | There are different types of routes:
35 |
36 | - [Route (template)](https://www.plubo.dev/docs/routing/)
37 | - [RedirectRoute](https://www.plubo.dev/docs/routing/redirect-routes.html)
38 | - [ActionRoute](https://www.plubo.dev/docs/routing/action-routes.html)
39 | - [PageRoute](https://www.plubo.dev/docs/routing/page-routes.html)
40 |
41 |
42 |
43 | ## How to add a new route
44 |
45 | You can add new routes using the following filter:
46 |
47 | ```php
48 | PluboRoutes\RoutesProcessor::init();
49 |
50 | add_filter( 'plubo/routes', array($this, 'add_routes') );
51 | public function add_routes( $routes ) {
52 | //Your routes
53 | return $routes;
54 | }
55 | ```
56 |
57 |
58 |
59 | ## Basic routes
60 |
61 | Basic routes take 3 parameters:
62 |
63 | | Parameter | Type |
64 | | ------------- | ------------- |
65 | | **Route Path** | String |
66 | | **Template file name** | String \| Callable |
67 | | **Config** | Array (optional) |
68 |
69 | Examples:
70 |
71 | ```php
72 | use PluboRoutes\Route\Route;
73 |
74 | add_filter( 'plubo/routes', array($this, 'add_routes') );
75 | public function add_routes( $routes ) {
76 | $routes[] = new Route('clients/list', 'template_name');
77 |
78 | //SAGE 10 example
79 | $routes[] = new Route(
80 | 'dashboard/{subpage:slug}',
81 | function($matches) {
82 | $subpage = 'dashboard/' . $matches['subpage'];
83 | return locate_template( app('sage.finder')->locate($subpage) );
84 | },
85 | [
86 | 'name' => 'my-route'
87 | ]
88 | );
89 | return $routes;
90 | }
91 | ```
92 |
93 |
94 |
95 | ## Available syntax
96 |
97 | You can use the format ***{variable_name:type}*** with any of the available types:
98 |
99 | * number (numbers only)
100 | * word (a-Z only)
101 | * slug (a valid WordPress slug)
102 | * date (yyyy-mm-dd date)
103 | * year (4 digits)
104 | * month (01-12)
105 | * day (01-31)
106 | * digit (single digit 0-9)
107 | * jwt (JWT token)
108 | * ip (IPv4)
109 |
110 | > You can also use custom regex patterns using the format ***{variable_name:regex_pattern}*** like ***{author:([a-z0-9-]+)}***
111 |
112 |
113 |
114 | ## Changing general template path
115 |
116 | By default, Plubo Routes will search the template inside your theme, but you can use a hook to chenge the default path.
117 |
118 | If you use Sage 10, you could add something like this:
119 |
120 | ```php
121 | add_filter( 'plubo/template', function($template) {
122 | return app('sage.finder')->locate($template);
123 | });
124 | ```
125 |
126 |
127 |
128 | ## Custom Actions
129 |
130 | Named routes provide a hook to execute your custom actions:
131 |
132 | ```php
133 | add_action('plubo/route_{route_name}', function($matches) {
134 | //Do something
135 | });
136 | ```
137 |
138 |
139 |
140 | ## Contributions
141 | [](https://github.com/joanrodas/plubo-routes/issues)
142 | [](https://github.com/joanrodas/plubo-routes/issues)
143 | [](https://github.com/joanrodas/plubo-routes/blob/main/LICENSE)
144 |
145 |
146 | Feel free to contribute to the project, suggesting improvements, reporting bugs and coding.
147 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | | Version | Supported |
6 | | ------- | ------------------ |
7 | | 0.1.x | :white_check_mark: |
8 |
9 | ## Reporting a Vulnerability
10 |
11 | **Do not open up a GitHub issue if the bug is a security vulnerability**
12 |
13 | Please send an email to .
14 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "joanrodas/plubo-routes",
3 | "description": "WordPress routes made simple.",
4 | "keywords": ["plugin", "wordpress", "routes", "wp", "routing"],
5 | "homepage": "https://github.com/joanrodas/plubo-routes",
6 | "license": "GPL-3.0+",
7 | "authors": [
8 | {
9 | "name": "Joan Rodas Cusidó",
10 | "email": "joan@sirvelia.com",
11 | "homepage": "https://sirvelia.com",
12 | "role": "Developer"
13 | }
14 | ],
15 | "autoload": {
16 | "psr-4": {
17 | "PluboRoutes\\": "PluboRoutes/"
18 | }
19 | },
20 | "require": {
21 | "php": ">=7.4",
22 | "justinrainbow/json-schema": "^6.0"
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/composer.lock:
--------------------------------------------------------------------------------
1 | {
2 | "_readme": [
3 | "This file locks the dependencies of your project to a known state",
4 | "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
5 | "This file is @generated automatically"
6 | ],
7 | "content-hash": "4b46f25c7947a817e3279baf000749d9",
8 | "packages": [
9 | {
10 | "name": "icecave/parity",
11 | "version": "1.0.0",
12 | "source": {
13 | "type": "git",
14 | "url": "https://github.com/icecave/parity.git",
15 | "reference": "0109fef58b3230d23b20b2ac52ecdf477218d300"
16 | },
17 | "dist": {
18 | "type": "zip",
19 | "url": "https://api.github.com/repos/icecave/parity/zipball/0109fef58b3230d23b20b2ac52ecdf477218d300",
20 | "reference": "0109fef58b3230d23b20b2ac52ecdf477218d300",
21 | "shasum": ""
22 | },
23 | "require": {
24 | "icecave/repr": "~1",
25 | "php": ">=5.3"
26 | },
27 | "require-dev": {
28 | "eloquent/liberator": "~1",
29 | "icecave/archer": "~1"
30 | },
31 | "suggest": {
32 | "eloquent/asplode": "Drop-in exception-based error handling."
33 | },
34 | "type": "library",
35 | "autoload": {
36 | "psr-0": {
37 | "Icecave\\Parity": "src"
38 | }
39 | },
40 | "notification-url": "https://packagist.org/downloads/",
41 | "license": [
42 | "MIT"
43 | ],
44 | "authors": [
45 | {
46 | "name": "James Harris",
47 | "email": "james.harris@icecave.com.au",
48 | "homepage": "https://github.com/jmalloc"
49 | }
50 | ],
51 | "description": "A customizable deep comparison library.",
52 | "homepage": "https://github.com/IcecaveStudios/parity",
53 | "keywords": [
54 | "compare",
55 | "comparison",
56 | "equal",
57 | "equality",
58 | "greater",
59 | "less",
60 | "sort",
61 | "sorting"
62 | ],
63 | "support": {
64 | "issues": "https://github.com/icecave/parity/issues",
65 | "source": "https://github.com/icecave/parity/tree/1.0.0"
66 | },
67 | "time": "2014-01-17T05:56:27+00:00"
68 | },
69 | {
70 | "name": "icecave/repr",
71 | "version": "1.0.1",
72 | "source": {
73 | "type": "git",
74 | "url": "https://github.com/icecave/repr.git",
75 | "reference": "8a3d2953adf5f464a06e3e2587aeacc97e2bed07"
76 | },
77 | "dist": {
78 | "type": "zip",
79 | "url": "https://api.github.com/repos/icecave/repr/zipball/8a3d2953adf5f464a06e3e2587aeacc97e2bed07",
80 | "reference": "8a3d2953adf5f464a06e3e2587aeacc97e2bed07",
81 | "shasum": ""
82 | },
83 | "require": {
84 | "php": ">=5.3"
85 | },
86 | "require-dev": {
87 | "icecave/archer": "~1"
88 | },
89 | "suggest": {
90 | "eloquent/asplode": "Drop-in exception-based error handling."
91 | },
92 | "type": "library",
93 | "autoload": {
94 | "psr-4": {
95 | "Icecave\\Repr\\": "src"
96 | }
97 | },
98 | "notification-url": "https://packagist.org/downloads/",
99 | "license": [
100 | "MIT"
101 | ],
102 | "authors": [
103 | {
104 | "name": "James Harris",
105 | "email": "james.harris@icecave.com.au",
106 | "homepage": "https://github.com/jmalloc"
107 | }
108 | ],
109 | "description": "A library for generating string representations of any value, inspired by Python's reprlib library.",
110 | "homepage": "https://github.com/IcecaveStudios/repr",
111 | "keywords": [
112 | "human",
113 | "readable",
114 | "repr",
115 | "representation",
116 | "string"
117 | ],
118 | "support": {
119 | "issues": "https://github.com/icecave/repr/issues",
120 | "source": "https://github.com/icecave/repr/tree/1.0.1"
121 | },
122 | "time": "2014-07-25T05:44:41+00:00"
123 | },
124 | {
125 | "name": "justinrainbow/json-schema",
126 | "version": "6.0.0",
127 | "source": {
128 | "type": "git",
129 | "url": "https://github.com/jsonrainbow/json-schema.git",
130 | "reference": "a38c6198d53b09c0702f440585a4f4a5d9137bd9"
131 | },
132 | "dist": {
133 | "type": "zip",
134 | "url": "https://api.github.com/repos/jsonrainbow/json-schema/zipball/a38c6198d53b09c0702f440585a4f4a5d9137bd9",
135 | "reference": "a38c6198d53b09c0702f440585a4f4a5d9137bd9",
136 | "shasum": ""
137 | },
138 | "require": {
139 | "icecave/parity": "1.0.0",
140 | "marc-mabe/php-enum": "^2.0 || ^3.0 || ^4.0",
141 | "php": ">=5.3.3"
142 | },
143 | "require-dev": {
144 | "friendsofphp/php-cs-fixer": "~2.2.20 || ~2.19.0",
145 | "json-schema/json-schema-test-suite": "1.2.0",
146 | "phpunit/phpunit": "^4.8.35"
147 | },
148 | "bin": [
149 | "bin/validate-json"
150 | ],
151 | "type": "library",
152 | "extra": {
153 | "branch-alias": {
154 | "dev-master": "6.x-dev"
155 | }
156 | },
157 | "autoload": {
158 | "psr-4": {
159 | "JsonSchema\\": "src/JsonSchema/"
160 | }
161 | },
162 | "notification-url": "https://packagist.org/downloads/",
163 | "license": [
164 | "MIT"
165 | ],
166 | "authors": [
167 | {
168 | "name": "Bruno Prieto Reis",
169 | "email": "bruno.p.reis@gmail.com"
170 | },
171 | {
172 | "name": "Justin Rainbow",
173 | "email": "justin.rainbow@gmail.com"
174 | },
175 | {
176 | "name": "Igor Wiedler",
177 | "email": "igor@wiedler.ch"
178 | },
179 | {
180 | "name": "Robert Schönthal",
181 | "email": "seroscho@googlemail.com"
182 | }
183 | ],
184 | "description": "A library to validate a json schema.",
185 | "homepage": "https://github.com/jsonrainbow/json-schema",
186 | "keywords": [
187 | "json",
188 | "schema"
189 | ],
190 | "support": {
191 | "issues": "https://github.com/jsonrainbow/json-schema/issues",
192 | "source": "https://github.com/jsonrainbow/json-schema/tree/6.0.0"
193 | },
194 | "time": "2024-07-30T17:49:21+00:00"
195 | },
196 | {
197 | "name": "marc-mabe/php-enum",
198 | "version": "v4.7.0",
199 | "source": {
200 | "type": "git",
201 | "url": "https://github.com/marc-mabe/php-enum.git",
202 | "reference": "3da42cc1daceaf98c858e56f59d1ccd52b011fdc"
203 | },
204 | "dist": {
205 | "type": "zip",
206 | "url": "https://api.github.com/repos/marc-mabe/php-enum/zipball/3da42cc1daceaf98c858e56f59d1ccd52b011fdc",
207 | "reference": "3da42cc1daceaf98c858e56f59d1ccd52b011fdc",
208 | "shasum": ""
209 | },
210 | "require": {
211 | "ext-reflection": "*",
212 | "php": "^7.1 | ^8.0"
213 | },
214 | "require-dev": {
215 | "phpbench/phpbench": "^0.16.10 || ^1.0.4",
216 | "phpstan/phpstan": "^1.3.1",
217 | "phpunit/phpunit": "^7.5.20 | ^8.5.22 | ^9.5.11",
218 | "vimeo/psalm": "^4.17.0"
219 | },
220 | "type": "library",
221 | "extra": {
222 | "branch-alias": {
223 | "dev-master": "4.6-dev",
224 | "dev-3.x": "3.2-dev"
225 | }
226 | },
227 | "autoload": {
228 | "psr-4": {
229 | "MabeEnum\\": "src/"
230 | },
231 | "classmap": [
232 | "stubs/Stringable.php"
233 | ]
234 | },
235 | "notification-url": "https://packagist.org/downloads/",
236 | "license": [
237 | "BSD-3-Clause"
238 | ],
239 | "authors": [
240 | {
241 | "name": "Marc Bennewitz",
242 | "email": "dev@mabe.berlin",
243 | "homepage": "https://mabe.berlin/",
244 | "role": "Lead"
245 | }
246 | ],
247 | "description": "Simple and fast implementation of enumerations with native PHP",
248 | "homepage": "https://github.com/marc-mabe/php-enum",
249 | "keywords": [
250 | "enum",
251 | "enum-map",
252 | "enum-set",
253 | "enumeration",
254 | "enumerator",
255 | "enummap",
256 | "enumset",
257 | "map",
258 | "set",
259 | "type",
260 | "type-hint",
261 | "typehint"
262 | ],
263 | "support": {
264 | "issues": "https://github.com/marc-mabe/php-enum/issues",
265 | "source": "https://github.com/marc-mabe/php-enum/tree/v4.7.0"
266 | },
267 | "time": "2022-04-19T02:21:46+00:00"
268 | }
269 | ],
270 | "packages-dev": [],
271 | "aliases": [],
272 | "minimum-stability": "stable",
273 | "stability-flags": [],
274 | "prefer-stable": false,
275 | "prefer-lowest": false,
276 | "platform": {
277 | "php": ">=7.4"
278 | },
279 | "platform-dev": [],
280 | "plugin-api-version": "2.2.0"
281 | }
282 |
--------------------------------------------------------------------------------
/plubo-routes.php:
--------------------------------------------------------------------------------
1 | true,
37 | // 'name' => 'test-route'
38 | // ]
39 | // );
40 |
41 | // // $test_route->useMiddleware('jwtMiddleware');
42 |
43 | // $routes[] = $test_route;
44 | // return $routes;
45 | // });
46 |
47 | // function loggingMiddleware($request, $next)
48 | // {
49 | // // Log the request data
50 | // $route = $_SERVER['REQUEST_URI'] ?? 'unknown';
51 | // $method = $_SERVER['REQUEST_METHOD'] ?? 'unknown';
52 |
53 | // error_log("Accessing route: {$route} with method: {$method} at " . date('Y-m-d H:i:s'));
54 |
55 | // // Proceed to the next middleware or main route action
56 | // return $next();
57 | // }
58 |
59 | // add_filter('plubo/endpoints', function ($routes) {
60 | // $test_route = new PluboRoutes\Endpoint\PostEndpoint(
61 | // 'sirvelia/v1',
62 | // 'test',
63 | // function ($request) {
64 | // return ['test' => 'TEST'];
65 | // }
66 | // );
67 |
68 | // $schemaPath = PLUBO_ROUTES_PLUGIN_DIR . 'test.json';
69 | // $schema = json_decode(file_get_contents($schemaPath));
70 | // $test_route->useMiddleware(new SchemaValidator($schema));
71 |
72 | // $test_route->useMiddleware(new Cors('*', ['GET', 'POST'], ['Content-Type', 'Authorization']));
73 | // $test_route->useMiddleware(new JwtValidation('secret')); // 10 minutes
74 | // $test_route->useMiddleware(new Cache(600)); // 10 minutes
75 | // $test_route->useMiddleware(new RateLimit(1, 30)); // 1 requests per 30 seconds
76 |
77 | // $routes[] = $test_route;
78 | // return $routes;
79 | // });
80 |
--------------------------------------------------------------------------------
/pull_request_template.md:
--------------------------------------------------------------------------------
1 | * **Please check if the PR fulfills these requirements**
2 | - [ ] I have read the guidelines
3 | - [ ] Docs have been added / updated (for bug fixes / features)
4 |
5 |
6 |
7 | * **What kind of change does this PR introduce?**
8 | - [ ] Bux fix
9 | - [ ] New feature
10 | - [ ] Docs update
11 | - [ ] Others (please specify)
12 |
13 |
14 |
15 | * **What is the current behavior?** (You can also link to an open issue here)
16 |
17 |
18 |
19 | * **What is the new behavior (if this is a feature change)?**
20 |
21 |
22 |
23 | * **Does this PR introduce a breaking change?** (If so, what changes might users need to make in their application?)
24 |
25 |
26 |
27 | * **Other info**:
28 |
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": [
3 | "config:base"
4 | ]
5 | }
6 |
--------------------------------------------------------------------------------
/test.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "username": {
5 | "type": "string",
6 | "minLength": 3,
7 | "maxLength": 15
8 | },
9 | "age": {
10 | "type": "integer",
11 | "minimum": 0,
12 | "maximum": 120
13 | },
14 | "email": {
15 | "type": "string",
16 | "format": "email"
17 | },
18 | "is_subscribed": {
19 | "type": "boolean"
20 | },
21 | "favorite_numbers": {
22 | "type": "array",
23 | "items": {
24 | "type": "integer"
25 | },
26 | "minItems": 1,
27 | "maxItems": 5
28 | },
29 | "profile": {
30 | "type": "object",
31 | "properties": {
32 | "bio": {
33 | "type": "string",
34 | "maxLength": 150
35 | },
36 | "website": {
37 | "type": "string",
38 | "format": "uri"
39 | }
40 | },
41 | "required": [
42 | "bio"
43 | ]
44 | }
45 | },
46 | "required": [
47 | "username",
48 | "age",
49 | "email",
50 | "is_subscribed",
51 | "favorite_numbers",
52 | "profile"
53 | ]
54 | }
--------------------------------------------------------------------------------