-
-
Save johnpbloch/c95fa70d21d157a7707d745ffb586606 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace JPB; | |
with( open( 'myfile.txt', 'w+' ), function( $file ) { | |
fwrite( $file, 'Hello World!' ); | |
} ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace JPB; | |
interface HasContextInterface | |
{ | |
function __invoke(...$args): \Generator; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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