Initial commit
This commit is contained in:
84
src/Key/FileKey.php
Normal file
84
src/Key/FileKey.php
Normal file
@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace NoccyLabs\Ipc\Key;
|
||||
|
||||
class FileKey implements KeyInterface
|
||||
{
|
||||
private $proj;
|
||||
|
||||
private $pathname;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param string $pathname
|
||||
* @param string $proj
|
||||
* @param boolean $create
|
||||
*/
|
||||
public function __construct(string $pathname, $proj="\0", bool $create=false)
|
||||
{
|
||||
if (!file_exists($pathname)) {
|
||||
if (!$create) {
|
||||
throw new \RuntimeException("Path does not exist: {$pathname}");
|
||||
}
|
||||
if (!is_dir(dirname($pathname))) {
|
||||
throw new \RuntimeException("The directory ".dirname($pathname)." does not exist");
|
||||
}
|
||||
touch($pathname);
|
||||
}
|
||||
|
||||
$this->pathname = $pathname;
|
||||
$this->proj = substr($proj,0,1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the pathname used to generate the key
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getPathname():string
|
||||
{
|
||||
return $this->pathname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the project identifier. Not guaranteed to be printable
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getProjectIdentifier():string
|
||||
{
|
||||
return $this->proj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the key value
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getKey():int
|
||||
{
|
||||
return ftok($this->pathname, $this->proj);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone the FileKey, increasing the project identifier to create a new key for the
|
||||
* same file
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __clone()
|
||||
{
|
||||
$this->proj = chr(ord($this->proj) + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create printable representation of the key
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function __toString()
|
||||
{
|
||||
return $this->getKey();
|
||||
}
|
||||
}
|
9
src/Key/KeyInterface.php
Normal file
9
src/Key/KeyInterface.php
Normal file
@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace NoccyLabs\Ipc\Key;
|
||||
|
||||
interface KeyInterface
|
||||
{
|
||||
public function getKey():int;
|
||||
public function __toString();
|
||||
}
|
Reference in New Issue
Block a user