Skip to content

Instantly share code, notes, and snippets.

@Phil-Venter
Last active August 18, 2020 08:08
Show Gist options
  • Save Phil-Venter/9a7273bd7a33d724295953e58a58c556 to your computer and use it in GitHub Desktop.
Save Phil-Venter/9a7273bd7a33d724295953e58a58c556 to your computer and use it in GitHub Desktop.
Playing around with Functional PHP
<?php
class Collection
{
private $data;
public function __construct($data)
{
$this->data = $data;
}
public function __invoke()
{
return $this->data;
}
public function concat($data)
{
$this->data = array_merge($this->data, $data);
return $this;
}
public function every($callback)
{
$this->data = sizeof($this->data) === sizeof(array_filter($this->data, $callback));
return $this;
}
public function filter($callback)
{
$this->data = array_filter($this->data, $callback);
return $this;
}
public function in($data)
{
$this->data = in_array($data, $this->data);
return $this;
}
public function key($data)
{
$this->data = array_key_exists($data, $this->data);
return $this;
}
public function map($callback)
{
$this->data = array_map($callback, $this->data);
return $this;
}
public function reduce($callback, $initial = null)
{
$this->data = array_reduce($this->data, $callback, $initial);
return $this;
}
public function remove($data)
{
$this->data = array_diff($this->data, $data);
return $this;
}
public function slice($start, $length = null)
{
$this->data = array_slice($this->data, $start, $length);
return $this->data;
}
public function some($callback)
{
$this->data = sizeof(array_filter($this->data, $callback)) > 0;
return $this;
}
}
<?php
class Filtering
{
public static function isType($comparator)
{
return function ($value) use ($comparator) {
$type = gettype($value);
if ($type !== 'resource')
return $type === $comparator;
return get_resource_type($value) === $comparator;
};
}
public static function isValue($comparator)
{
return function ($value) use ($comparator) {
return $value === $comparator;
};
}
}
<?php
class Mapping
{
public static function extract($key)
{
return function ($array) use ($key) {
return $array[$key];
};
}
}
<?php
class Reducing
{
public static function sumLength()
{
return function ($carry, $item) {
return $carry + strlen($item);
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment