Skip to content

Instantly share code, notes, and snippets.

@johnpbloch
Last active February 11, 2019 11:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnpbloch/c95fa70d21d157a7707d745ffb586606 to your computer and use it in GitHub Desktop.
Save johnpbloch/c95fa70d21d157a7707d745ffb586606 to your computer and use it in GitHub Desktop.
<?php
namespace JPB;
with( open( 'myfile.txt', 'w+' ), function( $file ) {
fwrite( $file, 'Hello World!' );
} );
<?php
namespace JPB;
class File implements HasContextInterface
{
protected $fileName;
protected $mode;
function __construct( $fileName, $mode = 'r' )
{
$this->fileName = $fileName;
$this->mode = $mode;
}
function __invoke(...$args): \Generator
{
$file = $this->getFile();
yield $file;
fclose($file);
}
protected function getFile(): resource
{
$file = fopen( $this->fileName, $this->mode );
if ( ! $file ) { throw new \InvalidInputException( 'Could not open the requested file' ); }
return $file;
}
}
<?php
namespace JPB;
interface HasContextInterface
{
function __invoke(...$args): \Generator;
}
<?php
namespace JPB;
function with( HasContextInterface $context, callable $do ) {
foreach( $context() as $thing ) {
$return = $do( $thing );
}
return $return;
}
function open( $file, $mode = 'r' ): File {
return new File( $file, $mode );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment