Ensure default value for composite field,

@param mixed                 $default
@param CompositionDefinition $composition
@param SchemaBuilder         $builder

@return array

@throws SchemaException
485338
protected function compositionDefault(
        $default,
        CompositionDefinition $composition,
        SchemaBuilder $builder
    ) {
        if (!is_array($default)) {
            if ($composition->getType() == DocumentEntity::MANY) {
                //Composition many must always defaults to array
                return [];
            }

            //Composite ONE must always defaults to null if no default value are specified
            return null;
        }

        //Nothing to do with value for composite many
        if ($composition->getType() == DocumentEntity::MANY) {
            return $default;
        }

        $embedded = $builder->getSchema($composition->getClass());
        if (!$embedded instanceof self) {
            //We can not normalize values handled by external schemas yet
            return $default;
        }

        if ($embedded->getClass() == $this->getClass()) {
            if (!empty($default)) {
                throw new SchemaException(
                    "Possible recursion issue in '{$this->getClass()}', model refers to itself (has default value)"
                );
            }

            //No recursions!
            return null;
        }

        return $embedded->packDefaults($builder, $default);
    }
23177
public function walkCompositeExpression(CompositeExpression $compositeExpr) : Expr
    {
        if (! isset(self::$compositeMethods[$compositeExpr->getType()])) {
            throw new RuntimeException('Unknown composite ' . $compositeExpr->getType());
        }

        $method = self::$compositeMethods[$compositeExpr->getType()];
        $expr   = $this->builder->expr();

        foreach ($compositeExpr->getExpressionList() as $child) {
            $expr->{$method}($this->dispatch($child));
        }

        return $expr;
    }
399394
public function when($value, $callback, $default = null)
    {
        $builder = $this;

        if ($value) {
            $builder = $callback($builder);
        } elseif ($default) {
            $builder = $default($builder);
        }

        return $builder;
    }
266361
public function value($field, $default = null)
    {
        $r = $this->first([$field]);
        return isset($r[$field]) ? $r[$field] : $default;
    }
200600
public function declareTables(SchemaBuilder $builder): array
    {
        if (!$this->option(Record::CREATE_PIVOT)) {
            //No pivot table creation were requested, noting really to do
            return [];
        }

        $sourceTable = $this->sourceTable($builder);
        $targetTable = $this->targetTable($builder);

        $sourceContext = $this->definition->sourceContext();
        $targetContext = $this->definition->targetContext();

        if (
            $sourceTable->getDriver() != $targetTable->getDriver()
            || $sourceContext->getDatabase() != $targetContext->getDatabase()
        ) {
            //todo: support cross database and cross driver many to many
            throw new RelationSchemaException(
                "ManyToMany relations can only exists inside same database"
            );
        }

        $pivotTable = $builder->requestTable(
            $this->pivotTable(),
            $sourceContext->getDatabase(),
            false,
            true
        );

        /*
         * Declare columns in map/pivot table.
         */
        $thoughtInnerKey = $pivotTable->column($this->option(Record::THOUGHT_INNER_KEY));
        $thoughtInnerKey->nullable(false);
        $thoughtInnerKey->setType($this->resolveType(
            $sourceContext->getColumn($this->option(Record::INNER_KEY))
        ));

        $thoughtOuterKey = $pivotTable->column($this->option(Record::THOUGHT_OUTER_KEY));
        $thoughtOuterKey->nullable(false);
        $thoughtOuterKey->setType($this->resolveType(
            $targetContext->getColumn($this->option(Record::OUTER_KEY))
        ));

        /*
         * Declare user columns in pivot table.
         */
        $rendered = new ColumnRenderer();
        $rendered->renderColumns(
            $this->option(Record::PIVOT_COLUMNS),
            $this->option(Record::PIVOT_DEFAULTS),
            $pivotTable
        );

        //Map might only contain unique link between source and target
        if ($this->option(Record::CREATE_INDEXES)) {
            $pivotTable->index([
                $thoughtInnerKey->getName(),
                $thoughtOuterKey->getName()
            ])->unique();
        }

        //There is 2 constrains between map table and source and table
        if ($this->isConstrained()) {
            $this->createForeign(
                $pivotTable,
                $thoughtInnerKey,
                $sourceContext->getColumn($this->option(Record::INNER_KEY)),
                $this->option(Record::CONSTRAINT_ACTION),
                $this->option(Record::CONSTRAINT_ACTION)
            );

            $this->createForeign(
                $pivotTable,
                $thoughtOuterKey,
                $targetContext->getColumn($this->option(Record::OUTER_KEY)),
                $this->option(Record::CONSTRAINT_ACTION),
                $this->option(Record::CONSTRAINT_ACTION)
            );
        }

        return [$pivotTable];
    }
898795
public function setSchema(SchemaBuilder $builder, bool $remember = false)
    {
        $this->schema = $builder->packSchema();

        if ($remember) {
            $this->memory->saveData(static::MEMORY, $this->schema);
        }
    }
148237
public function setDefaultDiscriminatorValue(?string $defaultDiscriminatorValue) : void
    {
        if ($this->isFile) {
            throw MappingException::discriminatorNotAllowedForGridFS($this->name);
        }

        if ($defaultDiscriminatorValue === null) {
            $this->defaultDiscriminatorValue = null;

            return;
        }

        if (! array_key_exists($defaultDiscriminatorValue, $this->discriminatorMap)) {
            throw MappingException::invalidDiscriminatorValue($defaultDiscriminatorValue, $this->name);
        }

        $this->defaultDiscriminatorValue = $defaultDiscriminatorValue;
    }
423027
public function extractDefault(ColumnSchema $field, $defaultValue)
    {
        if ($defaultValue === 'true') {
            $field->defaultValue = true;
        } elseif ($defaultValue === 'false') {
            $field->defaultValue = false;
        } elseif (strpos($defaultValue, 'nextval') === 0) {
            $field->defaultValue = null;
        } elseif (preg_match('/^\'(.*)\'::/', $defaultValue, $matches)) {
            parent::extractDefault($field, str_replace("''", "'", $matches[1]));
        } elseif (preg_match('/^(-?\d+(\.\d*)?)(::.*)?$/', $defaultValue, $matches)) {
            parent::extractDefault($field, $matches[1]);
        } else {
            // could be a internal function call like setting uuids
            $field->defaultValue = $defaultValue;
        }
    }
1136109
protected function prepareDefaultValue(Column $column)
    {
        $typeMapper = $this->getDataType();

        $default = $column->getDefault();

        if (!$column->getAllowNull() && $default === null && !$column->isPrimary()) {
            $default = $typeMapper::getDefaultValue($column->getType());

            $column->defaultValue($default);
        }

        return $column;
    }
289086
public function setDefault($default) {
        // Check, warn and auto-fix '' (empty) defaults for CHAR NOT NULL columns, changing them
        // to NULL so XMLDB will apply the proper default
        if ($this->type == XMLDB_TYPE_CHAR && $this->notnull && $default === '') {
            $this->errormsg = 'XMLDB has detected one CHAR NOT NULL column (' . $this->name . ") with '' (empty string) as DEFAULT value. This type of columns must have one meaningful DEFAULT declared or none (NULL). XMLDB have fixed it automatically changing it to none (NULL). The process will continue ok and proper defaults will be created accordingly with each DB requirements. Please fix it in source (XML and/or upgrade script) to avoid this message to be displayed.";
            $this->debug($this->errormsg);
            $default = null;
        }
        // Check, warn and autofix TEXT|BINARY columns having a default clause (only null is allowed)
        if (($this->type == XMLDB_TYPE_TEXT || $this->type == XMLDB_TYPE_BINARY) && $default !== null) {
            $this->errormsg = 'XMLDB has detected one TEXT/BINARY column (' . $this->name . ") with some DEFAULT defined. This type of columns cannot have any default value. Please fix it in source (XML and/or upgrade script) to avoid this message to be displayed.";
            $this->debug($this->errormsg);
            $default = null;
        }
        $this->default = $default;
    }
1267414
protected function mutateValue(array $mutators, string $field, $default)
    {
        //Let's process default value using associated setter
        if (isset($mutators[RecordEntity::MUTATOR_SETTER][$field])) {
            try {
                $setter = $mutators[RecordEntity::MUTATOR_SETTER][$field];
                $default = call_user_func($setter, $default);

                return $default;
            } catch (\Exception $exception) {
                //Unable to generate default value, use null or empty array as fallback
            }
        }

        if (isset($mutators[RecordEntity::MUTATOR_ACCESSOR][$field])) {
            $default = $this->accessorDefault(
                $default,
                $mutators[RecordEntity::MUTATOR_ACCESSOR][$field]
            );

            return $default;
        }

        return $default;
    }
719780
protected function hydrateAdditionalTxnFields(DOMDocument $xml, BaseBuilder $builder)
    {
        $additionalTxnFields = $xml->createElement('AdditionalTxnFields');

        if ($builder->description !== null && $builder->description !== '') {
            $additionalTxnFields->appendChild(
                $xml->createElement('Description', $builder->description)
            );
        }

        if ($builder->invoiceNumber !== null && $builder->invoiceNumber !== '') {
            $additionalTxnFields->appendChild(
                $xml->createElement('InvoiceNbr', $builder->invoiceNumber)
            );
        }

        if ($builder->customerId !== null && $builder->customerId !== '') {
            $additionalTxnFields->appendChild(
                $xml->createElement('CustomerID', $builder->customerId)
            );
        }

        return $additionalTxnFields;
    }
88854
protected function findOuter(SchemaBuilder $builder)
    {
        foreach ($this->findTargets($builder) as $schema) {
            $outerTable = $builder->requestTable($schema->getTable(), $schema->getDatabase());
            $outerKey = $this->option(Record::OUTER_KEY);

            if ($outerKey == ORMInterface::R_PRIMARY_KEY) {
                $outerKey = current($outerTable->getPrimaryKeys());
            }

            if (!$outerTable->hasColumn($outerKey)) {
                throw new RelationSchemaException(sprintf("Outer key '%s'.'%s' (%s) does not exists",
                    $outerTable->getName(),
                    $outerKey,
                    $this->getDefinition()->getName()
                ));
            }

            return $outerTable->column($outerKey);
        }

        return null;
    }
1286155
public function packCompositions(SchemaBuilder $builder): array
    {
        $result = [];
        foreach ($this->getCompositions($builder) as $name => $composition) {
            $result[$name] = $composition->packSchema();
        }

        return $result;
    }
11252
@Nonnull
  public static DocumentBuilderFactory createDocumentBuilderFactory (@Nonnull final Schema aSchema)
  {
    ValueEnforcer.notNull (aSchema, "Schema");

    final DocumentBuilderFactory aDocumentBuilderFactory = createDefaultDocumentBuilderFactory ();
    aDocumentBuilderFactory.setSchema (aSchema);
    return aDocumentBuilderFactory;
  }
1113683
protected function packAggregations(SchemaBuilder $builder): array
    {
        $result = [];
        foreach ($this->getAggregations() as $name => $aggregation) {
            if (!$builder->hasSchema($aggregation->getClass())) {
                throw new SchemaException(
                    "Aggregation {$this->getClass()}.'{$name}' refers to undefined document '{$aggregation->getClass()}'"
                );
            }

            if ($builder->getSchema($aggregation->getClass())->isEmbedded()) {
                throw new SchemaException(
                    "Aggregation {$this->getClass()}.'{$name}' refers to non storable document '{$aggregation->getClass()}'"
                );
            }

            $result[$name] = $aggregation->packSchema();
        }

        return $result;
    }
1235707
public function configure(ArrayNodeDefinition $builder)
    {
        $builder
            ->addDefaultsIfNotSet()
            ->children()
                ->arrayNode('fixtures')
                    ->beforeNormalization()
                        ->ifTrue(function($v) {
                            return is_scalar($v);
                        })
                        ->then(function($v){
                            return array(
                                'default'   => array('app'),
                                'key_paths' => array('app' => $v));
                        })
                    ->end()
                    ->validate()
                        ->ifTrue(function($v) {
                            foreach ($v['default'] as $default) {
                                if (!array_key_exists($default, $v['key_paths'])) {
                                    return true;
                                }
                            }
                        })
                        ->thenInvalid("You can't define a default which is not present in key_paths.")
                    ->end()
                    ->children()
                        ->scalarNode('default_loading')
                            ->defaultValue(AliceFixturesExecutor::DEFAULT_LOADING_IMPLICIT)
                            ->validate()
                                ->ifNotInArray(array(AliceFixturesExecutor::DEFAULT_LOADING_IMPLICIT, AliceFixturesExecutor::DEFAULT_LOADING_EXPLICIT))
                                ->thenInvalid('fixtures.default_loading should be implicit or explicit.')
                            ->end()
                        ->end()
                        ->arrayNode('default')
                            ->beforeNormalization()
                                ->ifTrue(function($v) {
                                    return is_scalar($v);
                                })
                                ->then(function($v) {
                                    return array($v);
                                })
                            ->end()
                            ->prototype('scalar')->end()
                        ->end()
                        ->arrayNode('key_paths')
                            ->useAttributeAsKey('key_path')
                            ->validate()
                                ->ifTrue(function($v) {
                                    return array_key_exists(FixtureStack::DEFAULT_KEY, $v);
                                })
                                ->thenInvalid('You cannot add a key_path with key “'.FixtureStack::DEFAULT_KEY.'“, this is a reserved word.')
                            ->end()
                            ->prototype('scalar')->end()
                        ->end()
                    ->end()
                ->end()
                ->scalarNode('lifetime')->end()
                ->arrayNode('faker')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('locale')->defaultValue('en_US')->end()
                        ->arrayNode('providers')
                            ->beforeNormalization()
                                ->always(function($v) {
                                    return array_map(function($class) {
                                        return new $class();
                                    }, $v);
                                })
                            ->end()
                            ->prototype('variable')->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('adapters')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->arrayNode('elastica')
                            ->children()
                                ->scalarNode('fixture_class')
                                    ->defaultValue('Rezzza\AliceExtension\Fixture\ElasticaFixture')
                                    ->cannotBeEmpty()
                                ->end()
                                ->scalarNode('index_service')
                                    ->cannotBeEmpty()
                                ->end()
                                ->arrayNode('mapping')
                                    ->prototype('scalar')->end()
                                ->end()
                            ->end()
                        ->end()
                        ->arrayNode('orm')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('fixture_class')
                                    ->defaultValue('Rezzza\AliceExtension\Fixture\ORMFixture')
                                    ->cannotBeEmpty()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('faker')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('locale')->defaultValue('en_US')->end()
                        ->arrayNode('providers')
                            ->beforeNormalization()
                                ->always(function($v) {
                                    return array_map(function($class) {
                                        return new $class();
                                    }, $v);
                                })
                            ->end()
                            ->prototype('variable')->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;
    }