Skip to content

Instantly share code, notes, and snippets.

@johnpbloch johnpbloch/File.php Secret
Last active Feb 11, 2019

Embed
What would you like to do?
<?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
You can’t perform that action at this time.