Store Delivery corresponding to the current test
@param $deliveryResultIdentifier
@param $deliveryIdentifier
170167
public function storeRelatedDelivery($deliveryResultIdentifier, $deliveryIdentifier)
    {
        $sql = 'SELECT COUNT(*) FROM ' . self::RESULTS_TABLENAME .
            ' WHERE ' . self::RESULTS_TABLE_ID . ' = ?';
        $params = array($deliveryResultIdentifier);
        if ($this->getPersistence()->query($sql, $params)->fetchColumn() == 0) {
            $this->getPersistence()->insert(
                self::RESULTS_TABLENAME,
                array(self::DELIVERY_COLUMN => $deliveryIdentifier, self::RESULTS_TABLE_ID => $deliveryResultIdentifier)
            );
        } else {
            $sqlUpdate = 'UPDATE ' . self::RESULTS_TABLENAME . ' SET ' . self::DELIVERY_COLUMN . ' = ? WHERE ' . self::RESULTS_TABLE_ID . ' = ?';
            $paramsUpdate = array($deliveryIdentifier, $deliveryResultIdentifier);
            $this->getPersistence()->exec($sqlUpdate, $paramsUpdate);
        }
    }
784333
public function storeItemVariable($deliveryResultIdentifier, $test, $item, taoResultServer_models_classes_Variable $itemVariable, $callIdItem)
    {
        common_logger::i("LoggerStorage - StoreItemVariable :" . $test . " item:" . $item . " callid:" . $callIdItem . "variable:" . serialize($itemVariable) . " into " . $deliveryResultIdentifier);
    }
1275465
public function saveDelivery(Delivery $delivery, array $params, $cart)
    {
        /** @var Carrier $carrier */
//        $carrier = $this->manager->getRepository('ModelBundle:Carrier')->find($delivery->getCarrier());

        if ('same' === $params['selectDelivery']) {
            $delivery->setDeliveryContactPerson($delivery->getContactPerson());
            $delivery->setDeliveryDni($delivery->getDni());
            $delivery->setDeliveryAddressInfo($delivery->getAddressInfo());
            $delivery->setDeliveryPhone($delivery->getPhone());
            $delivery->setDeliveryPhone2($delivery->getPhone2());
            $delivery->setDeliveryPreferredSchedule($delivery->getPreferredSchedule());
        } else if ('existing' === $params['selectDelivery']) {
            /** @var Address $address */
            $address = $this->manager->getRepository('EcommerceBundle:Address')->find($params['existingDeliveryAddress']);

            $delivery->setDeliveryContactPerson($address->getContactPerson());
            $delivery->setDeliveryDni($address->getDni());
            $delivery->setDeliveryAddressInfo($address->getAddressInfo());
            $delivery->setDeliveryPhone($address->getPhone());
            $delivery->setDeliveryPhone2($address->getPhone2());
            $delivery->setDeliveryPreferredSchedule($address->getPreferredSchedule());
            
        } else if ('new' === $params['selectDelivery']) {
            $this->addUserDeliveryAddress($delivery);
        }

        $deliveryCountry = $this->manager->getRepository('CoreBundle:Country')->find('es');
        $delivery->setDeliveryCountry($deliveryCountry);

         
        $total = 0;
        $productPurchases = $this->manager->getRepository('EcommerceBundle:ProductPurchase')->findByTransaction($delivery->getTransaction());
        foreach ($productPurchases as $item) {
            if($item->getDeliveryExpenses()>0)
            $total = $total + $item->getDeliveryExpenses();
        }
        $delivery->setExpenses($total);
        if($total>0) $delivery->setExpensesType('store_pickup');
        else $delivery->setExpensesType('send');

        
        $this->saveUserBillingAddress($delivery);
        
      
              
        $this->manager->persist($delivery);
        $this->manager->flush();

        $this->session->set('delivery-id', $delivery->getId());
        $this->session->set('select-delivery', $params['selectDelivery']);
        if ('existing' === $params['selectDelivery']) {
            $this->session->set('existing-delivery-address', intval($params['existingDeliveryAddress']));
        } else {
            $this->session->remove('existing-delivery-address');
        }

        $this->session->save();
    }
1219298
public function getVendorPackage($packageIdentifier, Package $searchIn = NULL) {
    $package = $searchIn ?: $this->getLocalPackage();

    $vendor = $package->getDirectory(Package::VENDOR);
    $packageRoot = $vendor->sub($packageIdentifier.'/');

    $e = NULL;
    try {
      if ($packageRoot->exists()) {
        return $this->getComposerPackageReader()->fromDirectory($packageRoot);
      }

    } catch (\Exception $e) {
    }

    throw VendorPackageInitException::fromIdentifierAndVendor($packageIdentifier, $vendor, $e);
  }
58605
public function getDeliveryThemeIdFromCache($deliveryId)
    {
        if ($this->getCachePersistence() === null) {
            return false;
        }

        return $this->getCachePersistence()->get($this->getCacheKey($deliveryId));
    }
91565
public function deleteResult($deliveryResultIdentifier)
    {
        // remove variables
        $sql = 'DELETE FROM ' . self::VARIABLES_TABLENAME . '
            WHERE ' . self::VARIABLES_FK_COLUMN . ' = ?';

        if ($this->getPersistence()->exec($sql, array($deliveryResultIdentifier)) === false) {
            return false;
        }

        // remove results
        $sql = 'DELETE FROM ' . self::RESULTS_TABLENAME . '
            WHERE ' . self::RESULTS_TABLE_ID . ' = ?';

        if ($this->getPersistence()->exec($sql, array($deliveryResultIdentifier)) === false) {
            return false;
        }

        return true;
    }
416471
public function getItemVariableDataFromDeliveryResult($resultIdentifier, $filter)
    {
        $itemCallIds = $this->getItemResultsFromDeliveryResult($resultIdentifier);
        $variablesByItem = array();
        foreach ($itemCallIds as $itemCallId) {
            $itemVariables = $this->getVariablesFromObjectResult($itemCallId);

            $item = $this->getItemInfos($itemCallId, $itemVariables);
            $itemIdentifier = $item['uri'];
            $itemLabel = $item['label'];
            $variablesByItem[$itemIdentifier]['itemModel'] = $item['itemModel'];
            foreach ($itemVariables as $variable) {
                //retrieve the type of the variable
                $variableTemp = $variable[0]->variable;
                $variableDescription = array();
                $type = get_class($variableTemp);


                $variableIdentifier = $variableTemp->getIdentifier();

                $variableDescription["uri"] = $variable[0]->uri;
                $variableDescription["var"] = $variableTemp;

                if (method_exists($variableTemp, 'getCorrectResponse') && !is_null($variableTemp->getCorrectResponse())) {
                    if($variableTemp->getCorrectResponse() >= 1){
                        $variableDescription["isCorrect"] = "correct";
                    }
                    else{
                        $variableDescription["isCorrect"] = "incorrect";
                    }
                }
                else{
                    $variableDescription["isCorrect"] = "unscored";
                }

                $variablesByItem[$itemIdentifier]['sortedVars'][$type][$variableIdentifier][$variableTemp->getEpoch()] = $variableDescription;
                $variablesByItem[$itemIdentifier]['label'] = $itemLabel;
            }
        }
        //sort by epoch and filter
        foreach ($variablesByItem as $itemIdentifier => $itemVariables) {

            foreach ($itemVariables['sortedVars'] as $variableType => $variables) {
                foreach ($variables as $variableIdentifier => $observation) {

                    uksort($variablesByItem[$itemIdentifier]['sortedVars'][$variableType][$variableIdentifier], "self::sortTimeStamps");

                    switch ($filter) {
                        case self::VARIABLES_FILTER_LAST_SUBMITTED: {
                                $variablesByItem[$itemIdentifier]['sortedVars'][$variableType][$variableIdentifier] = array(array_pop($variablesByItem[$itemIdentifier]['sortedVars'][$variableType][$variableIdentifier]));
                                break;
                            }
                        case self::VARIABLES_FILTER_FIRST_SUBMITTED: {
                                $variablesByItem[$itemIdentifier]['sortedVars'][$variableType][$variableIdentifier] = array(array_shift($variablesByItem[$itemIdentifier]['sortedVars'][$variableType][$variableIdentifier]));
                                break;
                            }
                    }
                }
            }
        }

        return $variablesByItem;
    }
1249063
public function deleteResult($deliveryResultIdentifier)
    {
        $return = true;
        foreach ($this->getRelatedTestCallIds($deliveryResultIdentifier) as $key) {
            $return = $return && $this->getPersistence()->del(self::PREFIX_CALL_ID . $key);
        }
        foreach ($this->getRelatedItemCallIds($deliveryResultIdentifier) as $key) {
            $return = $return && $this->getPersistence()->del(self::PREFIX_CALL_ID . $key);
        }
        $return = $return && $this->getPersistence()->del(self::PREFIX_DELIVERY . $deliveryResultIdentifier);
        $return = $return && $this->getPersistence()->del(self::PREFIX_TESTTAKER . $deliveryResultIdentifier);

        return $return;
    }
1191569
public function requireOnce(string $entryIdentifier)
    {
        if ($this->frozen === true) {
            if (isset($this->cacheEntryIdentifiers[$entryIdentifier])) {
                return require_once($this->cacheDirectory . $entryIdentifier . $this->cacheEntryFileExtension);
            }
            return false;
        }

        $pathAndFilename = $this->cacheDirectory . $entryIdentifier . $this->cacheEntryFileExtension;
        if ($entryIdentifier !== basename($entryIdentifier)) {
            throw new \InvalidArgumentException('The specified entry identifier (' . $entryIdentifier . ') must not contain a path segment.', 1282073036);
        }
        return ($this->isCacheFileExpired($pathAndFilename)) ? false : require_once($pathAndFilename);
    }
394258
protected function saveKvData(DeliveryMonitoringDataInterface $deliveryMonitoring)
    {
        $data = $deliveryMonitoring->get();

        $id = $data[self::COLUMN_DELIVERY_EXECUTION_ID];
        $kvTableData = $this->extractKvData($data);

        if (empty($kvTableData)) {
            return;
        }

        $query = 'SELECT ' . self::KV_COLUMN_KEY . ',' . self::KV_COLUMN_VALUE . '
            FROM ' . self::KV_TABLE_NAME . '
            WHERE ' . self::KV_COLUMN_PARENT_ID . ' =? AND ' . self::KV_COLUMN_KEY . ' IN(';
        $keys = array_fill(0, count($kvTableData), '?');
        $query .= implode(',', $keys);
        $query .= ')';

        $params = array_merge([$id], array_keys($kvTableData));

        $stmt = $this->getPersistence()->query($query, $params);
        $existent = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        $existent = array_combine(array_column($existent, self::KV_COLUMN_KEY), array_column($existent, self::KV_COLUMN_VALUE));
        $dataToBeInserted = [];
        $dataToBeUpdated = [];
        foreach ($kvTableData as $kvDataKey => $kvDataValue) {
            if (isset($existent[$kvDataKey]) && $existent[$kvDataKey] == $kvDataValue) {
                continue;
            }

            if (array_key_exists($kvDataKey, $existent)) {
                if ($this->getOption(static::OPTION_USE_UPDATE_MULTIPLE) === true) {
                    $dataToBeUpdated[] = [
                        'conditions' => [
                            self::KV_COLUMN_PARENT_ID => $id,
                            self::KV_COLUMN_KEY => $kvDataKey,
                        ],
                        'updateValues' => [
                            self::KV_COLUMN_VALUE => $kvDataValue
                        ]
                    ];
                } else {
                    $this->getPersistence()->exec(
                        'UPDATE ' . self::KV_TABLE_NAME . '
                              SET ' . self::KV_COLUMN_VALUE . ' = ?
                            WHERE ' . self::KV_COLUMN_PARENT_ID . ' = ?
                              AND ' . self::KV_COLUMN_KEY . ' = ?;',
                        [$kvDataValue, $id, $kvDataKey]
                    );
                }
            } else {
                $dataToBeInserted[] = [
                    self::KV_COLUMN_PARENT_ID => $id,
                    self::KV_COLUMN_KEY => $kvDataKey,
                    self::KV_COLUMN_VALUE => $kvDataValue,
                ];
            }
        }


        if ($this->getOption(static::OPTION_USE_UPDATE_MULTIPLE) === true && !empty($dataToBeUpdated)) {
            $this->getPersistence()->updateMultiple(self::KV_TABLE_NAME, $dataToBeUpdated);
        }

        if (!empty($dataToBeInserted)) {
            $this->getPersistence()->insertMultiple(self::KV_TABLE_NAME, $dataToBeInserted);
        }
    }
290888
public function setDelivery($delivery)
    {
        while (is_array($delivery) && list($key, $val) = each($delivery)) {
            $$key = $val;
            switch ($key) {
                case 'deliveryCity':
                    if (is_string($this->destinationCity) && empty($this->destinationCity)) {
                        $this->delivery[$key] = $val;
                    } else {
                        $this->delivery[$key] = $this->destinationCity;
                    }
                    break;

                case 'deliveryState':
                    if (is_string($this->destinationState) && empty($this->destinationState)) {
                        $this->delivery[$key] = $val;
                    } else {
                        $this->delivery[$key] = $this->destinationState;
                    }
                    break;

                case 'deliveryCountryCode':
                    if ($this->destinationCountry === 0) {
                        $this->delivery[$key] = $val;
                    } else {
                        $this->delivery[$key] = $this->destinationCountry;
                    }
                    break;

                default:
                    $this->delivery[$key] = $val;
            }
        }
        $this->deliverySet = true;
    }
722057
public function setDelivery(Delivery $delivery)
    {
        if (!$delivery->id) {
            throw new InvalidArgumentException("Can not set delivery. Delivery id is empty.");
        }

        $this->updateParams['deliveryProviderId'] = $delivery->id;
        $this->updateParams['deliveryCost']       = $delivery->getCost();

        return $this;
    }
1031674
private function exportIntoFolder(\core_kernel_classes_Class $deliveryClass, $destination)
    {
        /** @var \core_kernel_classes_Resource $delivery */
        foreach ($deliveryClass->getInstances(false) as $delivery) {
            (new SingleDeliveryResultsExporter(
                $delivery,
                $this->resultsService,
                (new ColumnsProvider($delivery, $this->resultsService))
            ))
                ->setServiceLocator($this->getServiceLocator())
                ->export($destination);
        }

        if ($subClasses = $deliveryClass->getSubClasses(false)) {
            /** @var \core_kernel_classes_Class $subClass */
            foreach ($subClasses as $subClass) {
                $newDestination = $destination . DIRECTORY_SEPARATOR . \tao_helpers_Display::textCleaner($subClass->getLabel(), '*');
                mkdir($newDestination);
                $this->exportIntoFolder($subClass, $newDestination);
            }
        }
    }
945765
public function getPrintableRubric(DeliveryExecutionInterface $deliveryExecution)
    {
        $testSessionService = ServiceManager::getServiceManager()->get(TestSessionService::SERVICE_ID);
        $session = $testSessionService->getTestSession($deliveryExecution);

        $inputParameters = $testSessionService->getRuntimeInputParameters($deliveryExecution);
        $testDefinition = \taoQtiTest_helpers_Utils::getTestDefinition($inputParameters['QtiTestCompilation']);
        $sections = $testDefinition->getComponentsByClassName('assessmentSection');

        $tag = $this->getOption(self::OPTION_PRINTABLE_RUBRIC_TAG);

        $directoryIds = explode('|', $inputParameters['QtiTestCompilation']);
        $compilationDirs = array(
            'private' => \tao_models_classes_service_FileStorage::singleton()->getDirectoryById($directoryIds[0]),
            'public' => \tao_models_classes_service_FileStorage::singleton()->getDirectoryById($directoryIds[1]),
        );

        $rubrics = [];

        // -- variables used in the included rubric block templates.
        // base path (base URI to be used for resource inclusion).
        $basePathVarName = taoQtiTest_models_classes_QtiTestService::TEST_BASE_PATH_NAME;
        $$basePathVarName = $compilationDirs['public']->getPublicAccessUrl();

        // state name (the variable to access to get the state of the assessmentTestSession).
        $stateName = taoQtiTest_models_classes_QtiTestService::TEST_RENDERING_STATE_NAME;
        $$stateName = $session;

        // views name (the variable to be accessed for the visibility of rubric blocks).
        $viewsName = taoQtiTest_models_classes_QtiTestService::TEST_VIEWS_NAME;
        $$viewsName = array(View::CANDIDATE);

        foreach ($sections as $section) {
            $assessmentItemsRef = $section->getComponentsByClassName('assessmentItemRef');
            foreach ($assessmentItemsRef as $item) {
                foreach($item->getCategories() as $category) {
                    if ($category === $tag) {
                        foreach ($section->getRubricBlockRefs() as $rubric) {
                            ob_start();
                            include $compilationDirs['private']->getPath() . '/' . ltrim($rubric->getHref(), './\\');
                            $rubrics[] = ob_get_clean();
                        }
                    }
                };
            };
        }

        return $rubrics;
    }
511104
protected function setItemDeliveryAddress(
        $addressData,
        ApiItemInterface $item,
        ContactInterface $contact = null,
        AccountInterface $account = null
    ) {
        if ($item->getDeliveryAddress() === null) {
            // Create new delivery address.
            $deliveryAddress = new $this->orderAddressEntity();
            // Persist entities.
            $this->em->persist($deliveryAddress);
            // Assign to order.
            $item->setDeliveryAddress($deliveryAddress);
        }

        if (is_array($addressData)) {
            // Set order-address.
            $this->orderAddressManager->setOrderAddress(
                $item->getDeliveryAddress(),
                $addressData,
                $contact,
                $account
            );
        } elseif (is_int($addressData)) {
            $contactAddressId = $addressData;
            // Create order-address and assign contact-address data.
            $deliveryAddress = $item->getEntity()->getDeliveryAddress();

            $orderAddress = $this->orderAddressManager->getAndSetOrderAddressByContactAddressId(
                $contactAddressId,
                $contact,
                $account,
                $deliveryAddress
            );

            // Set delivery address.
            $item->setDeliveryAddress($orderAddress);

            // If new delivery address persist.
            if (!$deliveryAddress) {
                $this->em->persist($orderAddress);
            }
        }
    }
1044219
public function setResponseIdentifier($responseIdentifier)
    {
        if (Format::isIdentifier($responseIdentifier, false) === true) {
            $this->responseIdentifier = $responseIdentifier;
        } else {
            $msg = "The 'responseIdentifier' argument must be a valid QTI identifier.";
            throw new InvalidArgumentException($msg);
        }
    }
742113
protected function verifyDeliveryStartAuthorized($deliveryId)
    {
        $user = common_session_SessionManager::getSession()->getUser();
        $this->getAuthorizationProvider()->verifyStartAuthorization($deliveryId, $user);
    }