Last active
August 29, 2015 14:02
-
-
Save felipevolpatto/61d6282b737bf1bef951 to your computer and use it in GitHub Desktop.
A class to work with the idea of collections in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Collections; | |
class ArrayCollection { | |
private $elements; | |
public function __construct(array $_elements = array()) { | |
$this->elements = $_elements; | |
} | |
public function set($key, $value) { | |
$this->elements[$key] = $value; | |
} | |
public function add($value) { | |
$this->elements[] = $value; | |
return true; | |
} | |
public function addWithKey($key, $value) { | |
if ($this->constainsKey($key)) return false; | |
$this->elements[$key] = $value; | |
return true; | |
} | |
public function clear() { | |
$this->elements = array(); | |
} | |
public function constainsKey($key) { | |
return (isset($this->elements[$key]) || array_key_exists($key, $this->elements)); | |
} | |
public function constainsElement($element) { | |
return in_array($element, $this->elements, true); | |
} | |
public function indexOf($element) { | |
return array_search($element, $this->elements, true); | |
} | |
public function count() { | |
return count($this->elements); | |
} | |
public function toArray() { | |
return $this->elements; | |
} | |
public function isEmpty() { | |
return !$this->elements; | |
} | |
public function getFirst() { | |
return reset($this->elements); | |
} | |
public function getLast() { | |
return end($this->elements); | |
} | |
public function getCurrent() { | |
return current($this->elements); | |
} | |
public function getNext() { | |
return next($this->elements); | |
} | |
public function getPrev() { | |
return prev($this->elements); | |
} | |
public function get($key) { | |
if (isset($this->elements[$key])) { | |
return $this->elements[$key]; | |
} | |
return null; | |
} | |
public function getKeys() { | |
return array_keys($this->elements); | |
} | |
public function getValues() { | |
return array_values($this->elements); | |
} | |
public function removeByKey($key) { | |
if (isset($this->elements[$key]) || array_key_exists($key, $this->elements)) { | |
$removed = $this->elements[$key]; | |
unset($this->elements[$key]); | |
return $removed; | |
} | |
return null; | |
} | |
public function removeByElement($element) { | |
$key = array_search($element, $this->elements, true); | |
if ($key !== false) { | |
unset($this->elements[$key]); | |
return true; | |
} | |
return false; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment