Skip to main content

ValueIfNotExistsMapper

Fills in a default value for a bindable that does not exist yet. If the bindable already exists (its value was present in the source), the mapper is a no-op and leaves it untouched. This is the convenient way to populate optProps with a fallback only when the caller omitted them.

Mappers::valueIfNotExists($closureOrValue) accepts either:

  • a literal value (any type), used directly as the bindable's value, or
  • a closure (): mixed whose return value becomes the bindable's value.

The bindable must be optional (optProp/optProps); a required prop that is absent is handled by the bind plan itself, not by this mapper.

Note: this is the inverse of valueIfNotNull (which replaces null values) — valueIfNotExists only touches bindables that are entirely missing from the source.

Example: defaults for absent optional props​

$sdm = new DataMap(); // empty source
$tdm = new DataMap();

$result = Bind::attrs($sdm)->toAttrs($tdm)
->optProp('holeradio', Mappers::valueIfNotExists('holeradio'))
->optProp('hahaha', Mappers::valueIfNotExists(fn () => 'hahaha'))
->exec($this->getMockBuilder(MagicContext::class)->getMock());
var_dump($result->isValid()); // true

Output:

bool(true)

Both props are absent from $sdm, so the mapper sets holeradio to the literal 'holeradio' and hahaha to the closure's return value 'hahaha', both written through to $tdm. Had the source been new DataMap(['holeradio' => 'hmm']), the existing 'hmm' would have been preserved and the mapper skipped for that prop.