Insphpect

This tool is currently proof-of-concept. Your feedback and evaluation is valuable in helping to improve it and ensure its reports are meaninful.

Please click here to complete a short survey to tell us what you think. It should take less than 5 minutes and help further this research project!

Symfony\Component\Routing\Matcher\Dumper\StaticPrefixCollection

Detected issues

Issue Method Line number
Use of static methods handleError 198

Code

Click highlighted lines for details

<?php/* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */namespace Symfony\Component\Routing\Matcher\Dumper;use Symfony\Component\Routing\RouteCollection;/** * Prefix tree of routes preserving routes order. * * @author Frank de Jonge <info@frankdejonge.nl> * @author Nicolas Grekas <p@tchwork.com> * * @internal */class StaticPrefixCollection{    private $prefix;    /**     * @var string[]     */    private $staticPrefixes = [];    /**     * @var string[]     */    private $prefixes = [];    /**     * @var array[]|self[]     */    private $items = [];    public function __construct(string $prefix = '/')    {        $this->prefix = $prefix;    }    public function getPrefix(): string    {        return $this->prefix;    }    /**     * @return array[]|self[]     */    public function getRoutes(): array    {        return $this->items;    }    /**     * Adds a route to a group.     *     * @param array|self $route     */    public function addRoute(string $prefix, $route)    {        list($prefix, $staticPrefix) = $this->getCommonPrefix($prefix, $prefix);        for ($i = \count($this->items) - 1; 0 <= $i; --$i) {            $item = $this->items[$i];            list($commonPrefix, $commonStaticPrefix) = $this->getCommonPrefix($prefix, $this->prefixes[$i]);            if ($this->prefix === $commonPrefix) {                // the new route and a previous one have no common prefix, let's see if they are exclusive to each others                if ($this->prefix !== $staticPrefix && $this->prefix !== $this->staticPrefixes[$i]) {                    // the new route and the previous one have exclusive static prefixes                    continue;                }                if ($this->prefix === $staticPrefix && $this->prefix === $this->staticPrefixes[$i]) {                    // the new route and the previous one have no static prefix                    break;                }                if ($this->prefixes[$i] !== $this->staticPrefixes[$i] && $this->prefix === $this->staticPrefixes[$i]) {                    // the previous route is non-static and has no static prefix                    break;                }                if ($prefix !== $staticPrefix && $this->prefix === $staticPrefix) {                    // the new route is non-static and has no static prefix                    break;                }                continue;            }            if ($item instanceof self && $this->prefixes[$i] === $commonPrefix) {                // the new route is a child of a previous one, let's nest it                $item->addRoute($prefix, $route);            } else {                // the new route and a previous one have a common prefix, let's merge them                $child = new self($commonPrefix);                list($child->prefixes[0], $child->staticPrefixes[0]) = $child->getCommonPrefix($this->prefixes[$i], $this->prefixes[$i]);                list($child->prefixes[1], $child->staticPrefixes[1]) = $child->getCommonPrefix($prefix, $prefix);                $child->items = [$this->items[$i], $route];                $this->staticPrefixes[$i] = $commonStaticPrefix;                $this->prefixes[$i] = $commonPrefix;                $this->items[$i] = $child;            }            return;        }        // No optimised case was found, in this case we simple add the route for possible        // grouping when new routes are added.        $this->staticPrefixes[] = $staticPrefix;        $this->prefixes[] = $prefix;        $this->items[] = $route;    }    /**     * Linearizes back a set of nested routes into a collection.     */    public function populateCollection(RouteCollection $routes): RouteCollection    {        foreach ($this->items as $route) {            if ($route instanceof self) {                $route->populateCollection($routes);            } else {                $routes->add(...$route);            }        }        return $routes;    }    /**     * Gets the full and static common prefixes between two route patterns.     *     * The static prefix stops at last at the first opening bracket.     */    private function getCommonPrefix(string $prefix, string $anotherPrefix): array    {        $baseLength = \strlen($this->prefix);        $end = min(\strlen($prefix), \strlen($anotherPrefix));        $staticLength = null;        set_error_handler([__CLASS__, 'handleError']);        for ($i = $baseLength; $i < $end && $prefix[$i] === $anotherPrefix[$i]; ++$i) {            if ('(' === $prefix[$i]) {                $staticLength = $staticLength ?? $i;                for ($j = 1 + $i, $n = 1; $j < $end && 0 < $n; ++$j) {                    if ($prefix[$j] !== $anotherPrefix[$j]) {                        break 2;                    }                    if ('(' === $prefix[$j]) {                        ++$n;                    } elseif (')' === $prefix[$j]) {                        --$n;                    } elseif ('\\' === $prefix[$j] && (++$j === $end || $prefix[$j] !== $anotherPrefix[$j])) {                        --$j;                        break;                    }                }                if (0 < $n) {                    break;                }                if (('?' === ($prefix[$j] ?? '') || '?' === ($anotherPrefix[$j] ?? '')) && ($prefix[$j] ?? '') !== ($anotherPrefix[$j] ?? '')) {                    break;                }                $subPattern = substr($prefix, $i, $j - $i);                if ($prefix !== $anotherPrefix && !preg_match('/^\(\[[^\]]++\]\+\+\)$/', $subPattern) && !preg_match('{(?<!'.$subPattern.')}', '')) {                    // sub-patterns of variable length are not considered as common prefixes because their greediness would break in-order matching                    break;                }                $i = $j - 1;            } elseif ('\\' === $prefix[$i] && (++$i === $end || $prefix[$i] !== $anotherPrefix[$i])) {                --$i;                break;            }        }        restore_error_handler();        if ($i < $end && 0b10 === (\ord($prefix[$i]) >> 6) && preg_match('//u', $prefix.' '.$anotherPrefix)) {            do {                // Prevent cutting in the middle of an UTF-8 characters                --$i;            } while (0b10 === (\ord($prefix[$i]) >> 6));        }        return [substr($prefix, 0, $i), substr($prefix, 0, $staticLength ?? $i)];    }

Static methods

Summary of issues

  • Tight Coupling
  • Hidden dependencies
  • Global state (if also using static variables)

Tight Coupling

Use of static methods always reduces flexibility by introducing tight coupling[1]. A static method tightly couples the calling code to the specific class the method exists in.

 
function totalAbs(double valuedouble value2) {
    return 
abs(value) + abs(value2);
}

Here, the method totalAbs has a dependency on the Math class and the .abs() method will always be called. Although for testing purposes this may not be a problem, the coupling reduces flexibility because the total method can only work with doubles/integers, as that's all the Math.abs() function can use. Although type coercion will allow the use of any primitive numeric type, these types have limitations. It's impossible to use another class such as BigInteger or a class for dealing with greater precision decimals or even alternative numbering systems such as Roman numerals.

The totalAbs function takes two doubles and converts them to their absolute values before adding them. This is inflexible because it only works with doubles. It's tied to doubles because that's what the Math.abs() static method requires. If, instead, using OOP an interface was created to handle any number that had this method:

 interface Numeric {
    public function 
abs(): Numeric;
}

It would then be possible to rewrite the totalAbs method to work with any kind of number:

 function totalAbs(Numeric valueNumeric value): Numeric {
    return 
value.abs() + value2.abs();
}

By removing the static method and using an instance method in its place the totalAbs method is now agnostic about the type of number it is dealing with. It could be called with any of the following (assuming they implement the Numeric interface)

 
totalAbs(new Integer(4), new Integer(-53));

totalAbs(new Double(34.4), new Integer(-2));

totalAbs(new BigInteger('123445454564765739878989343225778'), new Integer(2343));

totalAbs(new RomanNumeral('VII'), new RomanNumeral('CXV'));

Making the method reusable in a way that it wasn't when static methods were being used. By changing the static methods to instance methods, flexibility has been enhanced as the method can be used with any numeric type, not just numeric types that are supported by the Math.abs() method.

Broken encapsulation

Static methods also break encapsulation. Encapsulation is defined by Rogers[2] as:

the bundling of data with the methods that operate on that data

By passing the numeric value into the abs method, the data being operated on is being separated from the methods that operate on it, breaking encapsulation. Instead using num.abs() the data is encapsulated in the num instance and its type is not visible or relevant to the outside world. abs() will work on the data and work regardless of num's type, providing it implements the abs method.

This is a simple example, but applies to all static methods. Use of polymorphic instance methods that work on encapsulated data will always be more flexible than static method calls which can only ever deal with specific pre-defined types.

Further reading

Exceptions

The only exception to this rule is when a static method is used for object creation in place of the new keyword[3]. This is because the new keyword is already a static call. However, even here a non-static factory is often preferable for testing purposes[4][5].

References

  1. Popov, N. (2014) Don't be STUPID: GRASP SOLID! [online]. Available from: https://nikic.github.io/2011/12/27/Dont-be-STUPID-GRASP-SOLID.html
  2. Rogers, P. (2001) Encapsulation is not information hiding [online]. Available from: http://www.javaworld.com/article/2075271/core-java/encapsulation-is-not-information-hiding.html
  3. Sonmez, J. (2010) Static Methods Will Shock You [online]. Available from: http://simpleprogrammer.com/2010/01/29/static-methods-will-shock-you/
  4. Hevery, M. (2008) Static Methods are Death to Testability [online]. Available from: http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/
  5. Butler, T. (2013) Are Static Methods/Variables bad practice? [online]. Available from: https://r.je/static-methods-bad-practice.html
{ return false !== strpos($msg, 'Compilation failed: lookbehind assertion is not fixed length'); }}