Skip to content

Refactor getPostcodesArray(): Remove unreachable defensive checks to resolve coverage gaps #3

@charlesroper

Description

@charlesroper

Background

In TESTING.md, it is noted that there are untested error handling paths in getPostcodesArray() and suggests the following to improve coverage:

  1. Test the preg_split() error path by passing malformed regex patterns
  2. Test non-string elements in the postcode array

The Problem

Because the regex pattern /\r\n|\r|\n/ is hardcoded in the function, it can never be "malformed" dynamically by user input. preg_split() will only fail here if PHP suffers a catastrophic error (like running out of memory). Furthermore, preg_split() will only ever return an array of strings in this context, meaning the array elements will never be non-strings.

The checks if ($rows === false) and if (!is_string($row)) are defensive "dead code" that cannot be reached during normal execution, making them virtually impossible to unit test.

The Solution

Instead of trying to devise impossible test scenarios to hit 100% coverage, we should simply remove these unreachable defensive checks. This keeps the codebase leaner, reduces confusion for future maintainers, and automatically resolves the coverage gap.

Proposed Code Change:

Update src/functions.php to remove the dead code:

function getPostcodesArray(?string $postcodes_querystring): array
{
    // If the input is empty, return an empty array.
    if (!$postcodes_querystring) {
        return [];
    }

    // Use a regex to split on the CR+LF or just CR or just LF.
    $rows = preg_split('/\r\n|\r|\n/', $postcodes_querystring);
    $postcodes = [];

    // Normalise the postcode in each row and add non-empty results to the array.
    foreach ($rows as $row) {
        $clean = normalisePostcode($row);
        if ($clean !== '') {
            $postcodes[] = $clean;
        }
    }

    return $postcodes;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions