Skip to content

Return statements require inside callables for array functions #3185

@Krilo89

Description

@Krilo89

Codesniffer doesn't highlight the required return statements used in callables.

Some callables require a 'return', but codesniffer doesn't highlight this as an error. For example this doesn't work:

$data = [
    [
        'id' => 1,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ],
    [
        'id' => 2,
        'first_name' => 'John',
        'last_name' => 'Dont',
    ],
    [
        'id' => 3,
        'first_name' => 'John',
        'last_name' => 'Does',
    ],
];
$names = array_map(
    function($person) { 
        $person['first_name'] . ' ' . $person['last_name']; 
    },
    $data
);
var_dump($names);

//Wil return:
array(3) {
  [0]=>
  NULL
  [1]=>
  NULL
  [2]=>
  NULL
}

But CodeSniffer does know about this requirement, so it can create an error or notice about this. The code below works correct:

<?php

$data = [
    [
        'id' => 1,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ],
    [
        'id' => 2,
        'first_name' => 'John',
        'last_name' => 'Dont',
    ],
    [
        'id' => 3,
        'first_name' => 'John',
        'last_name' => 'Does',
    ],
];
$names = array_map(
    function($person) { 
        return $person['first_name'] . ' ' . $person['last_name']; 
    },
    $data
);
var_dump($names);

// Will return
array(3) {
  [0]=>
  string(8) "John Doe"
  [1]=>
  string(9) "John Dont"
  [2]=>
  string(9) "John Does"
}

The following array functions use callables, so it can be implemented for them:
array_map
array_filter
array_reduce
array_diff_uassoc
array_diff_ukey
array_intersect_uassoc
array_intersect_ukey
array_udiff
array_udiff_assoc
array_udiff_uassoc
array_uintersect
array_uintersect_assoc
array_uintersect_uassoc

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions