PHP syntactic sugar code example

According to Wikipedia, Syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express.

Though PHP doesn’t necessarily have much concept of sugaring, I across this one example sometime back. The idea here is to add a given set of values to an array but at the alternating ends.

Example

For a given set of values, 10, 12, 124, 349, 43, 0, 493, 3, 32. The output should have values pushed to each end alternatively. So, the first value into the array would be 10, 2nd would be 12, pushed to the end (or at the start), 3rd pushed other and so on.

#1    #2    #3    #4    #5    #6    #7    #8    #9
                                                32
                                    493   493   493
                        43    43    43    43    43
            124   124   124   124   124   124   124
10    10    10    10    10    10    10    10    10
      12    12    12    12    12    12    12    12
                  349   349   349   349   349   349
                              0     0     0     0
                                          3     3

The function here loops over an array pushes values in array $e alternatively.

$x = [10, 12, 124, 349, 43, 0, 493, 3, 32];
$i = 0;
foreach ($e as $v) {
      (array_.[unshift,push][++$i%2])($e,$d);
}

It’s an array with the two function names ['array_push','array_unshift'] with [++$i%2] as the index of the array alternating between a 0 or 1 so will evaluate to the other function each time. PHP’s “variable functions” let you assign a variable to a function and execute by calling with parenthesis (ex: $f='array_push'; $f($e,$d); == array_push($e,$d)) so the ($e,$d) is then calling the evaluated element of the array.

Just a shorter way to do

if (++$i%2)
      array_push($e,$d);
else
      array_unshift($e,$e);

Laravel Custom Exception Handlers

laravel

Laravel throws a large number of exceptions and is very easy to customize them to suit our needs as required.

Note: These exceptions are most helpful if you’re building an API.

The code for common exception handler lies in the {project_root}/app/Exceptions/ folder, named Handler.php. The default file looks like this in Laravel 5.7.

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }
}

Some of the common exceptions that we’re going to handle in this tutorial are AuthenticationException, MethodNotAllowedHttpException, ModelNotFoundException, NotAcceptableHttpException, NotFoundHttpException, PostTooLargeException, ValidationException.

Below is the explanation for each variable, functions and handler implemented.

protected $dontReport = [] is the array of exceptions that Laravel wouldn’t report. Here we’re going to mention the exceptions that we don’t want laravel to report.

Continue reading “Laravel Custom Exception Handlers”

Customizing Laravel validation JSON message format

laravel request validation customize error message format

By default laravel gives a good enough JSON format for validation errors but what if you want to customize it?

#Original JSON format
{
    "message": "The given data was invalid.",
    "errors": {
        "email": [
            "Please enter email address."
        ],
        "password": [
            "Please enter password."
        ]
    }
}

But for this particular project I decided to change the format to this.

{
    "success": false,
    "success_code": 400,
    "message": "Please enter email address.",
    "errors": [
        {
            "field": "email",
            "message": "Please enter email address."
        },
        {
            "field": "password",
            "message": "Please enter password."
        }
    ]
}

To achieve this I created a ValidationException handler function in app/Exceptions/Handler.php which helped me catch all the exceptions raised as a result of failed validations.

Continue reading “Customizing Laravel validation JSON message format”

Error handling in PHP with Error logger working

Error handling in PHP with Error logger working

Logging errors in php is easy, cool and helpful when it comes to test the site for errors as I explained it in my earlier post Logging errors to file in PHP but only till the site is at developer’s end and you working on it. Once you take the site live its just not good anymore. Once you take it on the production end, you cannot show the errors to the user or in case if its even 100% error free you will find that 1 in a 100 person who likes to mess up with the sites. Being a programmer you gotta be ready for it. This is the place where comes error handling into play.

Here is a simple script. Just place these two functions in a file and include it at the right place. Probably including from the point onward from where you expect and error would be just perfect.

// Define a custom error handler
function userErrorHandler($errno, $errstr, $errfile = '', $errline = 0, $errcontext = array()) {
	// Getting error type
	$errorType = array (
			E_ERROR				=> 'ERROR',
			E_WARNING			=> 'WARNING',
			E_PARSE				=> 'PARSING ERROR',
			E_NOTICE			=> 'NOTICE',
			E_CORE_ERROR		=> 'CORE ERROR',
			E_CORE_WARNING		=> 'CORE WARNING',
			E_COMPILE_ERROR		=> 'COMPILE ERROR',
			E_COMPILE_WARNING	=> 'COMPILE WARNING',
			E_USER_ERROR		=> 'USER ERROR',
			E_USER_WARNING		=> 'USER WARNING',
			E_USER_NOTICE		=> 'USER NOTICE',
			E_STRICT			=> 'STRICT NOTICE',
			E_RECOVERABLE_ERROR	=> 'RECOVERABLE ERROR'
			);
	
	if (array_key_exists($errno, $errorType)) {
		$err = $errorType[$errno];
	} else {
		$err = 'CAUGHT EXCEPTION';
	}
	
	// Getting the error log file from php.ini
	$file 		= ini_get('error_log');
	
	// Creating the error log script, same as normal logger would do
	$error_string 	= "[" . date("d-M-Y H:i:s", $_SERVER['REQUEST_TIME']) . '] PHP ' . $err . '::' . $errstr . " in " . $_SERVER['SCRIPT_FILENAME'] . " on line " . $errline . "\r\n";
	
	// Logging error to a certain file
	error_log($error_string, 3, $file);
	
	// Check if the error code is not included in error_reporting
	if (!(error_reporting() & $errno)) {
		return;
	}
	
	// Restore default handlers to prevent errors in errors
	restore_error_handler();
	
	if (function_exists('restore_exception_handler')) {
		restore_exception_handler();
	}
	
	// Load error page
	require('_errors/error.php');
	exit();
}
set_error_handler('userErrorHandler');

// Define a custom handler for uncaught exceptions
if (function_exists('set_exception_handler')) {
	function userExceptionHandler($exception) {
		// Restore default handlers to prevent errors in errors
		restore_error_handler();
		if (function_exists('restore_exception_handler')) {
			restore_exception_handler();
		}
		
		// Load error page
		require('error.php');
		exit();
	}
	set_exception_handler('userExceptionHandler');
}

Note: Once you start error handling in real time error logging stops. To overcome this a short code is included inside the function that uses PHP’s error_log function to log errors. So if you have a specific error log file, just point it towards that.

Good luck!!!

Increase PHP Script Execution Time Limit

Every once in a while I need to process a HUGE file. Though PHP probably isn’t the most efficient way of processing the file, I’ll usually use PHP because it makes coding the processing script much faster. To prevent the script from timing out, I need to increase the execution time of the specific processing script. Here’s how I do it.

ini_set('max_execution_time', 60); //60 seconds = 1 minutes

Place this at the top of your PHP script and let your script loose!