Skip to content

Instantly share code, notes, and snippets.

@dana-ross
Last active January 6, 2016 17:18
Show Gist options
  • Save dana-ross/3b10ae7f202335fc9f21 to your computer and use it in GitHub Desktop.
Save dana-ross/3b10ae7f202335fc9f21 to your computer and use it in GitHub Desktop.
Example of a WordPress plugin written in a point-free style using PHP Functional Programming Utils
<?php
/*
Plugin Name: Comment Hash
Description: Sign comments with a sha256 hash to prevent tampering
Author: Dave Ross
Version: 1.0
Author URI: http://davidmichaelross.com/
*/
// Leaving out the boilerplate that loads & sets up PHP Functional Programming Utils
// See https://github.com/daveross/functional-programming-utils
/**
* Call a function $fn on $value if $index is odd
* This is the only function actually written for this plugin
*/
$call_if_index_odd = function( $fn, $value, $index ) {
return ( 0 === $index % 2) ? $value : $fn( $value );
};
/**
* Hooks a function into the 'pre_comment_content' filter
*/
$add_pre_comment_content_filter = partially_apply( 'add_filter', 'pre_comment_content' );
/**
* Returns the sha256 hash of a value
*/
$sha256 = partially_apply( 'hash', 'sha256' );
/**
* Call $sha256 if $index is odd (uses $call_if_index_odd)
*/
$sha256_if_index_odd = partially_apply( $call_if_index_odd, $sha256 );
/**
* Implode an array of strings into a single string, separated by spaces
*/
$array_to_string = partially_apply( 'implode', ' ' );
/**
* Start filling an array from the beginning
* @param int $count
* @param mixed $value
* @return array
*/
$array_fill_from_beginning = partially_apply( 'array_fill', 0 );
/**
* Creates an array with the same value twice
* @param mixed
* @return array
*/
$value_twice_in_array = partially_apply( $array_fill_from_beginning, 2 );
/**
* Calls array_map for a two-element array, passing an extra parameter with the current $index
* @param Callable $fn
* @param Array $a
* @return Array
*/
$map_over_two_array_entries_with_indexes = partially_apply_right( 'array_map', range( 0, 1 ) );
/**
* Given a two-element array, call $sha256 on the second element
* @param Array $a
* @return Array
*/
$map_sha256_on_second_entry = partially_apply( $map_over_two_array_entries_with_indexes, $sha256_if_index_odd );
/**
* Append a sha256 hash to the end of a string
* @param string $x
* @return string
*/
$append_comment_hash = compose( $array_to_string, $map_sha256_on_second_entry, $value_twice_in_array );
// Register $append_comment_hash as a filter for comment contents
$add_pre_comment_content_filter( $append_comment_hash );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment