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);

Python convert random string date format to Datetime

Development in PHP is easy or it may be just that I’ve been writing code in PHP for long time. And anytime I had a string date that needs to be converted in another format, all that was required was.

$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));

It’s that simple. Do not need any package or library, this is built-in functionality. Now the original date, could be Y-m-d or Y-m-d H:i or Y-m-d H:i:s, where H is hour, i is minute and s is seconds, the above example works for all formats.

This week I had a small python script to fix. Firstly, for almost anything in Python you need to import packages and I used datetime package, the issue with this was datetime.strptime(date, format) expects date to be formatted same as format for it to convert into datetime object.

For example, if the date was say 2021-06-10 11:10 and the format provided was %Y-%m-%d %H:%M:%S it just wouldn’t work. Python expects the format be %Y-%m-%d %H:%M that is without expecting seconds.

Fix: After a few google searches and trials came across this.

import dateutil.parser
yourdate = dateutil.parser.parse(datestring)

The only library I was able to find was dateutil.parser which would convert any string date to datetime object be it 2010-03-21 or 2010-03-21 10:12 or 2010-03-21 10:12:13.

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”

Time killer and addictive Google Games

We’ve all at least once played the T-rex game on Google Chrome when the internet was done. But do you know Google offers more such games? Of course, these others require a working internet. .

1. 30th Anniversary of PAC-MAN
Google came out with one of the most addictive classic Pac-man game doodle on it’s 30th Anniversary on May 21, 2010. Go ahead and give it a try.

2. Basketball 2012
If you’re into basket ball, this one is definitely for you.

Continue reading “Time killer and addictive Google Games”