Generate a Create Request

@param Entity $entity

@return DOMNode
359372
public static function generateCreateRequest( Entity $entity ) {
        /* Generate the CreateRequest message */
        $createRequestDOM = new DOMDocument();
        $createNode       = $createRequestDOM->appendChild( $createRequestDOM->createElementNS( 'http://schemas.microsoft.com/xrm/2011/Contracts/Services', 'Create' ) );
        $createNode->appendChild( $createRequestDOM->importNode( $entity->getEntityDOM(), true ) );

        /* Return the DOMNode */

        return $createNode;
    }
1004778
public function getRepository(Entity $entity)
    {
        $repo = $this->getRepositories()[get_class($entity)];

        return $this->$repo;
    }
1168015
public function buildUrl($entity,$entityConfig) {
        $route = $entityConfig['route'];
        $routeParameters = $entityConfig['routeParameters'];
        $href = '';
        if($route != null){
            $href = $this->generateUrl($route,array_merge(array('id' => $entity->getId()),$routeParameters));
        }
        return $href;
    }
509091
public function create(Entity $entity)
    {
        if (!$entity->getValidator()->validate()) {
            throw new Exception\ValidatorException($entity->getValidator());
        }

        $values = $entity->getData();

        $reflection = $entity::getReflection();

        // Prevent to force empty primary property
        if ($reflection->hasPrimary()) {

            $primaryName = $reflection->getPrimaryProperty()->getName();

            if (empty($values[$primaryName])) {
                unset($values[$primaryName]);
            }
        }

        try {
            $primaryValue = $this->query()->insert($values)->run($this->connection);
        } catch (Exception\QueryException $e) {
            throw new Exception\RepositoryException($e->getMessage());
        }

        $this->_saveAssociated($primaryValue, $entity);

        return $primaryValue;
    }
1320226
protected function generateBody(Entity $entity)
    {
        $descriptor = $entity->getDescriptor();
        $fields     = $descriptor->getFieldList() ?: [];

        $body[] = '$stream      = $context->getStream();';
        $body[] = '$writer      = $context->getWriter();';
        $body[] = '$sizeContext = $context->getComputeSizeContext();';
        $body[] = null;

        foreach ($fields as $field) {
            $lines = $this->generateRequiredFieldException($entity, $field);
            $body  = array_merge($body, $lines);
        }

        foreach ($fields as $field) {
            $lines = $this->generateFieldCondition($entity, $field);
            $body  = array_merge($body, $lines, [null]);
        }

        $extensionsField = $this->getUniqueFieldName($descriptor, 'extensions');
        $extensionsVar   = '$this->' . $extensionsField;

        $body[] = 'if (' . $extensionsVar . ' !== null) {';
        $body[] = '    ' . $extensionsVar . '->writeTo($context);';
        $body[] = '}';
        $body[] = null;
        $body[] = 'return $stream;';

        return $body;
    }
173709
private function createCreateForm(Menu $entity)
    {
        $form = $this->createForm(new MenuType(), $entity, array(
            'action' => $this->generateUrl('admin_menu_create'),
            'method' => 'POST',
        ));

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

        return $form;
    }
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;
    }
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;
    }
369056
protected function generateMethods(Entity $entity)
    {
        $result     = [];
        $descriptor = $entity->getDescriptor();
        $methods    = $descriptor->getMethodList() ?: [];

        foreach ($methods as $method) {
            $result[] = $this->generateMethod($entity, $method);
        }

        return $result;
    }
498607
private function createCreateForm(Episode $entity)
    {
        $form = $this->createForm(EpisodeType::class, $entity, array(
            'action' => $this->generateUrl('oktolab_episode_create'),
            'method' => 'POST',
        ));

        $form->add(
            'submit',
            SubmitType::class,
            [
                'label' => 'oktolab_media.new_episode_create_button',
                'attr' => ['class' => 'btn btn-primary']
            ]
        );

        return $form;
    }
443444
protected function generateProperties(Entity $entity)
    {
        $descriptor = $entity->getDescriptor();
        $class      = $entity->getNamespacedName();
        $properties = $this->generateConstants($entity);
        $values     = $descriptor->getValueList() ?: [];

        foreach ($values as $value) {
            $properties[] = PropertyGenerator::fromArray([
                'static'       => true,
                'name'         => $value->getName(),
                'visibility'   => PropertyGenerator::VISIBILITY_PROTECTED,
                'docblock'     => [
                    'tags'     => [
                        [
                            'name'        => 'var',
                            'description' => $class,
                        ]
                    ]
                ]
            ]);
        }

        foreach ($properties as $value) {
            $value->getDocblock()->setWordWrap(false);
        }

        return $properties;
    }
869734
protected function generateFields(Entity $entity)
    {
        $fields     = [];
        $descriptor = $entity->getDescriptor();
        $extensions = $descriptor->getExtensionList() ?: [];

        foreach ($extensions as $field) {
            $fields[] = $this->generateExtensionField($entity, $field);
        }

        return $fields;
    }
142471
protected function buildEntityCreatePayload(EntityInterface $entity, array $context = []): string
    {
        return $this->getEntitySerializer()->serialize($entity, 'json', $context);
    }
812485
protected function newPostAction(Request $request)
    {
        $entityManager = $this->get('doctrine.orm.entity_manager');
        $page = $this->getNewPage();

        $form = $this->get('form.factory')->create($this->getNewPageType(), $page);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $page = $this->get('victoire_page.page_helper')->setPosition($page);
            $page->setAuthor($this->getUser());
            $entityManager->persist($page);
            $entityManager->flush();

            // If the $page is a BusinessEntity (eg. an Article), compute it's url
            if (null !== $this->get('victoire_core.helper.business_entity_helper')->findByEntityInstance($page)) {
                $page = $this
                    ->get('victoire_business_page.business_page_builder')
                    ->generateEntityPageFromTemplate($page->getTemplate(), $page, $entityManager);
            }

            $this->congrat($this->get('translator')->trans('victoire_page.create.success', [], 'victoire'));

            return $this->getViewReferenceRedirect($request, $page);
        }

        return [
            'success' => false,
            'message' => $this->get('victoire_form.error_helper')->getRecursiveReadableErrors($form),
            'html'    => $this->get('templating')->render(
                $this->getBaseTemplatePath().':new.html.twig',
                ['form' => $form->createView()]
            ),
        ];
    }
58414
protected function generateToStreamMethod(Entity $entity)
    {
        $lines   = $this->generateBody($entity);
        $body    = implode(PHP_EOL, $lines);
        $method  = MethodGenerator::fromArray([
            'name'       => 'toStream',
            'body'       => $body,
            'parameters' => [
                [
                    'name'          => 'configuration',
                    'type'          => '\Protobuf\Configuration',
                    'defaultValue'  => null
                ]
            ],
            'docblock'   => [
                'shortDescription' => "{@inheritdoc}"
            ]
        ]);

        return $method;
    }
1080373
private function _createEntity($entity, $path, array $links = null)
    {
        $method = Resources::HTTP_POST;
        $headers = [];
        $postParams = [];
        $queryParams = [];
        $statusCode = Resources::STATUS_CREATED;
        $body = $this->wrapAtomEntry($entity, $links);

        $response = $this->sendHttp(
            $method,
            $headers,
            $queryParams,
            $postParams,
            $path,
            $statusCode,
            $body
        );

        $entry = new Entry();
        $entry->parseXml($response->getBody());

        return $this->getPropertiesFromAtomEntry($entry);
    }
791896
public function createResource(Extractable $entity, string $uri): ?int
    {
        $request = new Request(
            'POST',
            $uri,
            $this->getDefaultHeaders(),
            $this->encodeEntity($entity)
        );

        $response = $this->send($request);

        return $response->hasHeader('Resource-ID')
            ? (int) \current($response->getHeader('Resource-ID'))
            : null;
    }