Skip to content

Instantly share code, notes, and snippets.

@dana-ross
Last active January 30, 2016 19:24
Show Gist options
  • Save dana-ross/b751d6f036234792bf96 to your computer and use it in GitHub Desktop.
Save dana-ross/b751d6f036234792bf96 to your computer and use it in GitHub Desktop.
<?php
use DaveRoss\FunctionalProgrammingUtils\Left as Left;
use DaveRoss\FunctionalProgrammingUtils\Right as Right;
/**
* @param string $json A JSON string
* @return Either
*/
function parse_json_returning_either( $json ) {
$value = json_decode( $json );
if( is_null( $value ) ) {
return Left::of( $value );
}
else {
return Right::of( $value );
}
}
/**
* Extract the 'value' member from the parsed JSON
*/
function extract_value( $obj ) {
return $obj->value;
};
$good = parse_json_returning_either( '{ "label": "This is valid JSON", "value": 5 }' );
$bad = parse_json_returning_either( '{ "label": This is invalid JSON, "value": 5 }' );
// It doesn't matter if these are Left or Right monads, we still map() our functions
$good_value = $good->map( 'extract_value' );
$bad_value = $bad->map( 'extract_value' );
if( $good_value instanceof Left ) {
// This doesn't get echoed because $good_value is a Right monad
echo "An error occurred parsing the good JSON";
}
if( $bad_value instanceof Left ) {
// This echoes because $bad_value is a Left monad
echo "An error occurred parsing the bad JSON";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment