Code Monkey home page Code Monkey logo

mezzio-problem-details's Introduction

Problem Details for PSR-7 Applications (RFC 7807)

Build Status

🇷🇺 Русским гражданам

Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.

У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.

Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"

🇺🇸 To Citizens of Russia

We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.

One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.

You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

This library provides a factory for generating Problem Details responses, error handling middleware for automatically generating Problem Details responses from errors and exceptions, and custom exception types for PSR-7 applications. All responses are RFC 7807 compliant.

Installation

Run the following to install this library:

$ composer require mezzio/mezzio-problem-details

Documentation

Documentation is in the doc tree, and can be compiled using mkdocs:

$ mkdocs build

You may also browse the documentation online.

mezzio-problem-details's People

Contributors

acelaya avatar akrabat avatar basz avatar bladeofsteel avatar boesing avatar breiteseite avatar froschdesign avatar geerteltink avatar ghostwriter avatar gsteel avatar laminas-bot avatar lhpalacio avatar michalbundyra avatar ncou avatar ocramius avatar orkin avatar oussous-hassan avatar pascalheidmann-check24 avatar renovate[bot] avatar samsonasik avatar snapshotpl avatar starkskalle avatar stephensamra avatar svycka avatar weierophinney avatar xerkus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mezzio-problem-details's Issues

Allow to configure a default type map

Currently, when the ProblemDetailsResponseFactory::createResponse method is called without a type, it tries to infer it from the status, generating values like https://httpstatus.es/404 or https://httpstatus.es/500.

This mainly happens when the ProblemDetailsNotFoundHandler is hit, or the ProblemDetailsMiddleware catches an exception not implementing ProblemDetailsExceptionInterface.

If your API has a specific pattern when generating the types for other errors, it's a bit inconsistent that these two errors follow a different pattern.

It would be nice to be able to define a config map where you set the default type to be used for "every" status code when a value for type was not provided. Something like this:

<?php

return [

    'zend_problem_details' => [
        'default_type_fallbacks' => [
            404 => '/my-app/errors/resource-not-found',
            500 => '/my-app/errors/unknown',
        ],
    ],

];

Then, by injecting this map in the ProblemDetailsResponseFactory, the createTypeFromStatus method could be refactored to look like this:

private function createTypeFromStatus(int $status) : string
{
    return $this->defaultTypeFallbacks[$status] ?? sprintf('https://httpstatus.es/%s', $status);
}

So it would continue working the same when the config map is not defined, but every user would have control over the values generated for the type.

I'm open to implement this if you think it's useful.


Originally posted by @acelaya at zendframework/zend-problem-details#50

PHP 8.3 support

Feature Request

Q A
New Feature yes
RFC no
BC Break yes

Summary

I've seen many other mezzio and laminas components have been updated to support PHP 8.3

I can add support for this one if needed.

`ProblemDetailsMiddleware::attachListener` does also allow `object&callable`

Bug Report

Q A
Version(s) 1.11.0

Summary

ProblemDetailsMiddleware::attachListener does also allow object&callable

Current behavior

Argument 1 of Mezzio\ProblemDetails\ProblemDetailsMiddleware::attachListener expects callable(Throwable, Psr\Http\Message\RequestInterface, Psr\Http\Message\ResponseInterface):void, but parent type Application\ProblemDetails\NonProblemResponseListener provided

How to reproduce

use Mezzio\ProblemDetails\Exception\ProblemDetailsExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Throwable;

final class Foo
{
   public function __invoke(Throwable $error, ServerRequestInterface $request, ResponseInterface $response): void
   {}
}

/** @var Mezzio\ProblemDetails\ProblemDetailsMiddleware $middleware */
$middleware = null;
$middleware->attachListener(new Foo());

Expected behavior

No psalm error.

Psalm integration

Feature Request

Q A
QA yes

Summary

As decided during the Technical-Steering-Committee Meeting on August 3rd, 2020, Laminas wants to implement vimeo/psalm in all packages.

Implementing psalm is quite easy.

Required

  • Create a psalm.xml in the project root
  • Copy and paste the contents from this psalm.xml.dist
  • Run $ composer require --dev vimeo/psalm
  • Run $ vendor/bin/psalm --set-baseline=psalm-baseline.xml
  • Add a composer script static-analysis with the command psalm --shepherd --stats
  • Add a new line to script: in .travis.yml: - if [[ $TEST_COVERAGE == 'true' ]]; then composer static-analysis ; fi
  • Remove phpstan from the project (phpstan.neon.dist, .travis.yml entry, composer.json require-dev and scripts)
Optional
  • Fix as many psalm errors as possible.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Use matchDepNames instead of matchPackageNames

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php ~8.1.0 || ~8.2.0 || ~8.3.0
  • fig/http-message-util ^1.1.2
  • psr/container ^1.0 || ^2.0
  • psr/http-factory ^1.0
  • psr/http-message ^1.0 || ^2.0
  • psr/http-server-middleware ^1.0
  • spatie/array-to-xml ^2.3 || ^3.0
  • webmozart/assert ^1.10
  • willdurand/negotiation ^3.0
  • laminas/laminas-coding-standard ~2.5.0
  • laminas/laminas-diactoros ^3.3
  • phpunit/phpunit ^10.5.10
  • psalm/plugin-phpunit ^0.18.4
  • vimeo/psalm ^5.21.1
github-actions
.github/workflows/continuous-integration.yml
.github/workflows/docs-build.yml
.github/workflows/release-on-milestone-closed.yml

  • Check this box to trigger a request for Renovate to run again on this repository

`ProblemDetailsExceptionInterface` should extend `Throwable`

Feature Request

Q A
New Feature yes
RFC no
BC Break yes

Summary

The ProblemDetailsExceptionInterface does not extend Throwable and thus, it cannot be used as a return type for throws.

This doesn't matter unless you are using static code analysers.

I want to propose extending the Throwable interface for the ProblemDetailsExceptionInterface as in most cases, this might be the use case anyway.

PHP 8.0.0 error due to incompatable dependency version

On PHP 8.0.0 an error is thrown. this is due to match becoming a reserved name this has been fixed bu the dependency author willdurand/negotiation. this composer JSON needs to reflect this to bump the version to ^3.0

Q A
Version(s) 1.2.0

Summary

In PHP 8.0.0 throws an unexpected error message

Current behavior

An unexpected error occurred; stack trace:

ParseError raised in file /home/cms/vendor/willdurand/negotiation/src/Negotiation/Negotiator.php line 41:
Message: syntax error, unexpected token "match"
Stack Trace:

#0 /home/cms/vendor/composer/ClassLoader.php(322): Composer\Autoload\includeFile('/home/cms/vendo...')
#1 /home/cms/vendor/mezzio/mezzio-problem-details/src/ProblemDetailsMiddleware.php(102):
Composer\Autoload\ClassLoader->loadClass('Negotiation\\Neg...')
#2 /home/cms/vendor/mezzio/mezzio-problem-details/src/ProblemDetailsMiddleware.php(54):
Mezzio\ProblemDetails\ProblemDetailsMiddleware->canActAsErrorHandler(Object(Laminas\Diactoros\ServerRequest))
#3 /home/cms/vendor/mezzio/mezzio/src/Middleware/LazyLoadingMiddleware.php(47):
Mezzio\ProblemDetails\ProblemDetailsMiddleware->process(Object(Laminas\Diactoros\ServerRequest),
Object(Laminas\Stratigility\Next))
#4 /home/cms/vendor/laminas/laminas-stratigility/src/Next.php(61):
Mezzio\Middleware\LazyLoadingMiddleware->process(Object(Laminas\Diactoros\ServerRequest),
Object(Laminas\Stratigility\Next))
#5 /home/cms/vendor/laminas/laminas-stratigility/src/Middleware/ErrorHandler.php(144):
Laminas\Stratigility\Next->handle(Object(Laminas\Diactoros\ServerRequest))
#6 /home/cms/vendor/mezzio/mezzio/src/Middleware/LazyLoadingMiddleware.php(47):
Laminas\Stratigility\Middleware\ErrorHandler->process(Object(Laminas\Diactoros\ServerRequest),
Object(Laminas\Stratigility\Next))
#7 /home/cms/vendor/laminas/laminas-stratigility/src/Next.php(61):
Mezzio\Middleware\LazyLoadingMiddleware->process(Object(Laminas\Diactoros\ServerRequest),
Object(Laminas\Stratigility\Next))
#8 /home/cms/vendor/laminas/laminas-stratigility/src/MiddlewarePipe.php(84):
Laminas\Stratigility\Next->handle(Object(Laminas\Diactoros\ServerRequest))
#9 /home/cms/vendor/laminas/laminas-stratigility/src/MiddlewarePipe.php(73):
Laminas\Stratigility\MiddlewarePipe->process(Object(Laminas\Diactoros\ServerRequest),
Object(Laminas\Stratigility\EmptyPipelineHandler))
#10 /home/cms/vendor/laminas/laminas-httphandlerrunner/src/RequestHandlerRunner.php(96):
Laminas\Stratigility\MiddlewarePipe->handle(Object(Laminas\Diactoros\ServerRequest))
#11 /home/cms/vendor/mezzio/mezzio/src/Application.php(82): Laminas\HttpHandlerRunner\RequestHandlerRunner->run()
#12 /home/cms/public/index.php(28): Mezzio\Application->run()
#13 /home/cms/public/index.php(29): {closure}()
#14 {main}

How to reproduce

run on PHP 8.0.0

Expected behavior

no error message

Being able to determine if only json or xml should be handled, instead of both.

I have run into this use case:

My application has a JSON API which is served under the /rest path, but also 3 or 4 more routes which are not part of this API context.

For the API I use "problem details" for the errors, but I also have some other error handling logic for the other routes.

Because of this, my middleware pipeline looks more or less like this:

// ...

$app->pipe(Zend\Stratigility\Middleware\ErrorHandler::class);
$app->pipe('/rest', Zend\ProblemDetails\ProblemDetailsMiddleware::class);

// More middlewares...

$app->pipe('/rest', Zend\ProblemDetails\ProblemDetailsNotFoundHandler::class);
$app->pipe(App\NotFoundHandler::class);

With this approach, most of the use cases work as expected, except when a request is performed to a not-found path which starts with /rest, proividing a non-JSON Accept header, but one that matches *+xml.

This usually happens when a request is performed from a browser, in which case the Accept has the value text/html,application/xhtml+xml,application/xml...

This is making the ProblemDetailsNotFoundHandler to generate an xml response, but I would expect/like it to be skipped and my custom NotFoundHandler (the second one) to be executed instead.

Proposal

In order to "solve" this, the first thing that comes to my mind is this approach:

Allowing to dynamically determine which "contexts" should be enabled for the module, as in "JSON only", "XML only" or "both".

I see that currently, the headers that determine if the ProblemDetailsMiddleware and the ProblemDetailsNotFoundHandler should act as error handlers, are hardcoded on ProblemDetailsResponseFactory::NEGOTIATION_PRIORITIES.

Since the three classes make use of that constant to call a Negotiator instance, maybe the whole logic could be wrapped into a helper which is injected in the three of them.

This helper could then get the "context" configuration or fallback to "both", keeping current behavior.

Let me know if you think this makes sense, or if you think there's any simpler way to achieve the same result.

In any case, I'm open to contribute a PR with the required changes.


Originally posted by @acelaya at zendframework/zend-problem-details#49

PHP 8.0 support

Feature Request

Q A
New Feature yes

Summary

To be prepared for the december release of PHP 8.0, this repository has some additional TODOs to be tested against the new major version.

In order to make this repository compatible, one has to follow these steps:

  • Modify composer.json to provide support for PHP 8.0 by adding the constraint ~8.0.0
  • Modify composer.json to drop support for PHP less than 7.3
  • Modify composer.json to implement phpunit 9.3 which supports PHP 7.3+
  • Modify .travis.yml to ignore platform requirements when installing composer dependencies (simply add --ignore-platform-reqs to COMPOSER_ARGS env variable)
  • Modify .travis.yml to add PHP 8.0 to the matrix (NOTE: Do not allow failures as PHP 8.0 has a feature freeze since 2020-08-04!)
  • Modify source code in case there are incompatibilities with PHP 8.0

Forward compatibility for PSR-17

Feature Request

Q A
New Feature yes
BC Break no

Summary

With mezzio/mezzio#75, a PoC was merged to mezzio to show how forward compatibility to PSR-17 could be added without having a BC break.

This package uses the callable response factory as well and can adapt the same logic as implemented in mezzio/mezzio v3.5.0.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.