Normalizes an object into a set of arrays/scalars

@param object $transaction   event to normalize
@param string $format  format the normalization result will be encoded as
@param array  $context Context options for the normalizer

@return array
195257
public function normalize($transaction, $format = null, array $context = array())
    {
        /** @var  $transaction Transaction */
        $credentials = $transaction->getCredentials();

        $createTransactionRequest = array();

        if ($format == 'xml') {
            $createTransactionRequest['@xmlns'] = 'AnetApi/xml/v1/schema/AnetApiSchema.xsd';
        }

        $merchantAuthentication = array(
            'name' => $credentials->getCredential('username'),
            'transactionKey' => $credentials->getCredential('password'),
        );

        $transactionRequest = array(
            "transactionType" => $this->getTransactionType($transaction)
        );

        if ($transaction->getType()->getValue() != Transaction\TransactionType::VOID) {
            $transactionRequest['amount'] = $transaction->getAmount();
        }

        $account = $transaction->getAccount();
        if (in_array($transaction->getType()->getValue(), array(
            Transaction\TransactionType::SALE,
            Transaction\TransactionType::AUTH,
            Transaction\TransactionType::REFUND))
        ){
            $payment = array();
            if ($account instanceof CardAccount) {
                if ($account instanceof SwipedCardAccount
                    && $transaction->getType()->getValue() != Transaction\TransactionType::REFUND
                ){
                    $payment['trackData'] = array();
                    if ($account->getTrackOne()) {
                        $payment['trackData']['track1'] = $account->getTrackOne();
                    } elseif ($account->getTrackTwo()) {
                        $payment['trackData']['track2'] = $account->getTrackTwo();
                    }
                } else {
                    $payment = array(
                        'creditCard' => array(
                            'cardNumber' => $account->getAccountNumber(),
                            'expirationDate' => $account->getExpMonth()->getLongMonth() . $account->getExpYear()->getShortYear(),
                        )
                    );

                    if (isset($options['enable_cvv']) && true === $options['enable_cvv']
                        && $transaction->getType()->getValue() != Transaction\TransactionType::REFUND) {
                        $payment['creditCard']['cardCode'] = $account->getCvv();
                    }
                }
            } elseif ($account instanceof BankAccount) {
                $payment = array(
                    'bankAccount' => array(
                        'accountType' => 'checking',
                        'routingNumber' => $account->getRoutingNumber(),
                        'accountNumber' => $account->getAccountNumber(),
                        'nameOnAccount' => $account->getName()
                    )
                );
            } else {
                throw new InvalidArgumentException(sprintf("Unsupported Account Type %s", get_class($account)));
            }

            $transactionRequest['payment'] = $payment;
        }

        if ($context['event_id']) {
            $transactionRequest['order'] = array();
            $transactionRequest['order']['invoiceNumber'] = $context['event_id'];
        }


        if (in_array($transaction->getType()->getValue(), array(
            Transaction\TransactionType::CAPTURE,
            Transaction\TransactionType::REFUND,
            Transaction\TransactionType::VOID))
        ) {
            $transactionRequest['refTransId'] = $transaction->getParent()->getResult()->getExternalId();
        }


        if (in_array($transaction->getType()->getValue(), array(
            Transaction\TransactionType::SALE,
            Transaction\TransactionType::AUTH))
        ) {
                $names = explode(' ', $account->getName(), 2);
                $firstName = isset($names[0]) ? $names[0] : '';
                $lastName = isset($names[1]) ? $names[1] : '';

                if (isset($context['email'])) {
                    $transactionRequest['customer'] = array(
                        'email' => $context['email']
                    );
                }

                $transactionRequest['billTo'] = array(
                    'firstName' => $firstName,
                    'lastName' => $lastName,
                    'address' => $account->getAddress(),
                    'city' => $account->getCity(),
                    'state' => $account->getRegion(),
                    'zip' => $account->getPostalCode(),
                    'country' => $account->getCountry(),
                );
        }

        if ($account instanceof SwipedCardAccount
            && !in_array($transaction->getType()->getValue(), array(Transaction\TransactionType::REFUND, Transaction\TransactionType::VOID))
        ){
            $transactionRequest['retail'] = array(
                'marketType' => 2,
                'deviceType' => 7
            );
        }

        if (isset($context['test']) && $context['test'])  {
            $transactionRequest['transactionSettings']['setting'][] = array(
                'settingName' => 'testRequest',
                'settingValue' => 'true'
            );
        }

        if (isset($context['userFields'])) {
            $transactionRequest['userFields'] = array();
            $transactionRequest['userFields']['userField'] = array();
            foreach ($context['userFields'] as $name => $value) {
                $transactionRequest['userFields']['userField'][] = array(
                    'name' => $name,
                    'value' => $value
                );
            }
        }

        $createTransactionRequest['merchantAuthentication'] = $merchantAuthentication;
        $createTransactionRequest['transactionRequest'] = $transactionRequest;

        return $createTransactionRequest;
    }
387828
protected function normalizeAssociation($association, $name, $format = null, array $context = array())
    {
        if ($association === null) {
            return;
        }

        $hint = $this->getHintFromObject($association);
        $ids = $this->getIdentifierFromObject($association);
        $id = $this->getIdentifiersAsString($ids);
        $data = array_merge($hint, $ids);
        $objectId = current($hint).'#'.$id;

        if (isset($context['@references'][$objectId])) {
            return $data;
        }

        $context['@references'][$objectId] = false;
        if ($association instanceof Proxy and !$association->__isInitialized()) {
            return $data;
        }

        $normalized = $this->serializer->normalize($association, $format, $context);

        $context['@references'][$objectId] = $normalized;

        return $data;
    }
1244202
protected function extractAttributes($object, $format = null, array $context = []): array
    {
        $class = \get_class($object);

        if (false === isset($this->localStorage[$class]))
        {
            $this->localStorage[$class] = parent::extractAttributes($object, $format, $context);
        }

        return $this->localStorage[$class];
    }
258688
public function normalize($object, $format = null, array $context = []): array
    {
        if (!$object instanceof RelationInterface && !$object instanceof ActionInterface) {
            throw new \InvalidArgumentException(sprintf(
                'The normalizer support only "%s" or "%s" but "%s" given.',
                RelationInterface::class,
                ActionInterface::class,
                is_object($object) ? get_class($object) : gettype($object)
            ));
        }

        $data = [
            'href' => $object->getHref()->getPath(),
        ];

        if ($object->getHref()->isTemplated()) {
            $data['templated'] = true;
        }

        if (count($object->getAttributes())) {
            $data['attributes'] = $object->getAttributes();
        }

        return $data;
    }
113087
public function normalize($object, $format = null, array $context = [])
    {
        /** @var object $normalized */
        $normalized = parent::normalize($object, $format, $context);

        // Fix the start- and end date of the rate plan if the organization's
        // timezone is different from the default PHP timezone.
        /** @var \Apigee\Edge\Api\Monetization\Entity\RatePlanInterface $object */
        if (null === $object->getPackage()) {
            throw new UninitializedPropertyException($object, 'package', 'Apigee\Edge\Api\Monetization\Entity\ApiPackageInterface');
        }

        if (null === $object->getPackage()->getOrganization()) {
            throw new UninitializedPropertyException($object->getPackage(), 'organization', 'Apigee\Edge\Api\Monetization\Entity\OrganizationProfileInterface');
        }

        $this->fixTimeZoneOnNormalization($object, $normalized, $object->getPackage()->getOrganization()->getTimezone());

        return $normalized;
    }
1051585
protected function getItemsData($object, string $format = null, array $context = []): array
    {
        $data = [
            'data' => [],
        ];

        foreach ($object as $obj) {
            $item = $this->normalizer->normalize($obj, $format, $context);
            if (!\is_array($item)) {
                throw new UnexpectedValueException('Expected item to be an array');
            }

            if (!isset($item['data'])) {
                throw new UnexpectedValueException('The JSON API document must contain a "data" key.');
            }

            $data['data'][] = $item['data'];

            if (isset($item['included'])) {
                $data['included'] = array_values(array_unique(array_merge($data['included'] ?? [], $item['included']), SORT_REGULAR));
            }
        }

        return $data;
    }
215774
public function denormalize($data, $class, $format = null, array $context = array())
    {
        $allowedAttributes = $this->getAllowedAttributes($class, $context, true);
        $normalizedData = $this->prepareForDenormalization($data);

        $reflectionClass = new \ReflectionClass($class);
        $subcontext = array_merge($context, array('format' => $format));
        $object = $this->instantiateObject($normalizedData, $class, $subcontext, $reflectionClass, $allowedAttributes);

        $classMethods = get_class_methods($object);

        foreach ($normalizedData as $attribute => $value) {
            if ($this->nameConverter) {
                $attribute = $this->nameConverter->denormalize($attribute);
            }

            $allowed = $allowedAttributes === false || in_array($attribute, $allowedAttributes);
            $ignored = in_array($attribute, $this->ignoredAttributes);

            if (!$allowed || $ignored) {
                continue;
            }

            $setter = 'set'.ucfirst($attribute);
            if (!in_array($setter, $classMethods)) {
                continue;
            }

            $value = $this->denormalizeProperty($value, $class, $attribute, $format, $context);

            $object->$setter($value);
        }

        return $object;
    }
961053
protected function denormalizeCollection($collection, $class, $name, $format = null, array $context = array())
    {
        /** @var ClassMetadata $meta */
        $meta = $context['entityMeta'];

        $targetEntity = $meta->associationMappings[$name]['targetEntity'];

        $result = array();
        foreach ($collection as $key => $element) {
            $class = $class ?: $targetEntity;

            $result[$key] = $this->denormalizeAssociation($element, $class, $name, $format, $context);
        }

        return $result;
    }
442396
private function _buildRequestData(Transaction $transaction): array
    {
        $currency = Commerce::getInstance()->getCurrencies()->getCurrencyByIso($transaction->paymentCurrency);

        if (!$currency) {
            throw new NotSupportedException('The currency “' . $transaction->paymentCurrency . '” is not supported!');
        }

        $metadata = [
            'order_id' => $transaction->getOrder()->id,
            'order_number' => $transaction->getOrder()->number,
            'transaction_id' => $transaction->id,
            'transaction_reference' => $transaction->hash,
        ];

        $appRequest = Craft::$app->getRequest();
        if (!$appRequest->getIsConsoleRequest()) {
            $metadata['client_ip'] = $appRequest->getUserIP();
        }

        $request = [
            'amount' => $transaction->paymentAmount * (10 ** $currency->minorUnit),
            'currency' => $transaction->paymentCurrency,
            'description' => Craft::t('commerce-stripe', 'Order') . ' #' . $transaction->orderId,
            'metadata' => $metadata
        ];

        $event = new BuildGatewayRequestEvent([
            'transaction' => $transaction,
            'metadata' => $metadata,
            'request' => $request
        ]);

        $this->trigger(self::EVENT_BUILD_GATEWAY_REQUEST, $event);

        $request = array_merge($event->request, $request);
        $request['metadata'] = array_merge($event->metadata, $metadata);

        if ($this->sendReceiptEmail) {
            $request['receipt_email'] = $transaction->getOrder()->email;
        }

        return $request;
    }
778767
private function normalizeRawCollection(iterable $object, ?string $format, array $context): array
    {
        $data = [];
        foreach ($object as $index => $obj) {
            $data[$index] = $this->normalizer->normalize($obj, $format, $context);
        }

        return $data;
    }
958837
public function normalize($object, $format = null, array $context = [])
    {
        if (!$object instanceof \DateTimeInterface) {
            throw new InvalidArgumentException('The object must implement the "\DateTimeInterface".');
        }

        $dateTimeFormat = $context[self::FORMAT_KEY] ?? $this->defaultContext[self::FORMAT_KEY];
        $timezone = $this->getTimezone($context);

        if (null !== $timezone) {
            $object = clone $object;
            $object = $object->setTimezone($timezone);
        }

        return $object->format($dateTimeFormat);
    }
1208781
public function normalize($string, $format = null, array $context = array())
    {
        $mime = isset($context[static::CONTEXT_MIME]) ? $context[static::CONTEXT_MIME] : 'application/octet-stream';
        $charset = isset($context[static::CONTEXT_CHARSET]) ? $context[static::CONTEXT_CHARSET] : null;
        $gzip = isset($context[static::CONTEXT_GZIP]) ? $context[static::CONTEXT_GZIP] : null;
        $base64 = isset($context[static::CONTEXT_BASE64]) ? $context[static::CONTEXT_BASE64] : null;
        $base64 = ($base64 !== null) ? $base64 : strpos($mime, '/octet-stream') !== false;
        $urlencode = isset($context[static::CONTEXT_URLENCODE]) ? $context[static::CONTEXT_URLENCODE] : null;
        $urlencode = ($urlencode !== null) ? $urlencode : strpos($mime, 'text/') !== false;

        if ($gzip) {
            $string = gzencode($string);
            $mime = 'application/x-gzip';
        }
        if ($urlencode and !$base64) {
            $string = urlencode($string);
        }
        if ($base64 or !$urlencode) {
            $string = base64_encode($string);
        }

        $options = $mime;
        if ($charset and $mime) {
            $options .= ';charset='.$charset;
        }
        if ($base64) {
            $options .= ';base64';
        }

        return sprintf('data:%s,%s', $options, $string);
    }
1004089
public function normalize($data, SerializationContext $context)
    {
        return $this->serializer->normalize($data->jsonSerialize(), $context);
    }
1208409
public function normalize($object, $format = null, array $context = [])
    {
        $this->maxDepthHandler->handleMaxDepth($context);

        /** @var ResourceInterface $object */
        if ($this->byReferenceHandler->isByShortReference($context)) {
            return $object->getIdentifier();
        }

        if ($this->byReferenceHandler->isByReference($context)) {
            $normalizedData = [
                'identifier' => $object->getIdentifier(),
                'originalFileName' => $object->getOriginalFileName(),
                'type' => $object::getType(),
            ];
        } else {
            $normalizedData = parent::normalize($object, $format, $context);
        }

        return $this->handleCustomFields($object, $format, $context, $normalizedData);
    }
212564
protected function normalizeTranslations(Model\TranslatableInterface $translatable, $format, array $context = [])
    {
        $data = [];

        $groups = isset($context['groups']) ? (array)$context['groups'] : [];

        /*if (in_array('Default', $groups)) {
            if ($translatable instanceof Model\TranslatableInterface) {
                $data['translations'] = array_map(function (Model\TranslationInterface $t) use ($format, $context) {
                    return $t->getId();
                }, $translatable->getTranslations()->toArray());
            }
        }*/
        if (in_array('Search', $groups)) {
            if ($translatable instanceof Model\TranslatableInterface) {
                $data['translations'] = array_map(function (Model\TranslationInterface $t) use ($format, $context) {
                    return $this->normalizeObject($t, $format, $context);
                }, $translatable->getTranslations()->toArray());
            }
        }

        return $data;
    }
631533
public function normalize($object, $format = null, array $context = [])
    {
        $normalized = (array) parent::normalize($object, $format, $context);

        $entityReferenceProperties = $this->getNestedObjectProperties($object);

        if (!empty($entityReferenceProperties)) {
            foreach ($entityReferenceProperties as $entityProperty => $normalizedProperty) {
                // Ensure we do not send the complete referenced entity object
                // only the referenced entity id.
                if (isset($normalized[$normalizedProperty]->id)) {
                    $normalized[$normalizedProperty] = [
                        'id' => $normalized[$normalizedProperty]->id,
                    ];
                }
            }
        }

        // Set missing ids of referenced entities passed by controllers.
        // Ex.: in case of entity create.
        // @see \Apigee\Edge\Api\Monetization\Controller\EntityCreateOperationControllerTrait::buildContextForEntityTransformerInCreate()
        if (!empty($context[self::MINT_ENTITY_REFERENCE_PROPERTY_VALUES])) {
            foreach ($context[self::MINT_ENTITY_REFERENCE_PROPERTY_VALUES] as $entityProperty => $value) {
                if (!isset($normalized[$entityProperty]['id'])) {
                    $normalized[$entityProperty] = [
                        'id' => $value,
                    ];
                }
            }
        }

        return (object) $normalized;
    }
417600
public function normalize($object, $format = null, array $context = array())
    {
        /** @var ClientCredentials $object */
        return array(
            'clientId' => $object->getClientId(),
            'permissions' => $object->getPermissions(),
            'signatureCredentials' => $this->algorithmManager->normalizeSignatureCredentials(
                $object->getSignatureCredentials()
            ),
        );
    }