You've already forked Php-Template
Compare commits
16 Commits
v1.1.0
...
e0ba77556d
| Author | SHA1 | Date | |
|---|---|---|---|
|
e0ba77556d
|
|||
|
f8b988ca0d
|
|||
|
2879cbe203
|
|||
|
eeb46bc982
|
|||
|
7d0b00fb89
|
|||
|
13445a0719
|
|||
|
54ea22c49a
|
|||
|
f8d3462cb7
|
|||
|
68614958a9
|
|||
|
413145f479
|
|||
|
d2bd9d2d1b
|
|||
|
78d5213892
|
|||
|
56b78f0102
|
|||
|
05d8c5b813
|
|||
|
2d6d0a43f3
|
|||
|
e203975294
|
@@ -1,3 +1,5 @@
|
|||||||
.idea/
|
.idea/
|
||||||
|
.DS_Store
|
||||||
vendor/
|
vendor/
|
||||||
.phpunit.cache/
|
.phpunit.cache/
|
||||||
|
tests/
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
on:
|
on:
|
||||||
create:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- '*'
|
- "v*"
|
||||||
|
|
||||||
name: 🏗️✨ Build Workflow
|
name: 🏗️✨ Build Workflow
|
||||||
|
|
||||||
@@ -12,7 +12,6 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
||||||
run: |
|
run: |
|
||||||
apt update && apt install -yq ca-certificates curl
|
|
||||||
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
||||||
update-ca-certificates
|
update-ca-certificates
|
||||||
|
|
||||||
@@ -30,9 +29,45 @@ jobs:
|
|||||||
- name: 🏗️ 🔧 Set up Docker Buildx
|
- name: 🏗️ 🔧 Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
- name: 🐳 🔨 Build Backend Container
|
- name: 🐳 🔨 Build Container
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
tags: siteworxpro/template:${{ gitea.ref_name }}
|
tags: siteworxpro/template:${{ gitea.ref_name }}
|
||||||
|
|
||||||
|
Build-Migrations:
|
||||||
|
needs:
|
||||||
|
- Build
|
||||||
|
name: 🖥️ 🔨 Build Migrations
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
||||||
|
run: |
|
||||||
|
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
||||||
|
update-ca-certificates
|
||||||
|
|
||||||
|
- name: 🔑 🔐 Login to Docker Hub
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
|
||||||
|
- name: 📖 🔍 Checkout Repository Code
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
fetch-depth: 1
|
||||||
|
|
||||||
|
- name: 🏗️ 🔧 Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: 🐳 🔨 Build Migrations Container
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
sbom: true
|
||||||
|
provenance: true
|
||||||
|
context: .
|
||||||
|
file: migrations.Dockerfile
|
||||||
|
tags: siteworxpro/template:${{ gitea.ref_name }}-migrations
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- "*"
|
- "**"
|
||||||
|
|
||||||
name: 🧪✨ Tests Workflow
|
name: 🧪✨ Tests Workflow
|
||||||
|
|
||||||
@@ -14,7 +14,6 @@ jobs:
|
|||||||
|
|
||||||
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
||||||
run: |
|
run: |
|
||||||
apt update && apt install -yq ca-certificates curl
|
|
||||||
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
||||||
update-ca-certificates
|
update-ca-certificates
|
||||||
|
|
||||||
@@ -75,7 +74,6 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
||||||
run: |
|
run: |
|
||||||
apt update && apt install -yq ca-certificates curl
|
|
||||||
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
||||||
update-ca-certificates
|
update-ca-certificates
|
||||||
|
|
||||||
@@ -93,6 +91,7 @@ jobs:
|
|||||||
- name: 📖 ✨ Install Composer Libraries
|
- name: 📖 ✨ Install Composer Libraries
|
||||||
run: |
|
run: |
|
||||||
docker run --rm \
|
docker run --rm \
|
||||||
|
-v composer-cache:/tmp/cache \
|
||||||
--volumes-from ${{ env.JOB_CONTAINER_NAME }} \
|
--volumes-from ${{ env.JOB_CONTAINER_NAME }} \
|
||||||
-w ${{ github.workspace }} \
|
-w ${{ github.workspace }} \
|
||||||
siteworxpro/composer \
|
siteworxpro/composer \
|
||||||
@@ -113,7 +112,6 @@ jobs:
|
|||||||
|
|
||||||
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
||||||
run: |
|
run: |
|
||||||
apt update && apt install -yq ca-certificates curl
|
|
||||||
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
||||||
update-ca-certificates
|
update-ca-certificates
|
||||||
|
|
||||||
@@ -131,6 +129,7 @@ jobs:
|
|||||||
- name: 📖 ✨ Install Composer Libraries
|
- name: 📖 ✨ Install Composer Libraries
|
||||||
run: |
|
run: |
|
||||||
docker run --rm \
|
docker run --rm \
|
||||||
|
-v composer-cache:/tmp/cache \
|
||||||
--volumes-from ${{ env.JOB_CONTAINER_NAME }} \
|
--volumes-from ${{ env.JOB_CONTAINER_NAME }} \
|
||||||
-w ${{ github.workspace }} \
|
-w ${{ github.workspace }} \
|
||||||
siteworxpro/composer \
|
siteworxpro/composer \
|
||||||
@@ -150,7 +149,6 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
||||||
run: |
|
run: |
|
||||||
apt update && apt install -yq ca-certificates curl
|
|
||||||
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
||||||
update-ca-certificates
|
update-ca-certificates
|
||||||
|
|
||||||
@@ -168,6 +166,7 @@ jobs:
|
|||||||
- name: 📖 ✨ Install Composer Libraries
|
- name: 📖 ✨ Install Composer Libraries
|
||||||
run: |
|
run: |
|
||||||
docker run --rm \
|
docker run --rm \
|
||||||
|
-v composer-cache:/tmp/cache \
|
||||||
--volumes-from ${{ env.JOB_CONTAINER_NAME }} \
|
--volumes-from ${{ env.JOB_CONTAINER_NAME }} \
|
||||||
-w ${{ github.workspace }} \
|
-w ${{ github.workspace }} \
|
||||||
siteworxpro/composer \
|
siteworxpro/composer \
|
||||||
@@ -187,7 +186,6 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
||||||
run: |
|
run: |
|
||||||
apt update && apt install -yq ca-certificates curl
|
|
||||||
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
||||||
update-ca-certificates
|
update-ca-certificates
|
||||||
|
|
||||||
@@ -202,9 +200,10 @@ jobs:
|
|||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
|
||||||
- name: Install Composer Libraries
|
- name: 📖 ✨ Install Composer Libraries
|
||||||
run: |
|
run: |
|
||||||
docker run --rm \
|
docker run --rm \
|
||||||
|
-v composer-cache:/tmp/cache \
|
||||||
--volumes-from ${{ env.JOB_CONTAINER_NAME }} \
|
--volumes-from ${{ env.JOB_CONTAINER_NAME }} \
|
||||||
-w ${{ github.workspace }} \
|
-w ${{ github.workspace }} \
|
||||||
siteworxpro/composer \
|
siteworxpro/composer \
|
||||||
@@ -224,7 +223,6 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
- name: 🛡️ 🔒 Add Siteworx CA Certificates
|
||||||
run: |
|
run: |
|
||||||
apt update && apt install -yq ca-certificates curl
|
|
||||||
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
curl -Ls https://siteworxpro.com/hosted/Siteworx+Root+CA.pem -o /usr/local/share/ca-certificates/sw.crt
|
||||||
update-ca-certificates
|
update-ca-certificates
|
||||||
|
|
||||||
@@ -239,18 +237,32 @@ jobs:
|
|||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
|
||||||
- name: Install Composer Libraries
|
- name: 📖 ✨ Install Composer Libraries
|
||||||
run: |
|
run: |
|
||||||
docker run --rm \
|
docker run --rm \
|
||||||
|
-v composer-cache:/tmp/cache \
|
||||||
--volumes-from ${{ env.JOB_CONTAINER_NAME }} \
|
--volumes-from ${{ env.JOB_CONTAINER_NAME }} \
|
||||||
-w ${{ github.workspace }} \
|
-w ${{ github.workspace }} \
|
||||||
siteworxpro/composer \
|
siteworxpro/composer \
|
||||||
install --ignore-platform-reqs --no-interaction --prefer-dist --optimize-autoloader
|
install --ignore-platform-reqs --no-interaction --prefer-dist --optimize-autoloader
|
||||||
|
|
||||||
- name: Run Unit Tests
|
- name: 🧪 ✅ Run Unit Tests
|
||||||
|
uses: addnab/docker-run-action@v3
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
image: siteworxpro/composer
|
||||||
|
options: --volumes-from ${{ env.JOB_CONTAINER_NAME }} -w ${{ gitea.workspace }}
|
||||||
run: |
|
run: |
|
||||||
docker run --rm \
|
bin/pcov.sh
|
||||||
--volumes-from ${{ env.JOB_CONTAINER_NAME }} \
|
composer run tests:unit:coverage
|
||||||
-w ${{ github.workspace }} \
|
|
||||||
siteworxpro/composer \
|
# - name: 📦 Publish Build Artifacts
|
||||||
run tests:unit
|
# env:
|
||||||
|
# NODE_TLS_REJECT_UNAUTHORIZED: 0
|
||||||
|
# uses: christopherhx/gitea-upload-artifact@v4
|
||||||
|
# with:
|
||||||
|
# options: --volumes-from ${{ env.JOB_CONTAINER_NAME }} -w ${{ gitea.workspace }}
|
||||||
|
# name: junit-coverage.xml
|
||||||
|
# path: tests/reports/junit.xml
|
||||||
|
# retention-days: 1
|
||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,3 +1,6 @@
|
|||||||
.idea/
|
.idea/
|
||||||
|
.DS_Store
|
||||||
vendor/
|
vendor/
|
||||||
.phpunit.cache/
|
.phpunit.cache/
|
||||||
|
|
||||||
|
tests/reports/
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
include:
|
|
||||||
- local: .gitlab/ci/stages.yml
|
|
||||||
- local: .gitlab/ci/tests.yml
|
|
||||||
- local: .gitlab/ci/libraries.yml
|
|
||||||
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
Install Composer Libraries:
|
|
||||||
stage: libraries
|
|
||||||
image: siteworxpro/composer:latest
|
|
||||||
rules:
|
|
||||||
- if: '$CI_COMMIT_TAG'
|
|
||||||
when: never
|
|
||||||
- if: '$CI_PIPELINE_SOURCE == "push"'
|
|
||||||
when: always
|
|
||||||
- when: never
|
|
||||||
script:
|
|
||||||
- composer install --ignore-platform-reqs
|
|
||||||
artifacts:
|
|
||||||
paths:
|
|
||||||
- vendor/
|
|
||||||
expire_in: 1 hour
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
stages:
|
|
||||||
- libraries
|
|
||||||
- tests
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
Unit Tests:
|
|
||||||
stage: tests
|
|
||||||
needs:
|
|
||||||
- Install Composer Libraries
|
|
||||||
rules:
|
|
||||||
- if: '$CI_COMMIT_TAG'
|
|
||||||
when: never
|
|
||||||
- if: '$CI_PIPELINE_SOURCE == "push"'
|
|
||||||
when: always
|
|
||||||
- when: never
|
|
||||||
image: siteworxpro/composer
|
|
||||||
before_script: |
|
|
||||||
bin/pcov.sh
|
|
||||||
script: |
|
|
||||||
echo "Running unit tests..."
|
|
||||||
composer run tests:unit:coverage
|
|
||||||
coverage: '/^\s*Lines:\s*\d+.\d+\%/'
|
|
||||||
artifacts:
|
|
||||||
expire_in: 1 day
|
|
||||||
reports:
|
|
||||||
junit: tests/reports/junit.xml
|
|
||||||
paths:
|
|
||||||
- tests/reports/
|
|
||||||
|
|
||||||
Run License Check:
|
|
||||||
stage: tests
|
|
||||||
needs:
|
|
||||||
- Install Composer Libraries
|
|
||||||
rules:
|
|
||||||
- if: '$CI_COMMIT_TAG'
|
|
||||||
when: never
|
|
||||||
- if: '$CI_PIPELINE_SOURCE == "push"'
|
|
||||||
when: on_success
|
|
||||||
- when: never
|
|
||||||
image: siteworxpro/composer
|
|
||||||
script:
|
|
||||||
- composer run tests:license
|
|
||||||
|
|
||||||
Run Code Lint:
|
|
||||||
stage: tests
|
|
||||||
needs:
|
|
||||||
- Install Composer Libraries
|
|
||||||
rules:
|
|
||||||
- if: '$CI_COMMIT_TAG'
|
|
||||||
when: never
|
|
||||||
- if: '$CI_PIPELINE_SOURCE == "push"'
|
|
||||||
when: on_success
|
|
||||||
- when: never
|
|
||||||
image: siteworxpro/composer
|
|
||||||
script:
|
|
||||||
- composer run tests:lint
|
|
||||||
|
|
||||||
Run Code Sniffer:
|
|
||||||
stage: tests
|
|
||||||
needs:
|
|
||||||
- Install Composer Libraries
|
|
||||||
rules:
|
|
||||||
- if: '$CI_COMMIT_TAG'
|
|
||||||
when: never
|
|
||||||
- if: '$CI_PIPELINE_SOURCE == "push"'
|
|
||||||
when: on_success
|
|
||||||
- when: never
|
|
||||||
image: siteworxpro/composer
|
|
||||||
script:
|
|
||||||
- composer run tests:phpstan
|
|
||||||
2
.rr.yaml
2
.rr.yaml
@@ -21,4 +21,4 @@ http:
|
|||||||
logs:
|
logs:
|
||||||
encoding: json
|
encoding: json
|
||||||
level: ${LOG_LEVEL:-info}
|
level: ${LOG_LEVEL:-info}
|
||||||
mode: production
|
mode: ${LOG_MODE:-production}
|
||||||
18
Dockerfile
18
Dockerfile
@@ -1,5 +1,5 @@
|
|||||||
# Use the RoadRunner image as a base for the first stage
|
# Use the RoadRunner image as a base for the first stage
|
||||||
FROM ghcr.io/roadrunner-server/roadrunner:2025.1.1 AS roadrunner
|
FROM ghcr.io/roadrunner-server/roadrunner:2025.1.4 AS roadrunner
|
||||||
|
|
||||||
# Use the official Composer image as the base for the library stage
|
# Use the official Composer image as the base for the library stage
|
||||||
FROM siteworxpro/composer AS library
|
FROM siteworxpro/composer AS library
|
||||||
@@ -12,14 +12,25 @@ RUN composer install --optimize-autoloader --ignore-platform-reqs --no-dev
|
|||||||
|
|
||||||
|
|
||||||
# Use the official PHP CLI image with Alpine Linux for the second stage
|
# Use the official PHP CLI image with Alpine Linux for the second stage
|
||||||
FROM php:8.4.6-alpine AS php
|
FROM php:8.4.14-alpine AS php
|
||||||
|
|
||||||
|
ARG KAFKA_ENABLED=0
|
||||||
|
|
||||||
# Move the production PHP configuration file to the default location
|
# Move the production PHP configuration file to the default location
|
||||||
RUN mv /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini \
|
RUN mv /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini \
|
||||||
&& apk add libpq-dev linux-headers --no-cache \
|
&& apk add libpq-dev linux-headers --no-cache \
|
||||||
&& docker-php-ext-install pdo_pgsql sockets \
|
&& docker-php-ext-install pdo_pgsql sockets pcntl \
|
||||||
&& rm -rf /var/cache/apk/*
|
&& rm -rf /var/cache/apk/*
|
||||||
|
|
||||||
|
RUN if [ "$KAFKA_ENABLED" -eq 1 ] ; then \
|
||||||
|
echo "Kafka support enabled" ; \
|
||||||
|
apk add autoconf g++ librdkafka-dev make --no-cache ; \
|
||||||
|
pecl install rdkafka && docker-php-ext-enable rdkafka ; \
|
||||||
|
else \
|
||||||
|
echo "Kafka support disabled" ; \
|
||||||
|
exit 0 ; \
|
||||||
|
fi
|
||||||
|
|
||||||
# Set the working directory to /app
|
# Set the working directory to /app
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -33,6 +44,7 @@ COPY --from=library /app/vendor /app/vendor
|
|||||||
ADD src src/
|
ADD src src/
|
||||||
ADD server.php .
|
ADD server.php .
|
||||||
ADD .rr.yaml .
|
ADD .rr.yaml .
|
||||||
|
ADD config.php .
|
||||||
|
|
||||||
EXPOSE 9501
|
EXPOSE 9501
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
# Template
|
# Template
|
||||||
|
|
||||||
[](https://git.siteworxpro.com/rrise/php-template/-/commits/master)
|

|
||||||
[](https://git.siteworxpro.com/rrise/php-template/-/commits/master)
|
|
||||||
[](https://git.siteworxpro.com/rrise/php-template/-/releases)
|
|
||||||
|
|
||||||
## Dev Environment
|
## Dev Environment
|
||||||
|
|
||||||
@@ -40,7 +38,7 @@ You can access the api at `http://localhost:9501/`
|
|||||||
|
|
||||||
xdebug needs to be built into the container before it will work
|
xdebug needs to be built into the container before it will work
|
||||||
```shell
|
```shell
|
||||||
docker exec -it template-runtime-1 bin/xdebug.sh
|
docker exec -it php-template-composer-runtime-1 bin/xdebug.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
### Install the dependencies
|
### Install the dependencies
|
||||||
|
|||||||
4
bin/migrate.sh
Executable file
4
bin/migrate.sh
Executable file
@@ -0,0 +1,4 @@
|
|||||||
|
eval #!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
migrate -path /app/db/migrations -database "postgres://$DB_USERNAME:$DB_PASSWORD@$DB_HOST:$DB_PORT/$DB_DATABASE?sslmode=disable" up
|
||||||
11
cli.php
Executable file
11
cli.php
Executable file
@@ -0,0 +1,11 @@
|
|||||||
|
#!/usr/local/bin/php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require __DIR__ . '/vendor/autoload.php';
|
||||||
|
|
||||||
|
use Siteworxpro\App\Cli\App;
|
||||||
|
|
||||||
|
$cliApp = new App();
|
||||||
|
exit($cliApp->run());
|
||||||
@@ -9,21 +9,27 @@
|
|||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
"php": "^8.4",
|
"php": "^8.4",
|
||||||
"league/route": "^6.2",
|
"league/route": "^6.2.0",
|
||||||
"illuminate/database": "^12.10",
|
"illuminate/database": "^v12.34.0",
|
||||||
"spiral/roadrunner-http": "^3.5",
|
"spiral/roadrunner-http": "^v3.6.0",
|
||||||
"nyholm/psr7": "^1.8",
|
"nyholm/psr7": "^1.8.2",
|
||||||
"illuminate/support": "^v12.10.2",
|
"illuminate/support": "^v12.10.2",
|
||||||
"roadrunner-php/app-logger": "^1.2",
|
"roadrunner-php/app-logger": "^1.2.0",
|
||||||
"siteworxpro/config": "^1.1",
|
"siteworxpro/config": "^1.1.1",
|
||||||
"predis/predis": "^3.0"
|
"predis/predis": "^v3.2.0",
|
||||||
|
"siteworxpro/http-status": "0.0.2",
|
||||||
|
"lcobucci/jwt": "^5.6",
|
||||||
|
"adhocore/cli": "^1.9",
|
||||||
|
"robinvdvleuten/ulid": "^5.0",
|
||||||
|
"monolog/monolog": "^3.9"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"phpunit/phpunit": "^12.1",
|
"phpunit/phpunit": "^12.4",
|
||||||
"mockery/mockery": "^1.6",
|
"mockery/mockery": "^1.6",
|
||||||
"squizlabs/php_codesniffer": "^3.12",
|
"squizlabs/php_codesniffer": "^3.12",
|
||||||
"lendable/composer-license-checker": "^1.2",
|
"lendable/composer-license-checker": "^1.2",
|
||||||
"phpstan/phpstan": "^2.1"
|
"phpstan/phpstan": "^2.1.31",
|
||||||
|
"kwn/php-rdkafka-stubs": "^2.2"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"tests:all": [
|
"tests:all": [
|
||||||
@@ -53,16 +59,10 @@
|
|||||||
"phpstan analyse --level 4 ./src/ -c phpstan.neon"
|
"phpstan analyse --level 4 ./src/ -c phpstan.neon"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"repositories": {
|
"repositories": [
|
||||||
"git.siteworxpro.com/24": {
|
{
|
||||||
"type": "composer",
|
"type": "composer",
|
||||||
"url": "https://git.siteworxpro.com/api/v4/group/24/-/packages/composer/packages.json",
|
"url": "https://gitea.siteworxpro.com/api/packages/php-packages/composer"
|
||||||
"options": {
|
|
||||||
"ssl": {
|
|
||||||
"verify_peer": false,
|
|
||||||
"allow_self_signed": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
1335
composer.lock
generated
1335
composer.lock
generated
File diff suppressed because it is too large
Load Diff
47
config.php
47
config.php
@@ -21,8 +21,14 @@ return [
|
|||||||
'database' => Env::get('DB_DATABASE', 'siteworxpro'),
|
'database' => Env::get('DB_DATABASE', 'siteworxpro'),
|
||||||
'username' => Env::get('DB_USERNAME', 'siteworxpro'),
|
'username' => Env::get('DB_USERNAME', 'siteworxpro'),
|
||||||
'password' => Env::get('DB_PASSWORD', 'password'),
|
'password' => Env::get('DB_PASSWORD', 'password'),
|
||||||
|
'port' => Env::get('DB_PORT', 5432, 'int'),
|
||||||
|
'charset' => Env::get('DB_CHARSET', 'utf8'),
|
||||||
|
'collation' => Env::get('DB_COLLATION', 'utf8_unicode_ci'),
|
||||||
|
'prefix' => Env::get('DB_PREFIX', ''),
|
||||||
|
'options' => [
|
||||||
|
// Add any additional PDO options here
|
||||||
|
],
|
||||||
],
|
],
|
||||||
|
|
||||||
|
|
||||||
'cors' => [
|
'cors' => [
|
||||||
'allowed_origins' => Env::get('CORS_ALLOWED_ORIGINS', 'localhost:3000'),
|
'allowed_origins' => Env::get('CORS_ALLOWED_ORIGINS', 'localhost:3000'),
|
||||||
@@ -34,5 +40,44 @@ return [
|
|||||||
'host' => Env::get('REDIS_HOST', 'localhost'),
|
'host' => Env::get('REDIS_HOST', 'localhost'),
|
||||||
'port' => Env::get('REDIS_PORT', 6379, 'int'),
|
'port' => Env::get('REDIS_PORT', 6379, 'int'),
|
||||||
'database' => Env::get('REDIS_DATABASE', 0, 'int'),
|
'database' => Env::get('REDIS_DATABASE', 0, 'int'),
|
||||||
|
'password' => Env::get('REDIS_PASSWORD'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'jwt' => [
|
||||||
|
'signing_key' => Env::get('JWT_SIGNING_KEY', 'a_super_secret_key'),
|
||||||
|
'audience' => Env::get('JWT_AUDIENCE', 'my_audience'),
|
||||||
|
'issuer' => Env::get('JWT_ISSUER', 'my_issuer'),
|
||||||
|
'strict_validation' => Env::get('JWT_STRICT_VALIDATION', true, 'bool'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'queue' => [
|
||||||
|
'broker' => Env::get('QUEUE_BROKER', 'kafka'),
|
||||||
|
|
||||||
|
'broker_config' => [
|
||||||
|
|
||||||
|
'redis' => [
|
||||||
|
'consumerGroup' => Env::get('QUEUE_REDIS_CONSUMER_GROUP', ''),
|
||||||
|
],
|
||||||
|
|
||||||
|
'kafka' => [
|
||||||
|
'brokers' => Env::get('QUEUE_KAFKA_BROKERS', 'kafka:9092'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'rabbitmq' => [
|
||||||
|
'host' => Env::get('QUEUE_RABBITMQ_HOST', 'localhost'),
|
||||||
|
'port' => Env::get('QUEUE_RABBITMQ_PORT', 5672, 'int'),
|
||||||
|
'username' => Env::get('QUEUE_RABBITMQ_USERNAME', 'guest'),
|
||||||
|
'password' => Env::get('QUEUE_RABBITMQ_PASSWORD', 'guest'),
|
||||||
|
'vhost' => Env::get('QUEUE_RABBITMQ_VHOST', '/'),
|
||||||
|
],
|
||||||
|
|
||||||
|
'sqs' => [
|
||||||
|
'key' => Env::get('QUEUE_SQS_KEY', ''),
|
||||||
|
'secret' => Env::get('QUEUE_SQS_SECRET', ''),
|
||||||
|
'region' => Env::get('QUEUE_SQS_REGION', 'us-east-1'),
|
||||||
|
'version' => Env::get('QUEUE_SQS_VERSION', 'latest'),
|
||||||
|
'queue_url' => Env::get('QUEUE_SQS_QUEUE_URL', ''),
|
||||||
|
]
|
||||||
|
]
|
||||||
]
|
]
|
||||||
];
|
];
|
||||||
@@ -4,6 +4,31 @@ volumes:
|
|||||||
|
|
||||||
services:
|
services:
|
||||||
|
|
||||||
|
traefik:
|
||||||
|
image: traefik:latest
|
||||||
|
container_name: traefik
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "traefik", "healthcheck", "--ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
- "443:443"
|
||||||
|
volumes:
|
||||||
|
- "/var/run/docker.sock:/var/run/docker.sock"
|
||||||
|
restart: always
|
||||||
|
command:
|
||||||
|
- "--providers.docker=true"
|
||||||
|
- "--ping"
|
||||||
|
- "--providers.docker.exposedByDefault=false"
|
||||||
|
- "--entrypoints.web.address=:80"
|
||||||
|
- "--entrypoints.web-secure.address=:443"
|
||||||
|
- "--accesslog=true"
|
||||||
|
- "--entrypoints.web.http.redirections.entryPoint.to=web-secure"
|
||||||
|
- "--entrypoints.web.http.redirections.entryPoint.scheme=https"
|
||||||
|
- "--entrypoints.web.http.redirections.entrypoint.permanent=true"
|
||||||
|
|
||||||
composer-runtime:
|
composer-runtime:
|
||||||
volumes:
|
volumes:
|
||||||
- .:/app
|
- .:/app
|
||||||
@@ -12,30 +37,112 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
PHP_IDE_CONFIG: serverName=localhost
|
PHP_IDE_CONFIG: serverName=localhost
|
||||||
|
|
||||||
|
migration-container:
|
||||||
|
volumes:
|
||||||
|
- ./db/migrations:/app/db/migrations
|
||||||
|
- ./bin:/app/bin
|
||||||
|
image: siteworxpro/migrate:v4.18.3
|
||||||
|
working_dir: /app
|
||||||
|
# entrypoint: "/bin/sh -c 'while true; do sleep 30; done;'"
|
||||||
|
entrypoint: /bin/sh -c '/app/bin/migrate.sh'
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
environment:
|
||||||
|
DB_USERNAME: ${DB_USERNAME:-siteworxpro}
|
||||||
|
DB_PASSWORD: ${DB_PASSWORD:-password}
|
||||||
|
DB_DATABASE: ${DB_DATABASE:-siteworxpro}
|
||||||
|
DB_HOST: ${DB_HOST-postgres}
|
||||||
|
DB_PORT: ${DB_PORT-5432}
|
||||||
|
|
||||||
dev-runtime:
|
dev-runtime:
|
||||||
ports:
|
labels:
|
||||||
- "9501:9501"
|
- "traefik.enable=true"
|
||||||
|
- "traefik.http.routers.api.entrypoints=web-secure"
|
||||||
|
- "traefik.http.routers.api.rule=Host(`localhost`) || Host(`127.0.0.1`)"
|
||||||
|
- "traefik.http.routers.api.tls=true"
|
||||||
|
- "traefik.http.routers.api.service=api"
|
||||||
|
- "traefik.http.services.api.loadbalancer.healthcheck.path=/healthz"
|
||||||
|
- "traefik.http.services.api.loadbalancer.healthcheck.interval=5s"
|
||||||
|
- "traefik.http.services.api.loadbalancer.healthcheck.timeout=60s"
|
||||||
volumes:
|
volumes:
|
||||||
- .:/app
|
- .:/app
|
||||||
build:
|
build:
|
||||||
|
args:
|
||||||
|
KAFKA_ENABLED: "1"
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
entrypoint: "/bin/sh -c 'while true; do sleep 30; done;'"
|
entrypoint: "/bin/sh -c 'while true; do sleep 30; done;'"
|
||||||
|
depends_on:
|
||||||
|
migration-container:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
traefik:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
environment:
|
environment:
|
||||||
PHP_IDE_CONFIG: serverName=localhost
|
PHP_IDE_CONFIG: serverName=localhost
|
||||||
WORKERS: 1
|
WORKERS: 1
|
||||||
DEBUG: 1
|
DEBUG: 1
|
||||||
REDIS_HOST: redis
|
REDIS_HOST: redis
|
||||||
|
DB_HOST: postgres
|
||||||
|
JWT_SIGNING_KEY: a-string-secret-at-least-256-bits-long
|
||||||
|
|
||||||
|
## Kafka and Zookeeper for local development
|
||||||
|
kafka-ui:
|
||||||
|
image: kafbat/kafka-ui:latest # Or kafbat/kafka-ui:latest for newer Kafka
|
||||||
|
container_name: kafka-ui
|
||||||
|
ports:
|
||||||
|
- "8080:8080" # Expose the UI port
|
||||||
|
environment:
|
||||||
|
KAFKA_CLUSTERS_0_NAME: local-kafka-cluster
|
||||||
|
KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka:9092
|
||||||
|
depends_on:
|
||||||
|
kafka:
|
||||||
|
condition: service_started
|
||||||
|
zookeeper:
|
||||||
|
condition: service_started
|
||||||
|
zookeeper:
|
||||||
|
image: ubuntu/zookeeper:latest
|
||||||
|
environment:
|
||||||
|
ALLOW_ANONYMOUS_LOGIN: "yes"
|
||||||
|
ports:
|
||||||
|
- "2181:2181"
|
||||||
|
kafka:
|
||||||
|
image: ubuntu/kafka:latest
|
||||||
|
environment:
|
||||||
|
KAFKA_BROKER_ID: 1
|
||||||
|
KAFKA_LISTENERS: PLAINTEXT://kafka:9092
|
||||||
|
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
|
||||||
|
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
|
||||||
|
ALLOW_PLAINTEXT_LISTENER: "yes"
|
||||||
|
ports:
|
||||||
|
- "9092:9092"
|
||||||
|
depends_on:
|
||||||
|
zookeeper:
|
||||||
|
condition: service_started
|
||||||
|
|
||||||
redis:
|
redis:
|
||||||
image: redis:latest
|
image: redis:latest
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
ports:
|
ports:
|
||||||
- "6379:6379"
|
- "6379:6379"
|
||||||
volumes:
|
volumes:
|
||||||
- redisdata:/data
|
- redisdata:/data
|
||||||
|
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:latest
|
image: postgres:18
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U ${DB_USERNAME:-siteworxpro}"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
environment:
|
environment:
|
||||||
POSTGRES_USER: ${DB_USERNAME:-siteworxpro}
|
POSTGRES_USER: ${DB_USERNAME:-siteworxpro}
|
||||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-password}
|
POSTGRES_PASSWORD: ${DB_PASSWORD:-password}
|
||||||
@@ -43,4 +150,4 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
- "5432:5432"
|
- "5432:5432"
|
||||||
volumes:
|
volumes:
|
||||||
- pgdata:/var/lib/postgresql/data
|
- pgdata:/var/lib/postgresql
|
||||||
8
migrations.Dockerfile
Normal file
8
migrations.Dockerfile
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
FROM siteworxpro/migrate:v4.18.3
|
||||||
|
|
||||||
|
ADD db/migrations /app/db/migrations
|
||||||
|
ADD bin/migrate.sh /app/bin/migrate.sh
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENTRYPOINT ["/app/bin/migrate.sh"]
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use Siteworxpro\App\Server;
|
use Siteworxpro\App\Api;
|
||||||
|
|
||||||
require __DIR__ . '/vendor/autoload.php';
|
require __DIR__ . '/vendor/autoload.php';
|
||||||
|
|
||||||
|
try {
|
||||||
// Instantiate the ExternalServer class
|
// Instantiate the ExternalServer class
|
||||||
$server = new Server();
|
$server = new Api();
|
||||||
|
|
||||||
// Start the server
|
// Start the server
|
||||||
try {
|
|
||||||
$server->startServer();
|
$server->startServer();
|
||||||
} catch (JsonException $e) {
|
} catch (JsonException $e) {
|
||||||
echo $e->getMessage();
|
echo $e->getMessage();
|
||||||
|
|||||||
24
src/Annotations/Async/HandlesMessage.php
Normal file
24
src/Annotations/Async/HandlesMessage.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Annotations\Async;
|
||||||
|
|
||||||
|
use Attribute;
|
||||||
|
|
||||||
|
#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
|
||||||
|
readonly class HandlesMessage
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public string $messageClass,
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getMessageClass(): string
|
||||||
|
{
|
||||||
|
return $this->messageClass;
|
||||||
|
}
|
||||||
|
}
|
||||||
15
src/Annotations/Events/ListensFor.php
Normal file
15
src/Annotations/Events/ListensFor.php
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Annotations\Events;
|
||||||
|
|
||||||
|
use Attribute;
|
||||||
|
|
||||||
|
#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
|
||||||
|
readonly class ListensFor
|
||||||
|
{
|
||||||
|
public function __construct(public string $eventClass)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
44
src/Annotations/Guards/Jwt.php
Normal file
44
src/Annotations/Guards/Jwt.php
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Annotations\Guards;
|
||||||
|
|
||||||
|
use Attribute;
|
||||||
|
use Siteworxpro\App\Services\Facades\Config;
|
||||||
|
|
||||||
|
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
|
||||||
|
readonly class Jwt
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private string $issuer = '',
|
||||||
|
private string $audience = '',
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getRequiredAudience(): string
|
||||||
|
{
|
||||||
|
return Config::get('jwt.audience') ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function getAudience(): string
|
||||||
|
{
|
||||||
|
if ($this->audience === '') {
|
||||||
|
return Config::get('jwt.audience') ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->audience;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getIssuer(): string
|
||||||
|
{
|
||||||
|
if ($this->issuer === '') {
|
||||||
|
return Config::get('jwt.issuer') ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->issuer;
|
||||||
|
}
|
||||||
|
}
|
||||||
21
src/Annotations/Guards/Scope.php
Normal file
21
src/Annotations/Guards/Scope.php
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Annotations\Guards;
|
||||||
|
|
||||||
|
use Attribute;
|
||||||
|
|
||||||
|
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
|
||||||
|
readonly class Scope
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private array $scopes = []
|
||||||
|
) {}
|
||||||
|
|
||||||
|
|
||||||
|
public function getScopes(): array
|
||||||
|
{
|
||||||
|
return $this->scopes;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,16 +4,19 @@ declare(strict_types=1);
|
|||||||
|
|
||||||
namespace Siteworxpro\App;
|
namespace Siteworxpro\App;
|
||||||
|
|
||||||
use Illuminate\Container\Container;
|
|
||||||
use Illuminate\Support\Facades\Facade;
|
|
||||||
use League\Route\Http\Exception\MethodNotAllowedException;
|
use League\Route\Http\Exception\MethodNotAllowedException;
|
||||||
use League\Route\Http\Exception\NotFoundException;
|
use League\Route\Http\Exception\NotFoundException;
|
||||||
use League\Route\Router;
|
use League\Route\Router;
|
||||||
use Nyholm\Psr7\Factory\Psr17Factory;
|
use Nyholm\Psr7\Factory\Psr17Factory;
|
||||||
use Siteworxpro\App\Facades\Config;
|
use Siteworxpro\App\Controllers\HealthcheckController;
|
||||||
use Siteworxpro\App\Facades\Logger;
|
use Siteworxpro\App\Controllers\IndexController;
|
||||||
use Siteworxpro\App\Http\JsonResponseFactory;
|
use Siteworxpro\App\Http\JsonResponseFactory;
|
||||||
use Siteworxpro\App\Http\Middleware\CorsMiddleware;
|
use Siteworxpro\App\Http\Middleware\CorsMiddleware;
|
||||||
|
use Siteworxpro\App\Http\Middleware\JwtMiddleware;
|
||||||
|
use Siteworxpro\App\Http\Middleware\ScopeMiddleware;
|
||||||
|
use Siteworxpro\App\Services\Facades\Config;
|
||||||
|
use Siteworxpro\App\Services\Facades\Logger;
|
||||||
|
use Siteworxpro\HttpStatus\CodesEnum;
|
||||||
use Spiral\RoadRunner\Http\PSR7Worker;
|
use Spiral\RoadRunner\Http\PSR7Worker;
|
||||||
use Spiral\RoadRunner\Worker;
|
use Spiral\RoadRunner\Worker;
|
||||||
|
|
||||||
@@ -26,7 +29,7 @@ use Spiral\RoadRunner\Worker;
|
|||||||
*
|
*
|
||||||
* @package Siteworxpro\App
|
* @package Siteworxpro\App
|
||||||
*/
|
*/
|
||||||
class Server
|
class Api
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @var Router The router instance for handling routes.
|
* @var Router The router instance for handling routes.
|
||||||
@@ -38,69 +41,13 @@ class Server
|
|||||||
*/
|
*/
|
||||||
protected PSR7Worker $worker;
|
protected PSR7Worker $worker;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Server constructor.
|
* @throws \ReflectionException
|
||||||
*
|
|
||||||
* Initializes the server by booting the PSR-7 worker and router.
|
|
||||||
*/
|
*/
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
$this->boot();
|
Kernel::boot();
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Bootstraps the server by initializing the PSR-7 worker and router.
|
|
||||||
*
|
|
||||||
* This method sets up the PSR-7 worker and router instances, and registers
|
|
||||||
* the routes for the server. It should be called in the constructor of
|
|
||||||
* subclasses to ensure proper initialization.
|
|
||||||
*
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
private function boot(): void
|
|
||||||
{
|
|
||||||
$container = new Container();
|
|
||||||
Facade::setFacadeApplication($container);
|
|
||||||
|
|
||||||
$this->worker = new PSR7Worker(
|
|
||||||
Worker::create(),
|
|
||||||
new Psr17Factory(),
|
|
||||||
new Psr17Factory(),
|
|
||||||
new Psr17Factory()
|
|
||||||
);
|
|
||||||
|
|
||||||
$this->router = new Router();
|
|
||||||
|
|
||||||
$this->registerRoutes();
|
$this->registerRoutes();
|
||||||
$this->bootModelCapsule();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Bootstraps the model capsule for database connections.
|
|
||||||
*
|
|
||||||
* This method sets up the database connection using the Eloquent ORM.
|
|
||||||
* It retrieves the database configuration from the Config facade and
|
|
||||||
* initializes the Eloquent capsule manager.
|
|
||||||
*
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function bootModelCapsule(): void
|
|
||||||
{
|
|
||||||
$capsule = new \Illuminate\Database\Capsule\Manager();
|
|
||||||
$capsule->addConnection([
|
|
||||||
'driver' => Config::get('db.driver'),
|
|
||||||
'host' => Config::get('db.host'),
|
|
||||||
'database' => Config::get('db.database'),
|
|
||||||
'username' => Config::get('db.username'),
|
|
||||||
'password' => Config::get('db.password'),
|
|
||||||
'charset' => 'utf8',
|
|
||||||
'collation' => 'utf8_unicode_ci',
|
|
||||||
'prefix' => '',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$capsule->setAsGlobal();
|
|
||||||
$capsule->bootEloquent();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -111,13 +58,22 @@ class Server
|
|||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
protected function registerRoutes(): void
|
public function registerRoutes(): void
|
||||||
{
|
{
|
||||||
$this->router->get('/', function () {
|
$this->worker = new PSR7Worker(
|
||||||
return JsonResponseFactory::createJsonResponse(['status_code' => 200, 'message' => 'Server is running']);
|
Worker::create(),
|
||||||
});
|
new Psr17Factory(),
|
||||||
|
new Psr17Factory(),
|
||||||
|
new Psr17Factory()
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->router = new Router();
|
||||||
|
$this->router->get('/', IndexController::class . '::get');
|
||||||
|
$this->router->get('/healthz', HealthcheckController::class . '::get');
|
||||||
|
|
||||||
$this->router->middleware(new CorsMiddleware());
|
$this->router->middleware(new CorsMiddleware());
|
||||||
|
$this->router->middleware(new JwtMiddleware());
|
||||||
|
$this->router->middleware(new ScopeMiddleware());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -151,7 +107,7 @@ class Server
|
|||||||
$this->worker->respond(
|
$this->worker->respond(
|
||||||
JsonResponseFactory::createJsonResponse(
|
JsonResponseFactory::createJsonResponse(
|
||||||
['status_code' => 404, 'reason_phrase' => 'Not Found'],
|
['status_code' => 404, 'reason_phrase' => 'Not Found'],
|
||||||
404
|
CodesEnum::NOT_FOUND
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
} catch (\Throwable $e) {
|
} catch (\Throwable $e) {
|
||||||
@@ -168,7 +124,9 @@ class Server
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->worker->respond(JsonResponseFactory::createJsonResponse($json, 500));
|
$this->worker->respond(
|
||||||
|
JsonResponseFactory::createJsonResponse($json, CodesEnum::INTERNAL_SERVER_ERROR)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
19
src/Async/Brokers/Broker.php
Normal file
19
src/Async/Brokers/Broker.php
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async\Brokers;
|
||||||
|
|
||||||
|
abstract class Broker implements BrokerInterface
|
||||||
|
{
|
||||||
|
public const array BROKER_TYPES = [
|
||||||
|
'redis' => Redis::class,
|
||||||
|
'rabbitmq' => RabbitMQ::class,
|
||||||
|
'kafka' => Kafka::class,
|
||||||
|
'sqs' => Sqs::class,
|
||||||
|
];
|
||||||
|
|
||||||
|
public function __construct(protected $config = [])
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
21
src/Async/Brokers/BrokerInterface.php
Normal file
21
src/Async/Brokers/BrokerInterface.php
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async\Brokers;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Async\Queues\Queue;
|
||||||
|
use Siteworxpro\App\Async\Messages\Message;
|
||||||
|
|
||||||
|
interface BrokerInterface
|
||||||
|
{
|
||||||
|
public function publish(Queue $queue, Message $message, ?int $delay = null): void;
|
||||||
|
|
||||||
|
public function consume(Queue $queue): Message | null;
|
||||||
|
|
||||||
|
public function acknowledge(Queue $queue, Message $message): void;
|
||||||
|
|
||||||
|
public function reject(Queue $queue, Message $message, bool $requeue = false): void;
|
||||||
|
|
||||||
|
public function purge(Queue $queue): void;
|
||||||
|
}
|
||||||
86
src/Async/Brokers/Kafka.php
Normal file
86
src/Async/Brokers/Kafka.php
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async\Brokers;
|
||||||
|
|
||||||
|
use RdKafka\Conf;
|
||||||
|
use RdKafka\Exception;
|
||||||
|
use RdKafka\KafkaConsumer;
|
||||||
|
use RdKafka\Producer;
|
||||||
|
use Siteworxpro\App\Async\Queues\Queue;
|
||||||
|
use Siteworxpro\App\Async\Messages\Message;
|
||||||
|
|
||||||
|
class Kafka extends Broker
|
||||||
|
{
|
||||||
|
private Producer $producer;
|
||||||
|
|
||||||
|
private KafkaConsumer $consumer;
|
||||||
|
|
||||||
|
public function __construct($config = [])
|
||||||
|
{
|
||||||
|
parent::__construct($config);
|
||||||
|
|
||||||
|
|
||||||
|
$conf = new Conf();
|
||||||
|
$conf->set('bootstrap.servers', $config['brokers'] ?? 'localhost:9092');
|
||||||
|
$this->producer = new Producer($conf);
|
||||||
|
$this->producer->addBrokers($config['brokers'] ?? 'localhost:9092');
|
||||||
|
|
||||||
|
$conf->set('group.id', $config['consumerGroup'] ?? 'default');
|
||||||
|
$conf->set('auto.offset.reset', 'earliest');
|
||||||
|
|
||||||
|
$this->consumer = new KafkaConsumer($conf);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __destruct()
|
||||||
|
{
|
||||||
|
$this->producer->flush(1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws \Exception
|
||||||
|
*/
|
||||||
|
public function publish(Queue $queue, Message $message, ?int $delay = null): void
|
||||||
|
{
|
||||||
|
$topic = $this->producer->newTopic($queue->queueName());
|
||||||
|
$topic->produce(RD_KAFKA_PARTITION_UA, 0, $message->serialize(), $message->getId());
|
||||||
|
$this->producer->flush(1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws Exception
|
||||||
|
*/
|
||||||
|
public function consume(Queue $queue): Message|null
|
||||||
|
{
|
||||||
|
$this->consumer->subscribe([$queue->queueName()]);
|
||||||
|
$kafkaMessage = $this->consumer->consume(1000);
|
||||||
|
|
||||||
|
if ($kafkaMessage->err === RD_KAFKA_RESP_ERR__TIMED_OUT) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$messageData = $kafkaMessage->payload;
|
||||||
|
if ($messageData !== null) {
|
||||||
|
/** @var Message $message */
|
||||||
|
$message = unserialize($messageData, ['allowed_classes' => true]);
|
||||||
|
$message->setId((string)$kafkaMessage->offset);
|
||||||
|
|
||||||
|
return $message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function acknowledge(Queue $queue, Message $message): void
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public function reject(Queue $queue, Message $message, bool $requeue = false): void
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public function purge(Queue $queue): void
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
36
src/Async/Brokers/RabbitMQ.php
Normal file
36
src/Async/Brokers/RabbitMQ.php
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async\Brokers;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Async\Queues\Queue;
|
||||||
|
use Siteworxpro\App\Async\Messages\Message;
|
||||||
|
|
||||||
|
class RabbitMQ extends Broker
|
||||||
|
{
|
||||||
|
public function publish(Queue $queue, Message $message, ?int $delay = null): void
|
||||||
|
{
|
||||||
|
// TODO: Implement publish() method.
|
||||||
|
}
|
||||||
|
|
||||||
|
public function consume(Queue $queue): Message | null
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function acknowledge(Queue $queue, Message $message): void
|
||||||
|
{
|
||||||
|
// TODO: Implement acknowledge() method.
|
||||||
|
}
|
||||||
|
|
||||||
|
public function reject(Queue $queue, Message $message, bool $requeue = false): void
|
||||||
|
{
|
||||||
|
// TODO: Implement reject() method.
|
||||||
|
}
|
||||||
|
|
||||||
|
public function purge(Queue $queue): void
|
||||||
|
{
|
||||||
|
// TODO: Implement purge() method.
|
||||||
|
}
|
||||||
|
}
|
||||||
190
src/Async/Brokers/Redis.php
Normal file
190
src/Async/Brokers/Redis.php
Normal file
@@ -0,0 +1,190 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async\Brokers;
|
||||||
|
|
||||||
|
use Predis\Client;
|
||||||
|
use Predis\Command\RawCommand;
|
||||||
|
use Siteworxpro\App\Async\Messages\SayHelloMessage;
|
||||||
|
use Siteworxpro\App\Async\Queues\Queue;
|
||||||
|
use Siteworxpro\App\Async\Messages\Message;
|
||||||
|
use Siteworxpro\App\Helpers\Ulid;
|
||||||
|
|
||||||
|
class Redis extends Broker
|
||||||
|
{
|
||||||
|
private Client $client;
|
||||||
|
|
||||||
|
private string $consumerId;
|
||||||
|
|
||||||
|
private string $consumerGroup;
|
||||||
|
|
||||||
|
private const string CONSUMER_ID_PREFIX = 'consumer-group:';
|
||||||
|
private const string QUEUE_PREFIX = 'queue:';
|
||||||
|
|
||||||
|
private array $queueNames = [];
|
||||||
|
|
||||||
|
public function __construct($config = [])
|
||||||
|
{
|
||||||
|
parent::__construct($config);
|
||||||
|
|
||||||
|
$this->client = \Siteworxpro\App\Services\Facades\Redis::getFacadeRoot();
|
||||||
|
$this->consumerId = php_uname('n') . ':' . getmypid();
|
||||||
|
$this->consumerGroup = $config['consumerGroup'] ?? 'default';
|
||||||
|
}
|
||||||
|
|
||||||
|
private function ensureQueue(string $queueName): void
|
||||||
|
{
|
||||||
|
if (in_array($queueName, $this->queueNames, true)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->client->executeCommand(
|
||||||
|
new RawCommand(
|
||||||
|
'XGROUP',
|
||||||
|
[
|
||||||
|
'CREATE',
|
||||||
|
self::QUEUE_PREFIX . $queueName,
|
||||||
|
self::CONSUMER_ID_PREFIX . $this->consumerGroup,
|
||||||
|
'$',
|
||||||
|
'MKSTREAM'
|
||||||
|
]
|
||||||
|
)
|
||||||
|
);
|
||||||
|
} catch (\Exception) {
|
||||||
|
// If the group already exists, we catch the exception and ignore it
|
||||||
|
// This is because Redis will throw an error if the group already exists
|
||||||
|
// We can safely ignore this error as it means the group is already set up
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->client->executeCommand(
|
||||||
|
new RawCommand(
|
||||||
|
'XGROUP',
|
||||||
|
[
|
||||||
|
'CREATECONSUMER',
|
||||||
|
self::QUEUE_PREFIX . $queueName,
|
||||||
|
self::CONSUMER_ID_PREFIX . $this->consumerGroup,
|
||||||
|
$this->consumerId
|
||||||
|
]
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->queueNames[] = $queueName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __destruct()
|
||||||
|
{
|
||||||
|
foreach ($this->queueNames as $queueName) {
|
||||||
|
try {
|
||||||
|
$this->client->executeCommand(
|
||||||
|
new RawCommand(
|
||||||
|
'XGROUP',
|
||||||
|
[
|
||||||
|
'DELCONSUMER',
|
||||||
|
self::QUEUE_PREFIX . $queueName,
|
||||||
|
self::CONSUMER_ID_PREFIX . $this->consumerGroup,
|
||||||
|
$this->consumerId
|
||||||
|
]
|
||||||
|
)
|
||||||
|
);
|
||||||
|
} catch (\Exception) {
|
||||||
|
// Ignore exceptions during cleanup
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws \Exception
|
||||||
|
*/
|
||||||
|
public function publish(Queue $queue, Message $message, ?int $delay = null): void
|
||||||
|
{
|
||||||
|
$command = '%s * data %s';
|
||||||
|
$command = sprintf(
|
||||||
|
$command,
|
||||||
|
self::QUEUE_PREFIX .
|
||||||
|
$queue->queueName(),
|
||||||
|
base64_encode($message->serialize())
|
||||||
|
);
|
||||||
|
|
||||||
|
/** @var string $result */
|
||||||
|
$result = $this
|
||||||
|
->client
|
||||||
|
->executeCommand(
|
||||||
|
new RawCommand('XADD', explode(' ', $command)),
|
||||||
|
);
|
||||||
|
|
||||||
|
$message->setId($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function consume(Queue $queue): Message|null
|
||||||
|
{
|
||||||
|
$this->ensureQueue($queue->queueName());
|
||||||
|
|
||||||
|
$command = 'GROUP %s %s COUNT 1 STREAMS %s >';
|
||||||
|
$command = sprintf(
|
||||||
|
$command,
|
||||||
|
self::CONSUMER_ID_PREFIX . $this->consumerGroup,
|
||||||
|
$this->consumerId,
|
||||||
|
self::QUEUE_PREFIX . $queue->queueName(),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** @var array | null $response */
|
||||||
|
$response = $this
|
||||||
|
->client
|
||||||
|
->executeCommand(
|
||||||
|
new RawCommand(
|
||||||
|
'XREADGROUP',
|
||||||
|
explode(' ', $command)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($response === null || !isset($response[0][1][0][1][1])) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$messageData = base64_decode($response[0][1][0][1][1]);
|
||||||
|
$messageId = $response[0][1][0][0];
|
||||||
|
|
||||||
|
if ($messageData === 'NOOP') {
|
||||||
|
// If the message is a NOOP, we return null to indicate no actual message
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$value = unserialize($messageData, ['allowed_classes' => true]);
|
||||||
|
if (!$value instanceof Message) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$value->setId($messageId);
|
||||||
|
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function acknowledge(Queue $queue, Message $message): void
|
||||||
|
{
|
||||||
|
$response = $this
|
||||||
|
->client
|
||||||
|
->executeCommand(
|
||||||
|
new RawCommand(
|
||||||
|
'XACK',
|
||||||
|
[
|
||||||
|
self::QUEUE_PREFIX . $queue->queueName(),
|
||||||
|
self::CONSUMER_ID_PREFIX . $this->consumerGroup,
|
||||||
|
$message->getId()
|
||||||
|
]
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function reject(Queue $queue, Message $message, bool $requeue = false): void
|
||||||
|
{
|
||||||
|
// TODO: Implement reject() method.
|
||||||
|
}
|
||||||
|
|
||||||
|
public function purge(Queue $queue): void
|
||||||
|
{
|
||||||
|
|
||||||
|
// TODO: Implement purge() method.
|
||||||
|
}
|
||||||
|
}
|
||||||
36
src/Async/Brokers/Sqs.php
Normal file
36
src/Async/Brokers/Sqs.php
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async\Brokers;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Async\Queues\Queue;
|
||||||
|
use Siteworxpro\App\Async\Messages\Message;
|
||||||
|
|
||||||
|
class Sqs extends Broker
|
||||||
|
{
|
||||||
|
public function publish(Queue $queue, Message $message, ?int $delay = null): void
|
||||||
|
{
|
||||||
|
// TODO: Implement publish() method.
|
||||||
|
}
|
||||||
|
|
||||||
|
public function consume(Queue $queue): Message | null
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function acknowledge(Queue $queue, Message $message): void
|
||||||
|
{
|
||||||
|
// TODO: Implement acknowledge() method.
|
||||||
|
}
|
||||||
|
|
||||||
|
public function reject(Queue $queue, Message $message, bool $requeue = false): void
|
||||||
|
{
|
||||||
|
// TODO: Implement reject() method.
|
||||||
|
}
|
||||||
|
|
||||||
|
public function purge(Queue $queue): void
|
||||||
|
{
|
||||||
|
// TODO: Implement purge() method.
|
||||||
|
}
|
||||||
|
}
|
||||||
157
src/Async/Consumer.php
Normal file
157
src/Async/Consumer.php
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(ticks=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Annotations\Async\HandlesMessage;
|
||||||
|
use Siteworxpro\App\Async\Queues\Queue;
|
||||||
|
use Siteworxpro\App\Services\Facades\Logger;
|
||||||
|
|
||||||
|
class Consumer
|
||||||
|
{
|
||||||
|
private static bool $shutDown = false;
|
||||||
|
|
||||||
|
private const array QUEUES = [
|
||||||
|
'default' => Queues\DefaultQueue::class,
|
||||||
|
];
|
||||||
|
|
||||||
|
private array $queues = [];
|
||||||
|
|
||||||
|
private array $handlers = [];
|
||||||
|
|
||||||
|
private const string HANDLER_NAMESPACE = 'Siteworxpro\\App\\Async\\Handlers\\';
|
||||||
|
|
||||||
|
public function __construct(array $queues = [])
|
||||||
|
{
|
||||||
|
if ($queues === []) {
|
||||||
|
$queues = self::QUEUES;
|
||||||
|
} else {
|
||||||
|
$mappedQueues = [];
|
||||||
|
foreach ($queues as $queueName) {
|
||||||
|
if (isset(self::QUEUES[$queueName])) {
|
||||||
|
$mappedQueues[] = self::QUEUES[$queueName];
|
||||||
|
} else {
|
||||||
|
throw new \InvalidArgumentException("Queue '$queueName' is not defined.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$queues = $mappedQueues;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
foreach ($queues as $queueClass) {
|
||||||
|
$this->queues[] = new $queueClass();
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->registerHandlers();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function registerHandlers(): void
|
||||||
|
{
|
||||||
|
$recursiveIterator = new \RecursiveIteratorIterator(
|
||||||
|
new \RecursiveDirectoryIterator(__DIR__ . '/Handlers/')
|
||||||
|
);
|
||||||
|
|
||||||
|
foreach ($recursiveIterator as $file) {
|
||||||
|
if ($file->isFile() && $file->getExtension() === 'php') {
|
||||||
|
$relativePath = str_replace(__DIR__ . '/Handlers/', '', $file->getPathname());
|
||||||
|
$className = self::HANDLER_NAMESPACE . str_replace('/', '\\', substr($relativePath, 0, -4));
|
||||||
|
|
||||||
|
|
||||||
|
if (class_exists($className)) {
|
||||||
|
$reflection = new \ReflectionClass($className);
|
||||||
|
$attributes = $reflection->getAttributes(HandlesMessage::class);
|
||||||
|
foreach ($attributes as $attribute) {
|
||||||
|
$instance = $attribute->newInstance();
|
||||||
|
$messageClass = $instance->getMessageClass();
|
||||||
|
$this->handlers[$messageClass][] = $className;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param $signal
|
||||||
|
*/
|
||||||
|
public static function handleSignal($signal): void
|
||||||
|
{
|
||||||
|
switch ($signal) {
|
||||||
|
// Graceful
|
||||||
|
case SIGINT:
|
||||||
|
case SIGTERM:
|
||||||
|
case SIGHUP:
|
||||||
|
self::$shutDown = true;
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
// Not Graceful
|
||||||
|
case SIGKILL:
|
||||||
|
exit(9);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function shouldShutDown(): bool
|
||||||
|
{
|
||||||
|
return self::$shutDown;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function start(): void
|
||||||
|
{
|
||||||
|
if (!\function_exists('pcntl_signal')) {
|
||||||
|
throw new \RuntimeException('The pcntl extension is required to handle signals.');
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger::info('Starting queue consumer...');
|
||||||
|
|
||||||
|
\pcntl_signal(SIGINT, [self::class, 'handleSignal']);
|
||||||
|
\pcntl_signal(SIGTERM, [self::class, 'handleSignal']);
|
||||||
|
\pcntl_signal(SIGHUP, [self::class, 'handleSignal']);
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
if ($this->shouldShutDown()) {
|
||||||
|
Logger::info('Shutting down queue consumer...');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Queue $queue */
|
||||||
|
foreach ($this->queues as $queue) {
|
||||||
|
Logger::info('Listening to queue: ' . $queue->queueName());
|
||||||
|
$message = $queue->pop();
|
||||||
|
if ($message) {
|
||||||
|
Logger::info('Processing message of type: ' . get_class($message));
|
||||||
|
|
||||||
|
$handlers = $this->getHandlerForMessage($message);
|
||||||
|
|
||||||
|
foreach ($handlers as $handler) {
|
||||||
|
$handler($message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function getHandlerForMessage($message): array
|
||||||
|
{
|
||||||
|
$callables = [];
|
||||||
|
|
||||||
|
$messageClass = get_class($message);
|
||||||
|
if (isset($this->handlers[$messageClass])) {
|
||||||
|
$handlerClasses = $this->handlers[$messageClass];
|
||||||
|
|
||||||
|
foreach ($handlerClasses as $handlerClass) {
|
||||||
|
if (class_exists($handlerClass)) {
|
||||||
|
$handlerInstance = new $handlerClass();
|
||||||
|
|
||||||
|
$callables[] = $handlerInstance;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $callables;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new \RuntimeException("No handler found for message class: $messageClass");
|
||||||
|
}
|
||||||
|
}
|
||||||
12
src/Async/Handlers/HandlerInterface.php
Normal file
12
src/Async/Handlers/HandlerInterface.php
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async\Handlers;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Async\Messages\Message;
|
||||||
|
|
||||||
|
interface HandlerInterface
|
||||||
|
{
|
||||||
|
public function __invoke(Message $message): void;
|
||||||
|
}
|
||||||
21
src/Async/Handlers/SayHelloHandler.php
Normal file
21
src/Async/Handlers/SayHelloHandler.php
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async\Handlers;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Annotations\Async\HandlesMessage;
|
||||||
|
use Siteworxpro\App\Async\Messages\Message;
|
||||||
|
use Siteworxpro\App\Async\Messages\SayHelloMessage;
|
||||||
|
use Siteworxpro\App\Services\Facades\Logger;
|
||||||
|
|
||||||
|
#[HandlesMessage(SayHelloMessage::class)]
|
||||||
|
class SayHelloHandler implements HandlerInterface
|
||||||
|
{
|
||||||
|
public function __invoke(Message | SayHelloMessage $message): void
|
||||||
|
{
|
||||||
|
$name = $message->getPayload()['name'] ?? 'Guest';
|
||||||
|
|
||||||
|
Logger::info(sprintf("Hello, %s!", $name));
|
||||||
|
}
|
||||||
|
}
|
||||||
102
src/Async/Messages/Message.php
Normal file
102
src/Async/Messages/Message.php
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async\Messages;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Async\Queues\DefaultQueue;
|
||||||
|
use Siteworxpro\App\Async\Queues\Queue;
|
||||||
|
use Siteworxpro\App\Helpers\Ulid;
|
||||||
|
|
||||||
|
abstract class Message implements \Serializable
|
||||||
|
{
|
||||||
|
protected string $id = '';
|
||||||
|
|
||||||
|
protected string $uniqueId;
|
||||||
|
|
||||||
|
protected array $payload;
|
||||||
|
|
||||||
|
protected int $timestamp;
|
||||||
|
|
||||||
|
protected string $queue = '';
|
||||||
|
|
||||||
|
protected const string DEFAULT_QUEUE = DefaultQueue::class;
|
||||||
|
|
||||||
|
abstract public static function dispatch(...$args): void;
|
||||||
|
|
||||||
|
abstract public static function dispatchLater(int $delay, ...$args): void;
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->uniqueId = Ulid::generate();
|
||||||
|
$this->timestamp = time();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getQueue(): Queue
|
||||||
|
{
|
||||||
|
if ($this->queue === '') {
|
||||||
|
$this->queue = static::DEFAULT_QUEUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new $this->queue();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getId(): string
|
||||||
|
{
|
||||||
|
return $this->id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $id
|
||||||
|
*/
|
||||||
|
public function setId(string $id): void
|
||||||
|
{
|
||||||
|
$this->id = $id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getPayload(): array
|
||||||
|
{
|
||||||
|
return $this->payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getTimestamp(): int
|
||||||
|
{
|
||||||
|
return $this->timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __serialize(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'id' => $this->id,
|
||||||
|
'payload' => $this->payload,
|
||||||
|
'timestamp' => $this->timestamp,
|
||||||
|
'queue' => $this->queue,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __unserialize(array $data): void
|
||||||
|
{
|
||||||
|
$this->id = $data['id'];
|
||||||
|
$this->payload = $data['payload'];
|
||||||
|
$this->timestamp = $data['timestamp'];
|
||||||
|
$this->queue = $data['queue'];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function serialize(): string
|
||||||
|
{
|
||||||
|
return serialize($this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function unserialize(string $data): Message
|
||||||
|
{
|
||||||
|
$unserializedData = unserialize($data, ['allowed_classes' => [Message::class]]);
|
||||||
|
|
||||||
|
$this->id = $unserializedData['id'];
|
||||||
|
$this->uniqueId = $unserializedData['uniqueId'];
|
||||||
|
$this->payload = $unserializedData['payload'];
|
||||||
|
$this->timestamp = $unserializedData['timestamp'];
|
||||||
|
$this->queue = $unserializedData['queue'];
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
}
|
||||||
41
src/Async/Messages/SayHelloMessage.php
Normal file
41
src/Async/Messages/SayHelloMessage.php
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async\Messages;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Services\Facades\Broker;
|
||||||
|
|
||||||
|
class SayHelloMessage extends Message
|
||||||
|
{
|
||||||
|
public static function dispatch(...$args): void
|
||||||
|
{
|
||||||
|
$name = $args[0] ?? 'World';
|
||||||
|
$message = new self($name);
|
||||||
|
Broker::publish(
|
||||||
|
$message->getQueue(),
|
||||||
|
$message
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function dispatchLater(int $delay, ...$args): void
|
||||||
|
{
|
||||||
|
$name = $args[0] ?? 'World';
|
||||||
|
$message = new self($name);
|
||||||
|
Broker::publishLater(
|
||||||
|
$message->getQueue(),
|
||||||
|
$message,
|
||||||
|
$delay
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function __construct(
|
||||||
|
private readonly string $name
|
||||||
|
) {
|
||||||
|
parent::__construct();
|
||||||
|
|
||||||
|
$this->payload = [
|
||||||
|
'name' => $this->name,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
13
src/Async/Queues/DefaultQueue.php
Normal file
13
src/Async/Queues/DefaultQueue.php
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async\Queues;
|
||||||
|
|
||||||
|
readonly class DefaultQueue extends Queue
|
||||||
|
{
|
||||||
|
public function queueName(): string
|
||||||
|
{
|
||||||
|
return 'default';
|
||||||
|
}
|
||||||
|
}
|
||||||
28
src/Async/Queues/Queue.php
Normal file
28
src/Async/Queues/Queue.php
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Async\Queues;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Async\Messages\Message;
|
||||||
|
use Siteworxpro\App\Services\Facades\Broker;
|
||||||
|
|
||||||
|
readonly abstract class Queue
|
||||||
|
{
|
||||||
|
abstract public function queueName(): string;
|
||||||
|
|
||||||
|
public function push(Message $message): void
|
||||||
|
{
|
||||||
|
Broker::publish($this, $message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function later(int $delay, Message $message): void
|
||||||
|
{
|
||||||
|
Broker::publish($this, $message, $delay);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function pop(): Message | null
|
||||||
|
{
|
||||||
|
return Broker::consume($this);
|
||||||
|
}
|
||||||
|
}
|
||||||
43
src/Cli/App.php
Normal file
43
src/Cli/App.php
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Cli;
|
||||||
|
|
||||||
|
use Ahc\Cli\Application;
|
||||||
|
use Siteworxpro\App\Cli\Commands\DemoCommand;
|
||||||
|
use Siteworxpro\App\Cli\Commands\Queue\Start;
|
||||||
|
use Siteworxpro\App\Kernel;
|
||||||
|
use Siteworxpro\App\Services\Facades\Config;
|
||||||
|
|
||||||
|
class App
|
||||||
|
{
|
||||||
|
private Application $app;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws \ReflectionException
|
||||||
|
*/
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
Kernel::boot();
|
||||||
|
$this->app = new Application('Php-Template', Config::get('app.version') ?? 'dev-master');
|
||||||
|
|
||||||
|
$this->app->add(new DemoCommand());
|
||||||
|
$this->app->add(new Start());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function run(): int
|
||||||
|
{
|
||||||
|
$this->app->logo(
|
||||||
|
<<<EOF
|
||||||
|
▄▄▄▄▄ ▄ ▄ ▄▄▄▄▄ ▄▄▄▄▄▄▄ ▀▀█ ▄
|
||||||
|
█ ▀█ █ █ █ ▀█ █ ▄▄▄ ▄▄▄▄▄ ▄▄▄▄ █ ▄▄▄ ▄▄█▄▄ ▄▄▄
|
||||||
|
█▄▄▄█▀ █▄▄▄▄█ █▄▄▄█▀ █ █▀ █ █ █ █ █▀ ▀█ █ ▀ █ █ █▀ █
|
||||||
|
█ █ █ █ ▀▀▀ █ █▀▀▀▀ █ █ █ █ █ █ ▄▀▀▀█ █ █▀▀▀▀
|
||||||
|
█ █ █ █ █ ▀█▄▄▀ █ █ █ ██▄█▀ ▀▄▄ ▀▄▄▀█ ▀▄▄ ▀█▄▄▀
|
||||||
|
█
|
||||||
|
EOF
|
||||||
|
);
|
||||||
|
return $this->app->handle($_SERVER['argv']);
|
||||||
|
}
|
||||||
|
}
|
||||||
15
src/Cli/Commands/CommandInterface.php
Normal file
15
src/Cli/Commands/CommandInterface.php
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Cli\Commands;
|
||||||
|
|
||||||
|
interface CommandInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Execute the command.
|
||||||
|
*
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
public function execute(): int;
|
||||||
|
}
|
||||||
47
src/Cli/Commands/DemoCommand.php
Normal file
47
src/Cli/Commands/DemoCommand.php
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Cli\Commands;
|
||||||
|
|
||||||
|
use Ahc\Cli\Input\Command;
|
||||||
|
|
||||||
|
class DemoCommand extends Command implements CommandInterface
|
||||||
|
{
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
parent::__construct('api:demo', 'A demo command to showcase the CLI functionality.');
|
||||||
|
|
||||||
|
$this->argument('[name]', 'Your name')
|
||||||
|
->option('-g, --greet', 'Include a greeting message');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function execute(): int
|
||||||
|
{
|
||||||
|
$pb = $this->progress(100);
|
||||||
|
|
||||||
|
for ($i = 0; $i < 100; $i += 10) {
|
||||||
|
usleep(100000); // Simulate work
|
||||||
|
$pb->advance(10);
|
||||||
|
}
|
||||||
|
|
||||||
|
$pb->finish();
|
||||||
|
|
||||||
|
$this->writer()->boldBlue("Demo Command Executed!\n");
|
||||||
|
|
||||||
|
if ($this->values()['name']) {
|
||||||
|
$name = $this->values()['name'];
|
||||||
|
$greet = $this->values()['greet'] ?? false;
|
||||||
|
} else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($greet) {
|
||||||
|
$this->writer()->green("Hello, $name! Welcome to the CLI demo.\n");
|
||||||
|
} else {
|
||||||
|
$this->writer()->yellow("Name provided: {$name}\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
34
src/Cli/Commands/Queue/Start.php
Normal file
34
src/Cli/Commands/Queue/Start.php
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Cli\Commands\Queue;
|
||||||
|
|
||||||
|
use Ahc\Cli\Input\Command;
|
||||||
|
use Siteworxpro\App\Async\Consumer;
|
||||||
|
use Siteworxpro\App\Async\Messages\SayHelloMessage;
|
||||||
|
use Siteworxpro\App\Cli\Commands\CommandInterface;
|
||||||
|
|
||||||
|
class Start extends Command implements CommandInterface
|
||||||
|
{
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
parent::__construct('queue:start', 'Start the queue consumer to process messages.');
|
||||||
|
$this->argument('[queues]', 'The name of the queue to consume from. ex. "first_queue,second_queue"');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function execute(): int
|
||||||
|
{
|
||||||
|
$queues = [];
|
||||||
|
if ($this->values()['queues'] !== null) {
|
||||||
|
$queues = explode(',', $this->values()['queues']);
|
||||||
|
}
|
||||||
|
|
||||||
|
SayHelloMessage::dispatch("hello from queue consumer!");
|
||||||
|
|
||||||
|
$consumer = new Consumer($queues);
|
||||||
|
$consumer->start();
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
54
src/Controllers/Controller.php
Normal file
54
src/Controllers/Controller.php
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Controllers;
|
||||||
|
|
||||||
|
use League\Route\Http\Exception\NotFoundException;
|
||||||
|
use Nyholm\Psr7\ServerRequest;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
|
||||||
|
abstract class Controller implements ControllerInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param ServerRequest $request
|
||||||
|
* @return ResponseInterface
|
||||||
|
* @throws NotFoundException
|
||||||
|
*/
|
||||||
|
public function get(ServerRequest $request): ResponseInterface
|
||||||
|
{
|
||||||
|
throw new NotFoundException("not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws NotFoundException
|
||||||
|
*/
|
||||||
|
public function post(ServerRequest $request): ResponseInterface
|
||||||
|
{
|
||||||
|
throw new NotFoundException("not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws NotFoundException
|
||||||
|
*/
|
||||||
|
public function put(ServerRequest $request): ResponseInterface
|
||||||
|
{
|
||||||
|
throw new NotFoundException("not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws NotFoundException
|
||||||
|
*/
|
||||||
|
public function delete(ServerRequest $request): ResponseInterface
|
||||||
|
{
|
||||||
|
throw new NotFoundException("not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws NotFoundException
|
||||||
|
*/
|
||||||
|
public function patch(ServerRequest $request): ResponseInterface
|
||||||
|
{
|
||||||
|
throw new NotFoundException("not found");
|
||||||
|
}
|
||||||
|
}
|
||||||
51
src/Controllers/ControllerInterface.php
Normal file
51
src/Controllers/ControllerInterface.php
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Controllers;
|
||||||
|
|
||||||
|
use Nyholm\Psr7\ServerRequest;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
|
||||||
|
interface ControllerInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Handle the request and return a response.
|
||||||
|
*
|
||||||
|
* @param ServerRequest $request The request data.
|
||||||
|
* @return ResponseInterface The response data.
|
||||||
|
*/
|
||||||
|
public function get(ServerRequest $request): ResponseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the request and return a response.
|
||||||
|
*
|
||||||
|
* @param ServerRequest $request The request data.
|
||||||
|
* @return ResponseInterface The response data.
|
||||||
|
*/
|
||||||
|
public function post(ServerRequest $request): ResponseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the request and return a response.
|
||||||
|
*
|
||||||
|
* @param ServerRequest $request The request data.
|
||||||
|
* @return ResponseInterface The response data.
|
||||||
|
*/
|
||||||
|
public function put(ServerRequest $request): ResponseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the request and return a response.
|
||||||
|
*
|
||||||
|
* @param ServerRequest $request The request data.
|
||||||
|
* @return ResponseInterface The response data.
|
||||||
|
*/
|
||||||
|
public function delete(ServerRequest $request): ResponseInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle the request and return a response.
|
||||||
|
*
|
||||||
|
* @param ServerRequest $request The request data.
|
||||||
|
* @return ResponseInterface The response data.
|
||||||
|
*/
|
||||||
|
public function patch(ServerRequest $request): ResponseInterface;
|
||||||
|
}
|
||||||
46
src/Controllers/HealthcheckController.php
Normal file
46
src/Controllers/HealthcheckController.php
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Controllers;
|
||||||
|
|
||||||
|
use Illuminate\Database\PostgresConnection;
|
||||||
|
use Nyholm\Psr7\ServerRequest;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Siteworxpro\App\Http\JsonResponseFactory;
|
||||||
|
use Siteworxpro\App\Models\Model;
|
||||||
|
use Siteworxpro\App\Services\Facades\Redis;
|
||||||
|
use Siteworxpro\HttpStatus\CodesEnum;
|
||||||
|
|
||||||
|
class HealthcheckController extends Controller
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @throws \JsonException
|
||||||
|
*/
|
||||||
|
public function get(ServerRequest $request): ResponseInterface
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
/** @var PostgresConnection $conn */
|
||||||
|
$conn = Model::getConnectionResolver()->connection();
|
||||||
|
$conn->getPdo()->exec('SELECT 1');
|
||||||
|
|
||||||
|
$response = Redis::ping();
|
||||||
|
if ($response->getPayload() !== 'PONG') {
|
||||||
|
throw new \Exception('Redis ping failed');
|
||||||
|
}
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
return JsonResponseFactory::createJsonResponse(
|
||||||
|
[
|
||||||
|
'status_code' => CodesEnum::SERVICE_UNAVAILABLE->value,
|
||||||
|
'message' => 'Healthcheck Failed',
|
||||||
|
'error' => $e->getMessage(),
|
||||||
|
],
|
||||||
|
CodesEnum::SERVICE_UNAVAILABLE
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return JsonResponseFactory::createJsonResponse(
|
||||||
|
['status_code' => 200, 'message' => 'Healthcheck OK']
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
40
src/Controllers/IndexController.php
Normal file
40
src/Controllers/IndexController.php
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Controllers;
|
||||||
|
|
||||||
|
use Nyholm\Psr7\ServerRequest;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Siteworxpro\App\Annotations\Guards;
|
||||||
|
use Siteworxpro\App\Http\JsonResponseFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class IndexController
|
||||||
|
*
|
||||||
|
* This class handles the index route of the application.
|
||||||
|
*/
|
||||||
|
class IndexController extends Controller
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Handles the GET request for the index route.
|
||||||
|
*
|
||||||
|
* @throws \JsonException
|
||||||
|
*/
|
||||||
|
#[Guards\Jwt]
|
||||||
|
#[Guards\Scope(['get.index'])]
|
||||||
|
public function get(ServerRequest $request): ResponseInterface
|
||||||
|
{
|
||||||
|
return JsonResponseFactory::createJsonResponse(['status_code' => 200, 'message' => 'Server is running']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws \JsonException
|
||||||
|
*/
|
||||||
|
#[Guards\Jwt]
|
||||||
|
#[Guards\Scope(['post.index'])]
|
||||||
|
public function post(ServerRequest $request): ResponseInterface
|
||||||
|
{
|
||||||
|
return JsonResponseFactory::createJsonResponse(['status_code' => 200, 'message' => 'Server is running']);
|
||||||
|
}
|
||||||
|
}
|
||||||
205
src/Events/Dispatcher.php
Normal file
205
src/Events/Dispatcher.php
Normal file
@@ -0,0 +1,205 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Events;
|
||||||
|
|
||||||
|
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
|
||||||
|
use Illuminate\Contracts\Support\Arrayable;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Siteworxpro\App\Annotations\Events\ListensFor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class Dispatcher
|
||||||
|
*
|
||||||
|
* A custom event dispatcher that automatically registers event listeners
|
||||||
|
* based on the ListensFor attribute.
|
||||||
|
*
|
||||||
|
* @package Siteworxpro\App\Events
|
||||||
|
*/
|
||||||
|
class Dispatcher implements DispatcherContract, Arrayable
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var array $listeners Registered event listeners
|
||||||
|
*/
|
||||||
|
private array $listeners = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var Collection $pushed Pushed events collection
|
||||||
|
*/
|
||||||
|
private Collection $pushed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var string LISTENERS_NAMESPACE The namespace where listeners are located
|
||||||
|
*/
|
||||||
|
private const string LISTENERS_NAMESPACE = 'Siteworxpro\\App\\Events\\Listeners\\';
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->pushed = new Collection();
|
||||||
|
$this->registerListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register event listeners based on the ListensFor attribute.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private function registerListeners(): void
|
||||||
|
{
|
||||||
|
// traverse the Listeners directory and register all listeners
|
||||||
|
$listenersPath = __DIR__ . '/Listeners';
|
||||||
|
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($listenersPath));
|
||||||
|
|
||||||
|
foreach ($iterator as $file) {
|
||||||
|
if ($file->isFile() && $file->getExtension() === 'php') {
|
||||||
|
$relativePath = str_replace($listenersPath . '/', '', $file->getPathname());
|
||||||
|
$className = self::LISTENERS_NAMESPACE . str_replace(['/', '.php'], ['\\', ''], $relativePath);
|
||||||
|
if (class_exists($className)) {
|
||||||
|
$reflectionClass = new \ReflectionClass($className);
|
||||||
|
$attributes = $reflectionClass->getAttributes(ListensFor::class);
|
||||||
|
foreach ($attributes as $attribute) {
|
||||||
|
$instance = $attribute->newInstance();
|
||||||
|
$eventClass = $instance->eventClass;
|
||||||
|
$this->listen($eventClass, new $className());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a listener for the given events.
|
||||||
|
*
|
||||||
|
* @param $events
|
||||||
|
* @param $listener
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function listen($events, $listener = null): void
|
||||||
|
{
|
||||||
|
$this->listeners[$events][] = $listener;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if there are listeners for the given event.
|
||||||
|
*
|
||||||
|
* @param $eventName
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function hasListeners($eventName): bool
|
||||||
|
{
|
||||||
|
return isset($this->listeners[$eventName]) && !empty($this->listeners[$eventName]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subscribe a subscriber to the dispatcher.
|
||||||
|
*
|
||||||
|
* @param Arrayable $subscriber
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function subscribe($subscriber): void
|
||||||
|
{
|
||||||
|
$this->listeners = array_merge($this->listeners, (array) $subscriber);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dispatch an event and halt on the first non-null response.
|
||||||
|
*
|
||||||
|
* @param $event
|
||||||
|
* @param array $payload
|
||||||
|
* @return array|null
|
||||||
|
*/
|
||||||
|
public function until($event, $payload = []): array|null
|
||||||
|
{
|
||||||
|
return $this->dispatch($event, $payload, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dispatch an event to its listeners.
|
||||||
|
*
|
||||||
|
* @param $event
|
||||||
|
* @param array $payload
|
||||||
|
* @param bool $halt
|
||||||
|
* @return array|null
|
||||||
|
*/
|
||||||
|
public function dispatch($event, $payload = [], $halt = false): array|null
|
||||||
|
{
|
||||||
|
if (is_object($event)) {
|
||||||
|
$eventClass = get_class($event);
|
||||||
|
} else {
|
||||||
|
$eventClass = $event;
|
||||||
|
}
|
||||||
|
|
||||||
|
$listeners = $this->listeners[$eventClass] ?? null;
|
||||||
|
|
||||||
|
if ($listeners === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$responses = [];
|
||||||
|
|
||||||
|
foreach ($listeners as $listener) {
|
||||||
|
$response = $listener($event, $payload);
|
||||||
|
$responses[] = $response;
|
||||||
|
|
||||||
|
if ($halt && $response !== null) {
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $responses;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Push an event to be dispatched later.
|
||||||
|
*
|
||||||
|
* @param $event
|
||||||
|
* @param array $payload
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function push($event, $payload = []): void
|
||||||
|
{
|
||||||
|
$this->pushed->put($event, $payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flush a pushed event, dispatching it if it exists.
|
||||||
|
*
|
||||||
|
* @param $event
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function flush($event): void
|
||||||
|
{
|
||||||
|
if ($this->pushed->has($event)) {
|
||||||
|
$payload = $this->pushed->get($event);
|
||||||
|
$this->dispatch($event, $payload);
|
||||||
|
$this->pushed->forget([$event]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forget a pushed event without dispatching it.
|
||||||
|
*
|
||||||
|
* @param $event
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function forget($event): void
|
||||||
|
{
|
||||||
|
$this->pushed->forget([$event]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forget all pushed events.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function forgetPushed(): void
|
||||||
|
{
|
||||||
|
$this->pushed = new Collection();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function toArray(): array
|
||||||
|
{
|
||||||
|
return $this->listeners;
|
||||||
|
}
|
||||||
|
}
|
||||||
28
src/Events/Listeners/Database/Connected.php
Normal file
28
src/Events/Listeners/Database/Connected.php
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Events\Listeners\Database;
|
||||||
|
|
||||||
|
use Illuminate\Database\Events\ConnectionEstablished;
|
||||||
|
use Illuminate\Database\Events\ConnectionEvent;
|
||||||
|
use Siteworxpro\App\Annotations\Events\ListensFor;
|
||||||
|
use Siteworxpro\App\Events\Listeners\Listener;
|
||||||
|
use Siteworxpro\App\Services\Facades\Logger;
|
||||||
|
|
||||||
|
#[ListensFor(ConnectionEstablished::class)]
|
||||||
|
class Connected extends Listener
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param ConnectionEvent $event
|
||||||
|
* @param array $payload
|
||||||
|
* @return null
|
||||||
|
*/
|
||||||
|
public function __invoke($event, array $payload = []): null
|
||||||
|
{
|
||||||
|
|
||||||
|
Logger::info("Database connection event", [get_class($event), $event->connectionName]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
9
src/Events/Listeners/Listener.php
Normal file
9
src/Events/Listeners/Listener.php
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Events\Listeners;
|
||||||
|
|
||||||
|
abstract class Listener implements ListenerInterface
|
||||||
|
{
|
||||||
|
}
|
||||||
10
src/Events/Listeners/ListenerInterface.php
Normal file
10
src/Events/Listeners/ListenerInterface.php
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Events\Listeners;
|
||||||
|
|
||||||
|
interface ListenerInterface
|
||||||
|
{
|
||||||
|
public function __invoke(mixed $event, array $payload = []): mixed;
|
||||||
|
}
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace Siteworxpro\App\Facades;
|
|
||||||
|
|
||||||
use Illuminate\Contracts\Container\BindingResolutionException;
|
|
||||||
use Illuminate\Support\Facades\Facade;
|
|
||||||
use Siteworx\Config\Exception\EmptyDirectoryException;
|
|
||||||
use Siteworx\Config\Exception\FileNotFoundException;
|
|
||||||
use Siteworx\Config\Exception\UnsupportedFormatException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Class Config
|
|
||||||
*
|
|
||||||
* This class serves as a facade for the configuration settings of the application.
|
|
||||||
* It extends the Facade class from the Illuminate\Support\Facades namespace.
|
|
||||||
*
|
|
||||||
* @method static bool | string | int get(string $key) Retrieve the configuration value for the given key.
|
|
||||||
*
|
|
||||||
* @package Siteworx\App\Facades
|
|
||||||
*/
|
|
||||||
class Config extends Facade
|
|
||||||
{
|
|
||||||
protected static $cached = false;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @throws UnsupportedFormatException
|
|
||||||
* @throws FileNotFoundException
|
|
||||||
* @throws EmptyDirectoryException
|
|
||||||
*/
|
|
||||||
public static function getFacadeRoot(): \Siteworx\Config\Config
|
|
||||||
{
|
|
||||||
if (self::$resolvedInstance !== null) {
|
|
||||||
try {
|
|
||||||
$config = self::resolveFacadeInstance(self::getFacadeAccessor());
|
|
||||||
if ($config instanceof \Siteworx\Config\Config) {
|
|
||||||
return $config;
|
|
||||||
}
|
|
||||||
} catch (BindingResolutionException) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return \Siteworx\Config\Config::load(__DIR__ . '/../../config.php');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the registered name of the component.
|
|
||||||
*
|
|
||||||
* @return string The name of the component.
|
|
||||||
*/
|
|
||||||
protected static function getFacadeAccessor(): string
|
|
||||||
{
|
|
||||||
return \Siteworx\Config\Config::class;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace Siteworxpro\App\Facades;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Facade;
|
|
||||||
use RoadRunner\Logger\Logger as RRLogger;
|
|
||||||
use Spiral\Goridge\RPC\RPC;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Class Logger
|
|
||||||
*
|
|
||||||
* This class serves as a facade for the Monolog logger.
|
|
||||||
* It extends the Facade class from the Illuminate\Support\Facades namespace.
|
|
||||||
*
|
|
||||||
* @method static info(string $message, array $context = []) Log an informational message.
|
|
||||||
* @method static error(string $message, array $context = []) Log an error message.
|
|
||||||
* @method static warning(string $message, array $context = []) Log a warning message.
|
|
||||||
*
|
|
||||||
* @package Siteworxpro\App\Facades
|
|
||||||
*/
|
|
||||||
class Logger extends Facade
|
|
||||||
{
|
|
||||||
public static function getFacadeRoot(): RRLogger
|
|
||||||
{
|
|
||||||
if (self::$resolvedInstance !== null) {
|
|
||||||
$logger = self::resolveFacadeInstance(self::getFacadeAccessor());
|
|
||||||
|
|
||||||
if ($logger instanceof RRLogger) {
|
|
||||||
return $logger;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
$rpc = RPC::create('tcp://127.0.0.1:6001');
|
|
||||||
|
|
||||||
return new RRLogger($rpc);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the registered name of the component.
|
|
||||||
*
|
|
||||||
* @return string The name of the component.
|
|
||||||
*/
|
|
||||||
protected static function getFacadeAccessor(): string
|
|
||||||
{
|
|
||||||
return RRLogger::class;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
13
src/Helpers/Ulid.php
Normal file
13
src/Helpers/Ulid.php
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Helpers;
|
||||||
|
|
||||||
|
class Ulid
|
||||||
|
{
|
||||||
|
public static function generate(): string
|
||||||
|
{
|
||||||
|
return \Ulid\Ulid::generate()->getRandomness();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
|||||||
namespace Siteworxpro\App\Http;
|
namespace Siteworxpro\App\Http;
|
||||||
|
|
||||||
use Nyholm\Psr7\Response;
|
use Nyholm\Psr7\Response;
|
||||||
|
use Siteworxpro\HttpStatus\CodesEnum;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class JsonResponseFactory
|
* Class JsonResponseFactory
|
||||||
@@ -17,14 +18,14 @@ class JsonResponseFactory
|
|||||||
* Create a JSON response with the given data and status code.
|
* Create a JSON response with the given data and status code.
|
||||||
*
|
*
|
||||||
* @param array $data The data to include in the response.
|
* @param array $data The data to include in the response.
|
||||||
* @param int $statusCode The HTTP status code for the response.
|
* @param CodesEnum $statusCode The HTTP status code for the response.
|
||||||
* @return Response The JSON response.
|
* @return Response The JSON response.
|
||||||
* @throws \JsonException
|
* @throws \JsonException
|
||||||
*/
|
*/
|
||||||
public static function createJsonResponse(array $data, int $statusCode = 200): Response
|
public static function createJsonResponse(array $data, CodesEnum $statusCode = CodesEnum::OK): Response
|
||||||
{
|
{
|
||||||
return new Response(
|
return new Response(
|
||||||
status: $statusCode,
|
status: $statusCode->value,
|
||||||
headers: [
|
headers: [
|
||||||
'Content-Type' => 'application/json',
|
'Content-Type' => 'application/json',
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use Psr\Http\Message\ResponseInterface;
|
|||||||
use Psr\Http\Message\ServerRequestInterface;
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
use Psr\Http\Server\MiddlewareInterface;
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
use Siteworxpro\App\Facades\Config;
|
use Siteworxpro\App\Services\Facades\Config;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class CorsMiddleware
|
* Class CorsMiddleware
|
||||||
|
|||||||
140
src/Http/Middleware/JwtMiddleware.php
Normal file
140
src/Http/Middleware/JwtMiddleware.php
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Http\Middleware;
|
||||||
|
|
||||||
|
use Carbon\Carbon;
|
||||||
|
use Carbon\WrapperClock;
|
||||||
|
use Lcobucci\JWT\JwtFacade;
|
||||||
|
use Lcobucci\JWT\Signer\Hmac\Sha256 as Hmac256;
|
||||||
|
use Lcobucci\JWT\Signer\Key\InMemory;
|
||||||
|
use Lcobucci\JWT\Signer\Rsa\Sha256;
|
||||||
|
use Lcobucci\JWT\Token\InvalidTokenStructure;
|
||||||
|
use Lcobucci\JWT\Validation\Constraint\IssuedBy;
|
||||||
|
use Lcobucci\JWT\Validation\Constraint\LooseValidAt;
|
||||||
|
use Lcobucci\JWT\Validation\Constraint\PermittedFor;
|
||||||
|
use Lcobucci\JWT\Validation\Constraint\SignedWith;
|
||||||
|
use Lcobucci\JWT\Validation\Constraint\StrictValidAt;
|
||||||
|
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
|
||||||
|
use League\Route\Dispatcher;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
|
use Siteworxpro\App\Annotations\Guards\Jwt;
|
||||||
|
use Siteworxpro\App\Controllers\Controller;
|
||||||
|
use Siteworxpro\App\Http\JsonResponseFactory;
|
||||||
|
use Siteworxpro\App\Services\Facades\Config;
|
||||||
|
use Siteworxpro\HttpStatus\CodesEnum;
|
||||||
|
|
||||||
|
class JwtMiddleware extends Middleware
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @throws \JsonException
|
||||||
|
* @throws \Exception
|
||||||
|
*/
|
||||||
|
public function process(
|
||||||
|
ServerRequestInterface $request,
|
||||||
|
RequestHandlerInterface|Dispatcher $handler
|
||||||
|
): ResponseInterface {
|
||||||
|
|
||||||
|
$callable = $this->extractRouteCallable($request, $handler);
|
||||||
|
if ($callable === null) {
|
||||||
|
return $handler->handle($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Controller $class */
|
||||||
|
[$class, $method] = $callable;
|
||||||
|
|
||||||
|
if (class_exists($class::class)) {
|
||||||
|
$reflectionClass = new \ReflectionClass($class);
|
||||||
|
|
||||||
|
if ($reflectionClass->hasMethod($method)) {
|
||||||
|
$reflectionMethod = $reflectionClass->getMethod($method);
|
||||||
|
$attributes = $reflectionMethod->getAttributes(Jwt::class);
|
||||||
|
|
||||||
|
if (empty($attributes)) {
|
||||||
|
return $handler->handle($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
$token = str_replace('Bearer ', '', $request->getHeaderLine('Authorization'));
|
||||||
|
|
||||||
|
if (empty($token)) {
|
||||||
|
return JsonResponseFactory::createJsonResponse([
|
||||||
|
'status_code' => 401,
|
||||||
|
'message' => 'Unauthorized: Missing token',
|
||||||
|
], CodesEnum::UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
|
||||||
|
$requiredIssuers = [];
|
||||||
|
$requiredAudience = '';
|
||||||
|
|
||||||
|
foreach ($attributes as $attribute) {
|
||||||
|
/** @var Jwt $jwtInstance */
|
||||||
|
$jwtInstance = $attribute->newInstance();
|
||||||
|
|
||||||
|
if ($jwtInstance->getRequiredAudience() !== '') {
|
||||||
|
$requiredAudience = $jwtInstance->getAudience();
|
||||||
|
}
|
||||||
|
|
||||||
|
$requiredIssuers[] = $jwtInstance->getIssuer();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$jwt = new JwtFacade()->parse(
|
||||||
|
$token,
|
||||||
|
$this->getSignedWith(),
|
||||||
|
Config::get('jwt.strict_validation') ?
|
||||||
|
new StrictValidAt(new WrapperClock(Carbon::now())) :
|
||||||
|
new LooseValidAt(new WrapperClock(Carbon::now())),
|
||||||
|
new IssuedBy(...$requiredIssuers),
|
||||||
|
new PermittedFor($requiredAudience)
|
||||||
|
);
|
||||||
|
} catch (RequiredConstraintsViolated $exception) {
|
||||||
|
$violations = [];
|
||||||
|
foreach ($exception->violations() as $violation) {
|
||||||
|
$violations[] = $violation->getMessage();
|
||||||
|
}
|
||||||
|
|
||||||
|
return JsonResponseFactory::createJsonResponse([
|
||||||
|
'status_code' => 401,
|
||||||
|
'message' => 'Unauthorized: Invalid token',
|
||||||
|
'errors' => $violations
|
||||||
|
], CodesEnum::UNAUTHORIZED);
|
||||||
|
} catch (InvalidTokenStructure) {
|
||||||
|
return JsonResponseFactory::createJsonResponse([
|
||||||
|
'status_code' => 401,
|
||||||
|
'message' => 'Unauthorized: Invalid token',
|
||||||
|
], CodesEnum::UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($jwt->claims()->all() as $item => $value) {
|
||||||
|
$request = $request->withAttribute($item, $value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $handler->handle($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function getSignedWith(): SignedWith
|
||||||
|
{
|
||||||
|
$key = Config::get('jwt.signing_key');
|
||||||
|
|
||||||
|
if ($key === null) {
|
||||||
|
throw new \RuntimeException('JWT signing key is not configured.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (str_starts_with($key, 'file://')) {
|
||||||
|
$key = InMemory::file(substr($key, 7));
|
||||||
|
} else {
|
||||||
|
$key = InMemory::plainText($key);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (str_contains($key->contents(), 'PUBLIC KEY')) {
|
||||||
|
return new SignedWith(new Sha256(), $key);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new SignedWith(new Hmac256(), $key);
|
||||||
|
}
|
||||||
|
}
|
||||||
41
src/Http/Middleware/Middleware.php
Normal file
41
src/Http/Middleware/Middleware.php
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Http\Middleware;
|
||||||
|
|
||||||
|
use League\Route\Dispatcher;
|
||||||
|
use League\Route\Route;
|
||||||
|
use Psr\Http\Server\MiddlewareInterface;
|
||||||
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
|
|
||||||
|
abstract class Middleware implements MiddlewareInterface
|
||||||
|
{
|
||||||
|
|
||||||
|
protected function extractRouteCallable($request, RequestHandlerInterface | Dispatcher $handler): array|null
|
||||||
|
{
|
||||||
|
if (!$handler instanceof Dispatcher) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Route | null $lastSegment */
|
||||||
|
$lastSegment = array_last($handler->getMiddlewareStack());
|
||||||
|
|
||||||
|
if ($lastSegment === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$callable = $lastSegment->getCallable();
|
||||||
|
$class = null;
|
||||||
|
$method = null;
|
||||||
|
|
||||||
|
if (is_array($callable) && count($callable) === 2) {
|
||||||
|
[$class, $method] = $callable;
|
||||||
|
} elseif (is_string($callable)) {
|
||||||
|
// Handle the case where the callable is a string (e.g., 'ClassName::methodName')
|
||||||
|
[$class, $method] = explode('::', $callable);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [$class, $method];
|
||||||
|
}
|
||||||
|
}
|
||||||
64
src/Http/Middleware/ScopeMiddleware.php
Normal file
64
src/Http/Middleware/ScopeMiddleware.php
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Http\Middleware;
|
||||||
|
|
||||||
|
use League\Route\Dispatcher;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
|
use Siteworxpro\App\Annotations\Guards\Scope;
|
||||||
|
use Siteworxpro\App\Controllers\Controller;
|
||||||
|
use Siteworxpro\App\Http\JsonResponseFactory;
|
||||||
|
use Siteworxpro\HttpStatus\CodesEnum;
|
||||||
|
|
||||||
|
class ScopeMiddleware extends Middleware
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @throws \JsonException
|
||||||
|
*/
|
||||||
|
public function process(
|
||||||
|
ServerRequestInterface $request,
|
||||||
|
RequestHandlerInterface | Dispatcher $handler
|
||||||
|
): ResponseInterface {
|
||||||
|
$callable = $this->extractRouteCallable($request, $handler);
|
||||||
|
if ($callable === null) {
|
||||||
|
return $handler->handle($request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var Controller $class */
|
||||||
|
[$class, $method] = $callable;
|
||||||
|
|
||||||
|
if (class_exists($class::class)) {
|
||||||
|
$reflectionClass = new \ReflectionClass($class);
|
||||||
|
if ($reflectionClass->hasMethod($method)) {
|
||||||
|
$reflectionMethod = $reflectionClass->getMethod($method);
|
||||||
|
$attributes = $reflectionMethod->getAttributes(Scope::class);
|
||||||
|
|
||||||
|
foreach ($attributes as $attribute) {
|
||||||
|
/** @var Scope $scopeInstance */
|
||||||
|
$scopeInstance = $attribute->newInstance();
|
||||||
|
$requiredScopes = $scopeInstance->getScopes();
|
||||||
|
|
||||||
|
$userScopes = $request->getAttribute('scopes', []);
|
||||||
|
|
||||||
|
if (
|
||||||
|
array_any(
|
||||||
|
$requiredScopes,
|
||||||
|
fn($requiredScope) => !in_array($requiredScope, $userScopes, true)
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return JsonResponseFactory::createJsonResponse([
|
||||||
|
'error' => 'insufficient_scope',
|
||||||
|
'error_description' =>
|
||||||
|
'The request requires higher privileges than provided by the access token.'
|
||||||
|
], CodesEnum::FORBIDDEN);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $handler->handle($request);
|
||||||
|
}
|
||||||
|
}
|
||||||
82
src/Kernel.php
Normal file
82
src/Kernel.php
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Siteworxpro\App;
|
||||||
|
|
||||||
|
use Illuminate\Container\Container;
|
||||||
|
use Illuminate\Database\Capsule\Manager;
|
||||||
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use Siteworx\Config\Config as SWConfig;
|
||||||
|
use Siteworxpro\App\Services\Facade;
|
||||||
|
use Siteworxpro\App\Services\Facades\Config;
|
||||||
|
use Siteworxpro\App\Services\Facades\Dispatcher;
|
||||||
|
use Siteworxpro\App\Services\ServiceProviders\BrokerServiceProvider;
|
||||||
|
use Siteworxpro\App\Services\ServiceProviders\DispatcherServiceProvider;
|
||||||
|
use Siteworxpro\App\Services\ServiceProviders\LoggerServiceProvider;
|
||||||
|
use Siteworxpro\App\Services\ServiceProviders\RedisServiceProvider;
|
||||||
|
|
||||||
|
class Kernel
|
||||||
|
{
|
||||||
|
private static array $serviceProviders = [
|
||||||
|
LoggerServiceProvider::class,
|
||||||
|
RedisServiceProvider::class,
|
||||||
|
DispatcherServiceProvider::class,
|
||||||
|
BrokerServiceProvider::class
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bootstraps the server by initializing the PSR-7 worker and router.
|
||||||
|
*
|
||||||
|
* This method sets up the PSR-7 worker and router instances, and registers
|
||||||
|
* the routes for the server. It should be called in the constructor of
|
||||||
|
* subclasses to ensure proper initialization.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
* @throws \ReflectionException
|
||||||
|
*/
|
||||||
|
public static function boot(): void
|
||||||
|
{
|
||||||
|
$container = new Container();
|
||||||
|
Facade::setFacadeContainer($container);
|
||||||
|
|
||||||
|
// Bind the container to the Config facade first so that it can be used by service providers
|
||||||
|
$container->bind(SWConfig::class, function () {
|
||||||
|
return SWConfig::load(__DIR__ . '/../config.php');
|
||||||
|
});
|
||||||
|
|
||||||
|
foreach (self::$serviceProviders as $serviceProvider) {
|
||||||
|
if (class_exists($serviceProvider)) {
|
||||||
|
$provider = new $serviceProvider($container);
|
||||||
|
if ($provider instanceof ServiceProvider) {
|
||||||
|
$provider->register();
|
||||||
|
} else {
|
||||||
|
throw new \RuntimeException(sprintf(
|
||||||
|
'Service provider %s is not an instance of ServiceProvider.',
|
||||||
|
$serviceProvider
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new \RuntimeException(sprintf('Service provider %s not found.', $serviceProvider));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self::bootModelCapsule();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bootstraps the model capsule for database connections.
|
||||||
|
*
|
||||||
|
* This method sets up the database connection using the Eloquent ORM.
|
||||||
|
* It retrieves the database configuration from the Config facade and
|
||||||
|
* initializes the Eloquent capsule manager.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
private static function bootModelCapsule(): void
|
||||||
|
{
|
||||||
|
$capsule = new Manager();
|
||||||
|
$capsule->setEventDispatcher(Dispatcher::getFacadeRoot());
|
||||||
|
$capsule->addConnection(Config::get('db'));
|
||||||
|
$capsule->setAsGlobal();
|
||||||
|
$capsule->bootEloquent();
|
||||||
|
}
|
||||||
|
}
|
||||||
117
src/Log/Logger.php
Normal file
117
src/Log/Logger.php
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Log;
|
||||||
|
|
||||||
|
use Monolog\Formatter\JsonFormatter;
|
||||||
|
use Monolog\Handler\StreamHandler;
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use Psr\Log\LogLevel;
|
||||||
|
use RoadRunner\Logger\Logger as RRLogger;
|
||||||
|
use Spiral\Goridge\RPC\RPC;
|
||||||
|
|
||||||
|
class Logger implements LoggerInterface
|
||||||
|
{
|
||||||
|
private ?RRLogger $rpcLogger = null;
|
||||||
|
|
||||||
|
private \Monolog\Logger $monologLogger;
|
||||||
|
|
||||||
|
private array $levels = [
|
||||||
|
LogLevel::EMERGENCY => 0,
|
||||||
|
LogLevel::ALERT => 1,
|
||||||
|
LogLevel::CRITICAL => 2,
|
||||||
|
LogLevel::ERROR => 3,
|
||||||
|
LogLevel::WARNING => 4,
|
||||||
|
LogLevel::NOTICE => 5,
|
||||||
|
LogLevel::INFO => 6,
|
||||||
|
LogLevel::DEBUG => 7,
|
||||||
|
];
|
||||||
|
|
||||||
|
public function __construct(private readonly string $level = LogLevel::DEBUG)
|
||||||
|
{
|
||||||
|
if (isset($_SERVER['RR_RPC'])) {
|
||||||
|
$rpc = RPC::create('tcp://127.0.0.1:6001');
|
||||||
|
$this->rpcLogger = new RRLogger($rpc);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->monologLogger = new \Monolog\Logger('app_logger');
|
||||||
|
$formatter = new JsonFormatter();
|
||||||
|
$this->monologLogger->pushHandler(new StreamHandler('php://stdout')->setFormatter($formatter));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function emergency(\Stringable|string $message, array $context = []): void
|
||||||
|
{
|
||||||
|
$this->log(LogLevel::EMERGENCY, $message, $context);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function alert(\Stringable|string $message, array $context = []): void
|
||||||
|
{
|
||||||
|
$this->log(LogLevel::ALERT, $message, $context);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function critical(\Stringable|string $message, array $context = []): void
|
||||||
|
{
|
||||||
|
$this->log(LogLevel::CRITICAL, $message, $context);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function error(\Stringable|string $message, array $context = []): void
|
||||||
|
{
|
||||||
|
$this->log(LogLevel::ERROR, $message, $context);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function warning(\Stringable|string $message, array $context = []): void
|
||||||
|
{
|
||||||
|
$this->log(LogLevel::WARNING, $message, $context);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function notice(\Stringable|string $message, array $context = []): void
|
||||||
|
{
|
||||||
|
$this->log(LogLevel::NOTICE, $message, $context);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function info(\Stringable|string $message, array $context = []): void
|
||||||
|
{
|
||||||
|
$this->log(LogLevel::INFO, $message, $context);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function debug(\Stringable|string $message, array $context = []): void
|
||||||
|
{
|
||||||
|
$this->log(LogLevel::DEBUG, $message, $context);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function log($level, \Stringable|string $message, array $context = []): void
|
||||||
|
{
|
||||||
|
if ($this->levels[$level] > $this->levels[$this->level]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->rpcLogger) {
|
||||||
|
switch ($level) {
|
||||||
|
case LogLevel::DEBUG:
|
||||||
|
$this->rpcLogger->debug((string)$message, $context);
|
||||||
|
break;
|
||||||
|
case LogLevel::NOTICE:
|
||||||
|
case LogLevel::INFO:
|
||||||
|
$this->rpcLogger->info((string)$message, $context);
|
||||||
|
break;
|
||||||
|
case LogLevel::WARNING:
|
||||||
|
$this->rpcLogger->warning((string)$message, $context);
|
||||||
|
break;
|
||||||
|
case LogLevel::CRITICAL:
|
||||||
|
case LogLevel::ERROR:
|
||||||
|
case LogLevel::ALERT:
|
||||||
|
case LogLevel::EMERGENCY:
|
||||||
|
$this->rpcLogger->error((string)$message, $context);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
$this->rpcLogger->log((string)$message, $context);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->monologLogger->log($this->levels[$level], (string)$message, $context);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,12 @@ namespace Siteworxpro\App\Models;
|
|||||||
|
|
||||||
use Illuminate\Database\Eloquent\Model as ORM;
|
use Illuminate\Database\Eloquent\Model as ORM;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class Model
|
||||||
|
*
|
||||||
|
* @package Siteworxpro\App\Models
|
||||||
|
*/
|
||||||
abstract class Model extends ORM
|
abstract class Model extends ORM
|
||||||
{
|
{
|
||||||
|
protected $dateFormat = 'Y-m-d H:i:s';
|
||||||
}
|
}
|
||||||
|
|||||||
52
src/Models/User.php
Normal file
52
src/Models/User.php
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Models;
|
||||||
|
|
||||||
|
use Carbon\Carbon;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class User
|
||||||
|
*
|
||||||
|
* @property string $id
|
||||||
|
* @property string $first_name
|
||||||
|
* @property string $last_name
|
||||||
|
* @property string $email
|
||||||
|
* @property string $password
|
||||||
|
* @property Carbon $created_at
|
||||||
|
*
|
||||||
|
* @property-read string $full_name
|
||||||
|
* @property-read string $formatted_email
|
||||||
|
*/
|
||||||
|
class User extends Model
|
||||||
|
{
|
||||||
|
protected $casts = [
|
||||||
|
'created_at' => 'datetime',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $hidden = [
|
||||||
|
'password',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'first_name',
|
||||||
|
'last_name',
|
||||||
|
'email',
|
||||||
|
'password',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function getFullNameAttribute(): string
|
||||||
|
{
|
||||||
|
return "$this->first_name $this->last_name";
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getFormattedEmailAttribute(): string
|
||||||
|
{
|
||||||
|
return sprintf(
|
||||||
|
'%s <%s>',
|
||||||
|
$this->getFullNameAttribute(),
|
||||||
|
strtolower($this->email)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
308
src/Services/Facade.php
Normal file
308
src/Services/Facade.php
Normal file
@@ -0,0 +1,308 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Services;
|
||||||
|
|
||||||
|
use Illuminate\Contracts\Container\Container;
|
||||||
|
use Illuminate\Support\Testing\Fakes\Fake;
|
||||||
|
use Mockery;
|
||||||
|
use Mockery\Expectation;
|
||||||
|
use Mockery\ExpectationInterface;
|
||||||
|
use Mockery\LegacyMockInterface;
|
||||||
|
use Mockery\MockInterface;
|
||||||
|
|
||||||
|
class Facade
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The application instance being facaded.
|
||||||
|
*
|
||||||
|
* @var Container | null
|
||||||
|
*/
|
||||||
|
protected static ?Container $container = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The resolved object instances.
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
protected static array $resolvedInstance;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates if the resolved instance should be cached.
|
||||||
|
*
|
||||||
|
* @var bool
|
||||||
|
*/
|
||||||
|
protected static bool $cached = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a Closure when the facade has been resolved.
|
||||||
|
*
|
||||||
|
* @param \Closure $callback
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function resolved(\Closure $callback): void
|
||||||
|
{
|
||||||
|
$accessor = static::getFacadeAccessor();
|
||||||
|
|
||||||
|
if (static::$container->resolved($accessor) === true) {
|
||||||
|
$callback(static::getFacadeRoot(), static::$container);
|
||||||
|
}
|
||||||
|
|
||||||
|
static::$container->afterResolving($accessor, function ($service, $app) use ($callback) {
|
||||||
|
$callback($service, $app);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert the facade into a Mockery spy.
|
||||||
|
*
|
||||||
|
* @return MockInterface
|
||||||
|
*/
|
||||||
|
public static function spy(): MockInterface
|
||||||
|
{
|
||||||
|
if (! static::isMock()) {
|
||||||
|
$class = static::getMockableClass();
|
||||||
|
|
||||||
|
return tap($class ? Mockery::spy($class) : Mockery::spy(), function ($spy) {
|
||||||
|
static::swap($spy);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new \RuntimeException('Cannot spy on an existing mock instance.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initiate a partial mock on the facade.
|
||||||
|
*
|
||||||
|
* @return MockInterface
|
||||||
|
*/
|
||||||
|
public static function partialMock(): MockInterface
|
||||||
|
{
|
||||||
|
$name = static::getFacadeAccessor();
|
||||||
|
|
||||||
|
$mock = static::isMock()
|
||||||
|
? static::$resolvedInstance[$name]
|
||||||
|
: static::createFreshMockInstance();
|
||||||
|
|
||||||
|
return $mock->makePartial();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initiate a mock expectation on the facade.
|
||||||
|
*
|
||||||
|
* @return Expectation|ExpectationInterface
|
||||||
|
*/
|
||||||
|
public static function shouldReceive(): Mockery\Expectation | Mockery\ExpectationInterface
|
||||||
|
{
|
||||||
|
$name = static::getFacadeAccessor();
|
||||||
|
|
||||||
|
$mock = static::isMock()
|
||||||
|
? static::$resolvedInstance[$name]
|
||||||
|
: static::createFreshMockInstance();
|
||||||
|
|
||||||
|
return $mock->shouldReceive(...func_get_args());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initiate a mock expectation on the facade.
|
||||||
|
*
|
||||||
|
* @return Expectation|ExpectationInterface
|
||||||
|
*/
|
||||||
|
public static function expects(): Mockery\Expectation | Mockery\ExpectationInterface
|
||||||
|
{
|
||||||
|
$name = static::getFacadeAccessor();
|
||||||
|
|
||||||
|
$mock = static::isMock()
|
||||||
|
? static::$resolvedInstance[$name]
|
||||||
|
: static::createFreshMockInstance();
|
||||||
|
|
||||||
|
return $mock->expects(...func_get_args());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a fresh mock instance for the given class.
|
||||||
|
*
|
||||||
|
* @return MockInterface|LegacyMockInterface
|
||||||
|
*/
|
||||||
|
protected static function createFreshMockInstance(): MockInterface | LegacyMockInterface
|
||||||
|
{
|
||||||
|
return tap(static::createMock(), function ($mock) {
|
||||||
|
static::swap($mock);
|
||||||
|
|
||||||
|
$mock->shouldAllowMockingProtectedMethods();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a fresh mock instance for the given class.
|
||||||
|
*
|
||||||
|
* @return MockInterface
|
||||||
|
*/
|
||||||
|
protected static function createMock(): MockInterface
|
||||||
|
{
|
||||||
|
$class = static::getMockableClass();
|
||||||
|
|
||||||
|
return $class ? Mockery::mock($class) : Mockery::mock();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determines whether a mock is set as the instance of the facade.
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
protected static function isMock(): bool
|
||||||
|
{
|
||||||
|
$name = static::getFacadeAccessor();
|
||||||
|
|
||||||
|
return isset(static::$resolvedInstance[$name]) &&
|
||||||
|
static::$resolvedInstance[$name] instanceof LegacyMockInterface;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the mockable class for the bound instance.
|
||||||
|
*
|
||||||
|
* @return string|null
|
||||||
|
*/
|
||||||
|
protected static function getMockableClass(): ?string
|
||||||
|
{
|
||||||
|
if ($root = static::getFacadeRoot()) {
|
||||||
|
return get_class($root);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hotswap the underlying instance behind the facade.
|
||||||
|
*
|
||||||
|
* @param mixed $instance
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function swap(mixed $instance): void
|
||||||
|
{
|
||||||
|
static::$resolvedInstance[static::getFacadeAccessor()] = $instance;
|
||||||
|
|
||||||
|
if (isset(static::$container)) {
|
||||||
|
static::$container->instance(static::getFacadeAccessor(), $instance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determines whether a "fake" has been set as the facade instance.
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public static function isFake(): bool
|
||||||
|
{
|
||||||
|
$name = static::getFacadeAccessor();
|
||||||
|
|
||||||
|
return isset(static::$resolvedInstance[$name]) &&
|
||||||
|
static::$resolvedInstance[$name] instanceof Fake;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the root object behind the facade.
|
||||||
|
*
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public static function getFacadeRoot(): mixed
|
||||||
|
{
|
||||||
|
return static::resolveFacadeInstance(static::getFacadeAccessor());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the registered name of the component.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*
|
||||||
|
* @throws \RuntimeException
|
||||||
|
*/
|
||||||
|
protected static function getFacadeAccessor(): string
|
||||||
|
{
|
||||||
|
throw new \RuntimeException('Facade does not implement getFacadeAccessor method.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the facade root instance from the container.
|
||||||
|
*
|
||||||
|
* @param string $name
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
protected static function resolveFacadeInstance(string $name): mixed
|
||||||
|
{
|
||||||
|
if (isset(static::$resolvedInstance[$name])) {
|
||||||
|
return static::$resolvedInstance[$name];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (static::$container) {
|
||||||
|
if (static::$cached) {
|
||||||
|
return static::$resolvedInstance[$name] = static::$container[$name];
|
||||||
|
}
|
||||||
|
|
||||||
|
return static::$container[$name];
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear a resolved facade instance.
|
||||||
|
*
|
||||||
|
* @param string $name
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function clearResolvedInstance(string $name): void
|
||||||
|
{
|
||||||
|
unset(static::$resolvedInstance[$name]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear all of the resolved instances.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function clearResolvedInstances(): void
|
||||||
|
{
|
||||||
|
static::$resolvedInstance = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the application instance behind the facade.
|
||||||
|
*/
|
||||||
|
public static function getFacadeContainer(): ?Container
|
||||||
|
{
|
||||||
|
return static::$container;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the application instance.
|
||||||
|
*
|
||||||
|
* @param Container | null $container
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public static function setFacadeContainer(Container | null $container): void
|
||||||
|
{
|
||||||
|
static::$container = $container;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle dynamic, static calls to the object.
|
||||||
|
*
|
||||||
|
* @param string $method
|
||||||
|
* @param array $args
|
||||||
|
* @return mixed
|
||||||
|
*
|
||||||
|
* @throws \RuntimeException
|
||||||
|
*/
|
||||||
|
public static function __callStatic(string $method, array $args)
|
||||||
|
{
|
||||||
|
$instance = static::getFacadeRoot();
|
||||||
|
|
||||||
|
if (! $instance) {
|
||||||
|
throw new \RuntimeException('A facade root has not been set.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $instance->$method(...$args);
|
||||||
|
}
|
||||||
|
}
|
||||||
29
src/Services/Facades/Broker.php
Normal file
29
src/Services/Facades/Broker.php
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Services\Facades;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Async\Messages\Message;
|
||||||
|
use Siteworxpro\App\Async\Queues\Queue;
|
||||||
|
use Siteworxpro\App\Services\Facade;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Broker Facade
|
||||||
|
*
|
||||||
|
* @method static void publish(Queue $queue, Message $message, int $delay = 0)
|
||||||
|
* @method static void publishLater(Queue $queue, Message $message, int $delay)
|
||||||
|
* @method static Message|null consume(Queue $queue)
|
||||||
|
*/
|
||||||
|
class Broker extends Facade
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the registered name of the component.
|
||||||
|
*
|
||||||
|
* @return string The name of the component.
|
||||||
|
*/
|
||||||
|
protected static function getFacadeAccessor(): string
|
||||||
|
{
|
||||||
|
return \Siteworxpro\App\Async\Brokers\Broker::class;
|
||||||
|
}
|
||||||
|
}
|
||||||
31
src/Services/Facades/Config.php
Normal file
31
src/Services/Facades/Config.php
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Services\Facades;
|
||||||
|
|
||||||
|
use Siteworx\Config\Config as SwConfig;
|
||||||
|
use Siteworxpro\App\Services\Facade;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class Config
|
||||||
|
*
|
||||||
|
* This class serves as a facade for the configuration settings of the application.
|
||||||
|
* It extends the Facade class from the Illuminate\Support\Facades namespace.
|
||||||
|
*
|
||||||
|
* @method static array | bool | string | int | null get(string $key) Retrieve the configuration value for the given key. // @codingStandardsIgnoreStart
|
||||||
|
*
|
||||||
|
* @package Siteworx\App\Facades
|
||||||
|
*/
|
||||||
|
class Config extends Facade
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the registered name of the component.
|
||||||
|
*
|
||||||
|
* @return string The name of the component.
|
||||||
|
*/
|
||||||
|
protected static function getFacadeAccessor(): string
|
||||||
|
{
|
||||||
|
return SwConfig::class;
|
||||||
|
}
|
||||||
|
}
|
||||||
35
src/Services/Facades/Dispatcher.php
Normal file
35
src/Services/Facades/Dispatcher.php
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Services\Facades;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Events\Dispatcher as DispatcherConcrete;
|
||||||
|
use Siteworxpro\App\Services\Facade;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class Dispatcher
|
||||||
|
*
|
||||||
|
* A facade for the event dispatcher.
|
||||||
|
*
|
||||||
|
* @package Siteworxpro\App\Services\Facades
|
||||||
|
*
|
||||||
|
* @method static void listen(string $event, callable|string $listener)
|
||||||
|
* @method static void dispatch(object|string $event, array $payload = [], bool $halt = false)
|
||||||
|
* @method static void push(object|string $event, array $payload = [])
|
||||||
|
* @method static array|null until(object|string $event, array $payload = [])
|
||||||
|
* @method static bool hasListeners(string $eventName)
|
||||||
|
* @method static void subscribe(mixed $subscriber)
|
||||||
|
*/
|
||||||
|
class Dispatcher extends Facade
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the registered name of the component.
|
||||||
|
*
|
||||||
|
* @return string The name of the component.
|
||||||
|
*/
|
||||||
|
protected static function getFacadeAccessor(): string
|
||||||
|
{
|
||||||
|
return DispatcherConcrete::class;
|
||||||
|
}
|
||||||
|
}
|
||||||
36
src/Services/Facades/Logger.php
Normal file
36
src/Services/Facades/Logger.php
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Services\Facades;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Services\Facade;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class Logger
|
||||||
|
*
|
||||||
|
* This class serves as a facade for the Monolog logger.
|
||||||
|
* It extends the Facade class from the Illuminate\Support\Facades namespace.
|
||||||
|
*
|
||||||
|
* @method static debug(\Stringable|string $message, array $context = []) Log an informational message.
|
||||||
|
* @method static info(\Stringable|string $message, array $context = []) Log an informational message.
|
||||||
|
* @method static error(\Stringable|string $message, array $context = []) Log an error message.
|
||||||
|
* @method static warning(\Stringable|string $message, array $context = []) Log a warning message.
|
||||||
|
* @method static critical(\Stringable|string $message, array $context = []) Log a critical error message.
|
||||||
|
* @method static alert(\Stringable|string $message, array $context = []) Log an alert message.
|
||||||
|
* @method static emergency(\Stringable|string $message, array $context = []) Log an emergency message.
|
||||||
|
*
|
||||||
|
* @package Siteworxpro\App\Facades
|
||||||
|
*/
|
||||||
|
class Logger extends Facade
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the registered name of the component.
|
||||||
|
*
|
||||||
|
* @return string The name of the component.
|
||||||
|
*/
|
||||||
|
protected static function getFacadeAccessor(): string
|
||||||
|
{
|
||||||
|
return \Siteworxpro\App\Log\Logger::class;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Siteworxpro\App\Facades;
|
namespace Siteworxpro\App\Services\Facades;
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Facade;
|
|
||||||
use Predis\Client;
|
use Predis\Client;
|
||||||
use Predis\Response\Status;
|
use Predis\Response\Status;
|
||||||
|
use Siteworxpro\App\Services\Facade;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Facade for the Redis client.
|
* Facade for the Redis client.
|
||||||
@@ -18,28 +18,10 @@ use Predis\Response\Status;
|
|||||||
* @method static Status|null set(string $key, $value, $expireResolution = null, $expireTTL = null, $flag = null)
|
* @method static Status|null set(string $key, $value, $expireResolution = null, $expireTTL = null, $flag = null)
|
||||||
* @method static array keys(string $pattern)
|
* @method static array keys(string $pattern)
|
||||||
* @method static int del(string $key)
|
* @method static int del(string $key)
|
||||||
|
* @method static Status ping()
|
||||||
*/
|
*/
|
||||||
class Redis extends Facade
|
class Redis extends Facade
|
||||||
{
|
{
|
||||||
public static function getFacadeRoot(): Client
|
|
||||||
{
|
|
||||||
if (self::$resolvedInstance !== null) {
|
|
||||||
$redis = self::resolveFacadeInstance(self::getFacadeAccessor());
|
|
||||||
|
|
||||||
if ($redis instanceof Client) {
|
|
||||||
return $redis;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a new Redis client instance if not already resolved
|
|
||||||
return new Client([
|
|
||||||
'scheme' => 'tcp',
|
|
||||||
'host' => Config::get('redis.host'),
|
|
||||||
'port' => Config::get('redis.port'),
|
|
||||||
'database' => Config::get('redis.database'),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the registered name of the component.
|
* Get the registered name of the component.
|
||||||
*
|
*
|
||||||
28
src/Services/ServiceProviders/BrokerServiceProvider.php
Normal file
28
src/Services/ServiceProviders/BrokerServiceProvider.php
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Services\ServiceProviders;
|
||||||
|
|
||||||
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use Siteworxpro\App\Async\Brokers\Broker;
|
||||||
|
use Siteworxpro\App\Services\Facades\Config;
|
||||||
|
|
||||||
|
class BrokerServiceProvider extends ServiceProvider
|
||||||
|
{
|
||||||
|
public function register(): void
|
||||||
|
{
|
||||||
|
$this->app->singleton(Broker::class, function (): Broker {
|
||||||
|
$configName = Config::get('queue.broker');
|
||||||
|
$brokerConfig = Config::get('queue.broker_config.' . $configName) ?? [];
|
||||||
|
|
||||||
|
$brokerClass = Broker::BROKER_TYPES[$configName] ?? null;
|
||||||
|
|
||||||
|
if ($brokerClass && class_exists($brokerClass)) {
|
||||||
|
return new $brokerClass($brokerConfig);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new \RuntimeException("Broker class $brokerClass does not exist.");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
18
src/Services/ServiceProviders/DispatcherServiceProvider.php
Normal file
18
src/Services/ServiceProviders/DispatcherServiceProvider.php
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Services\ServiceProviders;
|
||||||
|
|
||||||
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use Siteworxpro\App\Events\Dispatcher;
|
||||||
|
|
||||||
|
class DispatcherServiceProvider extends ServiceProvider
|
||||||
|
{
|
||||||
|
public function register(): void
|
||||||
|
{
|
||||||
|
$this->app->singleton(Dispatcher::class, function () {
|
||||||
|
return new Dispatcher();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
18
src/Services/ServiceProviders/LoggerServiceProvider.php
Normal file
18
src/Services/ServiceProviders/LoggerServiceProvider.php
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Services\ServiceProviders;
|
||||||
|
|
||||||
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use Siteworxpro\App\Log\Logger;
|
||||||
|
|
||||||
|
class LoggerServiceProvider extends ServiceProvider
|
||||||
|
{
|
||||||
|
public function register(): void
|
||||||
|
{
|
||||||
|
$this->app->singleton(Logger::class, function () {
|
||||||
|
return new Logger();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
25
src/Services/ServiceProviders/RedisServiceProvider.php
Normal file
25
src/Services/ServiceProviders/RedisServiceProvider.php
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\App\Services\ServiceProviders;
|
||||||
|
|
||||||
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use Predis\Client;
|
||||||
|
use Siteworxpro\App\Services\Facades\Config;
|
||||||
|
|
||||||
|
class RedisServiceProvider extends ServiceProvider
|
||||||
|
{
|
||||||
|
public function register(): void
|
||||||
|
{
|
||||||
|
$this->app->singleton(Client::class, function () {
|
||||||
|
return new Client([
|
||||||
|
'scheme' => 'tcp',
|
||||||
|
'host' => Config::get('redis.host'),
|
||||||
|
'port' => Config::get('redis.port'),
|
||||||
|
'database' => Config::get('redis.database'),
|
||||||
|
'password' => Config::get('redis.password'),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
16
tests/Controllers/AbstractController.php
Normal file
16
tests/Controllers/AbstractController.php
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\Tests\Controllers;
|
||||||
|
|
||||||
|
use Nyholm\Psr7\ServerRequest;
|
||||||
|
use Siteworxpro\Tests\Unit;
|
||||||
|
|
||||||
|
abstract class AbstractController extends Unit
|
||||||
|
{
|
||||||
|
protected function getMockRequest(string $method = 'GET', string $uri = '/'): ServerRequest
|
||||||
|
{
|
||||||
|
return new ServerRequest($method, $uri);
|
||||||
|
}
|
||||||
|
}
|
||||||
54
tests/Controllers/ControllerTest.php
Normal file
54
tests/Controllers/ControllerTest.php
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\Tests\Controllers;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Controllers\Controller;
|
||||||
|
|
||||||
|
class ControllerTest extends AbstractController
|
||||||
|
{
|
||||||
|
public function testNotFoundExceptions()
|
||||||
|
{
|
||||||
|
$testClass = new TestClass();
|
||||||
|
|
||||||
|
$this->expectException(\League\Route\Http\Exception\NotFoundException::class);
|
||||||
|
$testClass->get($this->getMockRequest());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNotFoundExceptionPost()
|
||||||
|
{
|
||||||
|
$testClass = new TestClass();
|
||||||
|
|
||||||
|
$this->expectException(\League\Route\Http\Exception\NotFoundException::class);
|
||||||
|
$testClass->post($this->getMockRequest());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNotFoundExceptionPut()
|
||||||
|
{
|
||||||
|
$testClass = new TestClass();
|
||||||
|
|
||||||
|
$this->expectException(\League\Route\Http\Exception\NotFoundException::class);
|
||||||
|
$testClass->put($this->getMockRequest());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNotFoundExceptionDelete()
|
||||||
|
{
|
||||||
|
$testClass = new TestClass();
|
||||||
|
|
||||||
|
$this->expectException(\League\Route\Http\Exception\NotFoundException::class);
|
||||||
|
$testClass->delete($this->getMockRequest());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNotFoundExceptionPatch()
|
||||||
|
{
|
||||||
|
$testClass = new TestClass();
|
||||||
|
|
||||||
|
$this->expectException(\League\Route\Http\Exception\NotFoundException::class);
|
||||||
|
$testClass->patch($this->getMockRequest());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class TestClass extends Controller // phpcs:ignore
|
||||||
|
{
|
||||||
|
}
|
||||||
25
tests/Controllers/IndexControllerTest.php
Normal file
25
tests/Controllers/IndexControllerTest.php
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\Tests\Controllers;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Controllers\IndexController;
|
||||||
|
|
||||||
|
class IndexControllerTest extends AbstractController
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @throws \JsonException
|
||||||
|
*/
|
||||||
|
public function testGet(): void
|
||||||
|
{
|
||||||
|
$this->assertTrue(true);
|
||||||
|
|
||||||
|
$controller = new IndexController();
|
||||||
|
|
||||||
|
$response = $controller->get($this->getMockRequest());
|
||||||
|
|
||||||
|
$this->assertEquals(200, $response->getStatusCode());
|
||||||
|
$this->assertEquals('{"status_code":200,"message":"Server is running"}', (string)$response->getBody());
|
||||||
|
}
|
||||||
|
}
|
||||||
32
tests/Facades/AbstractFacade.php
Normal file
32
tests/Facades/AbstractFacade.php
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\Tests\Facades;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Services\Facade;
|
||||||
|
use Siteworxpro\Tests\Unit;
|
||||||
|
|
||||||
|
abstract class AbstractFacade extends Unit
|
||||||
|
{
|
||||||
|
abstract protected function getFacadeClass(): string;
|
||||||
|
abstract protected function getConcrete(): string;
|
||||||
|
|
||||||
|
public function testFacadeAccessor(): void
|
||||||
|
{
|
||||||
|
/** @var Facade | string $class */
|
||||||
|
$class = $this->getFacadeClass();
|
||||||
|
|
||||||
|
$this->assertTrue(
|
||||||
|
method_exists($class, 'getFacadeAccessor'),
|
||||||
|
sprintf('The class %s must implement the method getFacadeAccessor.', $class)
|
||||||
|
);
|
||||||
|
|
||||||
|
$facade = $class::getFacadeRoot();
|
||||||
|
|
||||||
|
$this->assertNotNull(
|
||||||
|
$facade,
|
||||||
|
sprintf('The facade %s is not properly initialized.', $this->getConcrete())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
21
tests/Facades/RedisTest.php
Normal file
21
tests/Facades/RedisTest.php
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\Tests\Facades;
|
||||||
|
|
||||||
|
use Predis\Client;
|
||||||
|
use Siteworxpro\App\Services\Facades\Redis;
|
||||||
|
|
||||||
|
class RedisTest extends AbstractFacade
|
||||||
|
{
|
||||||
|
protected function getFacadeClass(): string
|
||||||
|
{
|
||||||
|
return Redis::class;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getConcrete(): string
|
||||||
|
{
|
||||||
|
return Client::class;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,29 +6,36 @@ namespace Siteworxpro\Tests\Http;
|
|||||||
|
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
use Siteworxpro\App\Http\JsonResponseFactory;
|
use Siteworxpro\App\Http\JsonResponseFactory;
|
||||||
|
use Siteworxpro\HttpStatus\CodesEnum;
|
||||||
|
|
||||||
class JsonResponseFactoryTest extends TestCase
|
class JsonResponseFactoryTest extends TestCase
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* @throws \JsonException
|
||||||
|
*/
|
||||||
public function testCreateJsonResponseReturnsValidResponse(): void
|
public function testCreateJsonResponseReturnsValidResponse(): void
|
||||||
{
|
{
|
||||||
$data = ['key' => 'value'];
|
$data = ['key' => 'value'];
|
||||||
$statusCode = 200;
|
$statusCode = CodesEnum::OK;
|
||||||
|
|
||||||
$response = JsonResponseFactory::createJsonResponse($data, $statusCode);
|
$response = JsonResponseFactory::createJsonResponse($data, $statusCode);
|
||||||
|
|
||||||
$this->assertSame($statusCode, $response->getStatusCode());
|
$this->assertSame($statusCode->value, $response->getStatusCode());
|
||||||
$this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
|
$this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
|
||||||
$this->assertSame(json_encode($data), (string) $response->getBody());
|
$this->assertSame(json_encode($data), (string) $response->getBody());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws \JsonException
|
||||||
|
*/
|
||||||
public function testCreateJsonResponseHandlesEmptyData(): void
|
public function testCreateJsonResponseHandlesEmptyData(): void
|
||||||
{
|
{
|
||||||
$data = [];
|
$data = [];
|
||||||
$statusCode = 204;
|
$statusCode = CodesEnum::NO_CONTENT;
|
||||||
|
|
||||||
$response = JsonResponseFactory::createJsonResponse($data, $statusCode);
|
$response = JsonResponseFactory::createJsonResponse($data, $statusCode);
|
||||||
|
|
||||||
$this->assertSame($statusCode, $response->getStatusCode());
|
$this->assertSame($statusCode->value, $response->getStatusCode());
|
||||||
$this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
|
$this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
|
||||||
$this->assertSame(json_encode($data), (string) $response->getBody());
|
$this->assertSame(json_encode($data), (string) $response->getBody());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ namespace Siteworxpro\Tests\Http\Middleware;
|
|||||||
use Nyholm\Psr7\Response;
|
use Nyholm\Psr7\Response;
|
||||||
use Nyholm\Psr7\ServerRequest;
|
use Nyholm\Psr7\ServerRequest;
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
use Siteworxpro\App\Facades\Config;
|
|
||||||
use Siteworxpro\App\Http\Middleware\CorsMiddleware;
|
use Siteworxpro\App\Http\Middleware\CorsMiddleware;
|
||||||
|
use Siteworxpro\App\Services\Facades\Config;
|
||||||
use Siteworxpro\Tests\Unit;
|
use Siteworxpro\Tests\Unit;
|
||||||
|
|
||||||
class CorsMiddlewareTest extends Unit
|
class CorsMiddlewareTest extends Unit
|
||||||
|
|||||||
43
tests/ServiceProviders/AbstractServiceProvider.php
Normal file
43
tests/ServiceProviders/AbstractServiceProvider.php
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\Tests\ServiceProviders;
|
||||||
|
|
||||||
|
use Illuminate\Container\Container;
|
||||||
|
use Illuminate\Contracts\Container\BindingResolutionException;
|
||||||
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use Siteworxpro\Tests\Unit;
|
||||||
|
|
||||||
|
abstract class AbstractServiceProvider extends Unit
|
||||||
|
{
|
||||||
|
abstract protected function getProviderClass(): string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws BindingResolutionException
|
||||||
|
*/
|
||||||
|
public function testProvider(): void
|
||||||
|
{
|
||||||
|
$container = new Container();
|
||||||
|
|
||||||
|
$providerClass = $this->getProviderClass();
|
||||||
|
|
||||||
|
/** @var ServiceProvider $providerClass */
|
||||||
|
$provider = new $providerClass($container);
|
||||||
|
|
||||||
|
$this->assertInstanceOf($providerClass, $provider);
|
||||||
|
$provider->register();
|
||||||
|
|
||||||
|
$bindings = $provider->bindings;
|
||||||
|
foreach ($bindings as $abstract => $concrete) {
|
||||||
|
$this->assertTrue($container->bound($abstract), "The $abstract is not bound in the container.");
|
||||||
|
$this->assertNotNull($container->make($abstract), "The $abstract could not be resolved.");
|
||||||
|
|
||||||
|
$this->assertInstanceOf(
|
||||||
|
$concrete,
|
||||||
|
$container->make($abstract),
|
||||||
|
"The $abstract is not an instance of $concrete."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
15
tests/ServiceProviders/LoggerServiceProviderTest.php
Normal file
15
tests/ServiceProviders/LoggerServiceProviderTest.php
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\Tests\ServiceProviders;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Services\ServiceProviders\LoggerServiceProvider;
|
||||||
|
|
||||||
|
class LoggerServiceProviderTest extends AbstractServiceProvider
|
||||||
|
{
|
||||||
|
protected function getProviderClass(): string
|
||||||
|
{
|
||||||
|
return LoggerServiceProvider::class;
|
||||||
|
}
|
||||||
|
}
|
||||||
15
tests/ServiceProviders/RedisServiceProviderTest.php
Normal file
15
tests/ServiceProviders/RedisServiceProviderTest.php
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Siteworxpro\Tests\ServiceProviders;
|
||||||
|
|
||||||
|
use Siteworxpro\App\Services\ServiceProviders\RedisServiceProvider;
|
||||||
|
|
||||||
|
class RedisServiceProviderTest extends AbstractServiceProvider
|
||||||
|
{
|
||||||
|
protected function getProviderClass(): string
|
||||||
|
{
|
||||||
|
return RedisServiceProvider::class;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,21 +5,29 @@ declare(strict_types=1);
|
|||||||
namespace Siteworxpro\Tests;
|
namespace Siteworxpro\Tests;
|
||||||
|
|
||||||
use Illuminate\Container\Container;
|
use Illuminate\Container\Container;
|
||||||
use Illuminate\Support\Facades\Facade;
|
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
use Siteworxpro\App\Facades\Config;
|
use Siteworx\Config\Config as SWConfig;
|
||||||
|
use Siteworxpro\App\Services\Facade;
|
||||||
|
use Siteworxpro\App\Services\Facades\Config;
|
||||||
|
|
||||||
abstract class Unit extends TestCase
|
abstract class Unit extends TestCase
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* @throws \ReflectionException
|
||||||
|
*/
|
||||||
protected function setUp(): void
|
protected function setUp(): void
|
||||||
{
|
{
|
||||||
$container = new Container();
|
$container = new Container();
|
||||||
Facade::setFacadeApplication($container);
|
Facade::setFacadeContainer($container);
|
||||||
|
|
||||||
|
$container->bind(SWConfig::class, function () {
|
||||||
|
return SWConfig::load(__DIR__ . '/../config.php');
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function tearDown(): void
|
protected function tearDown(): void
|
||||||
{
|
{
|
||||||
Config::clearResolvedInstances();
|
Config::clearResolvedInstances();
|
||||||
Facade::setFacadeApplication(null);
|
Facade::setFacadeContainer(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user