1.2.11. Abstract Away

Avoid using PHP native functions that produce data directly in the code. For example, date() or random_int(). They should be abstracted away in a method, that will be replaced later for testing purposes, or even debugging.

To abstract such calls, place them in a method, and add an interface to this method. Then, create and use those objects. This analysis targets two API for abstraction : time and random values. Time and date related functions may be replaced by Carbon, Clock, Chronos. Random values may be replaced with RandomLib or a custom interface.

<?php

// abstracted away date
$today = new MyDate();
echo 'Date : '.$today->date('r');

// hard coded date of today : it changes all the time.
echo 'Date : '.date('r');

interface MyCalendar{
    function date($format) : string ;
}

class MyDate implements MyCalendar {
    function date($format) : string { return date('r'); }
}

// Valid implementation, reserved for testing purpose
// This prevents from waiting 4 years for a test.
class MyDateForTest implements MyCalendar {
    function date($format) : string { return date('r', strtotime('2016-02-29 12:00:00')); }
}

?>

Name

Default

Type

Description

abstractableCalls

ini_hash

Functions that shouldn’t be called directly, unless in a method.

abstractableClasses

ini_hash

Classes that shouldn’t be instantiated directly, unless in a method.

See also Being in control of time in PHP and How to test non-deterministic code.

1.2.11.1. Suggestions

  • Abstract away the calls to native PHP functions, and upgrade the unit tests

1.2.11.2. Specs

Short name

Patterns/AbstractAway

Rulesets

All, Changed Behavior, Suggestions

Exakat since

2.1.5

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Medium

Available in

Entreprise Edition, Exakat Cloud