Setting HTTP status code based on Exception in Slim 4 – Rob Allen

One thing that’s quite convenient is to be able to throw an exception with a valid HTTP code set and have that code sent to the client.

For example, you may have:

throw new \RuntimeException("Not Found", 404);

With the standard Slim 4 error handler, this response is sent to the client:

$ curl -i -H "Accept:application/json" http://localhost:8888
HTTP/1.1 500 Internal Server Error
Host: localhost:8888
Content-type: application/json { "message": "Slim Application Error"
}

Ideally we want the status code to be 404.

Option 1: Use an HttpException

The simplest solution is to use one of Slim’s HttpException classes:

use Slim\Exception\HttpNotFoundException; ... throw new HttpNotFoundException($request);

This is only useful in a Request Handler as you need a Request object, but the expected response is sent to the client:

$ curl -i -H "Accept:application/json" http://localhost:8888
HTTP/1.1 404 Not Found
Host: localhost:8888
Content-type: application/json { "message": "404 Not Found"
}

Simple and easy!

Option 2: Override the ErrorMiddleware

There are situation when you can’t simply replace the exception thrown. For example, you’re updating an application from Slim 3 and you have hundreds of customised exceptions already throwing, or you throw from a class that doesn’t have a Request object instance available.

In these cases, the easiest solution is to extend the Slim ErrorMiddleware to wrap the exception in an

HttpException

and then the standard error handling and rendering will “just work”.

I’m feeling a little lazy, so let’s use an anonymous class to do replace the call to $app->addErrorMiddleware():

$container = $app->getContainer(); $logger = $container->has(LoggerInterface::class) ?$container->get(LoggerInterface::class) : null; $errorMiddleware = new class ( callableResolver: $app->getCallableResolver(), responseFactory: $app->getResponseFactory(), displayErrorDetails: false, logErrors: true, logErrorDetails: true, logger: $logger ) extends \Slim\Middleware\ErrorMiddleware { public function handleException( ServerRequestInterface $request, Throwable $exception ): \Psr\Http\Message\ResponseInterface { // determine that this exception should be wrapped. I'm checking for code between 400 & 599 if ($exception->getCode() >= 400 && $exception->getCode() < 600) { // wrap the exception in an HttpException $exception = new \Slim\Exception\HttpException( $request, $exception->getMessage(), $exception->getCode(), $exception ); $exception->setTitle($exception->getMessage()); } return parent::handleException($request, $exception); } }; $app->addMiddleware($errorMiddleware);

Behind the scenes of $app->addErrorMiddleware(), the \Slim\Middleware\ErrorMiddleware is constructed and then added to the middleware stack. We replicate that we an anonymous class that overrides handleException() to wrap the thrown exception if required.

Looking at the code in detail

There’s quite a lot going on here, so let’s break it down into parts.

$container = $app->getContainer(); $logger = $container->has(LoggerInterface::class) ?$container->get(LoggerInterface::class) : null; $errorMiddleware = new class ( callableResolver: $app->getCallableResolver(), responseFactory: $app->getResponseFactory(), displayErrorDetails: false, logErrors: true, logErrorDetails: true, logger: $logger ) extends \Slim\Middleware\ErrorMiddleware {

The constructor to \Slim\Middleware\ErrorMiddleware takes 6 parameters, so when we instantiate, we have to pass them all in though it’s not unusual for the $logger parameter to be left off in the call to $app->addErrorMiddleware(). The easiest way to get a logger instance if there is one, is to grab it from the container where it should be registered under the \Psr\Log\LoggerInterface key which is imported into the file with a use statement.

I’ve used PHP 8’s named arguments as this constructor takes three booleans and it’s easier to remember what they do if they are label

Truncated by Planet PHP, read more at the original (another 2865 bytes)

PHP Internals News: Episode 91: is_literal – Derick Rethans

PHP Internals News: Episode 91: is_literal

In this episode of “PHP Internals News” I chat with Craig Francis (Twitter, GitHub, Website), and Joe Watkins (Twitter, GitHub, Website) about the “is_literal” RFC.

The RSS feed for this podcast is https://derickrethans.nl/feed-phpinternalsnews.xml, you can download this episode’s MP3 file, and it’s available on Spotify and iTunes. There is a dedicated website: https://phpinternals.news

Transcript

Derick Rethans 0:14

Hi, I’m Derick. Welcome to PHP internals news, a podcast dedicated to explaining the latest developments in the PHP language. This is Episode 91. Today I’m talking with Craig Francis and Joe Watkins, talking about the is_literal RFC that they have been proposing. Craig, would you please introduce yourself?

Craig Francis 0:34

Hi, I’m Craig Francis. I’ve been a PHP developer for about 20 years, doing code auditing, pentesting, training. And I’m also the co-lead for the Bristol chapter of OWASP, which is the open web application security project.

Derick Rethans 0:48

Very well. And Joe, will you introduce yourself as well, please?

Joe Watkins 0:51

Hi, everyone. I’m Joe, the same Joe from last time.

Derick Rethans 0:56

Well, it’s good to have you back, Joe, and welcome to the podcast Craig. Let’s dive straight in. What is the problem that this proposal’s trying to resolve?

Craig Francis 1:05

So we try to address the problem where injection vulnerabilities are being introduced by developers. When they use libraries incorrectly, we will have people using the libraries, but they still introduce injection vulnerabilities because they use it incorrectly.

Derick Rethans 1:17

What is this RFC proposing?

Craig Francis 1:19

We’re providing a function for libraries to easily check that certain strings have been written by the developer. It’s an idea developed by Christoph Kern in 2016. There is a link in the video, and the Google using this to prevent injection vulnerabilities in their Java and Go libraries. It works because libraries know how to handle these data safely, typically using parameterised queries, or escaping where appropriate, but they still require certain values to be written by the developer. So for example, when using a query a database, the developer might need to write a complex WHERE clause or maybe they’re using functions like datediff, round, if null, although obviously, this function could be used by developers themselves if they want to, but the primary purpose is for the library to check these values.

Derick Rethans 2:05

That is a method of doing it. What is this RFC adding to PHP itself?

Craig Francis 2:09

It just simply provides a function which just returns true or false if the variable is a literal, and that’s basically a string that was written by the developer. It’s a bit like if you did is_int or is_string, it’s just a different way of just sort of saying, has this variable been written by the developer?

Derick Rethans 2:28

Is that basically it?

Craig Francis 2:30

That’s it? Yeah.

Joe Watkins 2:32

It would also return true for variables that are the res

Truncated by Planet PHP, read more at the original (another 20645 bytes)

PHP Internals News: Episode 90: Read Only Properties – Derick Rethans

PHP Internals News: Episode 90: Read Only Properties

In this episode of “PHP Internals News” I chat with Nikita Popov (Twitter, GitHub, Website) about the “Read Only Properties” RFC.

The RSS feed for this podcast is https://derickrethans.nl/feed-phpinternalsnews.xml, you can download this episode’s MP3 file, and it’s available on Spotify and iTunes. There is a dedicated website: https://phpinternals.news

Transcript

Derick Rethans 0:14

Hi, I’m Derick. Welcome to PHP internals news, a podcast dedicated to explaining the latest developments in the PHP language. This is Episode 90. Today I’m talking with Nikita Popov about the read only properties version two RFC that he’s proposing. Nikita, would you please introduce yourself?

Nikita Popov 0:33

Hi, Derick. I’m Nikita and I do PHP core development work by JetBrains.

Derick Rethans 0:39

What does this RFC proposing?

Nikita Popov 0:41

This RFC is proposing read only properties, which means that the property can only be initialized once and then not changed afterwards. Again, the idea here is that since PHP 7.4, we have typed properties. A remaining problem with them is that people are not confident making public type properties because they still ensure that the type is correct, but they might not be upholding other invariants. For example, if you have some, like additional checks in your constructor, that string property is actually a non empty string property, then you might not want to make it public because then it could be modified to an empty value for example. One nowadays fairly common case is where properties are actually only initialized in the constructor and not changed afterwards any more. So I think this kind of mutable object pattern is becoming more and more popular in PHP.

Derick Rethans 1:35

You mean the immutable object?

Nikita Popov 1:37

Sorry, immutable. And read only properties address that case. So you can simply put a public read only typed property in your class, and then it can be initialized once in the constructor and you can be… You don’t have to be afraid that someone outside the class is going to modify it afterwards. That’s the basic premise of this RFC.

Derick Rethans 1:57

But it also means that objects of the class itself can modify that value any more, either.

Nikita Popov 2:01

Exactly. So that’s, I think, a primary distinction we have to make. Genuinely, there are two ways to make this read only concept work. One is like actually read only or maybe more precisely init once, which is what this RFC proposes. We can only set that once and then even in the same class, you can’t modify it again. And the alternative is the asymmetric visibility approach where you say that, okay, only in the public scope, the property can only be read, but in the private scope, you can modify it. I think the distinction there is very important, because read only property tells you that it’s genuinely read only, like, if you access a property multiple times in sequence, you will always get back the same value. While the asymmetric visibility only says that the public interface is read only, but internally, it could be mutated. And that might like be, you know, intentional, just that you want to like have your state management private, but that the property is not supposed to be immutable.

Derick Rethans 3:05

How’s this RFC different from read only properties, version one?

Nikita Popov 3:09

Read only pr

Truncated by Planet PHP, read more at the original (another 15552 bytes)

PHP 8.1.0 Alpha 3 available for testing – PHP: Hypertext Preprocessor

The PHP team is pleased to announce the third testing release of PHP 8.1.0, Alpha 3. This continues the PHP 8.1 release cycle, the rough outline of which is specified in the PHP Wiki. For source downloads of PHP 8.1.0 Alpha 3 please visit the download page.Please carefully test this version and report any issues found in the bug reporting system.Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 1, planned for Jul 22 2021.The signatures for the release can be found in the manifest or on the QA site.Thank you for helping us make PHP better.

Xdebug Update: June 2021 – Derick Rethans

Xdebug Update: June 2021

In this monthly update I explain what happened with Xdebug development in this past month. These will be published on the first Tuesday after the 5th of each month.

Patreon and GitHub supporters will get it earlier, around the first of each month.

You can become a patron or support me through GitHub Sponsors. I am currently 55% towards my $2,000 per month goal. If you are leading a team or company, then it is also possible to support Xdebug through a subscription.

In June, I worked on Xdebug for about 48 hours, with funding being around 24 hours, which is only half.

PHP 8.1 Support

PHP 8.1 recently acquired a new Enum type, and I added support for that in Xdebug’s myriad of modes, such as tracing, profiling, and debugging.

Enumerations are implemented as a special case of classes, and the step debugger was already be able to communicate these new enums. However, their name and value are displayed as normal class properties, which is less than ideal. The debugging protocol already has facilities for communicating additional information with data, which is what Xdebug now does. IDEs will need to make use of this additional information though.

I also had to make some more tweaks with regard to PHP 8.1’s Fibers. Although PHP 8.1 feature freeze is coming up soon, I suspect that I will need to make more tweaks.

Xdebug 3.1

I have continued to work on the issues that were raised by the developer of the PHP Debug Adapter for Visual Studio Code. The main new addition is the xdebug_notify() function that you can use to send variables to the IDE. The IDE can then choose to display this information in a structured way.

I have not yet worked on the UNC paths issue. In order to reproduce it, I need to be able to run Windows’ WSL2, which I can’t do in my virtualised Windows, and I don’t have (or want!) extra hardware to run Windows natively.

Xdebug Cloud

To make Xdebug Cloud applicable in more situations, I recently added the support of being to set your Cloud ID (User Key) through the browser extensions as the value of the Debug Session Name.

I have now improved Xdebug’s Shared Secret for triggers, which compares the value that comes in through the browser extensions, with a value as configured in the php.ini file. Only if it matches, would the debugger initiate a connection. The new functionality allows you to specify multiple values, separated by a , as value for xdebug.trigger_value so that you can control which multiple Cloud IDs can initiate a debugging connection. This adds additional protection so that other Xdebug Cloud users with a valid ID can’t use the browser extensions against third party web sites to initiate a debug session.

Xdebug Cloud is the Proxy As A Service platform to allow for debugging in more scenarios, where it is hard, or impossible, to have Xdebug make a connection to the IDE. It is continuing to operate as Beta release.

Packages start at £49/month, and revenue will be used to further the development of Xdebug.

If you want to be kept up to date with Xdebug Cloud, please sign up to the mailinglist, which I will use to send out an update not more than once a month.

Truncated by Planet PHP, read more at the original (another 1395 bytes)

PHP 8.1.0 Alpha 2 available for testing – PHP: Hypertext Preprocessor

The PHP team is pleased to announce the second testing release of PHP 8.1.0, Alpha 2. This continues the PHP 8.1 release cycle, the rough outline of which is specified in the PHP Wiki.For source downloads of PHP 8.1.0 Alpha 2 please visit the download page.Please carefully test this version and report any issues found in the bug reporting system.Please DO NOT use this version in production, it is an early test version.For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive.The next release will be Alpha 3, planned for 8 Jul 2021.The signatures for the release can be found in the manifest or on the QA site.Thank you for helping us make PHP better.

The case for partials and pipes in PHP – larry@garfieldtech.com

The case for partials and pipes in PHP

The Partial Function Application RFC is currently in voting, and right now it’s a close vote to the negative. I wanted to take this opportunity to try and make the broader case for partial application and for its related RFC, the pipe operator, in a way that is more appropriate for a blog post than the RFC body (which is, by design, more concerned with the finer details of “what”).

The main pushback on the RFC so far is that the benefits don’t outweigh the cost of yet-more-syntax in the language. Which is a fair position to hold, albeit one I hope to convince you is incorrect. That is, I believe the benefits vastly outweigh the syntax and implementation cost.

Continue reading this post on PeakD.

Larry
23 June 2021 – 3:07pm

The case for partials and pipes in PHP – Larry Garfield

The case for partials and pipes in PHP

The Partial Function Application RFC is currently in voting, and right now it’s a close vote to the negative. I wanted to take this opportunity to try and make the broader case for partial application and for its related RFC, the pipe operator, in a way that is more appropriate for a blog post than the RFC body (which is, by design, more concerned with the finer details of “what”).

The main pushback on the RFC so far is that the benefits don’t outweigh the cost of yet-more-syntax in the language. Which is a fair position to hold, albeit one I hope to convince you is incorrect. That is, I believe the benefits vastly outweigh the syntax and implementation cost.

Continue reading this post on PeakD.

Larry
23 June 2021 – 3:07pm

PHP Internals News: Episode 89: Partial Function Applications – Derick Rethans

PHP Internals News: Episode 89: Partial Function Applications

In this episode of “PHP Internals News” I chat with Larry Garfield (Twitter) and Joe Watkins (Twitter, GitHub, Blog about the “Partial Function Applications” RFC.

The RSS feed for this podcast is https://derickrethans.nl/feed-phpinternalsnews.xml, you can download this episode’s MP3 file, and it’s available on Spotify and iTunes. There is a dedicated website: https://phpinternals.news

Transcript

Derick Rethans 0:14

Hi, I’m Derick. Welcome to PHP internals news, a podcast dedicated to explaining the latest developments in the PHP language. This is Episode 89. Today I’m talking with Larry Garfield and Joe Watkins about a partial function application RFC that they’re proposing with Paul Crevela and Levi Morrison. Larry, would you please introduce yourself?

Larry Garfield 0:36

Hello World. I’m Larry Garfield or Crell on most social medias. I’m a staff engineer for Typo3 the CMS. And I’ve been getting more involved in internals these days, mostly as a general nudge and project manager.

Derick Rethans 0:52

And hello, Joe, would you please introduce yourself as well?

Joe Watkins 0:55

Hi, I’m Joe, or Krakjoe, I do various PHP stuff. That’s all there is to say about that really.

Derick Rethans 1:02

I think you do quite a bit more than just a little bit. In any case, I think for this RFC, you, you wrote the implementation of it, whereas Larry, as he said, did some of the project management, I’m sure there’s more to it than I’ve just paraphrased in a single sentence. But can one of you explain in one sentence, or if you must, maybe two or three, what partial function applications, or I hope for short, partials are?

Larry Garfield 1:27

Partial function application, in the broadest sense, is taking a function that has some number of parameters, and making a new function that pre fills some of those parameters. So if you have a function that takes four parameters, or four arguments, you can produce a new function that takes two arguments. And those other two you’ve already provided a value for in advance.

Derick Rethans 1:54

Okay, I feel we’ll get into the details in a moment. But what are its main benefits of doing this? What would you use this for?

Larry Garfield 2:01

Oh, there’s a couple of places that you can use partial application. It is what got me interested. It’s very common in functional programming. But it’s also really helpful when you want to, you have a function that like, let’s say, string replace takes three arguments, two of which are instructions for what to replace, and one of which is the thing in which you want to replace. If you want to reuse that a bunch of times, you could build an object and pass in constructor values and save those and then call a function. Or you can just partially apply string replace with the things to search for, and the things to replace with and get back a function that takes one argument and will do that replacement on it. And you can then reuse that over and over again. There are a lot of cases like that, usually use in combination with functions that wants a callback. And that callback takes one argument. So array map or array filter are cases where very often you want to give it a function that takes one argument, you have a function that takes three arguments, you want to fill in those first ones first, and then pass the result that only takes one argument to array map or a filter, or whatever. So that’s the one of the common use cases for it.

Truncated by Planet PHP, read more at the original (another 23522 bytes)