Serialize entity.

@param \Railken\Lem\Contracts\EntityContract $entity
@param \Illuminate\Http\Request              $request

@return array
481805
public function serialize(EntityContract $entity, Request $request)
    {
        $transformer = $this->getFractalTransformer($entity, $request);

        $resource = new Fractal\Resource\Item($entity, $transformer, $this->getResourceName());

        return $this->getFractalManager($request)->createData($resource)->toArray();
    }
1035468
protected function generateBody(Entity $entity)
    {
        $lines      = [];
        $fields     = [];
        $extensions = [];
        $descriptor = $entity->getDescriptor();

        if ($descriptor->hasOptions()) {
            $lines   = $this->createOptionsBody($entity);
            $lines[] = null;
        }

        foreach (($descriptor->getFieldList() ?: []) as $field) {
            $values = $this->generateFieldBody($field);
            $fields = array_merge($fields, $this->addIndentation($values, 2));
        }

        foreach (($descriptor->getExtensionList() ?: []) as $field) {
            $values     = $this->generateFieldBody($field);
            $extensions = array_merge($extensions, $this->addIndentation($values, 2));
        }

        $lines[] = "return \google\protobuf\DescriptorProto::fromArray([";
        $lines[] = "    'name'      => " . var_export($descriptor->getName(), true) . ",";

        if ( ! empty($fields)) {
            $lines[] = "    'field'     => [";
            $lines   = array_merge($lines, $fields);
            $lines[] = "    ],";
        }

        if ( ! empty($extensions)) {
            $lines[] = "    'extension' => [";
            $lines   = array_merge($lines, $extensions);
            $lines[] = "    ],";
        }

        if ($descriptor->hasOptions()) {
            $lines[] = "    'options' => \$options";
        }

        $lines[] = "]);";

        return $lines;
    }
763407
public function duplicate(Entity $entity = null)
    {
        $entity = $this->getEntityIfEmpty($entity);

        $data = $this->toArray();
        if (isset($data['id'])) {
            unset($data['id']);
        }

        foreach ($data as $key => &$val) {
            if ($key && array_key_exists($key . '_x', $data) && array_key_exists($key . '_y', $data)) {
                $val = [
                    $data[$key . '_x'],
                    $data[$key . '_y'],
                ];
            }
        }

        $record = new static($data);
        $record->save($entity);

        return $record;
    }
1252734
public static function generateUpdateRequest( Entity $entity ) {
        /* Generate the UpdateRequest message */
        $updateRequestDOM = new DOMDocument();
        $updateNode       = $updateRequestDOM->appendChild( $updateRequestDOM->createElementNS( 'http://schemas.microsoft.com/xrm/2011/Contracts/Services', 'Update' ) );
        $updateNode->appendChild( $updateRequestDOM->importNode( $entity->getEntityDOM(), true ) );

        /* Return the DOMNode */

        return $updateNode;
    }
904573
public function setTrackingCodeAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        /** @var Transaction $entity */
        $entity = $em->getRepository('EcommerceBundle:Transaction')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Transaction entity.');
        }

        $form = $this->createFormBuilder($entity->getDelivery())
            ->add('trackingCode', 'text', array(
                    'required' => true
                ))
            ->getForm();

        if ($request->isMethod('POST')) {
            $form->bind($request);

            if ($form->isValid()) {
                $entity->setStatus(Transaction::STATUS_DELIVERED);

                $em->persist($entity);
                $em->flush();

                $this->get('core.mailer')->sendTrackingCodeEmailMessage($entity);

                $this->get('session')->getFlashBag()->add('success', 'transaction.sent');
            }else{
                $string = (string) $form->getErrors(true, false);
                print_r($string);
                die('invalid');
            }

            return $this->redirect($this->generateUrl('ecommerce_transaction_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView()
        );
    }
688609
public function createEntityRequest(
        RequestInterface $request,
        ContainerInterface $container
    ): EntityRequestInterface
    {
        /** @var EntityRequestInterface $er */
        $er = new $this->entityRequest($request);
        $er->setContainer($container);

        return $er;
    }
1253897
def serialize(self, entity, request=None):
        

        def should_we_insert(value, field_spec):
            return value not in self.missing or field_spec.required

        errors = {}
        ret = {}

        for field_name, field_spec in self.spec.fields.items():
            value = self._get_value_for_serialization(entity, field_name, field_spec)
            func = self._get_serialize_func(field_name, self.spec)
            try:
                # perform serialization
                value = func(value, entity, request)
                if should_we_insert(value, field_spec):
                    ret[field_name] = value
            except ValidationError, e:
                if hasattr(e, 'message_dict'):
                    # prefix error keys with top level field name
                    errors.update(dict(zip(
                        [field_name + '.' + key for key in e.message_dict.keys()],
                        e.message_dict.values())))
                else:
                    errors[field_name] = e.messages

        if errors:
            raise ValidationError(errors)

        return None if ret == {} else ret
540829
public function data($entity = '') {
        $entities = [];

        foreach ($this->_data as $line) {
            if ($entity != '') {
                /** @var  $entityObject \Gcs\Framework\Core\Orm\Entity\Entity */
                $entityObject = self::Entity()->$entity();

                foreach ($line as $key => $field) {
                    $value = null;
                    $parent = '';

                    $key = str_replace('count_one_' . $entityObject->name() . '_', '', $key);
                    $key = str_replace('count_many_' . $entityObject->name() . '_', '', $key);
                    $key = str_replace($entityObject->name() . '_', '', $key);

                    if ($entityObject->getField($key) != null) {
                        if (in_array($entityObject->getField($key)->type, [Field::INCREMENT, Field::INT, Field::TEXT, Field::FLOAT, Field::STRING, Field::CHAR, Field::BOOL, Field::DATE, Field::DATETIME, Field::TIMESTAMP, Field::ENUM])) {
                            if ($entityObject->getField($key)->foreign == null) {
                                //If the field is a Datetime or Date or Timestamp we must convert it to \DateTime
                                switch ($entityObject->getField($key)->type) {
                                    case Field::DATETIME:
                                        $value = new \DateTime($field);
                                        break;

                                    case Field::DATE:
                                        $value = new \DateTime($field);
                                        break;

                                    case Field::TIMESTAMP:
                                        $value = new \DateTime($field);
                                        break;

                                    default:
                                        $value = $field;
                                        break;
                                }
                            }
                            elseif (in_array($entityObject->getField($key)->foreign->type(), [ForeignKey::ONE_TO_MANY, ForeignKey::MANY_TO_MANY])) {
                                $value = $field;
                            }
                            else {
                                foreach ($entityObject->fields() as $fieldIsRightForeign) {
                                    if ($fieldIsRightForeign->foreign != null) {
                                        $parent = $fieldIsRightForeign->name . '_';
                                        $value = $this->_getDataRelation($line, $entityObject->getField(str_replace($fieldIsRightForeign->name . '_', '', $key))->foreign, $parent);
                                    }
                                }
                            }
                        }
                        else {
                            switch ($entityObject->getField($key)->type) {
                                case Field::FILE :
                                    $file = new File('', '', '', '');
                                    $file->hydrate($field);
                                    $value = $file;
                                    break;
                            }
                        }

                        $fieldName = str_replace($parent, '', $key);
                        $entityObject->set($fieldName, $value);
                    }
                }
            }
            else {
                $entityObject = new Multiple($line);
            }

            array_push($entities, $entityObject);
        }

        return new Collection($entities);
    }
1309598
private function createCreateForm(Contract $entity)
    {
        $form = $this->createForm(new ContractType(), $entity, array(
            'action' => $this->generateUrl('ecommerce_contract_create'),
            'method' => 'POST',
        ));

//        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }
772125
public function serialize(EntityContract $entity, Collection $select = null)
    {
        $bag = new Bag($entity->toArray());

        foreach ($this->getManager()->getAttributes() as $attribute) {
            $attribute->pushReadable($entity, $bag);
        }

        if ($select) {
            $bag = $bag->only($select->toArray());
        }
                
        return $bag;
    }
142471
protected function buildEntityCreatePayload(EntityInterface $entity, array $context = []): string
    {
        return $this->getEntitySerializer()->serialize($entity, 'json', $context);
    }
103639
public static function generateUpsertRequest( Entity $entity ) {
        /* Generate the ExecuteAction message */
        $executeActionRequestDOM = new DOMDocument();

        $executeActionNode = $executeActionRequestDOM->appendChild( $executeActionRequestDOM->createElementNS( 'http://schemas.microsoft.com/xrm/2011/Contracts/Services', 'Execute' ) );
        $executeActionNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:i', 'http://www.w3.org/2001/XMLSchema-instance' );

        $requestNode = $executeActionNode->appendChild( $executeActionRequestDOM->createElement( 'request' ) );
        $requestNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:b', 'http://schemas.microsoft.com/xrm/2011/Contracts' );
        /* Set request type */
        $requestNode->setAttribute( 'i:type', 'b:UpsertRequest' );

        $parametersNode = $requestNode->appendChild( $executeActionRequestDOM->createElement( 'b:Parameters' ) );
        $parametersNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:c', 'http://schemas.datacontract.org/2004/07/System.Collections.Generic' );

        /* Create a Key/Value Pair of String/Any Type */
        $propertyNode = $parametersNode->appendChild( $executeActionRequestDOM->createElement( 'b:KeyValuePairOfstringanyType' ) );
        /* Set the Property Name */
        $propertyNode->appendChild( $executeActionRequestDOM->createElement( 'c:key', "Target" ) );

        /* Now create the XML Node for the Value */
        $mainValueNode = $propertyNode->appendChild( $executeActionRequestDOM->createElement( 'c:value' ) );
        /* Set the Type of the Value */
        $mainValueNode->setAttribute( 'i:type', 'b:Entity' );

        $attributeNode = $mainValueNode->appendChild( $executeActionRequestDOM->createElementNS( 'http://schemas.microsoft.com/xrm/2011/Contracts', 'b:Attributes' ) );
        $attributeNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:c', 'http://schemas.datacontract.org/2004/07/System.Collections.Generic' );

        foreach ( $entity->properties as $property => $propertyDetails ) {
            /* Only include changed properties */
            if ( $entity->propertyValues[ $property ]['Changed'] ) {
                /* Create a Key/Value Pair of String/Any Type */
                $propertyNode = $attributeNode->appendChild( $executeActionRequestDOM->createElement( 'b:KeyValuePairOfstringanyType' ) );
                /* Set the Property Name */
                $propertyNode->appendChild( $executeActionRequestDOM->createElement( 'c:key', $property ) );
                /* Check the Type of the Value */
                if ( $propertyDetails->isLookup ) {
                    /* Special handling for Lookups - use an AlexaCRM\CRMToolkit\Entity\EntityReference, not the AttributeType */
                    $valueNode = $propertyNode->appendChild( $executeActionRequestDOM->createElement( 'c:value' ) );

                    if ( $entity->propertyValues[ $property ]['Value'] != null ) {
                        $valueNode->setAttribute( 'i:type', 'b:EntityReference' );
                        $valueNode->appendChild( $executeActionRequestDOM->createElement( 'b:Id', ( $entity->propertyValues[ $property ]['Value'] ) ? $entity->propertyValues[ $property ]['Value']->ID : "" ) );
                        $valueNode->appendChild( $executeActionRequestDOM->createElement( 'b:LogicalName', ( $entity->propertyValues[ $property ]['Value'] ) ? $entity->propertyValues[ $property ]['Value']->logicalname : "" ) );
                        $valueNode->appendChild( $executeActionRequestDOM->createElement( 'b:Name' ) )->setAttribute( 'i:nil', 'true' );
                    } else {
                        $valueNode->setAttribute( 'i:nil', 'true' );
                    }
                } else if ( strtolower( $propertyDetails->type ) == "money" ) {

                    $valueNode = $propertyNode->appendChild( $executeActionRequestDOM->createElement( 'c:value' ) );

                    if ( $entity->propertyValues[ $property ]['Value'] ) {
                        $valueNode->setAttribute( 'i:type', 'b:Money' );
                        $valueNode->appendChild( $executeActionRequestDOM->createElement( 'b:Value', $entity->propertyValues[ $property ]['Value'] ) );
                    } else {
                        $valueNode->setAttribute( 'i:nil', 'true' );
                    }
                } else if ( strtolower( $propertyDetails->type ) == "datetime" ) {

                    $valueNode = $propertyNode->appendChild( $executeActionRequestDOM->createElement( 'c:value' ) );

                    if ( $entity->propertyValues[ $property ]['Value'] ) {
                        $valueNode->setAttribute( 'i:type', 'd:dateTime' );
                        $valueNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:d', 'http://www.w3.org/2001/XMLSchema' );
                        $valueNode->appendChild( new DOMText( gmdate( "Y-m-d\TH:i:s\Z", $entity->propertyValues[ $property ]['Value'] ) ) );
                    } else {
                        $valueNode->setAttribute( 'i:nil', 'true' );
                    }
                } else if ( strtolower( $propertyDetails->type ) == "picklist" ) {
                    $valueNode = $propertyNode->appendChild( $executeActionRequestDOM->createElement( 'c:value' ) );

                    if ( $entity->propertyValues[ $property ]['Value'] ) {
                        $valueNode->setAttribute( 'i:type', 'd:OptionSetValue' );
                        $valueNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:d', 'http://schemas.microsoft.com/xrm/2011/Contracts' );
                        $val = $entity->propertyValues[ $property ]['Value'];
                        if ( $val instanceof OptionSetValue ) {
                            $val = $val->value;
                        }
                        $valueNode->appendChild( $executeActionRequestDOM->createElement( 'b:Value', $val ) );
                    } else {
                        $valueNode->setAttribute( 'i:nil', 'true' );
                    }
                } else {
                    /* Determine the Type, Value and XML Namespace for this field */
                    $xmlValue      = $entity->propertyValues[ $property ]['Value'];
                    $xmlValueChild = null;
                    $xmlType       = strtolower( $propertyDetails->type );
                    $xmlTypeNS     = 'http://www.w3.org/2001/XMLSchema';
                    /* Special Handing for certain types of field */
                    switch ( strtolower( $propertyDetails->type ) ) {
                        case 'memo':
                            /* Memo - This gets treated as a normal String */
                            $xmlType = 'string';
                            break;
                        case 'integer':
                            /* Integer - This gets treated as an "int" */
                            $xmlType = 'int';
                            break;
                        case 'uniqueidentifier':
                            /* Uniqueidentifier - This gets treated as a guid */
                            $xmlType = 'guid';
                            break;
                        case 'state':
                        case 'status':
                            /* OptionSetValue - Just get the numerical value, but as an XML structure */
                            $xmlType       = 'OptionSetValue';
                            $xmlTypeNS     = 'http://schemas.microsoft.com/xrm/2011/Contracts';
                            $xmlValue      = null;
                            $xmlValueChild = $executeActionRequestDOM->createElement( 'b:Value', $entity->propertyValues[ $property ]['Value'] );
                            break;
                        case 'boolean':
                            /* Boolean - Just get the numerical value */
                            $xmlValue = $entity->propertyValues[ $property ]['Value']? '1' : '0';
                            break;
                        case 'string':
                        case 'int':
                        case 'decimal':
                        case 'double':
                        case 'guid':
                            /* No special handling for these types */
                            break;
                        default:
                            /* If we're using Default, Warn user that the XML handling is not defined */
                            trigger_error( 'No Create/Update handling implemented for type ' . $propertyDetails->type . ' used by field ' . $property, E_USER_WARNING );
                    }
                    /* Now create the XML Node for the Value */
                    $valueNode = $propertyNode->appendChild( $executeActionRequestDOM->createElement( 'c:value' ) );
                    /* Set the Type of the Value */
                    $valueNode->setAttribute( 'i:type', 'd:' . $xmlType );
                    $valueNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:d', $xmlTypeNS );
                    /* If there is a child node needed, append it */
                    if ( $xmlValueChild != null ) {
                        $valueNode->appendChild( $xmlValueChild );
                    }
                    /* If there is a value, set it */
                    if ( $xmlValue != null ) {
                        $valueNode->appendChild( new DOMText( $xmlValue ) );
                    }
                }
            }
        }
        /* Entity State */
        $mainValueNode->appendChild( $executeActionRequestDOM->createElement( 'b:EntityState' ) )->setAttribute( 'i:nil', 'true' );
        /* Formatted Values */
        $formattedValuesNode = $mainValueNode->appendChild( $executeActionRequestDOM->createElement( 'b:FormattedValues' ) );
        $formattedValuesNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:c', 'http://schemas.datacontract.org/2004/07/System.Collections.Generic' );
        /* Entity ID */
        $mainValueNode->appendChild( $executeActionRequestDOM->createElement( 'b:Id', $entity->id ) );
        /* Logical Name */
        $mainValueNode->appendChild( $executeActionRequestDOM->createElement( 'b:LogicalName', $entity->logicalName ) );
        /* Related Entities */
        $relatedEntitiesNode = $mainValueNode->appendChild( $executeActionRequestDOM->createElement( 'b:RelatedEntities' ) );
        $relatedEntitiesNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:c', 'http://schemas.datacontract.org/2004/07/System.Collections.Generic' );

        if ( $entity->keyAttribute && $entity->keyAttribute->keys ) {
            $keyAttributesNode = $mainValueNode->appendChild( $executeActionRequestDOM->createElement( 'b:KeyAttributes' ) );
            $keyAttributesNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:d', 'http://schemas.microsoft.com/xrm/7.1/Contracts' );

            foreach ( $entity->keyAttribute->keys as $keyAttribute ) {
                $keyAttributesNode = $mainValueNode->appendChild( $executeActionRequestDOM->createElement( 'b:KeyAttributes' ) );
                $keyAttributesNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:d', 'http://schemas.microsoft.com/xrm/7.1/Contracts' );

                $keyValuePairOfstringanyTypeNode = $keyAttributesNode->appendChild( $executeActionRequestDOM->createElement( 'd:KeyValuePairOfstringanyType' ) );

                $keyValuePairOfstringanyTypeNode->appendChild( $executeActionRequestDOM->createElement( 'c:key', $keyAttribute->key ) );

                $alternativeKeyValueNode = $keyValuePairOfstringanyTypeNode->appendChild( $executeActionRequestDOM->createElement( 'c:value', $keyAttribute->value ) );
                $alternativeKeyValueNode->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:e', 'http://www.w3.org/2001/XMLSchema' );
                $alternativeKeyValueNode->setAttribute( 'i:type', 'e:string' );
            }
        }

        $requiestIdNode = $requestNode->appendChild( $executeActionRequestDOM->createElement( 'b:RequestId' ) );
        $requiestIdNode->setAttribute( 'i:nil', 'true' );
        $requestNode->appendChild( $executeActionRequestDOM->createElement( 'b:RequestName', "Upsert" ) );

        return $executeActionNode;
    }
45591
public function update(EntityContract $entity, Bag $parameters)
    {
        $entity->checksum = $this->getManager()->checksum(!empty($entity->content) ? $entity->content : '');

        return new Collection();
    }
1360687
public function objectToRequest(EntityInterface $entity)
    {
        $data = $entity->get();

        $properties = [];
        foreach ($data as $key => $value) {
            $exclude = in_array($key, $entity->excludedProperties());
            $meaning = (isset($entity->meanings()[$key]))
                ? $entity->meanings()[$key]
                : null;

            $properties[$key] = $this->valueObject(
                $value,
                $exclude,
                $meaning
            );
        }

        $key = $entity->key()
            ? $entity->key()->keyObject()
            : null;

        return array_filter([
            'key' => $key,
            'properties' => $properties
        ]);
    }
479209
public function persist(Entity $entity)
    {
        $this->checkEntityType($entity);

        $this->events->invokeCallbacks(Events::EVENT_BEFORE_PERSIST, $entity);
        if ($entity->isDetached()) {
            $entity->makeAlive($this->entityFactory, $this->connection, $this->mapper);
            $this->events->invokeCallbacks(Events::EVENT_BEFORE_CREATE, $entity);
            $result = $id = $this->insertIntoDatabase($entity);
            $entity->attach($id);
            $this->events->invokeCallbacks(Events::EVENT_AFTER_CREATE, $entity);
        } else {
            if ($entity->isModified()) {
                $this->events->invokeCallbacks(Events::EVENT_BEFORE_UPDATE, $entity);
                $result = $this->updateInDatabase($entity);
                $this->events->invokeCallbacks(Events::EVENT_AFTER_UPDATE, $entity);
            }
            $this->persistHasManyChanges($entity);
            $entity->markAsUpdated();
        }
        $this->events->invokeCallbacks(Events::EVENT_AFTER_PERSIST, $entity);

        return isset($result) ? $result : null;
    }
1205864
public function serialize(EntityContract $entity, Collection $select = null)
    {
        $bag = parent::serialize($entity, $select);

        $bag->set('files', $entity->files->map(function ($file) {
            return [
                'url' => $file->media->first()->getFullUrl(),
            ];
        }));

        return $bag;
    }
89210
public function entriesDeleteAction(Request $request)
    {
        $entries = [];
        $serializedEntries = [];
        $entriesParams = $this->decodeIdsString($request, 'Claroline\ClacoFormBundle\Entity\Entry');

        foreach ($entriesParams as $entryParam) {
            if (!$entryParam->isLocked()) {
                $entries[] = $entryParam;
            }
        }
        foreach ($entries as $entry) {
            $this->clacoFormManager->checkEntryEdition($entry);
            $serializedEntries[] = $this->entrySerializer->serialize($entry);
        }
        $this->clacoFormManager->deleteEntries($entries);

        return new JsonResponse($serializedEntries, 200);
    }