Mongolid\DataMapper\SchemaMapper::parseField PHP Method

parseField() public method

Parse a value based on a field yype of the schema.
public parseField ( mixed $value, string $fieldType ) : mixed
$value mixed Value to be parsed.
$fieldType string Description of how the field should be treated.
return mixed $value Value parsed to match $type
    public function parseField($value, string $fieldType)
    {
        // Uses $fieldType method of the schema to parse the value
        if (method_exists($this->schema, $fieldType)) {
            return $this->schema->{$fieldType}($value);
        }
        // Returns null or an empty array
        if (null === $value || is_array($value) && empty($value)) {
            return $value;
        }
        // If fieldType is castable (Ex: 'int')
        if (in_array($fieldType, $this->castableTypes)) {
            return $this->cast($value, $fieldType);
        }
        // If the field type points to another schema.
        if (substr($fieldType, 0, 7) == 'schema.') {
            return $this->mapToSchema($value, substr($fieldType, 7));
        }
        return $value;
    }

Usage Example

 public function testShouldParseFieldIntoCastableType()
 {
     // Arrange
     $schema = m::mock(Schema::class);
     $schemaMapper = new SchemaMapper($schema);
     // Assert
     $this->assertSame(23, $schemaMapper->parseField('23', 'int'));
     $this->assertSame('1234', $schemaMapper->parseField(1234, 'string'));
 }