refactor three level indentation
decayingMind
php
3 years ago
1.7 kB
10
Indexable
<?php
// Three levels of indentation
class BankAccounts {
protected $accounts;
function __construct($accounts)
{
$this->accounts = $accounts;
}
// refactoring 3 levels of indentation
// public function filterBY($accountType)
// {
// $filtered = [];
//
// foreach ($this->accounts as $key => $account) {
//
// if ($account->type() == $accountType)
// {
// if ($account->isActive())
// {
// $filtered[] = $account;
// }
// }
// }
// return $filtered;
// }
public function filterBY($accountType) : array {
return array_filter($this->accounts, function ($account) use($accountType) {
return $this->isOfType($accountType, $account);
});
}
private function isOfType($accountType, $account) {
return $account->type() == $accountType && $account->isActive();
}
}
class Account {
protected $type;
function __construct($type)
{
$this->type = $type;
}
public static function open($type)
{
return new static($type);
}
public function type()
{
return $this->type;
}
public function isActive()
{
return true;
}
}
$accounts = [
Account::open('checking'),
Account::open('savings'),
Account::open('checking'),
Account::open('savings')
];
$bankAccounts = new BankAccounts($accounts);
$savings = $bankAccounts->filterBY('savings');
print_r($savings);Editor is loading...