php-ipc/src/Key/FileKey.php

99 lines
2.1 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)
{
$this->setPathname($pathname, $create);
$this->setProjectIdentifier($proj);
}
/**
* Get the pathname used to generate the key
*
* @return string
*/
public function getPathname():string
{
return $this->pathname;
}
public function setPathname(string $pathname, 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;
}
/**
* Get the project identifier. Not guaranteed to be printable
*
* @return string
*/
public function getProjectIdentifier():string
{
return $this->proj;
}
/**
* Set the project identifier
*
* @param string $proj
* @return void
*/
public function setProjectIdentifier(string $proj)
{
$this->proj = substr($proj, 0, 1);
}
/**
* 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();
}
}