Create a gist now

Instantly share code, notes, and snippets.

@zuzuleinen /if.php Secret
Last active Mar 16, 2017

What would you like to do?
Avoid using ifs
<?php
//instead of using ifs in foreach
foreach ($this->currentPackingList->packingBoxes() as $packingBox) {
if (!$this->packingService->isPackingMaterial($packingBox->itemId())) {
continue;
}
$price += $this->merchantPriceForItem($packingBox->itemId()) * $this->packagingInfo->itemCount($packingBox->itemId());
}
//sometimes makes sense to have a collection
$packingMaterials = new PackingMaterialCollection($this->currentPackingList);
foreach ($packingMaterials as $packingMaterial) {
$price += $this->merchantPriceForItem($packingBox->itemId()) * $this->packagingInfo->itemCount($packingBox->itemId());
}
//class
final class PackingMaterialCollection implements \IteratorAggregate
{
/**
* @var PackingList
*/
private $packingList;
/**
* @var \CallbackFilterIterator
*/
private $iterator;
public function __construct(PackingList $packingList)
{
$this->packingList = $packingList;
$this->iterator = new \CallbackFilterIterator(
new \ArrayIterator($this->packingList->packingBoxes()),
function (PackingBox $packingBox) {
return $this->isPackingMaterial($packingBox);
}
);
}
public function isPackingMaterial(PackingBox$packingBox)
{
$packingMaterials = [
PackingMaterials::BOTTLE_BOX,
PackingMaterials::GLASS_BOX,
PackingMaterials::DISH_BOX,
PackingMaterials::PACKING_TAPE,
PackingMaterials::WRAPPING_TISSUE,
PackingMaterials::STRETCH_WRAP,
PackingMaterials::BUBBLE_WRAP,
PackingMaterials::CLOTHES_BOX,
PackingMaterials::SMALL_BOX,
PackingMaterials::PROFI_BOX
];
return in_array($packingBox->itemId(), $packingMaterials);
}
public function getIterator()
{
return new \IteratorIterator($this->iterator);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment