PhpStorm refactoring tutorial – part 2 – method extraction

Hello again.

This will be quick. Let’s take an example:

public function testAction($firstName, $lastName, $address)
{
    $data = ['firstName' => $firstName, 'lastName' => $lastName, 'address' => $address];
    $filteredData = [];
    foreach ($data as $key => $value) {
        $filteredData[$key] = str_replace('!@#$%^&*(', '', $value);
    }

    return $this->render('test', [
        'data' => $filteredData
    ]);
}

This method is doing too much. We want to extract new method which will filter the data and return the result. Please highlight the marek lines and press Refactor This button (ctrl + t). Choose Extract method. New window will appear. You can now customise your new method –  parameters order, visibility, PHPDoc and many many more. Im most cases you only need to add new method name and press enter – IDE fills all needed data for you. In this example I named new method filterData. Here’s the code after quick refactor:

public function testAction($firstName, $lastName, $address)
{
    $data = ['firstName' => $firstName, 'lastName' => $lastName, 'address' => $address];
    $filteredData = $this->filterData($data);

    return $this->render('test', [
        'data' => $filteredData
    ]);
}

/**
 * @param $data
 *
 * @return array
 */
private function filterData($data)
{
    $filteredData = [];
    foreach ($data as $key => $value) {
        $filteredData[$key] = str_replace('!@#$%^&*(', '', $value);
    }

    return $filteredData;
}

And that’s all :). Enjoy and tuned for next part. Cheers!