84 lines
1.7 KiB
PHP
84 lines
1.7 KiB
PHP
<?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();
|
|
}
|
|
} |