diff --git a/src/helpers/App.php b/src/helpers/App.php index ab5ffc526ee..6bfab4fed41 100644 --- a/src/helpers/App.php +++ b/src/helpers/App.php @@ -32,12 +32,14 @@ use craft\web\User as WebUser; use craft\web\View; use HTMLPurifier_Encoder; +use Illuminate\Support\Collection; use ReflectionClass; use ReflectionProperty; use yii\base\Event; use yii\base\Exception; use yii\base\InvalidArgumentException; use yii\base\InvalidValueException; +use yii\base\Model; use yii\helpers\Inflector; use yii\mutex\FileMutex; use yii\web\JsonParser; @@ -134,34 +136,38 @@ public static function env(string $name): mixed * For example, if an object has a `fooBar` property, and `X`/`X_` is passed as the prefix, the resulting array * may contain a `fooBar` key set to an `X_FOO_BAR` environment variable value, if it exists. * - * @param string $class The class name + * @param object|string $class The class name or object * @phpstan-param class-string $class * @param string|null $envPrefix The environment variable name prefix * @return array * @phpstan-return array * @since 4.0.0 */ - public static function envConfig(string $class, ?string $envPrefix = null): array + public static function envConfig(object|string $class, ?string $envPrefix = null): array { $envPrefix = $envPrefix !== null ? StringHelper::ensureRight($envPrefix, '_') : ''; - $properties = (new ReflectionClass($class))->getProperties(ReflectionProperty::IS_PUBLIC); - $envConfig = []; - - foreach ($properties as $prop) { - if ($prop->isStatic()) { - continue; - } - - $propName = $prop->getName(); - $envName = $envPrefix . strtoupper(StringHelper::toSnakeCase($propName)); - $envValue = static::env($envName); - - if ($envValue !== null) { - $envConfig[$propName] = $envValue; - } - } - - return $envConfig; + $isModel = (new ReflectionClass($class))->isSubclassOf(Model::class); + + /** @var ?Model $model */ + $model = $isModel + ? ($class instanceof Model ? $class : Craft::createObject($class)) + : null; + + $properties = $model + ? Collection::make($model->attributes()) + : Collection::make((new ReflectionClass($class))->getProperties(ReflectionProperty::IS_PUBLIC)) + ->filter(fn(ReflectionProperty $prop) => !$prop->isStatic()) + ->map(fn(ReflectionProperty $prop) => $prop->getName()); + + return $properties + ->mapWithKeys(function(string $propName) use ($envPrefix) { + $envName = $envPrefix . strtoupper(StringHelper::toSnakeCase($propName)); + $envValue = static::env($envName); + + return [$propName => $envValue]; + }) + ->whereNotNull() + ->all(); } /**