Closed thekid closed 3 years ago
Additional changes to xp-framework/reflection
and xp-framework/core
reflection need to be made to support reflective access to parameter defaults:
diff --git a/src/main/php/lang/reflect/Parameter.class.php b/src/main/php/lang/reflect/Parameter.class.php
index decf71dc6..789e51192 100755
--- a/src/main/php/lang/reflect/Parameter.class.php
+++ b/src/main/php/lang/reflect/Parameter.class.php
@@ -1,6 +1,6 @@
<?php namespace lang\reflect;
-use lang\{ElementNotFoundException, ClassLoadingException, ClassNotFoundException, XPClass, Type, TypeUnion};
+use lang\{ElementNotFoundException, IllegalStateException, ClassLoadingException, ClassNotFoundException, XPClass, Type, TypeUnion};
use util\Objects;
/**
@@ -160,17 +160,24 @@ class Parameter {
}
/**
- * Get default value.
+ * Get default value. Additionally checks `default` annotation for NULL defaults.
*
* @throws lang.IllegalStateException in case this argument is not optional
* @return var
*/
public function getDefaultValue() {
if ($this->_reflect->isOptional()) {
- return $this->_reflect->isDefaultValueAvailable() ? $this->_reflect->getDefaultValue() : null;
+ if (!$this->_reflect->isDefaultValueAvailable()) return null;
+
+ $value= $this->_reflect->getDefaultValue();
+ if (null === $value) {
+ $details= XPClass::detailsForMethod($this->_reflect->getDeclaringClass(), $this->_details[1]);
+ return $details[DETAIL_TARGET_ANNO]['$'.$this->_reflect->getName()]['default'] ?? null;
+ }
+ return $value;
}
- throw new \lang\IllegalStateException('Parameter "'.$this->_reflect->getName().'" has no default value');
+ throw new IllegalStateException('Parameter "'.$this->_reflect->getName().'" has no default value');
}
/**
Additional changes to xp-framework/reflection and xp-framework/core reflection need to be made
Real-world example
use net\daringfireball\markdown\Markdown;
use web\frontend\helpers\Extension;
class RenderMarkdown extends Extension {
private $engine;
/** Creates new markdown renderer */
public function __construct() {
$this->engine= new Markdown();
}
// ...
}
use net\daringfireball\markdown\Markdown;
use web\frontend\helpers\Extension;
class RenderMarkdown extends Extension {
private $engine= new Markdown();
// ...
}
Initialization is now supported for properties, static variables, parameter defaults and in combination with property promotion. On top of https://wiki.php.net/rfc/new_in_initializers, this pull request also supports arbitrary expressions in any of these places (as hinted in the RFC PHP might do in the future).
The parser already supported expressions in these place, but emitting the code generated compile errors of the kind Constant expression contains invalid operations.
⚠️ This pull request does not support non-constant expressions for
const
, as there is no way to emit valid PHP 7.X / PHP 8.0 code nor any behind-the-scenes trickery (not even with runkit) to achieve this!Code added to
main
is less than 100 lines:/cc @mikey179