3 Commits

Author SHA1 Message Date
7fe2722fc1 chore: add deployment configurations and tests for logger and dispatcher (#17)
All checks were successful
🧪✨ Tests Workflow / 🛡️ 🔒 Library Audit (push) Successful in 1m40s
🧪✨ Tests Workflow / 📝 ✨ Code Lint (push) Successful in 1m36s
🧪✨ Tests Workflow / 🛡️ 🔒 License Check (push) Successful in 2m4s
🧪✨ Tests Workflow / 🐙 🔍 Code Sniffer (push) Successful in 2m24s
🧪✨ Tests Workflow / 🧪 ✨ Database Migrations (push) Successful in 2m46s
🧪✨ Tests Workflow / 🧪 ✅ Unit Tests (push) Successful in 1m27s
🏗️✨ Build Workflow / 🖥️ 🔨 Build (push) Successful in 16m7s
🏗️✨ Build Workflow / 🖥️ 🔨 Build Migrations (push) Successful in 1m29s
Reviewed-on: #17
Co-authored-by: Ron Rise <ron@siteworxpro.com>
Co-committed-by: Ron Rise <ron@siteworxpro.com>
2025-11-13 19:38:26 +00:00
5542ad1e75 chore: added documentation (#16)
All checks were successful
🧪✨ Tests Workflow / 🛡️ 🔒 Library Audit (push) Successful in 1m42s
🧪✨ Tests Workflow / 📝 ✨ Code Lint (push) Successful in 1m38s
🧪✨ Tests Workflow / 🛡️ 🔒 License Check (push) Successful in 2m5s
🧪✨ Tests Workflow / 🧪 ✨ Database Migrations (push) Successful in 2m44s
🧪✨ Tests Workflow / 🐙 🔍 Code Sniffer (push) Successful in 2m28s
🧪✨ Tests Workflow / 🧪 ✅ Unit Tests (push) Successful in 1m27s
Reviewed-on: #16
Co-authored-by: Ron Rise <ron@siteworxpro.com>
Co-committed-by: Ron Rise <ron@siteworxpro.com>
2025-11-13 04:14:13 +00:00
e4a55af694 feat/queue-kafka (#15)
All checks were successful
🧪✨ Tests Workflow / 🛡️ 🔒 Library Audit (push) Successful in 1m26s
🧪✨ Tests Workflow / 🧪 ✨ Database Migrations (push) Successful in 2m8s
🧪✨ Tests Workflow / 🛡️ 🔒 License Check (push) Successful in 59s
🧪✨ Tests Workflow / 📝 ✨ Code Lint (push) Successful in 1m14s
🧪✨ Tests Workflow / 🐙 🔍 Code Sniffer (push) Successful in 1m16s
🧪✨ Tests Workflow / 🧪 ✅ Unit Tests (push) Successful in 1m13s
Reviewed-on: #15
Co-authored-by: Ron Rise <ron@siteworxpro.com>
Co-committed-by: Ron Rise <ron@siteworxpro.com>
2025-11-12 20:29:42 +00:00
42 changed files with 1228 additions and 171 deletions

View File

@@ -0,0 +1,10 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name=" Compose Deployment" type="docker-deploy" factoryName="docker-compose.yml" server-name="Docker">
<deployment type="docker-compose.yml">
<settings>
<option name="sourceFilePath" value="docker-compose.yml" />
</settings>
</deployment>
<method v="2" />
</configuration>
</component>

8
.run/All.run.xml Normal file
View File

@@ -0,0 +1,8 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="All" type="ComposerRunConfigurationType" factoryName="Composer Script">
<option name="commandLineParameters" value="" />
<option name="pathToComposerJson" value="$PROJECT_DIR$/composer.json" />
<option name="script" value="tests:all" />
<method v="2" />
</configuration>
</component>

8
.run/Lint_fix.run.xml Normal file
View File

@@ -0,0 +1,8 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Lint:fix" type="ComposerRunConfigurationType" factoryName="Composer Script">
<option name="commandLineParameters" value="" />
<option name="pathToComposerJson" value="$PROJECT_DIR$/composer.json" />
<option name="script" value="tests:lint:fix" />
<method v="2" />
</configuration>
</component>

11
.run/Main.run.xml Normal file
View File

@@ -0,0 +1,11 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Main" type="PHPUnitRunConfigurationType" factoryName="PHPUnit">
<CommandLine>
<PhpTestInterpreterSettings>
<option name="interpreterName" value="composer-runtime" />
</PhpTestInterpreterSettings>
</CommandLine>
<TestRunner configuration_file="$PROJECT_DIR$/phpunit.xml" scope="XML" use_alternative_configuration_file="true" />
<method v="2" />
</configuration>
</component>

View File

@@ -14,12 +14,23 @@ RUN composer install --optimize-autoloader --ignore-platform-reqs --no-dev
# Use the official PHP CLI image with Alpine Linux for the second stage
FROM php:8.4.14-alpine AS php
ARG KAFKA_ENABLED=0
# 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 \
&& apk add libpq-dev linux-headers --no-cache \
&& docker-php-ext-install pdo_pgsql sockets pcntl \
&& 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
WORKDIR /app

View File

@@ -28,7 +28,8 @@
"mockery/mockery": "^1.6",
"squizlabs/php_codesniffer": "^3.12",
"lendable/composer-license-checker": "^1.2",
"phpstan/phpstan": "^2.1.31"
"phpstan/phpstan": "^2.1.31",
"kwn/php-rdkafka-stubs": "^2.2"
},
"scripts": {
"tests:all": [

199
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "f920b7224ee908f6a4270f200dbbca3a",
"content-hash": "7c2d40400d6f4d0469324dc1645eba3c",
"packages": [
{
"name": "adhocore/cli",
@@ -300,16 +300,16 @@
},
{
"name": "google/protobuf",
"version": "v4.32.1",
"version": "v4.33.0",
"source": {
"type": "git",
"url": "https://github.com/protocolbuffers/protobuf-php.git",
"reference": "c4ed1c1f9bbc1e91766e2cd6c0af749324fe87cb"
"reference": "b50269e23204e5ae859a326ec3d90f09efe3047d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/protocolbuffers/protobuf-php/zipball/c4ed1c1f9bbc1e91766e2cd6c0af749324fe87cb",
"reference": "c4ed1c1f9bbc1e91766e2cd6c0af749324fe87cb",
"url": "https://api.github.com/repos/protocolbuffers/protobuf-php/zipball/b50269e23204e5ae859a326ec3d90f09efe3047d",
"reference": "b50269e23204e5ae859a326ec3d90f09efe3047d",
"shasum": ""
},
"require": {
@@ -338,22 +338,22 @@
"proto"
],
"support": {
"source": "https://github.com/protocolbuffers/protobuf-php/tree/v4.32.1"
"source": "https://github.com/protocolbuffers/protobuf-php/tree/v4.33.0"
},
"time": "2025-09-14T05:14:52+00:00"
"time": "2025-10-15T20:10:28+00:00"
},
{
"name": "illuminate/collections",
"version": "v12.34.0",
"version": "v12.38.0",
"source": {
"type": "git",
"url": "https://github.com/illuminate/collections.git",
"reference": "b323866d9e571f8c444f3ccca6f645c05fadf568"
"reference": "deb291b109b6f7fd776a3550a120771137b3c5d1"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/illuminate/collections/zipball/b323866d9e571f8c444f3ccca6f645c05fadf568",
"reference": "b323866d9e571f8c444f3ccca6f645c05fadf568",
"url": "https://api.github.com/repos/illuminate/collections/zipball/deb291b109b6f7fd776a3550a120771137b3c5d1",
"reference": "deb291b109b6f7fd776a3550a120771137b3c5d1",
"shasum": ""
},
"require": {
@@ -399,11 +399,11 @@
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"time": "2025-10-10T13:31:43+00:00"
"time": "2025-10-30T12:22:05+00:00"
},
{
"name": "illuminate/conditionable",
"version": "v12.34.0",
"version": "v12.38.0",
"source": {
"type": "git",
"url": "https://github.com/illuminate/conditionable.git",
@@ -449,7 +449,7 @@
},
{
"name": "illuminate/container",
"version": "v12.34.0",
"version": "v12.38.0",
"source": {
"type": "git",
"url": "https://github.com/illuminate/container.git",
@@ -510,7 +510,7 @@
},
{
"name": "illuminate/contracts",
"version": "v12.34.0",
"version": "v12.38.0",
"source": {
"type": "git",
"url": "https://github.com/illuminate/contracts.git",
@@ -558,16 +558,16 @@
},
{
"name": "illuminate/database",
"version": "v12.34.0",
"version": "v12.38.0",
"source": {
"type": "git",
"url": "https://github.com/illuminate/database.git",
"reference": "3ad07bda64019d18fc6fda97fec0b3b7cb6ecae1"
"reference": "eacbdddf31f655fba5406fdf31bd264d880dd1a8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/illuminate/database/zipball/3ad07bda64019d18fc6fda97fec0b3b7cb6ecae1",
"reference": "3ad07bda64019d18fc6fda97fec0b3b7cb6ecae1",
"url": "https://api.github.com/repos/illuminate/database/zipball/eacbdddf31f655fba5406fdf31bd264d880dd1a8",
"reference": "eacbdddf31f655fba5406fdf31bd264d880dd1a8",
"shasum": ""
},
"require": {
@@ -625,11 +625,11 @@
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"time": "2025-10-10T13:33:40+00:00"
"time": "2025-11-11T14:13:21+00:00"
},
{
"name": "illuminate/macroable",
"version": "v12.34.0",
"version": "v12.38.0",
"source": {
"type": "git",
"url": "https://github.com/illuminate/macroable.git",
@@ -675,16 +675,16 @@
},
{
"name": "illuminate/support",
"version": "v12.34.0",
"version": "v12.38.0",
"source": {
"type": "git",
"url": "https://github.com/illuminate/support.git",
"reference": "89291f59ef6c170c00f10a41c566c49ee32ca09a"
"reference": "008b6c0d45f548de0f801d60a5854a7f9e4dd32f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/illuminate/support/zipball/89291f59ef6c170c00f10a41c566c49ee32ca09a",
"reference": "89291f59ef6c170c00f10a41c566c49ee32ca09a",
"url": "https://api.github.com/repos/illuminate/support/zipball/008b6c0d45f548de0f801d60a5854a7f9e4dd32f",
"reference": "008b6c0d45f548de0f801d60a5854a7f9e4dd32f",
"shasum": ""
},
"require": {
@@ -750,7 +750,7 @@
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"time": "2025-10-13T21:11:33+00:00"
"time": "2025-11-06T14:27:18+00:00"
},
{
"name": "laravel/serializable-closure",
@@ -1857,16 +1857,16 @@
},
{
"name": "roadrunner-php/roadrunner-api-dto",
"version": "v1.13.0",
"version": "v1.14.0",
"source": {
"type": "git",
"url": "https://github.com/roadrunner-php/roadrunner-api-dto.git",
"reference": "8a683f5057005bef742916847c0befbf9a00c543"
"reference": "e6efb759f0a73b8516b7f28317230ecd4010005e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/roadrunner-php/roadrunner-api-dto/zipball/8a683f5057005bef742916847c0befbf9a00c543",
"reference": "8a683f5057005bef742916847c0befbf9a00c543",
"url": "https://api.github.com/repos/roadrunner-php/roadrunner-api-dto/zipball/e6efb759f0a73b8516b7f28317230ecd4010005e",
"reference": "e6efb759f0a73b8516b7f28317230ecd4010005e",
"shasum": ""
},
"require": {
@@ -1912,7 +1912,7 @@
"docs": "https://docs.roadrunner.dev",
"forum": "https://forum.roadrunner.dev",
"issues": "https://github.com/roadrunner-server/roadrunner/issues",
"source": "https://github.com/roadrunner-php/roadrunner-api-dto/tree/v1.13.0"
"source": "https://github.com/roadrunner-php/roadrunner-api-dto/tree/v1.14.0"
},
"funding": [
{
@@ -1920,7 +1920,7 @@
"type": "github"
}
],
"time": "2025-08-12T14:04:38+00:00"
"time": "2025-11-06T13:03:11+00:00"
},
{
"name": "robinvdvleuten/ulid",
@@ -1972,9 +1972,9 @@
"name": "siteworxpro/config",
"version": "1.1.1",
"source": {
"type": "",
"url": "",
"reference": ""
"type": "git",
"url": "https://gitea.siteworxpro.com/php-packages/config",
"reference": "1.1.1"
},
"dist": {
"type": "zip",
@@ -2941,16 +2941,16 @@
},
{
"name": "symfony/translation-contracts",
"version": "v3.6.0",
"version": "v3.6.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/translation-contracts.git",
"reference": "df210c7a2573f1913b2d17cc95f90f53a73d8f7d"
"reference": "65a8bc82080447fae78373aa10f8d13b38338977"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/translation-contracts/zipball/df210c7a2573f1913b2d17cc95f90f53a73d8f7d",
"reference": "df210c7a2573f1913b2d17cc95f90f53a73d8f7d",
"url": "https://api.github.com/repos/symfony/translation-contracts/zipball/65a8bc82080447fae78373aa10f8d13b38338977",
"reference": "65a8bc82080447fae78373aa10f8d13b38338977",
"shasum": ""
},
"require": {
@@ -2999,7 +2999,7 @@
"standards"
],
"support": {
"source": "https://github.com/symfony/translation-contracts/tree/v3.6.0"
"source": "https://github.com/symfony/translation-contracts/tree/v3.6.1"
},
"funding": [
{
@@ -3010,12 +3010,16 @@
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-09-27T08:32:26+00:00"
"time": "2025-07-15T13:41:35+00:00"
},
{
"name": "voku/portable-ascii",
@@ -3144,6 +3148,44 @@
},
"time": "2025-04-30T06:54:44+00:00"
},
{
"name": "kwn/php-rdkafka-stubs",
"version": "v2.2.1",
"source": {
"type": "git",
"url": "https://github.com/kwn/php-rdkafka-stubs.git",
"reference": "23b865d6b3e8fe1f080aa7371dc1da3339361996"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/kwn/php-rdkafka-stubs/zipball/23b865d6b3e8fe1f080aa7371dc1da3339361996",
"reference": "23b865d6b3e8fe1f080aa7371dc1da3339361996",
"shasum": ""
},
"require": {
"ext-rdkafka": ">=4.0"
},
"require-dev": {
"phpunit/phpunit": "^8.2.4"
},
"type": "library",
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Karol Wnuk",
"email": "k.wnuk@ascetic.pl"
}
],
"description": "Rdkafka extension stubs for your IDE",
"support": {
"issues": "https://github.com/kwn/php-rdkafka-stubs/issues",
"source": "https://github.com/kwn/php-rdkafka-stubs/tree/v2.2.1"
},
"time": "2022-08-16T15:27:51+00:00"
},
{
"name": "lendable/composer-license-checker",
"version": "1.2.2",
@@ -3347,16 +3389,16 @@
},
{
"name": "nikic/php-parser",
"version": "v5.6.1",
"version": "v5.6.2",
"source": {
"type": "git",
"url": "https://github.com/nikic/PHP-Parser.git",
"reference": "f103601b29efebd7ff4a1ca7b3eeea9e3336a2a2"
"reference": "3a454ca033b9e06b63282ce19562e892747449bb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/f103601b29efebd7ff4a1ca7b3eeea9e3336a2a2",
"reference": "f103601b29efebd7ff4a1ca7b3eeea9e3336a2a2",
"url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/3a454ca033b9e06b63282ce19562e892747449bb",
"reference": "3a454ca033b9e06b63282ce19562e892747449bb",
"shasum": ""
},
"require": {
@@ -3399,9 +3441,9 @@
],
"support": {
"issues": "https://github.com/nikic/PHP-Parser/issues",
"source": "https://github.com/nikic/PHP-Parser/tree/v5.6.1"
"source": "https://github.com/nikic/PHP-Parser/tree/v5.6.2"
},
"time": "2025-08-13T20:13:15+00:00"
"time": "2025-10-21T19:32:17+00:00"
},
{
"name": "phar-io/manifest",
@@ -3523,11 +3565,11 @@
},
{
"name": "phpstan/phpstan",
"version": "2.1.31",
"version": "2.1.32",
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/ead89849d879fe203ce9292c6ef5e7e76f867b96",
"reference": "ead89849d879fe203ce9292c6ef5e7e76f867b96",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/e126cad1e30a99b137b8ed75a85a676450ebb227",
"reference": "e126cad1e30a99b137b8ed75a85a676450ebb227",
"shasum": ""
},
"require": {
@@ -3572,7 +3614,7 @@
"type": "github"
}
],
"time": "2025-10-10T14:14:11+00:00"
"time": "2025-11-11T15:18:17+00:00"
},
{
"name": "phpunit/php-code-coverage",
@@ -3910,16 +3952,16 @@
},
{
"name": "phpunit/phpunit",
"version": "12.4.1",
"version": "12.4.2",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "fc5413a2e6d240d2f6d9317bdf7f0a24e73de194"
"reference": "a94ea4d26d865875803b23aaf78c3c2c670ea2ea"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/fc5413a2e6d240d2f6d9317bdf7f0a24e73de194",
"reference": "fc5413a2e6d240d2f6d9317bdf7f0a24e73de194",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/a94ea4d26d865875803b23aaf78c3c2c670ea2ea",
"reference": "a94ea4d26d865875803b23aaf78c3c2c670ea2ea",
"shasum": ""
},
"require": {
@@ -3987,7 +4029,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
"source": "https://github.com/sebastianbergmann/phpunit/tree/12.4.1"
"source": "https://github.com/sebastianbergmann/phpunit/tree/12.4.2"
},
"funding": [
{
@@ -4011,7 +4053,7 @@
"type": "tidelift"
}
],
"time": "2025-10-09T14:08:29+00:00"
"time": "2025-10-30T08:41:39+00:00"
},
{
"name": "sebastian/cli-parser",
@@ -4912,16 +4954,16 @@
},
{
"name": "squizlabs/php_codesniffer",
"version": "3.13.4",
"version": "3.13.5",
"source": {
"type": "git",
"url": "https://github.com/PHPCSStandards/PHP_CodeSniffer.git",
"reference": "ad545ea9c1b7d270ce0fc9cbfb884161cd706119"
"reference": "0ca86845ce43291e8f5692c7356fccf3bcf02bf4"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/ad545ea9c1b7d270ce0fc9cbfb884161cd706119",
"reference": "ad545ea9c1b7d270ce0fc9cbfb884161cd706119",
"url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/0ca86845ce43291e8f5692c7356fccf3bcf02bf4",
"reference": "0ca86845ce43291e8f5692c7356fccf3bcf02bf4",
"shasum": ""
},
"require": {
@@ -4938,11 +4980,6 @@
"bin/phpcs"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.x-dev"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
@@ -4992,7 +5029,7 @@
"type": "thanks_dev"
}
],
"time": "2025-09-05T05:47:09+00:00"
"time": "2025-11-04T16:30:35+00:00"
},
{
"name": "staabm/side-effects-detector",
@@ -5048,16 +5085,16 @@
},
{
"name": "symfony/console",
"version": "v7.3.4",
"version": "v7.3.6",
"source": {
"type": "git",
"url": "https://github.com/symfony/console.git",
"reference": "2b9c5fafbac0399a20a2e82429e2bd735dcfb7db"
"reference": "c28ad91448f86c5f6d9d2c70f0cf68bf135f252a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/console/zipball/2b9c5fafbac0399a20a2e82429e2bd735dcfb7db",
"reference": "2b9c5fafbac0399a20a2e82429e2bd735dcfb7db",
"url": "https://api.github.com/repos/symfony/console/zipball/c28ad91448f86c5f6d9d2c70f0cf68bf135f252a",
"reference": "c28ad91448f86c5f6d9d2c70f0cf68bf135f252a",
"shasum": ""
},
"require": {
@@ -5122,7 +5159,7 @@
"terminal"
],
"support": {
"source": "https://github.com/symfony/console/tree/v7.3.4"
"source": "https://github.com/symfony/console/tree/v7.3.6"
},
"funding": [
{
@@ -5142,7 +5179,7 @@
"type": "tidelift"
}
],
"time": "2025-09-22T15:31:00+00:00"
"time": "2025-11-04T01:21:42+00:00"
},
{
"name": "symfony/polyfill-ctype",
@@ -5461,16 +5498,16 @@
},
{
"name": "symfony/service-contracts",
"version": "v3.6.0",
"version": "v3.6.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/service-contracts.git",
"reference": "f021b05a130d35510bd6b25fe9053c2a8a15d5d4"
"reference": "45112560a3ba2d715666a509a0bc9521d10b6c43"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/service-contracts/zipball/f021b05a130d35510bd6b25fe9053c2a8a15d5d4",
"reference": "f021b05a130d35510bd6b25fe9053c2a8a15d5d4",
"url": "https://api.github.com/repos/symfony/service-contracts/zipball/45112560a3ba2d715666a509a0bc9521d10b6c43",
"reference": "45112560a3ba2d715666a509a0bc9521d10b6c43",
"shasum": ""
},
"require": {
@@ -5524,7 +5561,7 @@
"standards"
],
"support": {
"source": "https://github.com/symfony/service-contracts/tree/v3.6.0"
"source": "https://github.com/symfony/service-contracts/tree/v3.6.1"
},
"funding": [
{
@@ -5535,12 +5572,16 @@
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2025-04-25T09:37:31+00:00"
"time": "2025-07-15T11:30:57+00:00"
},
{
"name": "symfony/string",

View File

@@ -60,8 +60,8 @@ return [
],
'kafka' => [
'brokers' => Env::get('QUEUE_KAFKA_BROKERS', 'localhost:9092'),
'topic' => Env::get('QUEUE_KAFKA_TOPIC', 'my_topic'),
'brokers' => Env::get('QUEUE_KAFKA_BROKERS', 'kafka:9092'),
'consumerGroup' => Env::get('QUEUE_KAFKA_CONSUMER_GROUP', 'default_group'),
],
'rabbitmq' => [

View File

@@ -68,6 +68,8 @@ services:
volumes:
- .:/app
build:
args:
KAFKA_ENABLED: "1"
context: .
dockerfile: Dockerfile
entrypoint: "/bin/sh -c 'while true; do sleep 30; done;'"
@@ -81,6 +83,7 @@ services:
postgres:
condition: service_healthy
environment:
QUEUE_BROKER: redis
PHP_IDE_CONFIG: serverName=localhost
WORKERS: 1
DEBUG: 1
@@ -88,6 +91,40 @@ services:
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:
image: redis:latest
healthcheck:

View File

@@ -6,16 +6,28 @@ namespace Siteworxpro\App\Annotations\Async;
use Attribute;
/**
* Attribute to mark a class as a handler for a specific message class in an async workflow.
*
* Repeatable: attach multiple times to handle multiple message classes.
*/
#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
readonly class HandlesMessage
{
/**
* Create a new HandlesMessage attribute.
*
* @param class-string $messageClass Fully-qualified class name of the message handled.
*/
public function __construct(
public string $messageClass,
) {
}
/**
* @return string
* Get the fully-qualified message class this handler processes.
*
* @return class-string
*/
public function getMessageClass(): string
{

View File

@@ -6,9 +6,22 @@ namespace Siteworxpro\App\Annotations\Events;
use Attribute;
/**
* Attribute to mark a class as an event listener for a specific event class.
*
* Apply this attribute to classes that subscribe to domain or application events.
* Repeatable: can be attached multiple times to the same class to listen for multiple events.
*
* Targets: class only.
*/
#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
readonly class ListensFor
{
/**
* Initialize the ListensFor attribute.
*
* @param class-string $eventClass Fully-qualified class name of the event to listen for.
*/
public function __construct(public string $eventClass)
{
}

View File

@@ -7,22 +7,47 @@ namespace Siteworxpro\App\Annotations\Guards;
use Attribute;
use Siteworxpro\App\Services\Facades\Config;
/**
* Attribute to guard classes or methods with JWT claim requirements.
*
* Apply this attribute to a class or method to declare the expected JWT issuer and/or audience.
* If either the issuer or audience is an empty string, the value will be resolved from configuration:
* - `jwt.issuer`
* - `jwt.audience`
*
* Targets: class or method.
*/
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
readonly class Jwt
{
/**
* Initialize the Jwt attribute with optional overrides for expected JWT claims.
*
* @param string $issuer Optional expected JWT issuer (`iss`). Empty string uses `Config::get('jwt.issuer')`.
* @param string $audience Optional expected JWT audience (`aud`). Empty string uses `Config::get('jwt.audience')`.
*/
public function __construct(
private string $issuer = '',
private string $audience = '',
) {
}
/**
* Get the required audience from configuration, ignoring any local override.
*
* @return string The globally configured audience or an empty string if not set.
*/
public function getRequiredAudience(): string
{
return Config::get('jwt.audience') ?? '';
}
/**
* @return string
* Get the expected audience for validation.
*
* Returns the constructor-provided audience when non-empty; otherwise falls back to `jwt.audience` config.
*
* @return string The audience value to enforce.
*/
public function getAudience(): string
{
@@ -33,6 +58,13 @@ readonly class Jwt
return $this->audience;
}
/**
* Get the expected issuer for validation.
*
* Returns the constructor-provided issuer when non-empty; otherwise falls back to `jwt.issuer` config.
*
* @return string The issuer value to enforce.
*/
public function getIssuer(): string
{
if ($this->issuer === '') {
@@ -41,4 +73,4 @@ readonly class Jwt
return $this->issuer;
}
}
}

View File

@@ -11,8 +11,8 @@ readonly class Scope
{
public function __construct(
private array $scopes = []
) {}
) {
}
public function getScopes(): array
{

View File

@@ -4,33 +4,91 @@ 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
{
public function publish(Queue $queue, Message $message, ?int $delay = null): void
private Producer $producer;
private KafkaConsumer $consumer;
public function __construct($config = [])
{
// TODO: Implement publish() method.
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 consume(Queue $queue): Message | null
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;
}
if ($kafkaMessage->err === RD_KAFKA_RESP_ERR_UNKNOWN_TOPIC_OR_PART) {
throw new \RuntimeException(
"Topic '{$queue->queueName()}' or partition does not exist. Kafka does not auto-create topics" .
" unless configured to do so."
);
}
/** @var string | null $messageData */
$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
{
// 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.
}
}

View File

@@ -5,72 +5,96 @@ declare(ticks=1);
namespace Siteworxpro\App\Async;
use Siteworxpro\App\Annotations\Async\HandlesMessage;
use Siteworxpro\App\Async\Messages\Message;
use Siteworxpro\App\Async\Queues\Queue;
use Siteworxpro\App\Services\Facades\Broker;
use Siteworxpro\App\Services\Facades\Logger;
/**
* Long-running process that listens to queues, pops messages, and dispatches them to handlers.
*/
class Consumer
{
private static bool $shutDown = false;
/** @var array<string,string> */
private const array QUEUES = [
Queues\DefaultQueue::class,
'default' => Queues\DefaultQueue::class,
];
/** @var Queue[] */
private array $queues = [];
/** @var array<string, string[]> message FQCN => handler FQCNs */
private array $handlers = [];
private const string HANDLER_NAMESPACE = 'Siteworxpro\\App\\Async\\Handlers\\';
public function __construct()
/**
* @param string[] $queues Optional list of queue names (keys from self::QUEUES)
*/
public function __construct(array $queues = [])
{
foreach (self::QUEUES as $queueClass) {
$this->queues[] = new $queueClass();
$queueClasses = $queues === []
? array_values(self::QUEUES)
: array_map(
static function (string $name): string {
if (!isset(self::QUEUES[$name])) {
throw new \InvalidArgumentException("Queue '$name' is not defined.");
}
return self::QUEUES[$name];
},
$queues
);
foreach ($queueClasses as $class) {
$this->queues[] = new $class();
}
$this->registerHandlers();
}
/**
* Discover handler classes under `Handlers` and register them via HandlesMessage attributes.
*/
private function registerHandlers(): void
{
$recursiveIterator = new \RecursiveIteratorIterator(
$it = 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));
/** @var \SplFileInfo $file */
foreach ($it as $file) {
if (!$file->isFile() || $file->getExtension() !== 'php') {
continue;
}
$relative = str_replace(__DIR__ . '/Handlers/', '', $file->getPathname());
$class = self::HANDLER_NAMESPACE . str_replace('/', '\\', substr($relative, 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;
}
}
if (!class_exists($class)) {
continue;
}
$ref = new \ReflectionClass($class);
foreach ($ref->getAttributes(HandlesMessage::class) as $attr) {
$messageClass = $attr->newInstance()->getMessageClass();
$this->handlers[$messageClass][] = $class;
}
}
}
/**
* @param $signal
* Signal handler used to initiate graceful or immediate shutdown.
*/
public static function handleSignal($signal): void
public static function handleSignal(int $signal): void
{
switch ($signal) {
// Graceful
case SIGINT:
case SIGTERM:
case SIGHUP:
self::$shutDown = true;
break;
// Not Graceful
return;
case SIGKILL:
exit(9);
}
@@ -81,6 +105,9 @@ class Consumer
return self::$shutDown;
}
/**
* Start the consumer main loop.
*/
public function start(): void
{
if (!\function_exists('pcntl_signal')) {
@@ -88,10 +115,11 @@ class Consumer
}
Logger::info('Starting queue consumer...');
Logger::info('Using Broker: ' . Broker::getFacadeRoot()::class);
\pcntl_signal(SIGINT, [self::class, 'handleSignal']);
\pcntl_signal(SIGTERM, [self::class, 'handleSignal']);
\pcntl_signal(SIGHUP, [self::class, 'handleSignal']);
foreach ([SIGINT, SIGTERM, SIGHUP] as $sig) {
\pcntl_signal($sig, [self::class, 'handleSignal']);
}
while (true) {
if ($this->shouldShutDown()) {
@@ -103,40 +131,43 @@ class Consumer
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);
}
if (!$message) {
continue;
}
Logger::info('Processing message of type: ' . get_class($message));
foreach ($this->getHandlersForMessage($message) as $handler) {
$handler($message);
}
// Continue polling from the top of the loop after processing a message.
continue 2;
}
// Avoid busy-looping when no messages are available.
sleep(1);
}
}
private function getHandlerForMessage($message): array
/**
* @return callable[] Handler instances invokable with the message
*/
private function getHandlersForMessage(Message $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;
if (!isset($this->handlers[$messageClass])) {
throw new \RuntimeException("No handler found for message class: $messageClass");
}
throw new \RuntimeException("No handler found for message class: $messageClass");
$callables = [];
foreach ($this->handlers[$messageClass] as $handlerClass) {
if (class_exists($handlerClass)) {
$callables[] = new $handlerClass();
}
}
return $callables;
}
}

View File

@@ -7,6 +7,7 @@ namespace Siteworxpro\App\Cli;
use Ahc\Cli\Application;
use Siteworxpro\App\Cli\Commands\DemoCommand;
use Siteworxpro\App\Cli\Commands\Queue\Start;
use Siteworxpro\App\Cli\Commands\Queue\TestJob;
use Siteworxpro\App\Kernel;
use Siteworxpro\App\Services\Facades\Config;
@@ -24,6 +25,7 @@ class App
$this->app->add(new DemoCommand());
$this->app->add(new Start());
$this->app->add(new TestJob());
}
public function run(): int

View File

@@ -6,6 +6,7 @@ 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
@@ -13,14 +14,17 @@ class Start extends Command implements CommandInterface
public function __construct()
{
parent::__construct('queue:start', 'Start the queue consumer to process messages.');
$this->argument('[name]', 'Your name')
->option('-g, --greet', 'Include a greeting message');
$this->argument('[queues]', 'The name of the queue to consume from. ex. "first_queue,second_queue"');
}
public function execute(): int
{
$consumer = new Consumer();
$queues = [];
if ($this->values()['queues'] !== null) {
$queues = explode(',', $this->values()['queues']);
}
$consumer = new Consumer($queues);
$consumer->start();
return 0;

View 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\Messages\SayHelloMessage;
use Siteworxpro\App\Cli\Commands\CommandInterface;
/**
* Class TestJob
*
* A CLI command to schedule a demo job that dispatches a SayHelloMessage.
*/
class TestJob extends Command implements CommandInterface
{
public function __construct()
{
parent::__construct('queue:demo', 'Schedule a demo job.');
}
/**
* Execute the command to dispatch a SayHelloMessage.
*
* @return int Exit code
*/
public function execute(): int
{
SayHelloMessage::dispatch('World from TestJob Command!');
return 0;
}
}

View File

@@ -8,6 +8,13 @@ use League\Route\Http\Exception\NotFoundException;
use Nyholm\Psr7\ServerRequest;
use Psr\Http\Message\ResponseInterface;
/**
* Class Controller
*
* An abstract base controller providing default implementations for HTTP methods.
*
* @package Siteworxpro\App\Controllers
*/
abstract class Controller implements ControllerInterface
{
/**

View File

@@ -7,6 +7,11 @@ namespace Siteworxpro\App\Controllers;
use Nyholm\Psr7\ServerRequest;
use Psr\Http\Message\ResponseInterface;
/**
* Interface ControllerInterface
*
* Defines the contract for handling HTTP requests in a controller.
*/
interface ControllerInterface
{
/**

View File

@@ -12,6 +12,13 @@ use Siteworxpro\App\Models\Model;
use Siteworxpro\App\Services\Facades\Redis;
use Siteworxpro\HttpStatus\CodesEnum;
/**
* Class HealthcheckController
*
* Handles health check requests to verify database and cache connectivity.
*
* @package Siteworxpro\App\Controllers
*/
class HealthcheckController extends Controller
{
/**

View File

@@ -10,6 +10,10 @@ use Siteworxpro\App\Annotations\Events\ListensFor;
use Siteworxpro\App\Events\Listeners\Listener;
use Siteworxpro\App\Services\Facades\Logger;
/**
* Class Connected
* @package Siteworxpro\App\Events\Listeners\Database
*/
#[ListensFor(ConnectionEstablished::class)]
class Connected extends Listener
{

View File

@@ -4,6 +4,11 @@ declare(strict_types=1);
namespace Siteworxpro\App\Events\Listeners;
/**
* Class Listener
*
* @package Siteworxpro\App\Events\Listeners
*/
abstract class Listener implements ListenerInterface
{
}

View File

@@ -4,7 +4,16 @@ declare(strict_types=1);
namespace Siteworxpro\App\Events\Listeners;
/**
* Interface ListenerInterface
* @package Siteworxpro\App\Events\Listeners
*/
interface ListenerInterface
{
/**
* @param mixed $event
* @param array $payload
* @return mixed
*/
public function __invoke(mixed $event, array $payload = []): mixed;
}

View File

@@ -4,6 +4,10 @@ declare(strict_types=1);
namespace Siteworxpro\App\Helpers;
/**
* Class Env
* @package Siteworxpro\App\Helpers
*/
abstract class Env
{
/**

View File

@@ -4,8 +4,17 @@ declare(strict_types=1);
namespace Siteworxpro\App\Helpers;
/**
* Class Ulid
* @package Siteworxpro\App\Helpers
*/
class Ulid
{
/**
* Generate a ULID string
*
* @return string
*/
public static function generate(): string
{
return \Ulid\Ulid::generate()->getRandomness();

View File

@@ -27,18 +27,44 @@ use Siteworxpro\App\Http\JsonResponseFactory;
use Siteworxpro\App\Services\Facades\Config;
use Siteworxpro\HttpStatus\CodesEnum;
/**
* JWT authorization middleware.
*
* Applies JWT validation to controller actions annotated with `Jwt` attribute.
* Flow:
* - Resolve the targeted controller and method for the current route.
* - If the method has `Jwt`, read the `Authorization` header and parse the Bearer token.
* - Validate signature, time constraints, issuer\(\) and audience\(\) based on attribute and config.
* - On success, attach all token claims to the request as attributes.
* - On failure, return a 401 JSON response with validation errors.
*
* Configuration:
* - `jwt.signing_key`: key material or `file://` path to key.
* - `jwt.strict_validation`: bool toggling strict vs loose time validation.
*/
class JwtMiddleware extends Middleware
{
/**
* @throws \JsonException
* @throws \Exception
* Process the incoming request.
*
* If the matched controller method is annotated with `Jwt`, validates the token and
* augments the request with claims on success. Otherwise, just delegates to the next handler.
*
* @param ServerRequestInterface $request PSR-7 request instance.
* @param RequestHandlerInterface|Dispatcher $handler Next middleware or route dispatcher.
*
* @return ResponseInterface Response produced by the next handler or a 401 JSON response.
*
* @throws \JsonException On JSON error response encoding issues.
* @throws \Exception On unexpected reflection or JWT parsing issues.
*/
public function process(
ServerRequestInterface $request,
RequestHandlerInterface|Dispatcher $handler
): ResponseInterface {
$callable = $this->extractRouteCallable($request, $handler);
// Resolve the callable \[Controller, method] for the current route.
$callable = $this->extractRouteCallable($handler);
if ($callable === null) {
return $handler->handle($request);
}
@@ -51,12 +77,15 @@ class JwtMiddleware extends Middleware
if ($reflectionClass->hasMethod($method)) {
$reflectionMethod = $reflectionClass->getMethod($method);
// Read `Jwt` attribute on the controller method.
$attributes = $reflectionMethod->getAttributes(Jwt::class);
// If no `Jwt` attribute, do not enforce auth here.
if (empty($attributes)) {
return $handler->handle($request);
}
// Extract Bearer token from Authorization header.
$token = str_replace('Bearer ', '', $request->getHeaderLine('Authorization'));
if (empty($token)) {
@@ -66,6 +95,7 @@ class JwtMiddleware extends Middleware
], CodesEnum::UNAUTHORIZED);
}
// Aggregate required issuers and audience from attributes.
$requiredIssuers = [];
$requiredAudience = '';
@@ -81,6 +111,7 @@ class JwtMiddleware extends Middleware
}
try {
// Parse and validate the token with signature, time, issuer and audience constraints.
$jwt = new JwtFacade()->parse(
$token,
$this->getSignedWith(),
@@ -91,6 +122,7 @@ class JwtMiddleware extends Middleware
new PermittedFor($requiredAudience)
);
} catch (RequiredConstraintsViolated $exception) {
// Collect human-readable violations to return to the client.
$violations = [];
foreach ($exception->violations() as $violation) {
$violations[] = $violation->getMessage();
@@ -102,12 +134,14 @@ class JwtMiddleware extends Middleware
'errors' => $violations
], CodesEnum::UNAUTHORIZED);
} catch (InvalidTokenStructure) {
// Token could not be parsed due to malformed structure.
return JsonResponseFactory::createJsonResponse([
'status_code' => 401,
'message' => 'Unauthorized: Invalid token',
], CodesEnum::UNAUTHORIZED);
}
// Expose all token claims as request attributes for downstream consumers.
foreach ($jwt->claims()->all() as $item => $value) {
$request = $request->withAttribute($item, $value);
}
@@ -117,6 +151,17 @@ class JwtMiddleware extends Middleware
return $handler->handle($request);
}
/**
* Build the signature validation constraint from configured key.
*
* - If the configured key content includes the string `PUBLIC KEY`, use RSA SHA-256.
* - Otherwise assume an HMAC SHA-256 shared secret.
* - Supports raw key strings or `file://` paths.
*
* @return SignedWith Signature constraint used during JWT parsing.
*
* @throws \RuntimeException When no signing key is configured.
*/
private function getSignedWith(): SignedWith
{
$key = Config::get('jwt.signing_key');
@@ -125,12 +170,14 @@ class JwtMiddleware extends Middleware
throw new \RuntimeException('JWT signing key is not configured.');
}
// Load key either from file or raw text.
if (str_starts_with($key, 'file://')) {
$key = InMemory::file(substr($key, 7));
} else {
$key = InMemory::plainText($key);
}
// Heuristic: if PEM public key content is detected, use RSA; otherwise use HMAC.
if (str_contains($key->contents(), 'PUBLIC KEY')) {
return new SignedWith(new Sha256(), $key);
}

View File

@@ -9,30 +9,60 @@ use League\Route\Route;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Base middleware helper for extracting route callables.
*
* This abstract middleware provides a utility method to inspect a League\Route
* dispatcher and obtain the underlying route callable as a [class, method] tuple.
*
* @package Siteworxpro\App\Http\Middleware
*/
abstract class Middleware implements MiddlewareInterface
{
protected function extractRouteCallable($request, RequestHandlerInterface | Dispatcher $handler): array|null
{
/**
* Extract the route callable [class, method] from a League\Route dispatcher.
*
* When the provided handler is a League\Route\Dispatcher, this inspects its
* middleware stack, looks at the last segment (the resolved Route), and
* attempts to normalize its callable into a [class, method] pair.
*
* Supported callable forms:
* - array callable: [object|class-string, method-string]
* - string callable: "ClassName::methodName"
*
* Returns null when the handler is not a Dispatcher, the stack is empty,
* or the callable cannot be parsed.
*
* @param RequestHandlerInterface|Dispatcher $handler The downstream handler or dispatcher.
*
* @return array{0: class-string|object|null, 1: string|null}|null Tuple of [class|object, method] or null.
*/
protected function extractRouteCallable(
RequestHandlerInterface|Dispatcher $handler
): array|null {
// Only proceed if this is a League\Route dispatcher.
if (!$handler instanceof Dispatcher) {
return null;
}
/** @var Route | null $lastSegment */
// Retrieve the last middleware in the stack, which should be the Route.
$lastSegment = array_last($handler->getMiddlewareStack());
if ($lastSegment === null) {
return null;
}
// Obtain the callable associated with the route.
$callable = $lastSegment->getCallable();
$class = null;
$method = null;
// Handle array callable: [object|class-string, 'method']
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')
// Handle string callable: 'ClassName::methodName'
[$class, $method] = explode('::', $callable);
}

View File

@@ -13,36 +13,65 @@ use Siteworxpro\App\Controllers\Controller;
use Siteworxpro\App\Http\JsonResponseFactory;
use Siteworxpro\HttpStatus\CodesEnum;
/**
* Middleware that enforces scope-based access control on controller actions.
*
* It inspects PHP 8 attributes of type \`Scope\` applied to the resolved controller method,
* compares the required scopes with the user scopes provided on the request attribute \`scopes\`,
* and returns a 403 JSON response when any required scope is missing.
*
* If the route callable cannot be resolved, or no scope is required, the request is passed through.
*
* @see Scope
*/
class ScopeMiddleware extends Middleware
{
/**
* @throws \JsonException
* Resolve the route callable, read any \`Scope\` attributes, and enforce required scopes.
*
* Expected user scopes are provided on the request under the attribute name \`scopes\`
* as an array of strings.
*
* @param ServerRequestInterface $request Incoming PSR-7 request (expects \`scopes\` attribute).
* @param RequestHandlerInterface|Dispatcher $handler Next handler or League\Route dispatcher.
*
* @return ResponseInterface A 403 JSON response when scopes are insufficient; otherwise the handler response.
*
* @throws \JsonException If encoding the JSON error response fails.
* @throws \ReflectionException If reflection on the controller or method fails.
*/
public function process(
ServerRequestInterface $request,
RequestHandlerInterface | Dispatcher $handler
): ResponseInterface {
$callable = $this->extractRouteCallable($request, $handler);
// Attempt to resolve the route's callable [Controller instance, method name].
$callable = $this->extractRouteCallable($handler);
if ($callable === null) {
// If no callable is available, delegate to the next handler.
return $handler->handle($request);
}
/** @var Controller $class */
/** @var Controller $class Controller instance resolved from the route. */
[$class, $method] = $callable;
// Ensure the controller exists and the method is defined before reflecting.
if (class_exists($class::class)) {
$reflectionClass = new \ReflectionClass($class);
if ($reflectionClass->hasMethod($method)) {
$reflectionMethod = $reflectionClass->getMethod($method);
// Fetch all Scope attributes declared on the method.
$attributes = $reflectionMethod->getAttributes(Scope::class);
foreach ($attributes as $attribute) {
/** @var Scope $scopeInstance */
/** @var Scope $scopeInstance Concrete Scope attribute instance. */
$scopeInstance = $attribute->newInstance();
$requiredScopes = $scopeInstance->getScopes();
// Retrieve user scopes from the request (defaults to an empty array).
$userScopes = $request->getAttribute('scopes', []);
// Deny if any required scope is missing from the user's scopes.
if (
array_any(
$requiredScopes,
@@ -59,6 +88,7 @@ class ScopeMiddleware extends Middleware
}
}
// All checks passed; continue down the middleware pipeline.
return $handler->handle($request);
}
}

View File

@@ -14,8 +14,21 @@ use Siteworxpro\App\Services\ServiceProviders\DispatcherServiceProvider;
use Siteworxpro\App\Services\ServiceProviders\LoggerServiceProvider;
use Siteworxpro\App\Services\ServiceProviders\RedisServiceProvider;
/**
* Class Kernel
*
* The Kernel class is responsible for bootstrapping the application by
* initializing service providers and setting up the database connection.
*
* @package Siteworxpro\App
*/
class Kernel
{
/**
* List of service providers to be registered during bootstrapping.
*
* @var array
*/
private static array $serviceProviders = [
LoggerServiceProvider::class,
RedisServiceProvider::class,

View File

@@ -6,17 +6,51 @@ namespace Siteworxpro\App\Log;
use Monolog\Formatter\JsonFormatter;
use Monolog\Handler\StreamHandler;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use RoadRunner\Logger\Logger as RRLogger;
use Spiral\Goridge\RPC\RPC;
use Siteworxpro\App\Services\Facades\RoadRunnerLogger;
/**
* Logger implementation that conforms to PSR-3 (`Psr\Log\LoggerInterface`).
*
* Behavior:
* - If environment indicates RoadRunner RPC (`$_SERVER['RR_RPC']`), logs are forwarded
* to a RoadRunner RPC logger (`RoadRunner\Logger\Logger`) created via Goridge RPC.
* - Otherwise, logs are written to `php://stdout` using Monolog with a JSON formatter.
* - Messages below the configured threshold are ignored (level filtering).
*
* Supported PSR-3 levels are mapped to an internal numeric ordering in `$levels`.
* When using the RPC logger, levels are translated to the respective RPC methods
* (debug, info, warning, error). When using Monolog, the numeric mapping is used
* as the numeric level passed to Monolog's `log` method.
*/
class Logger implements LoggerInterface
{
private ?RRLogger $rpcLogger = null;
/**
* RoadRunner RPC logger instance when running under RoadRunner.
*
* @var RRLogger | LoggerInterface | null
*/
private RRLogger | LoggerInterface | null $rpcLogger = null;
/**
* Monolog logger used as a fallback to write JSON-formatted logs to stdout.
*
* @var \Monolog\Logger
*/
private \Monolog\Logger $monologLogger;
/**
* Numeric ordering for PSR-3 log levels.
*
* Lower numbers represent higher severity. This mapping is used for filtering
* messages according to the configured minimum level and for Monolog numeric level.
*
* @var array<string,int>
*/
private array $levels = [
LogLevel::EMERGENCY => 0,
LogLevel::ALERT => 1,
@@ -28,61 +62,146 @@ class Logger implements LoggerInterface
LogLevel::DEBUG => 7,
];
public function __construct(private readonly string $level = LogLevel::DEBUG)
{
/**
* Create a new Logger.
*
* @param string $level Minimum level to log (PSR-3 level string). Messages with
* a higher numeric value in `$levels` will be ignored.
*
* @param resource | null $streamOutput Optional stream handler for Monolog.
*
* The default is `LogLevel::DEBUG` (log everything).
*
* If `$_SERVER['RR_RPC']` is set, an RPC connection will be attempted at
* $_SERVER['RR_RPC'] and a RoadRunner RPC logger will be used.
*
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function __construct(
private readonly string $level = LogLevel::DEBUG,
$streamOutput = null,
) {
if (isset($_SERVER['RR_RPC'])) {
$rpc = RPC::create('tcp://127.0.0.1:6001');
$this->rpcLogger = new RRLogger($rpc);
$this->rpcLogger = RoadRunnerLogger::getFacadeRoot();
}
$this->monologLogger = new \Monolog\Logger('app_logger');
$formatter = new JsonFormatter();
$this->monologLogger->pushHandler(new StreamHandler('php://stdout')->setFormatter($formatter));
$stream = $streamOutput ?? 'php://stdout';
$this->monologLogger->pushHandler(new StreamHandler($stream)->setFormatter($formatter));
}
/**
* System is unusable.
*
* @param \Stringable|string $message
* @param array $context
*/
public function emergency(\Stringable|string $message, array $context = []): void
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
/**
* Action must be taken immediately.
*
* @param \Stringable|string $message
* @param array $context
*/
public function alert(\Stringable|string $message, array $context = []): void
{
$this->log(LogLevel::ALERT, $message, $context);
}
/**
* Critical conditions.
*
* @param \Stringable|string $message
* @param array $context
*/
public function critical(\Stringable|string $message, array $context = []): void
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
/**
* Runtime errors that do not require immediate action but should typically be logged and monitored.
*
* @param \Stringable|string $message
* @param array $context
*/
public function error(\Stringable|string $message, array $context = []): void
{
$this->log(LogLevel::ERROR, $message, $context);
}
/**
* Exceptional occurrences that are not errors.
*
* @param \Stringable|string $message
* @param array $context
*/
public function warning(\Stringable|string $message, array $context = []): void
{
$this->log(LogLevel::WARNING, $message, $context);
}
/**
* Normal but significant events.
*
* @param \Stringable|string $message
* @param array $context
*/
public function notice(\Stringable|string $message, array $context = []): void
{
$this->log(LogLevel::NOTICE, $message, $context);
}
/**
* Interesting events.
*
* @param \Stringable|string $message
* @param array $context
*/
public function info(\Stringable|string $message, array $context = []): void
{
$this->log(LogLevel::INFO, $message, $context);
}
/**
* Detailed debug information.
*
* @param \Stringable|string $message
* @param array $context
*/
public function debug(\Stringable|string $message, array $context = []): void
{
$this->log(LogLevel::DEBUG, $message, $context);
}
/**
* Logs with an arbitrary level.
*
* Behavior details:
* - If the provided `$level` maps to a numeric value greater than the configured
* minimum level, the message is discarded (filtered).
* - If an RPC logger is available, the message is forwarded to the RPC logger
* using a method chosen by level (debug, info, warning, error).
* - Otherwise, the message is written to Monolog using the numeric mapping.
*
* Notes:
* - `$level` should be a PSR-3 level string (values defined in `Psr\Log\LogLevel`).
* - If an unknown level string is passed, accessing `$this->levels[$level]` may
* trigger a PHP notice or undefined index. Ensure callers use valid PSR-3 levels.
*
* @param mixed $level PSR-3 log level (string)
* @param \Stringable|string $message
* @param array $context
*/
public function log($level, \Stringable|string $message, array $context = []): void
{
if ($this->levels[$level] > $this->levels[$this->level]) {
if (isset($this->levels[$level]) && $this->levels[$level] > $this->levels[$this->level]) {
return;
}
@@ -105,7 +224,7 @@ class Logger implements LoggerInterface
$this->rpcLogger->error((string)$message, $context);
break;
default:
$this->rpcLogger->log((string)$message, $context);
$this->rpcLogger->log($level, (string)$message, $context);
break;
}

View File

@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Siteworxpro\App\Services;
use Illuminate\Contracts\Container\Container;
use Illuminate\Support\HigherOrderTapProxy;
use Illuminate\Support\Testing\Fakes\Fake;
use Mockery;
use Mockery\Expectation;
@@ -57,9 +58,9 @@ class Facade
/**
* Convert the facade into a Mockery spy.
*
* @return MockInterface
* @return HigherOrderTapProxy | MockInterface
*/
public static function spy(): MockInterface
public static function spy(): HigherOrderTapProxy | MockInterface
{
if (! static::isMock()) {
$class = static::getMockableClass();

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Siteworxpro\App\Services\Facades;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use RoadRunner\Logger\Logger;
use Siteworxpro\App\Services\Facade;
use Spiral\Goridge\RPC\RPC;
class RoadRunnerLogger extends Facade
{
/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public static function getFacadeRoot(): mixed
{
$container = static::getFacadeContainer();
if ($container && $container->has(Logger::class) === false) {
$rpc = RPC::create($_SERVER['RR_RPC']);
$logger = new Logger($rpc);
$container->bind(static::getFacadeAccessor(), function () use ($logger) {
return $logger;
});
return $logger;
}
return $container->get(Logger::class);
}
protected static function getFacadeAccessor(): string
{
return Logger::class;
}
}

View File

@@ -8,13 +8,30 @@ use Illuminate\Support\ServiceProvider;
use Siteworxpro\App\Async\Brokers\Broker;
use Siteworxpro\App\Services\Facades\Config;
/**
* Class BrokerServiceProvider
*
* This service provider is responsible for binding the Broker implementation
* to the Laravel service container based on configuration settings.
*
* @package Siteworxpro\App\Services\ServiceProviders
*/
class BrokerServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* This method binds the Broker interface to a specific implementation
* based on the configuration defined in 'queue.broker' and 'queue.broker_config'.
*
* @return void
* @throws \RuntimeException if the specified broker class does not exist.
*/
public function register(): void
{
$this->app->singleton(Broker::class, function (): Broker {
$configName = Config::get('queue.broker');
$brokerConfig = Config::get('queue.' . $configName) ?? [];
$brokerConfig = Config::get('queue.broker_config.' . $configName) ?? [];
$brokerClass = Broker::BROKER_TYPES[$configName] ?? null;

View File

@@ -7,6 +7,11 @@ namespace Siteworxpro\App\Services\ServiceProviders;
use Illuminate\Support\ServiceProvider;
use Siteworxpro\App\Events\Dispatcher;
/**
* Class DispatcherServiceProvider
*
* @package Siteworxpro\App\Services\ServiceProviders
*/
class DispatcherServiceProvider extends ServiceProvider
{
public function register(): void

View File

@@ -7,6 +7,11 @@ namespace Siteworxpro\App\Services\ServiceProviders;
use Illuminate\Support\ServiceProvider;
use Siteworxpro\App\Log\Logger;
/**
* Class LoggerServiceProvider
*
* @package Siteworxpro\App\Services\ServiceProviders
*/
class LoggerServiceProvider extends ServiceProvider
{
public function register(): void

View File

@@ -8,6 +8,13 @@ use Illuminate\Support\ServiceProvider;
use Predis\Client;
use Siteworxpro\App\Services\Facades\Config;
/**
* Class RedisServiceProvider
*
* This service provider registers a Redis client as a singleton in the application container.
*
* @package Siteworxpro\App\Services\ServiceProviders
*/
class RedisServiceProvider extends ServiceProvider
{
public function register(): void

View File

@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Siteworxpro\Tests\Facades;
use Siteworxpro\App\Services\Facades\Dispatcher;
class DispatcherTest extends AbstractFacade
{
protected function getFacadeClass(): string
{
return Dispatcher::class;
}
protected function getConcrete(): string
{
return \Siteworxpro\App\Events\Dispatcher::class;
}
}

View File

@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Siteworxpro\Tests\Facades;
use Siteworxpro\App\Services\Facades\Logger;
class LoggerTest extends AbstractFacade
{
protected function getFacadeClass(): string
{
return Logger::class;
}
protected function getConcrete(): string
{
return \Siteworxpro\App\Log\Logger::class;
}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Siteworxpro\Tests\Helpers;
use Siteworxpro\App\Helpers\Env;
use Siteworxpro\App\Helpers\Ulid;
use Siteworxpro\Tests\Unit;
class UlidTest extends Unit
{
public function testGetString(): void
{
$ulid = Ulid::generate();
$this->assertIsString($ulid);
$this->assertEquals(16, strlen($ulid));
}
}

167
tests/Log/LoggerRpcTest.php Normal file
View File

@@ -0,0 +1,167 @@
<?php
declare(strict_types=1);
namespace Siteworxpro\Tests\Log;
use Mockery;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Siteworxpro\App\Log\Logger;
use Siteworxpro\Tests\Unit;
class LoggerRpcTest extends Unit
{
protected function tearDown(): void
{
parent::tearDown();
unset($_SERVER['RR_RPC']);
}
/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws \Throwable
*/
public function testLogsDebugMessageWhenLevelIsDebug(): void
{
$this->expectNotToPerformAssertions();
$_SERVER['RR_RPC'] = 'tcp://127.0.0.1:6001';
$mock = Mockery::mock(LoggerInterface::class);
$mock->expects('debug')
->with('message', ['key' => 'value'])
->once();
\Siteworxpro\App\Services\Facades\Logger::getFacadeContainer()
->bind(\RoadRunner\Logger\Logger::class, function () use ($mock) {
return $mock;
});
$inputBuffer = fopen('php://memory', 'r+');
$logger = new Logger(LogLevel::DEBUG, $inputBuffer);
$logger->debug('message', ['key' => 'value']);
$mock->shouldHaveReceived('debug');
Mockery::close();
}
/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function testLogsDebugMessageWhenLevelIsInfoNotice(): void
{
$this->expectNotToPerformAssertions();
$_SERVER['RR_RPC'] = 'tcp://127.0.0.1:6001';
$mock = Mockery::mock(LoggerInterface::class);
$mock->expects('info')
->with('message', ['key' => 'value'])
->times(2);
\Siteworxpro\App\Services\Facades\Logger::getFacadeContainer()
->bind(\RoadRunner\Logger\Logger::class, function () use ($mock) {
return $mock;
});
$inputBuffer = fopen('php://memory', 'r+');
$logger = new Logger(LogLevel::DEBUG, $inputBuffer);
$logger->info('message', ['key' => 'value']);
$logger->notice('message', ['key' => 'value']);
$mock->shouldHaveReceived('info')->times(2);
Mockery::close();
}
/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function testLogsDebugMessageWhenLevelIsInfoWarning(): void
{
$this->expectNotToPerformAssertions();
$_SERVER['RR_RPC'] = 'tcp://127.0.0.1:6001';
$mock = Mockery::mock(LoggerInterface::class);
$mock->expects('warning')
->with('message', ['key' => 'value'])
->times(1);
\Siteworxpro\App\Services\Facades\Logger::getFacadeContainer()
->bind(\RoadRunner\Logger\Logger::class, function () use ($mock) {
return $mock;
});
$inputBuffer = fopen('php://memory', 'r+');
$logger = new Logger(LogLevel::DEBUG, $inputBuffer);
$logger->warning('message', ['key' => 'value']);
$mock->shouldHaveReceived('warning');
Mockery::close();
}
/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function testLogsDebugMessageWhenLevelIsInfoError(): void
{
$this->expectNotToPerformAssertions();
$_SERVER['RR_RPC'] = 'tcp://127.0.0.1:6001';
$mock = Mockery::mock(LoggerInterface::class);
$mock->expects('error')
->with('message', ['key' => 'value'])
->times(4);
\Siteworxpro\App\Services\Facades\Logger::getFacadeContainer()
->bind(\RoadRunner\Logger\Logger::class, function () use ($mock) {
return $mock;
});
$inputBuffer = fopen('php://memory', 'r+');
$logger = new Logger(LogLevel::DEBUG, $inputBuffer);
$logger->error('message', ['key' => 'value']);
$logger->critical('message', ['key' => 'value']);
$logger->alert('message', ['key' => 'value']);
$logger->emergency('message', ['key' => 'value']);
$mock->shouldHaveReceived('error')->times(4);
Mockery::close();
}
/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function testLogsLog(): void
{
$this->expectNotToPerformAssertions();
$_SERVER['RR_RPC'] = 'tcp://127.0.0.1:6001';
$mock = Mockery::mock(LoggerInterface::class);
$mock->expects('log')
->with('notaloglevel', 'message', ['key' => 'value']);
\Siteworxpro\App\Services\Facades\Logger::getFacadeContainer()
->bind(\RoadRunner\Logger\Logger::class, function () use ($mock) {
return $mock;
});
$inputBuffer = fopen('php://memory', 'r+');
$logger = new Logger(LogLevel::DEBUG, $inputBuffer);
$logger->log('notaloglevel', 'message', ['key' => 'value']);
$mock->shouldHaveReceived('log')->times(1);
Mockery::close();
}
}

155
tests/Log/LoggerTest.php Normal file
View File

@@ -0,0 +1,155 @@
<?php
declare(strict_types=1);
namespace Siteworxpro\Tests\Log;
use Psr\Log\LogLevel;
use Siteworxpro\App\Log\Logger;
use Siteworxpro\Tests\Unit;
class LoggerTest extends Unit
{
private function getLoggerWithBuffer(string $logLevel): array
{
$inputBuffer = fopen('php://memory', 'r+');
return [new Logger($logLevel, $inputBuffer), $inputBuffer];
}
private function getContents($inputBuffer): string
{
return stream_get_contents($inputBuffer, -1, 0);
}
private function testLogLevel(string $level): void
{
[$logger, $inputBuffer] = $this->getLoggerWithBuffer($level);
$logger->$level('message', ['key' => 'value']);
$output = $this->getContents($inputBuffer);
$this->assertNotEmpty($output);
$decoded = json_decode($output, true);
$this->assertEquals('message', $decoded['message']);
$this->assertEquals('value', $decoded['context']['key']);
}
private function testLogLevelEmpty(string $configLevel, string $logLevel): void
{
[$logger, $inputBuffer] = $this->getLoggerWithBuffer($configLevel);
$logger->$logLevel('message', ['key' => 'value']);
$output = $this->getContents($inputBuffer);
$this->assertEmpty($output);
}
public function testLogsDebugMessageWhenLevelIsDebug(): void
{
$this->testLogLevel(LogLevel::DEBUG);
}
public function testLogsInfoMessageWhenLevelIsInfo(): void
{
$this->testLogLevel(LogLevel::INFO);
}
public function testLogsWarningMessageWhenLevelIsWarning(): void
{
$this->testLogLevel(LogLevel::WARNING);
}
public function testLogsErrorMessageWhenLevelIsError(): void
{
$this->testLogLevel(LogLevel::ERROR);
}
public function testLogsCriticalMessageWhenLevelIsCritical(): void
{
$this->testLogLevel(LogLevel::CRITICAL);
}
public function testLogsAlertMessageWhenLevelIsAlert(): void
{
$this->testLogLevel(LogLevel::ALERT);
}
public function testLogsEmergencyMessageWhenLevelIsEmergency(): void
{
$this->testLogLevel(LogLevel::EMERGENCY);
}
public function testLogsNoticeMessageWhenLevelIsNotice(): void
{
$this->testLogLevel(LogLevel::NOTICE);
}
public function testDoesNotLogWhenMinimumLevelIsInfo(): void
{
$this->testLogLevelEmpty(LogLevel::INFO, LogLevel::DEBUG);
}
public function testDoesNotLogWhenMinimumLevelIsWarning(): void
{
$this->testLogLevelEmpty(LogLevel::WARNING, LogLevel::INFO);
$this->testLogLevelEmpty(LogLevel::WARNING, LogLevel::DEBUG);
}
public function testDoesNotLogWhenMinimumLevelIsError(): void
{
$this->testLogLevelEmpty(LogLevel::ERROR, LogLevel::DEBUG);
$this->testLogLevelEmpty(LogLevel::ERROR, LogLevel::INFO);
$this->testLogLevelEmpty(LogLevel::ERROR, LogLevel::WARNING);
}
public function testDoesNotLogWhenMinimumLevelIsNotice(): void
{
$this->testLogLevelEmpty(LogLevel::NOTICE, LogLevel::DEBUG);
$this->testLogLevelEmpty(LogLevel::NOTICE, LogLevel::INFO);
}
public function testLogsMessageWithEmptyContext(): void
{
[$logger, $buffer] = $this->getLoggerWithBuffer(LogLevel::INFO);
$logger->info('Message without context');
$output = $this->getContents($buffer);
$this->assertNotEmpty($output);
$decoded = json_decode($output, true);
$this->assertEquals('Message without context', $decoded['message']);
}
public function testLogsMessageWithComplexContext(): void
{
[$logger, $buffer] = $this->getLoggerWithBuffer(LogLevel::INFO);
$logger->info('Complex context', [
'user_id' => 123,
'nested' => ['key' => 'value'],
'array' => [1, 2, 3]
]);
$output = $this->getContents($buffer);
$this->assertNotEmpty($output);
$decoded = json_decode($output, true);
$this->assertEquals(123, $decoded['context']['user_id']);
$this->assertEquals('value', $decoded['context']['nested']['key']);
}
public function testLogsStringableMessage(): void
{
[$logger, $buffer] = $this->getLoggerWithBuffer(LogLevel::INFO);
$stringable = new class implements \Stringable {
public function __toString(): string
{
return 'Stringable message';
}
};
$logger->info($stringable);
$output = $this->getContents($buffer);
$this->assertNotEmpty($output);
$decoded = json_decode($output, true);
$this->assertEquals('Stringable message', $decoded['message']);
}
}