master

laravel/framework

Last updated at: 29/12/2023 09:23

ConvertEmptyStringsToNull.php

TLDR

This file is a part of the Illuminate/Foundation/Http\Middleware namespace in the Demo Projects project. It contains a class called ConvertEmptyStringsToNull which extends another class called TransformsRequest. The class is responsible for handling an incoming request and converting empty strings to null values. It also provides methods to register skip callbacks and flush the middleware's global state.

Methods

handle

This method handles an incoming request and checks if any skip callbacks are registered. If a skip callback returns true, the method calls the next middleware in the pipeline. Otherwise, it calls the handle method of the parent class.

transform

This method is a protected method that is responsible for transforming a given value. If the value is an empty string, it returns null. Otherwise, it returns the value unchanged.

skipWhen

This static method is used to register a callback that instructs the middleware to be skipped. The callback should be a Closure and will be added to the skipCallbacks array.

flushState

This static method is used to flush the middleware's global state by resetting the skipCallbacks array.

<?php

namespace Illuminate\Foundation\Http\Middleware;

use Closure;

class ConvertEmptyStringsToNull extends TransformsRequest
{
    /**
     * All of the registered skip callbacks.
     *
     * @var array
     */
    protected static $skipCallbacks = [];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        foreach (static::$skipCallbacks as $callback) {
            if ($callback($request)) {
                return $next($request);
            }
        }

        return parent::handle($request, $next);
    }

    /**
     * Transform the given value.
     *
     * @param  string  $key
     * @param  mixed  $value
     * @return mixed
     */
    protected function transform($key, $value)
    {
        return $value === '' ? null : $value;
    }

    /**
     * Register a callback that instructs the middleware to be skipped.
     *
     * @param  \Closure  $callback
     * @return void
     */
    public static function skipWhen(Closure $callback)
    {
        static::$skipCallbacks[] = $callback;
    }

    /**
     * Flush the middleware's global state.
     *
     * @return void
     */
    public static function flushState()
    {
        static::$skipCallbacks = [];
    }
}