Skip to content

Commit

Permalink
Optimize PyClass code
Browse files Browse the repository at this point in the history
  • Loading branch information
matyhtf committed Sep 5, 2024
1 parent 1a66175 commit cd693eb
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
2 changes: 2 additions & 0 deletions examples/class/proxy_class.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@

PyCore::import('sys')->path->append('.');

\phpy\PyClass::setProxyPath(__DIR__, true);

$dog = new Dog('dog', 1);
$dog->speak('hello');
39 changes: 29 additions & 10 deletions lib/phpy/PyClass.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,30 @@
class PyClass
{
static private string $_proxyPath = '';
static private bool $_checkStat = false;
static private ?PyObject $_sys = null;
protected ?PyObject $_self = null;
protected ?PyObject $_super = null;
protected string $_proxyClass;
private string $_proxyFile;
private string $_class;

/**
* @throws \Exception
*/
function __construct()
{
if (!self::$_sys) {
self::$_sys = PyCore::import('sys');
}
if (!self::$_proxyPath) {
self::setProxyPath(getcwd() . '/__phpy_proxy__');
self::setProxyPath(getcwd());
}

$this->_class = get_class($this);
$this->_proxyClass = strtolower(str_replace('\\', '_', $this->_class));
$class = get_class($this);
$this->_proxyClass = strtolower(str_replace('\\', '_', $class));
$this->_proxyFile = self::$_proxyPath . '/' . $this->_proxyClass . '.py';

if (self::$_checkStat) {
$this->checkProxyFile();
}

if (!is_file($this->_proxyFile)) {
$this->makeProxy();
}
Expand Down Expand Up @@ -106,10 +107,19 @@ protected function self(): ?PyObject
return $this->_self;
}

public static function setProxyPath(string $path): void
/**
* @param string $rootPath
* @param bool $checkStat Check file changes and delete proxy files when PHP class files are updated
* @return void
*/
public static function setProxyPath(string $rootPath, bool $checkStat = false): void
{
self::$_proxyPath = $path;
self::$_sys->path->append($path);
self::$_proxyPath = $rootPath . '/__phpy_proxy__';
if (!self::$_sys) {
self::$_sys = PyCore::import('sys');
}
self::$_sys->path->append(self::$_proxyPath);
self::$_checkStat = $checkStat;
}

/**
Expand All @@ -126,4 +136,13 @@ private static function checkName(string $name, string $type): string
}
return $name;
}

private function checkProxyFile(): void
{
clearstatcache(true, $this->_proxyFile);
$ref = new ReflectionClass($this);
if (filemtime($ref->getFileName()) > filemtime($this->_proxyFile)) {
unlink($this->_proxyFile);
}
}
}

0 comments on commit cd693eb

Please sign in to comment.