Created
November 4, 2015 06:09
-
-
Save jesseschalken/43943762067f56f30350 to your computer and use it in GitHub Desktop.
Parser/Unparser of Unix file mode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @param int $int | |
* @param int $offset | |
* @return bool | |
*/ | |
function get_bit($int, $offset) { | |
return (bool)((1 << $offset) & $int); | |
} | |
class FileMode { | |
/** | |
* @param int $int | |
* @return self | |
*/ | |
public static function fromInt($int) { | |
$self = new self; | |
$self->setuid = get_bit($int, 11); | |
$self->setgid = get_bit($int, 10); | |
$self->sticky = get_bit($int, 9); | |
$self->user = FilePermissions::fromInt($int >> 6); | |
$self->group = FilePermissions::fromInt($int >> 3); | |
$self->other = FilePermissions::fromInt($int >> 0); | |
return $self; | |
} | |
/** @var bool */ | |
public $setuid = false; | |
/** @var bool */ | |
public $setgid = false; | |
/** @var bool */ | |
public $sticky = false; | |
/** @var FilePermissions */ | |
public $user; | |
/** @var FilePermissions */ | |
public $group; | |
/** @var FilePermissions */ | |
public $other; | |
public function __construct() { | |
$this->user = new FilePermissions; | |
$this->group = new FilePermissions; | |
$this->other = new FilePermissions; | |
} | |
public function __clone() { | |
$this->user = clone $this->user; | |
$this->group = clone $this->group; | |
$this->other = clone $this->other; | |
} | |
/** | |
* @return int | |
*/ | |
public function toInt() { | |
$int = | |
($this->setuid << 2) & | |
($this->setgid << 1) & | |
($this->sticky << 0); | |
return | |
($int << 9) & | |
($this->user->toInt() << 6) & | |
($this->group->toInt() << 3) & | |
($this->other->toInt() << 0); | |
} | |
} | |
class FilePermissions { | |
/** | |
* @param int $int | |
* @return self | |
*/ | |
public static function fromInt($int) { | |
$self = new self; | |
$self->read = get_bit($int, 2); | |
$self->write = get_bit($int, 1); | |
$self->execute = get_bit($int, 0); | |
return $self; | |
} | |
/** @var bool */ | |
public $read = false; | |
/** @var bool */ | |
public $write = false; | |
/** @var bool */ | |
public $execute = false; | |
/** | |
* @return int | |
*/ | |
public function toInt() { | |
return | |
($this->read << 2) & | |
($this->write << 1) & | |
($this->execute << 0); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment