php-ipc/src/Key/FileKey.php

99 lines
2.1 KiB
PHP
Raw Permalink Normal View History

2018-04-15 14:41:46 +00:00
<?php
namespace NoccyLabs\Ipc\Key;
class FileKey implements KeyInterface
{
private $proj;
private $pathname;
/**
* Constructor
*
* @param string $pathname
* @param string $proj
* @param boolean $create
*/
2018-04-15 22:41:13 +00:00
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)
2018-04-15 14:41:46 +00:00
{
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);
}
2018-04-15 22:41:13 +00:00
$this->pathname = $pathname;
2018-04-15 14:41:46 +00:00
}
/**
2018-04-15 22:41:13 +00:00
* Get the project identifier. Not guaranteed to be printable
2018-04-15 14:41:46 +00:00
*
* @return string
*/
2018-04-15 22:41:13 +00:00
public function getProjectIdentifier():string
2018-04-15 14:41:46 +00:00
{
2018-04-15 22:41:13 +00:00
return $this->proj;
2018-04-15 14:41:46 +00:00
}
/**
2018-04-15 22:41:13 +00:00
* Set the project identifier
2018-04-15 14:41:46 +00:00
*
2018-04-15 22:41:13 +00:00
* @param string $proj
* @return void
2018-04-15 14:41:46 +00:00
*/
2018-04-15 22:41:13 +00:00
public function setProjectIdentifier(string $proj)
2018-04-15 14:41:46 +00:00
{
2018-04-15 22:41:13 +00:00
$this->proj = substr($proj, 0, 1);
2018-04-15 14:41:46 +00:00
}
/**
* 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();
}
}