Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,24 @@ jobs:

- name: Run blackbox tests
run: test/run-blackbox-tests.sh

php-cs-fixer:
runs-on: ubuntu-latest
name: PHP-CS-Fixer

steps:
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.5
tools: composer:v2

- name: Checkout
uses: actions/checkout@v4
with:
show-progress: false

- run: composer install

- name: PHP-CS-Fixer
run: vendor/bin/php-cs-fixer check --diff
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ Thumbs.db
thumbs.db
/composer.lock
.phpunit.cache
.php-cs-fixer.cache
34 changes: 34 additions & 0 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

use PhpCsFixer\Config;
use PhpCsFixer\Finder;
use PhpCsFixer\Runner\Parallel\ParallelConfigFactory;

$finder = new Finder()
->in(__DIR__)
->exclude([
'vendor',
'test/blackbox/implementation/htdocs/dynamic',
])
;

return new Config()
->setParallelConfig(ParallelConfigFactory::detect())
->setRules([
'@Symfony' => true,
'concat_space' => false, // override Symfony
'global_namespace_import' => [ // override Symfony
'import_classes' => true,
'import_constants' => true,
'import_functions' => true,
],
'phpdoc_align' => false, // override Symfony
'single_line_throw' => false, // override Symfony
'yoda_style' => false, // override Symfony
'phpdoc_to_comment' => [ // Keep as a phpdoc if it contains the `@var` annotation
'ignored_tags' => ['var'],
],
])
->setFinder($finder);
21 changes: 20 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
"type": "library",
"require": {
"php": "~8.5.0",
"guzzlehttp/psr7": "^2.7 | ^3.2",
"ingenerator/php-utils": "^3.0",
"guzzlehttp/psr7": "^2.7 | ^3.2"
"php-cs-fixer/shim": "^3.95"
},
"require-dev": {
"fig/log-test": "^1.1",
"guzzlehttp/guzzle": "^7.9.1 | ^8.3",
"phpstan/phpstan": "^2.3",
"phpunit/phpunit": "^13.4",
"rector/rector": "2.8.4",
"symfony/filesystem": "^8.1"
Expand Down Expand Up @@ -39,5 +41,22 @@
"config": {
"preferred-install": "dist",
"sort-packages": true
},
"scripts": {
"precommit": [
"@test:unit",
"@test:integration",
"@phpstan",
"@rector:fix",
"@cs:fix"
],
"test:unit": "vendor/bin/phpunit --testsuite unit",
"test:integration": "vendor/bin/phpunit --testsuite integration",
"test:blackbox": "test/run-blackbox-tests.sh",
"phpstan": "vendor/bin/phpstan analyse",
"rector": "vendor/bin/rector process --dry-run",
"rector:fix": "vendor/bin/rector process",
"cs": "vendor/bin/php-cs-fixer check --diff",
"cs:fix": "vendor/bin/php-cs-fixer fix"
}
}
1 change: 1 addition & 0 deletions rector.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@
->withRootFiles()
->withSkipPath(__DIR__.'/test/blackbox/implementation/htdocs/dynamic')
->withComposerBased(phpunit: true)
->withPhpSets()
->withImportNames();
4 changes: 1 addition & 3 deletions src/DefaultStackdriverLoggerProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,16 @@

class DefaultStackdriverLoggerProvider implements LoggerProvider
{

public function __construct(
protected readonly string $service_name,
protected readonly string $version_file_path,
protected readonly string $log_destination = 'php://stdout',
) {

}

public function getLogger(): LoggerInterface
{
if ( ! StackdriverApplicationLogger::isInitialised()) {
if (!StackdriverApplicationLogger::isInitialised()) {
StackdriverApplicationLogger::initialise(
fn () => new StackdriverApplicationLogger(
$this->log_destination,
Expand Down
10 changes: 5 additions & 5 deletions src/FactoryFunction.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@

class FactoryFunction
{

/**
* Wraps a callable to ensure that it returns an instance of an expected type
* Wraps a callable to ensure that it returns an instance of an expected type.
*
* So for example:
*
Expand All @@ -20,19 +19,20 @@ class FactoryFunction
* $stdclass = FactoryFunction::call(fn() => new DateTimeImmutable, stdClass::class)
*
* @psalm-template T
*
* @psalm-param callable():T $callable
* @psalm-param class-string<T> $expect_class
* @psalm-param array $arguments that will be passed to the function
* @psalm-return T
*
* @psalm-return T
*/
public static function call(callable $factory, string $expect_class, array $arguments = []): object
{
$object = $factory(...$arguments);

if ( ! $object instanceof $expect_class) {
if (!$object instanceof $expect_class) {
throw new UnexpectedValueException(
sprintf("Factory for %s incorrectly returned %s", $expect_class, get_debug_type($object))
sprintf('Factory for %s incorrectly returned %s', $expect_class, get_debug_type($object))
);
}

Expand Down
6 changes: 2 additions & 4 deletions src/LoggerProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use Psr\Log\LoggerInterface;

/**
* The LoggerProvider is responsible for providing a suitable PSR Logger and a compatible RequestLogger
* The LoggerProvider is responsible for providing a suitable PSR Logger and a compatible RequestLogger.
*
* It should be essentially impossible for these services to produce runtime errors under any
* conditions. If they could produce errors, these must be handled & ideally logged internally.
Expand All @@ -15,9 +15,7 @@
interface LoggerProvider
{
/**
* Get a usable LoggerInterface - either by creating, or e.g. accessing from a DI container / singleton / factory etc
*
* @return LoggerInterface
* Get a usable LoggerInterface - either by creating, or e.g. accessing from a DI container / singleton / factory etc.
*/
public function getLogger(): LoggerInterface;

Expand Down
34 changes: 17 additions & 17 deletions src/MicroFramework.php
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
<?php
declare(strict_types=1);

declare(strict_types=1);

namespace Ingenerator\MicroFramework;


use ErrorException;
use GuzzleHttp\Psr7\ServerRequest;
use Ingenerator\PHPUtils\Logging\StackdriverApplicationLogger;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Throwable;
use UnexpectedValueException;

use function date_default_timezone_set;
use function error_reporting;
use function get_class;
use function header;
use function headers_sent;
Expand All @@ -22,13 +25,14 @@
use function setlocale;
use function sprintf;
use function substr;

use const LC_ALL;

class MicroFramework
{
public static function throwingErrorHandler($code, $error, $file = null, $line = null): bool
{
if (\error_reporting() & $code) {
if (error_reporting() & $code) {
// This error is not suppressed by current error reporting settings
// Convert the error into an ErrorException
throw new ErrorException($error, $code, 0, $file, $line);
Expand All @@ -39,21 +43,19 @@ public static function throwingErrorHandler($code, $error, $file = null, $line =
}

/**
* Executes a request
* Executes a request.
*
* @param callable():LoggerProvider $logger_provider_factory function that returns a LoggerProvider to get/create a suitable logger
* @param callable(LoggerInterface $logger):RequestHandler $handler_factory function that returns a class containing the application code
* @param null|callable():ServerRequestInterface $request_factory callable that provides a ServerRequest - defaults to guzzle/psr7's ServerRequest::fromGlobals()
* @param null|int|float $start_hr_time the hrtime() at the start of the request - ideally captured as the very first thing in index.php. Used for logging latency
* @param callable():ServerRequestInterface|null $request_factory callable that provides a ServerRequest - defaults to guzzle/psr7's ServerRequest::fromGlobals()
* @param int|float|null $start_hr_time the hrtime() at the start of the request - ideally captured as the very first thing in index.php. Used for logging latency
* @param string $default_timezone default timezone to set before execution
* @param string $locale default locale to set before execution
*
* @return void
*/
public function execute(
callable $logger_provider_factory,
callable $handler_factory,
null|int|float $start_hr_time = null,
int|float|null $start_hr_time = null,
?callable $request_factory = null,
string $default_timezone = 'Europe/London',
string $locale = 'en_UK.utf-8',
Expand Down Expand Up @@ -101,17 +103,16 @@ public function execute(
}
}


private function resetOutputBuffersAssertingNoOutput(): void
{
if (headers_sent($file, $line)) {
throw new \RuntimeException('Headers already sent (output started at '.$file.':'.$line);
throw new RuntimeException('Headers already sent (output started at '.$file.':'.$line);
}

while (ob_get_level()) {
$buffer = ob_get_clean();
if ( ! empty($buffer)) {
throw new \RuntimeException('Unexpected buffered output during request ('.substr($buffer, 0, 50));
if (!empty($buffer)) {
throw new RuntimeException('Unexpected buffered output during request ('.substr($buffer, 0, 50));
}
}
}
Expand All @@ -122,7 +123,7 @@ private function renderResponseToClient(ResponseInterface $response): void
// When behind apache, at least, it is not valid to send an 'HTTP/xx {code}' without a reason phrase for a
// custom response code - apache will attempt to look up the reason phrase for the code and will convert the
// response to a 500 if it doesn't find anything (despite logging in the request log with the custom code).
throw new \UnexpectedValueException(
throw new UnexpectedValueException(
'HTTP reason phrase cannot be empty and there is no default for status "'.$response->getStatusCode().
'"',
);
Expand All @@ -139,7 +140,7 @@ private function renderResponseToClient(ResponseInterface $response): void

foreach ($response->getHeaders() as $header => $header_values) {
if (count($header_values) > 1) {
throw new \UnexpectedValueException('Cannot specify multiple values for the '.$header.' header');
throw new UnexpectedValueException('Cannot specify multiple values for the '.$header.' header');
}
header($header.': '.array_shift($header_values), replace: true);
}
Expand All @@ -163,11 +164,10 @@ private function logUncaughtException(LoggerInterface $logger, Throwable $e): vo

private function renderErrorResponse(): void
{
if ( ! headers_sent()) {
if (!headers_sent()) {
// We can't send these if they've already been sent...
header('Content-Type: text/plain', response_code: 500);
}
echo "Unexpected fatal error\n";
}

}
2 changes: 1 addition & 1 deletion src/RequestHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use Psr\Http\Message\ServerRequestInterface;

/**
* The RequestHandler is the main implementation of the function / app code
* The RequestHandler is the main implementation of the function / app code.
*
* As far as MicroFramework is concerned, there is only one RequestHandler class / instance - there
* is no (and never will be) built-in support for routing etc. If a function needs to route / handle
Expand Down
4 changes: 1 addition & 3 deletions src/RequestLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use Psr\Log\LoggerInterface;

/**
* Responsible for logging requests on completion
* Responsible for logging requests on completion.
*
* This allows for a custom request log decorated with the same metadata etc as any entries in
* the event log. It is called by MicroFramework at the very end of request execution, after the
Expand All @@ -16,8 +16,6 @@ interface RequestLogger
/**
* @param LoggerInterface $logger destination to log to
* @param int|float $start_hr_time the high-resolution time that the PHP execution began - useful for calculating latency
*
* @return void
*/
public function logRequest(LoggerInterface $logger, int|float $start_hr_time): void;
}
7 changes: 3 additions & 4 deletions src/StackdriverRequestLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@
use Psr\Log\LoggerInterface;

/**
* Logs requests using the functionality built into StackdriverApplicationLogger
* Logs requests using the functionality built into StackdriverApplicationLogger.
*/
class StackdriverRequestLogger implements RequestLogger
{
public function logRequest(LoggerInterface $logger, float|int $start_hr_time): void
{
if ( ! $logger instanceof StackdriverApplicationLogger) {
if (!$logger instanceof StackdriverApplicationLogger) {
// This should never happen in any normal usecase, only if there's been an error in the way the
// dependencies are wired up - e.g. someone has made a LoggerProvider that provides a
// StackdriverRequestLogger with some other type of LoggerInterface. Just report it as an error
// but don't interrupt request processing.
$e = new InvalidArgumentException(
sprintf(
"Could not log request details - got a %s instead of a %s",
'Could not log request details - got a %s instead of a %s',
$logger::class,
StackdriverApplicationLogger::class
)
Expand All @@ -45,5 +45,4 @@ protected function getMicrotime(): float
{
return microtime(true);
}

}
Loading
Loading