Skip to content

Instantly share code, notes, and snippets.

@salodev
Created February 12, 2023 13:23
Show Gist options
  • Save salodev/aadae00f849b8d57bd55fa32c924e1e1 to your computer and use it in GitHub Desktop.
Save salodev/aadae00f849b8d57bd55fa32c924e1e1 to your computer and use it in GitHub Desktop.
Este es un ejemplo sencillo de programación funcional y tuberías con php
<?php
function pipe(...$functions): callable {
return function($value) use ($functions) {
foreach($functions as $function) {
$value = $function($value);
}
return $value;
};
}
function map(callable $function): callable {
return function(array $values) use ($function) {
return array_map(function($item) use ($function) {
return $function($item);
}, $values);
};
}
function splitBy(string $string): callable {
return function(string $value) use($string): array {
return explode($string, $value);
};
}
function reverseArr(): callable {
return function(array $value): array {
return array_reverse($value);
};
}
function takeFirst(): callable {
return function(array $value): ?string {
return $value[0] ?? null;
};
}
function takeElement(int $offset): callable {
return function(array $value) use($offset): ?string {
return $value[$offset] ?? null;
};
}
function dateFormat(string $format): callable {
return function(string $value) use($format): ?string {
return date($format, strtotime($value));
};
}
function enquote(): callable {
return function(string $value) {
return "'{$value}'";
};
}
$formatter = pipe(
splitBy(' '),
reverseArr(),
takeFirst(),
);
$input = ['prueba uno a las 09:12:22', 'prueba dos a las 10:00:00'];
$result = pipe(
map($formatter),
map(enquote())
)($input);
print_r($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment