Skip to content

Commit

Permalink
Optimize code
Browse files Browse the repository at this point in the history
  • Loading branch information
matyhtf committed Sep 5, 2024
1 parent 17ff71c commit 1a66175
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 8 deletions.
1 change: 0 additions & 1 deletion examples/class/proxy_class.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?php
require dirname(__DIR__, 2) . '/vendor/autoload.php';
require dirname(__DIR__, 2) . '/lib/phpy/PyClass.php';
require __DIR__ . '/Dog.php';

PyCore::import('sys')->path->append('.');
Expand Down
36 changes: 29 additions & 7 deletions lib/phpy/PyClass.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ class PyClass
private string $_proxyFile;
private string $_class;

/**
* @throws \Exception
*/
function __construct()
{
if (!self::$_sys) {
Expand All @@ -39,7 +42,11 @@ function __construct()
}
}

private function makeProxy()
/**
* @return void
* @throws \Exception
*/
private function makeProxy(): void
{
$ref = new ReflectionClass($this);
$refParents = $ref->getAttributes('parent');
Expand All @@ -53,11 +60,11 @@ private function makeProxy()
foreach ($refParents as $refParent) {
$parent = $refParent->getArguments();
if (count($parent) == 1) {
$parents[] = $parent[0];
$parents[] = self::checkName($parent[0], 'class');
} else {
[$class, $package] = $parent;
$import .= 'import ' . $package . PHP_EOL;
$parents[] = $package . '.' . $class;
$import .= 'import ' . self::checkName($package, 'package') . PHP_EOL;
$parents[] = $package . '.' . self::checkName($class, 'class');
}
}
}
Expand Down Expand Up @@ -89,19 +96,34 @@ private function makeProxy()
file_put_contents($this->_proxyFile, $content);
}

protected function super()
protected function super(): ?PyObject
{
return $this->_super;
}

protected function self()
protected function self(): ?PyObject
{
return $this->_self;
}

static function setProxyPath(string $path): void
public static function setProxyPath(string $path): void
{
self::$_proxyPath = $path;
self::$_sys->path->append($path);
}

/**
* @throws \Exception
*/
private static function checkName(string $name, string $type): string
{
static $regx = [
'class' => '#^[a-z_][a-z_0-9]*$#i',
'package' => '#^[a-z_][a-z_0-9]*(\.[a-z_][a-z_0-9]*)*$#i'
];
if (!preg_match($regx[$type], $name)) {
throw new \Exception("Invalid $type name: '$name'");
}
return $name;
}
}
5 changes: 5 additions & 0 deletions lib/phpy/proxy.tpl
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
"""
This file is auto-generated by phpy. Please do not modify it.
"""

<?=$import?>


class <?=$this->_proxyClass?>(<?=implode(', ', $parents)?>):
def __init__(self, _this):
self.__this = _this
Expand Down

0 comments on commit 1a66175

Please sign in to comment.