Skip to main content

MustExistIfMapper

Enforces that bindables exist only when a condition holds. The condition is either a bool or a closure returning bool, evaluated against the whole BindBoundary. When it is truthy, every bindable in the current group must doesExist() — otherwise an UnresolvableBindableException is thrown. When it is falsy the mapper is a no-op and the bind carries on.

FactoryCondition
Mappers::mustExistIf($cond, $elseChExistToFalse)$cond is a bool or Closure(BindBoundary): bool
Mappers::mustExistAllIfAnyExist()"if any bindable exists, then all must exist"

The $elseChExistToFalse option (default false) flips the falsy-condition branch: instead of leaving the bindables untouched, it marks them non-existing (doesExist() = false). Use it to drop a group of props entirely when the condition is not met, so trailing mappers (and the final output) skip them.

Note: this is a hard requirement, not a validation error — a missing prop throws UnresolvableBindableException, so it is best placed on optProp/optProps groups where presence is genuinely optional.

Example: requiring a prop only when a condition is true​

Bind::attrs(['prop' => 'holeradio'])
->optProp('conditionalReqProp', Mappers::mustExistIf(true))
->toArray()->exec(); // throws UnresolvableBindableException

conditionalReqProp is optional and absent, but the condition is true, so the mapper requires it to exist and throws. With mustExistIf(false) (or a closure returning false) the mapper would pass through and the bind would complete normally.

Example: "all or nothing" props​

$result = Bind::attrs(['prop' => 'holeradio', 'prop2' => 'holeradio2'])
->optProps(['prop', 'prop2'], Mappers::mustExistAllIfAnyExist())
->toArray()->exec();
var_dump($result->get());

Output:

array(2) {
["prop"]=>
string(9) "holeradio"
["prop2"]=>
string(10) "holeradio2"
}

mustExistAllIfAnyExist() is the equivalent of mustExistIf(fn (BindBoundary $b) => 0 < count(array_filter($b->getBindables(), fn ($b) => $b->doesExist()))) — if at least one of the listed props is present, every one of them must be present. Here both exist, so the bind succeeds; had prop2 been absent, the presence of prop would trigger the requirement and the bind would throw.