Skip to content

Commit

Permalink
Update Stream
Browse files Browse the repository at this point in the history
  • Loading branch information
VennDev authored Jul 28, 2023
1 parent 7979166 commit fff5f1e
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/vennv/vapm/Error.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,6 @@ final class Error

public const FILE_DOES_NOT_EXIST = "Error: File does not exist!";

public const FILE_ALREADY_EXISTS = "Error: File already exists!";

}
68 changes: 68 additions & 0 deletions src/vennv/vapm/Stream.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,20 @@ public static function append(string $path, string $data) : Promise;
*/
public static function delete(string $path) : Promise;

/**
* @throws Throwable
*
* Use this to create a file.
*/
public static function create(string $path) : Promise;

/**
* @throws Throwable
*
* Use this to create a file or overwrite a file.
*/
public static function overWrite(string $path, string $data) : Promise;

}

final class Stream implements StreamInterface
Expand Down Expand Up @@ -178,4 +192,58 @@ public static function delete(string $path): Promise
});
}

/**
* @throws Throwable
*/
public static function create(string $path): Promise
{
return new Promise(function($resolve , $reject) use ($path): void
{
$generator = function($path) use ($reject): Generator
{
if (!file_exists($path))
{
yield touch($path);
}
else
{
$reject(Error::FILE_ALREADY_EXISTS);
}
};

$generator($path);

$resolve();
});
}

/**
* @throws Throwable
*/
public static function overWrite(string $path, string $data): Promise
{
return new Promise(function($resolve , $reject) use ($path, $data): void
{
$generator = function($path, $data) use ($reject): Generator
{
$handle = fopen($path, 'w+');

if ($handle === false)
{
$reject(Error::UNABLE_TO_OPEN_FILE);
}
else
{
stream_set_blocking($handle, false);

yield fwrite($handle, $data);
}
};

$generator($path, $data);

$resolve();
});
}

}

0 comments on commit fff5f1e

Please sign in to comment.