Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 43 additions & 7 deletions doc/UPGRADING.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,14 +210,38 @@ $form->addVariable(
```

The `$type` parameter is a string, not a Type object. BaseForm maps
it to a Variable class internally:
it to a Variable class using three shapes, tried in order:

1. **FQCN**. Any string containing a `\` is treated as a fully-qualified
class name and used as-is. Preferred for new code and required for any
package whose Variable classes live outside the naming conventions below
(for example non-Horde vendors).

```php
$form->addVariable('Address(es)', 'addresses', \Horde\Ingo\Form\V3\LongemailVariable::class, false);
```

2. **`'app:type'`**. Resolved to `Horde\{App}\Form\V3\{Type}Variable`
first (matches the Composer PSR-4 map every modern Horde package
publishes), then to `{App}\Form\V3\{Type}Variable` as a BC fallback
for packages that shipped Variable classes under that root before this
dispatch was corrected. The legacy PSR-0 `{App}_Form_Type_{Type}`
class is used as a last resort when `Horde_Form::$legacy` is on.

3. **bare `'type'`**. Resolved to `Horde\Form\V3\{Type}Variable`.

Examples:

- `'text'` -> `Horde\Form\V3\TextVariable`
- `'enum'` -> `Horde\Form\V3\EnumVariable`
- `'whups:priority'` -> `Whups\Form\V3\PriorityVariable`
- `'whups:priority'` -> `Horde\Whups\Form\V3\PriorityVariable`
(with `Whups\Form\V3\PriorityVariable` as BC fallback)
- `\Horde\Ingo\Form\V3\FoldersVariable::class` -> used directly

This mapping is **intended**, not a compromise — it keeps the form
definition readable and decoupled from class names.
The string-shape mapping is **intended**, not a compromise. It keeps
form definitions readable and decoupled from class names. The FQCN
shape is there for the cases where a package can't or shouldn't rely
on the naming convention.

---

Expand Down Expand Up @@ -530,8 +554,10 @@ class MyApp_Form_Type_zipcode extends Horde_Form_Type
public function isValid($var, $vars, $value, $message) { ... }
}

// V3 — Variable subclass (Type merged in)
namespace MyApp\Form\V3;
// V3 — Variable subclass (Type merged in). Namespace matches the
// package's Composer PSR-4 map, i.e. Horde\{App}\... for Horde
// packages.
namespace Horde\MyApp\Form\V3;
use Horde\Form\V3\BaseVariable;

class ZipcodeVariable extends BaseVariable
Expand All @@ -546,7 +572,17 @@ class ZipcodeVariable extends BaseVariable
}
}

// Usage unchanged:
// Preferred: pass the FQCN, no naming-convention magic required.
$form->addVariable(
'ZIP', 'zip',
\Horde\MyApp\Form\V3\ZipcodeVariable::class,
true, false, null, ['US']
);

// Also supported: 'app:type' short form. Resolves to
// Horde\MyApp\Form\V3\ZipcodeVariable, falling back to
// MyApp\Form\V3\ZipcodeVariable for packages that shipped
// Variable classes under the unvendored root.
$form->addVariable('ZIP', 'zip', 'myapp:zipcode', true, false, null, ['US']);
```

Expand Down
75 changes: 61 additions & 14 deletions lib/Horde/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,16 @@ public function getRenderer($params = [])
*
* @param string $humanName The human-readable label for the field.
* @param string $varName The internal variable name.
* @param string $type The field type identifier.
* @param string $type The field type identifier. Accepted shapes:
* - a fully-qualified class name of a V3
* Variable subclass (preferred);
* - 'app:type', resolved to
* Horde\{App}\Form\V3\{Type}Variable, then
* {App}\Form\V3\{Type}Variable, then the
* legacy {App}_Form_Type_{Type} class;
* - a bare type name, resolved to
* Horde\Form\V3\{Type}Variable then the
* legacy Horde_Form_Type_{Type} class.
* @param array $params Type initialization parameters.
* @param boolean $required Whether the field is required.
* @param boolean $readonly Whether the field is read-only.
Expand All @@ -200,18 +209,56 @@ public static function createVariable(
$readonly = false,
$description = null,
) {
$arr = explode(':', $type, 2);
if (count($arr) == 2) {
$app = ucfirst($arr[0]);
$name = $arr[1];
// Resolve $type to a concrete Variable/Type class. Three shapes are
// accepted, tried in order:
//
// 1. FQCN — any string containing a namespace separator is treated
// as a fully-qualified class name and used as-is. This is the
// preferred shape for new code and lets integrators point at a
// class in any namespace (including non-Horde vendors) without
// naming-convention gymnastics.
//
// 2. 'app:type' — try the vendor-namespaced convention
// "Horde\{App}\Form\V3\{Type}Variable" first (matches the
// Composer PSR-4 map every modern Horde package publishes),
// then the historical "{App}\Form\V3\{Type}Variable" as a BC
// fallback for packages that shipped variables under that
// root before this dispatch was fixed.
//
// 3. bare 'type' — "Horde\Form\V3\{Type}Variable" (unchanged).
//
// Each shape falls back to the legacy PSR-0 "{App}_Form_Type_{Type}"
// form when self::$legacy is on, so pre-V3 packages keep working.
$modern = false;
$legacyClass = null;
if (str_contains($type, '\\')) {
$class = ltrim($type, '\\');
$modern = class_exists($class);
} else {
$app = 'Horde';
$name = $arr[0];
$arr = explode(':', $type, 2);
if (count($arr) == 2) {
$app = ucfirst($arr[0]);
$name = ucfirst($arr[1]);
$candidates = [
'Horde\\' . $app . '\\Form\\V3\\' . $name . 'Variable',
$app . '\\Form\\V3\\' . $name . 'Variable',
];
$legacyClass = $app . '_Form_Type_' . $name;
} else {
$name = ucfirst($arr[0]);
$candidates = ['Horde\\Form\\V3\\' . $name . 'Variable'];
$legacyClass = 'Horde_Form_Type_' . $name;
}
$class = $candidates[0];
foreach ($candidates as $candidate) {
if (class_exists($candidate)) {
$class = $candidate;
$modern = true;
break;
}
}
}

$name = ucfirst($name);
$class = $app . '\\Form\\V3\\' . $name . 'Variable';
$modern = class_exists($class);
if ($modern) {
$var = new $class(
$humanName,
Expand All @@ -220,15 +267,15 @@ public static function createVariable(
$readonly,
$description
);
} elseif (self::$legacy) {
$class = $app . '_Form_Type_' . $name;
$var = class_exists($class) ? new $class() : null;
} elseif (self::$legacy && $legacyClass !== null && class_exists($legacyClass)) {
$class = $legacyClass;
$var = new $class();
} else {
$var = null;
}

if ($var === null) {
throw new Horde_Exception(sprintf('Nonexistent class "%s" for field type "%s"', $class, $name));
throw new Horde_Exception(sprintf('Nonexistent class "%s" for field type "%s"', $class, $type));
}

// retrieve list of parameters
Expand Down
11 changes: 8 additions & 3 deletions lib/Horde/Form/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -3195,13 +3195,18 @@ public function isValid($var, $vars, $value, $message)

public function checktime($hour, $minute, $second)
{
if (!isset($hour) || $hour == '' || ($hour < 0 || $hour > 23)) {
// Function parameters always exist (PHPStan level 1: isset.variable),
// so the historical isset() guards here are dropped. Legacy callers
// that passed undefined array keys already trigger PHP's own
// "undefined array key" warning at the call site; the '' and range
// checks below still reject the resulting null/empty values.
if ($hour == '' || ($hour < 0 || $hour > 23)) {
return false;
}
if (!isset($minute) || $minute == '' || ($minute < 0 || $minute > 60)) {
if ($minute == '' || ($minute < 0 || $minute > 60)) {
return false;
}
if (!isset($second) || $second === '' || ($second < 0 || $second > 60)) {
if ($second === '' || ($second < 0 || $second > 60)) {
return false;
}

Expand Down
8 changes: 8 additions & 0 deletions src/V3/EnumVariable.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,14 @@ protected function getInfoV3($vars)
{
$value = $this->getValue($vars);

// Multi-select enums submit an array of selected keys; there is
// no single-key lookup to do in that case, hand it back verbatim
// so the caller can iterate. (Casting an array to string here
// triggers a PHP warning under failOnWarning.)
if (is_array($value)) {
return $value;
}

// Look up the actual key in the values array to preserve its type.
// Browser always sends strings, but the enum keys may be int.
foreach ($this->_values as $key => $label) {
Expand Down
55 changes: 43 additions & 12 deletions src/V3/VariableFactoryTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,23 @@ trait VariableFactoryTrait
/**
* Create a Variable instance from a type string.
*
* Maps type strings like 'text', 'email', 'enum' to Variable classes.
* Supports app-specific types via 'app:typename' format (e.g., 'whups:priority').
* The $type argument accepts three shapes, tried in order:
* 1. A fully-qualified class name of a Variable subclass (preferred).
* Any string containing a namespace separator is treated as an FQCN
* and used as-is; the class must be autoloadable.
* 2. 'app:typename' — resolved to Horde\{App}\Form\V3\{Type}Variable
* first (matches the Composer PSR-4 map every modern Horde package
* publishes), then to {App}\Form\V3\{Type}Variable as a BC fallback
* for packages that shipped variables under that root before this
* dispatch was fixed.
* 3. bare 'typename' — resolved to Horde\Form\V3\{Type}Variable.
*
* When no candidate class is found, InvalidVariable is used so form
* rendering can continue.
*
* @param string $humanName Human-readable field label
* @param string $varName Internal variable name
* @param string $type Variable type string
* @param string $type Variable type string (FQCN, 'app:type', or bare type)
* @param bool $required Whether field is required
* @param bool $readonly Whether field is read-only
* @param string|null $description Field description
Expand All @@ -51,18 +62,38 @@ private function createVariable(
?string $description = null,
array $params = []
): Variable {
// Handle app:typename format (e.g., 'whups:priority')
if (str_contains($type, ':')) {
[$app, $type] = explode(':', $type, 2);
$class = ucfirst($app) . '\\Form\\V3\\' . ucfirst($type) . 'Variable';
if (str_contains($type, '\\')) {
// FQCN shape.
$candidates = [ltrim($type, '\\')];
} elseif (str_contains($type, ':')) {
// 'app:typename' shape — vendor-namespaced first, then the
// historical unprefixed root for BC.
[$app, $typeName] = explode(':', $type, 2);
$app = ucfirst($app);
$typeName = ucfirst($typeName);
$candidates = [
'Horde\\' . $app . '\\Form\\V3\\' . $typeName . 'Variable',
$app . '\\Form\\V3\\' . $typeName . 'Variable',
];
} else {
// Standard Horde types
$class = 'Horde\\Form\\V3\\' . ucfirst($type) . 'Variable';
// Bare Horde type.
$candidates = ['Horde\\Form\\V3\\' . ucfirst($type) . 'Variable'];
}

$class = null;
foreach ($candidates as $candidate) {
if (class_exists($candidate)) {
$class = $candidate;
break;
}
}

// Fallback to InvalidVariable if class doesn't exist
if (!class_exists($class)) {
error_log("Warning: Form type class '$class' not found, using InvalidVariable");
if ($class === null) {
error_log(
"Warning: Form type class for '$type' not found (tried: "
. implode(', ', $candidates)
. '); using InvalidVariable'
);
$class = 'Horde\\Form\\V3\\InvalidVariable';
}

Expand Down
29 changes: 25 additions & 4 deletions test/unit/FormTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Horde_Form_Type;
use Horde_Form_Variable;
use Horde_Variables;
use Horde\Form\V3\Variable;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
Expand All @@ -39,6 +40,26 @@
#[CoversClass(Horde_Form::class)]
class FormTest extends TestCase
{
/**
* Assert that $var is a form variable regardless of era. Horde_Form's
* dispatch returns Horde_Form_Variable for legacy types (a wrapper
* around a Horde_Form_Type) and a V3 Variable instance directly for
* modernized types like 'text'. Both shapes are valid callers of
* addVariable(); tests care about the protocol, not the concrete class.
*/
private static function assertIsFormVariable($var, string $message = ''): void
{
self::assertTrue(
$var instanceof Horde_Form_Variable || $var instanceof Variable,
$message !== ''
? $message
: sprintf(
'Expected Horde_Form_Variable or Horde\Form\V3\Variable, got %s',
is_object($var) ? get_class($var) : gettype($var)
)
);
}

protected function setUp(): void
{
parent::setUp();
Expand Down Expand Up @@ -161,7 +182,7 @@ public function testAddVariableWith4Parameters(): void

$var = $form->addVariable('Name', 'name', 'text', true);

$this->assertInstanceOf(Horde_Form_Variable::class, $var);
self::assertIsFormVariable($var);
$this->assertEquals('Name', $var->humanName);
$this->assertEquals('name', $var->getVarName());
$this->assertTrue($var->isRequired());
Expand All @@ -174,7 +195,7 @@ public function testAddVariableWith5Parameters(): void

$var = $form->addVariable('Name', 'name', 'text', true, false);

$this->assertInstanceOf(Horde_Form_Variable::class, $var);
self::assertIsFormVariable($var);
$this->assertTrue($var->isRequired());
$this->assertFalse($var->isReadonly());
}
Expand Down Expand Up @@ -223,7 +244,7 @@ public function testAddVariableReturnsVariable(): void

$var = $form->addVariable('Test', 'test', 'text', true);

$this->assertInstanceOf(Horde_Form_Variable::class, $var);
self::assertIsFormVariable($var);
}

public function testAddVariableAddsToFormVariables(): void
Expand Down Expand Up @@ -289,7 +310,7 @@ public function testAddHidden(): void

$var = $form->addHidden('', 'hidden_field', 'text', false);

$this->assertInstanceOf(Horde_Form_Variable::class, $var);
self::assertIsFormVariable($var);
$this->assertTrue($var->isHidden());
}

Expand Down
Loading