soapApiClient = $soapApiClient; $this->orderValidator = $orderValidator; $this->logger = $logger; $this->orderRepository = $orderRepository; } /** * Submits packet data to Packeta API. * * @param WC_Order $order WC order. * @param array $resultsCounter Array with results. */ public function submitPacket( WC_Order $order, array &$resultsCounter ): void { $commonEntity = $this->orderRepository->getByWcOrder( $order ); if ( null === $commonEntity ) { $resultsCounter['ignored'] ++; return; } $orderData = $order->get_data(); $shippingMethods = $order->get_shipping_methods(); $shippingMethod = reset( $shippingMethods ); $shippingMethodData = $shippingMethod->get_data(); $shippingMethodId = $shippingMethodData['method_id']; if ( ShippingMethod::PACKETERY_METHOD_ID === $shippingMethodId && null !== $commonEntity && ! $commonEntity->isExported() ) { try { $createPacketRequest = $this->preparePacketRequest( $commonEntity ); } catch ( InvalidRequestException $e ) { $record = new Log\Record(); $record->action = Log\Record::ACTION_PACKET_SENDING; $record->status = Log\Record::STATUS_ERROR; $record->title = __( 'packetSendingErrorLogTitle', 'packetery' ); $record->params = [ 'orderId' => $orderData['id'], 'errorMessage' => $e->getMessage(), ]; $this->logger->add( $record ); $resultsCounter['errors'] ++; return; } $response = $this->soapApiClient->createPacket( $createPacketRequest ); if ( $response->hasFault() ) { $record = new Log\Record(); $record->action = Log\Record::ACTION_PACKET_SENDING; $record->status = Log\Record::STATUS_ERROR; $record->title = __( 'packetSendingErrorLogTitle', 'packetery' ); $record->params = [ 'request' => $createPacketRequest->getSubmittableData(), 'errorMessage' => $response->getErrorsAsString(), ]; $this->logger->add( $record ); $resultsCounter['errors'] ++; } else { $commonEntity->setIsExported( true ); $commonEntity->setPacketId( (string) $response->getId() ); $this->orderRepository->save( $commonEntity ); $resultsCounter['success'] ++; $record = new Log\Record(); $record->action = Log\Record::ACTION_PACKET_SENDING; $record->status = Log\Record::STATUS_SUCCESS; $record->title = __( 'packetSendingSuccessLogTitle', 'packetery' ); $record->params = [ 'packetId' => $response->getId(), ]; $this->logger->add( $record ); } } else { $resultsCounter['ignored'] ++; } } /** * Prepares packet attributes. * * @param Entity\Order $commonEntity Order entity. * * @return CreatePacket * @throws InvalidRequestException For the case request is not eligible to be sent to API. */ private function preparePacketRequest( Entity\Order $commonEntity ): CreatePacket { /* TODO: extend validator to return specific errors. if ( ! $this->orderValidator->validate( $commonEntity ) ) { throw new InvalidRequestException( 'All required order attributes are not set.' ); } */ return new CreatePacket( $commonEntity ); } }