function processLenderInvite(Lender $invitee, InviteVisit $lenderInviteVisit) { $con = Propel::getWriteConnection(TransactionTableMap::DATABASE_NAME); for ($retry = 0; $retry < 3; $retry++) { $con->beginTransaction(); try { $invite = $lenderInviteVisit->getInvite(); if ($invite) { $res1 = $invite->setInvitee($invitee)->save(); } else { $invite = new Invite(); $invite->setLender($lenderInviteVisit->getLender()); $invite->setEmail($invitee->getUser()->getEmail()); $invite->setInvitee($invitee); $invite->setInvited(false); $res1 = $invitee->save($con); } if (!$res1) { throw new \Exception(); } $this->transactionService->addLenderInviteTransaction($con, $invite); } catch (\Exception $e) { $con->rollback(); } $con->commit(); //TODO , invite_notify(see below commented if statement) // if ($lender['invite_notify']) { $this->lenderMailer->sendLenderInviteCredit($invite); // } $this->mixpanelService->trackInviteAccept($invite); return $invite; } return false; }
/** * @param int $titleId customer title id (from customer_title table) * @param string $firstname customer first name * @param string $lastname customer last name * @param string $address1 customer address * @param string $address2 customer adress complement 1 * @param string $address3 customer adress complement 2 * @param string $phone customer phone number * @param string $cellphone customer cellphone number * @param string $zipcode customer zipcode * @param string $city * @param int $countryId customer country id (from Country table) * @param string $email customer email, must be unique * @param string $plainPassword customer plain password, hash is made calling setPassword method. Not mandatory parameter but an exception is thrown if customer is new without password * @param string $lang * @param int $reseller * @param null $sponsor * @param int $discount * @param null $company * @param null $ref * @param bool $forceEmailUpdate true if the email address could be updated. * @param int $stateId customer state id (from State table) * @throws \Exception * @throws \Propel\Runtime\Exception\PropelException */ public function createOrUpdate($titleId, $firstname, $lastname, $address1, $address2, $address3, $phone, $cellphone, $zipcode, $city, $countryId, $email = null, $plainPassword = null, $lang = null, $reseller = 0, $sponsor = null, $discount = 0, $company = null, $ref = null, $forceEmailUpdate = false, $stateId = null) { $this->setTitleId($titleId)->setFirstname($firstname)->setLastname($lastname)->setEmail($email, $forceEmailUpdate)->setPassword($plainPassword)->setReseller($reseller)->setSponsor($sponsor)->setDiscount($discount)->setRef($ref); if (!is_null($lang)) { $this->setLangId($lang); } $con = Propel::getWriteConnection(CustomerTableMap::DATABASE_NAME); $con->beginTransaction(); try { if ($this->isNew()) { $address = new Address(); $address->setLabel(Translator::getInstance()->trans("Main address"))->setCompany($company)->setTitleId($titleId)->setFirstname($firstname)->setLastname($lastname)->setAddress1($address1)->setAddress2($address2)->setAddress3($address3)->setPhone($phone)->setCellphone($cellphone)->setZipcode($zipcode)->setCity($city)->setCountryId($countryId)->setStateId($stateId)->setIsDefault(1); $this->addAddress($address); if (ConfigQuery::isCustomerEmailConfirmationEnable()) { $this->setConfirmationToken(bin2hex(random_bytes(32))); } } else { $address = $this->getDefaultAddress(); $address->setCompany($company)->setTitleId($titleId)->setFirstname($firstname)->setLastname($lastname)->setAddress1($address1)->setAddress2($address2)->setAddress3($address3)->setPhone($phone)->setCellphone($cellphone)->setZipcode($zipcode)->setCity($city)->setCountryId($countryId)->setStateId($stateId)->save($con); } $this->save($con); $con->commit(); } catch (PropelException $e) { $con->rollBack(); throw $e; } }
public function updateModules() { $finder = new Finder(); $finder->name('module.xml')->in($this->baseModuleDir . '/*/Config'); $descriptorValidator = new ModuleDescriptorValidator(); foreach ($finder as $file) { $content = $descriptorValidator->getDescriptor($file->getRealPath()); $reflected = new \ReflectionClass((string) $content->fullnamespace); $code = basename(dirname($reflected->getFileName())); $con = Propel::getWriteConnection(ModuleTableMap::DATABASE_NAME); $con->beginTransaction(); try { $module = ModuleQuery::create()->filterByCode($code)->findOne(); if (null === $module) { $module = new Module(); $module->setCode($code)->setFullNamespace((string) $content->fullnamespace)->setType($this->getModuleType($reflected))->setActivate(0)->save($con); } $this->saveDescription($module, $content, $con); $con->commit(); } catch (PropelException $e) { $con->rollBack(); throw $e; } } }
public function __construct() { $this->helper = new Helper(); $this->debug = Propel::getWriteConnection(\Map\JaCategoriasTableMap::DATABASE_NAME); $this->debug->setLogMethods(array('exec', 'query', 'execute', 'beginTransaction', 'commit', 'rollBack', 'bindValue')); $this->debug->useDebug(Config::$DEBUG_SQL); }
/** * Set up propel connection * * @return \Propel\Runtime\Connection\ConnectionInterface */ protected function setupAndGetPropelConnection() { $config = Helper::getConfig(); Helper::setupPropel(); $con = Propel::getWriteConnection($config['database']['connectionName']); return $con; }
/** * Create or Update this Coupon * * @param string $code Coupon Code * @param string $title Coupon title * @param array $effects Ready to be serialized in JSON effect params * @param string $type Coupon type * @param bool $isRemovingPostage Is removing Postage * @param string $shortDescription Coupon short description * @param string $description Coupon description * @param boolean $isEnabled Enable/Disable * @param \DateTime $expirationDate Coupon expiration date * @param boolean $isAvailableOnSpecialOffers Is available on special offers * @param boolean $isCumulative Is cumulative * @param int $maxUsage Coupon quantity * @param string $defaultSerializedRule Serialized default rule added if none found * @param string $locale Coupon Language code ISO (ex: fr_FR) * @param array $freeShippingForCountries ID of Countries to which shipping is free * @param array $freeShippingForMethods ID of Shipping modules for which shipping is free * @param bool $perCustomerUsageCount True if usage coiunt is per customer * * @throws \Exception */ public function createOrUpdate($code, $title, array $effects, $type, $isRemovingPostage, $shortDescription, $description, $isEnabled, $expirationDate, $isAvailableOnSpecialOffers, $isCumulative, $maxUsage, $defaultSerializedRule, $locale, $freeShippingForCountries, $freeShippingForMethods, $perCustomerUsageCount) { $con = Propel::getWriteConnection(CouponTableMap::DATABASE_NAME); $con->beginTransaction(); try { $this->setCode($code)->setType($type)->setEffects($effects)->setIsRemovingPostage($isRemovingPostage)->setIsEnabled($isEnabled)->setExpirationDate($expirationDate)->setIsAvailableOnSpecialOffers($isAvailableOnSpecialOffers)->setIsCumulative($isCumulative)->setMaxUsage($maxUsage)->setPerCustomerUsageCount($perCustomerUsageCount)->setLocale($locale)->setTitle($title)->setShortDescription($shortDescription)->setDescription($description); // If no rule given, set default rule if (null === $this->getSerializedConditions()) { $this->setSerializedConditions($defaultSerializedRule); } $this->save(); // Update countries and modules relation for free shipping CouponCountryQuery::create()->filterByCouponId($this->id)->delete(); CouponModuleQuery::create()->filterByCouponId($this->id)->delete(); foreach ($freeShippingForCountries as $countryId) { if ($countryId <= 0) { continue; } $couponCountry = new CouponCountry(); $couponCountry->setCouponId($this->getId())->setCountryId($countryId)->save(); } foreach ($freeShippingForMethods as $moduleId) { if ($moduleId <= 0) { continue; } $couponModule = new CouponModule(); $couponModule->setCouponId($this->getId())->setModuleId($moduleId)->save(); } $con->commit(); } catch (\Exception $ex) { $con->rollback(); throw $ex; } }
public function execute($params) { $id = $params['id']; $movie = \Engine\MovieQuery::create()->findPK($id); $movie->setTitle($params['title']); $movie->setYear($params['year']); $movie->setFormat($params['format']); $actors = []; //generate array of new actors foreach ($params['actor_name'] as $key => $name) { $actor = new \Engine\Actor(); $actor->setMovieId($id); $actor->setName($name); $actor->setSurname($params['actor_surname'][$key]); $actors[] = $actor; } //propel accepts a collection to set related data $collection = new \Propel\Runtime\Collection\ObjectCollection($actors); $con = \Propel\Runtime\Propel::getWriteConnection(\Engine\Map\MovieTableMap::DATABASE_NAME); $con->beginTransaction(); try { //set collection of actors; this automatically deletes old related actors $movie->setActors($collection); $movie->save($con); $con->commit(); } catch (Exception $e) { $con->rollback(); throw $e; } return ['Message' => 'Movie has beed updated successfully.', 'Status' => 1]; }
/** * Delete a category entry * * @param \Thelia\Core\Event\Category\CategoryDeleteEvent $event */ public function delete(CategoryDeleteEvent $event) { if (null !== ($category = CategoryQuery::create()->findPk($event->getCategoryId()))) { $con = Propel::getWriteConnection(CategoryTableMap::DATABASE_NAME); $con->beginTransaction(); try { // Get category's files to delete after category deletion $fileList['images']['list'] = CategoryImageQuery::create()->findByCategoryId($event->getCategoryId()); $fileList['images']['type'] = TheliaEvents::IMAGE_DELETE; $fileList['documentList']['list'] = CategoryDocumentQuery::create()->findByCategoryId($event->getCategoryId()); $fileList['documentList']['type'] = TheliaEvents::DOCUMENT_DELETE; // Delete category $category->setDispatcher($event->getDispatcher())->delete($con); $event->setCategory($category); // Dispatch delete category's files event foreach ($fileList as $fileTypeList) { foreach ($fileTypeList['list'] as $fileToDelete) { $fileDeleteEvent = new FileDeleteEvent($fileToDelete); $event->getDispatcher()->dispatch($fileTypeList['type'], $fileDeleteEvent); } } $con->commit(); } catch (\Exception $e) { $con->rollback(); throw $e; } } }
public function delete(FolderDeleteEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== ($folder = FolderQuery::create()->findPk($event->getFolderId()))) { $con = Propel::getWriteConnection(FolderTableMap::DATABASE_NAME); $con->beginTransaction(); try { $fileList = ['images' => [], 'documentList' => []]; // Get folder's files to delete after folder deletion $fileList['images']['list'] = FolderImageQuery::create()->findByFolderId($event->getFolderId()); $fileList['images']['type'] = TheliaEvents::IMAGE_DELETE; $fileList['documentList']['list'] = FolderDocumentQuery::create()->findByFolderId($event->getFolderId()); $fileList['documentList']['type'] = TheliaEvents::DOCUMENT_DELETE; // Delete folder $folder->setDispatcher($dispatcher)->delete($con); $event->setFolder($folder); // Dispatch delete folder's files event foreach ($fileList as $fileTypeList) { foreach ($fileTypeList['list'] as $fileToDelete) { $fileDeleteEvent = new FileDeleteEvent($fileToDelete); $dispatcher->dispatch($fileTypeList['type'], $fileDeleteEvent); } } $con->commit(); } catch (\Exception $e) { $con->rollback(); throw $e; } } }
public function delete(ModuleDeleteEvent $event) { if (null !== ($module = ModuleQuery::create()->findPk($event->getModuleId()))) { $con = Propel::getWriteConnection(ModuleTableMap::DATABASE_NAME); $con->beginTransaction(); try { if (null === $module->getFullNamespace()) { throw new \LogicException(Translator::getInstance()->trans('Cannot instanciante module "%name%": the namespace is null. Maybe the model is not loaded ?', array('%name%' => $module->getCode()))); } try { $instance = $module->createInstance(); $instance->setContainer($this->container); $path = $module->getAbsoluteBaseDir(); $instance->destroy($con, $event->getDeleteData()); $fs = new Filesystem(); $fs->remove($path); } catch (\ReflectionException $ex) { // Happens probably because the module directory has been deleted. // Log a warning, and delete the database entry. Tlog::getInstance()->addWarning(Translator::getInstance()->trans('Failed to create instance of module "%name%" when trying to delete module. Module directory has probably been deleted', array('%name%' => $module->getCode()))); } $module->delete($con); $con->commit(); $event->setModule($module); $this->cacheClear($event->getDispatcher()); } catch (\Exception $e) { $con->rollBack(); throw $e; } } }
public function execute($params) { $movie = new \Engine\Movie(); $movie->setTitle($params['title']); $movie->setYear($params['year']); $movie->setFormat($params['format']); $actors = []; foreach ($params['actor_name'] as $key => $name) { $actor = new \Engine\Actor(); $actor->setName($name); $actor->setSurname($params['actor_surname'][$key]); $actors[] = $actor; } $con = \Propel\Runtime\Propel::getWriteConnection(\Engine\Map\MovieTableMap::DATABASE_NAME); $con->beginTransaction(); try { $movie->save($con); foreach ($actors as $actor) { $actor->setMovieId($movie->getId()); $actor->save($con); } $con->commit(); } catch (Exception $e) { $con->rollback(); throw $e; } return ['Message' => 'Movie has beed added successfully.', 'Status' => 1]; }
/** * @param \Codeception\TestCase $test * @param bool $fail * * @return void */ public function _failed(TestCase $test, $fail) { parent::_failed($test, $fail); Propel::getWriteConnection('zed')->rollBack(); if (session_status() === PHP_SESSION_ACTIVE) { session_destroy(); } }
public function getVolunteerMentorCity() { $countryCode = \Session::get('BorrowerJoin.countryCode'); $country = CountryQuery::create()->filterByCountryCode($countryCode)->findOne(); $con = Propel::getWriteConnection(TransactionTableMap::DATABASE_NAME); $sql = "SELECT DISTINCT city FROM borrower_profiles WHERE borrower_id IN " . "(SELECT borrower_id FROM volunteer_mentor WHERE country_id = :country_id AND status = :status\n AND mentee_count < :mentee_count)"; $stmt = $con->prepare($sql); //TODO to make mentee_count = 50 $stmt->execute(array(':country_id' => $country->getId(), ':status' => '1', ':mentee_count' => '25')); $cities = $stmt->fetchAll(\PDO::FETCH_COLUMN); return array_combine($cities, $cities); }
protected function migrateShippingZones(MigrateCountryEvent $event) { $con = Propel::getWriteConnection(CountryAreaTableMap::DATABASE_NAME); $con->beginTransaction(); try { $updatedRows = CountryAreaQuery::create()->filterByCountryId($event->getCountry())->update(['CountryId' => $event->getNewCountry(), 'StateId' => $event->getNewState()]); $con->commit(); return $updatedRows; } catch (PropelException $e) { $con->rollback(); throw $e; } }
public static function runInTransaction($function) { $con = \Propel\Runtime\Propel::getWriteConnection(\Engine\Map\MovieTableMap::DATABASE_NAME); $con->beginTransaction(); try { $result = $function(); $con->commit(); return $result; } catch (\Exception $e) { $con->rollback(); throw $e; } }
public function getVolunteerMentorCities() { if ($this->cities === null) { $country = $this->getCountry(); $con = Propel::getWriteConnection(TransactionTableMap::DATABASE_NAME); $sql = "SELECT DISTINCT city FROM borrower_profiles WHERE borrower_id IN " . "(SELECT borrower_id FROM volunteer_mentors WHERE country_id = :country_id AND status = :status\n AND mentee_count < :mentee_count)"; $stmt = $con->prepare($sql); //TODO to make mentee_count = 50 $stmt->execute(array(':country_id' => $country->getId(), ':status' => '1', ':mentee_count' => '25')); $cities = $stmt->fetchAll(\PDO::FETCH_COLUMN); $this->cities = array_combine($cities, $cities); } return $this->cities; }
private function parseRows($file) { //read file using generators $handle = fopen($file['tmp_name'], "r"); if ($handle) { $title = $this->getCheckedRow(fgets($handle)); //read title $con = \Propel\Runtime\Propel::getWriteConnection(\Engine\Map\MovieTableMap::DATABASE_NAME); try { while (!empty($title)) { $year = $this->getCheckedRow(fgets($handle)); //read year $format = $this->getCheckedRow(fgets($handle)); //read format //create new movie $movie = new \Engine\Movie(); $movie->setTitle($title); $movie->setYear($year); $movie->setFormat($format); $movie->save($con); $actors_row = $this->getCheckedRow(fgets($handle)); // read actors $actors_arr = explode(',', $actors_row); //split line by ',' foreach ($actors_arr as $actorInitials) { $actorInitialsKV = explode(' ', trim($actorInitials)); //split actor by [name,surname] Key-Value pair //create new actor $actor = new \Engine\Actor(); $actor->setMovieId($movie->getId()); $actor->setName($actorInitialsKV[0]); $actor->setSurname($actorInitialsKV[1]); $actor->save($con); } fgets($handle); //pass whitespace //set new title $title = $this->getCheckedRow(fgets($handle)); } } catch (Exception $e) { fclose($handle); $con->rollback(); throw new \Service\X(['Message' => 'Error during database transaction', 'Fields' => '$row', 'Type' => "{$e}"]); } fclose($handle); } else { throw new \Service\X(['Message' => 'Error - file could not be opened', 'Fields' => '$handle', 'Type' => 'Stream error']); } }
public function redeemGiftCard(Lender $recipient, $redemptionCode) { $giftCard = GiftCardQuery::create()->findOneByCardCode($redemptionCode); $con = Propel::getWriteConnection(TransactionTableMap::DATABASE_NAME); $con->beginTransaction(); try { $giftCard->setClaimed(1)->setRecipient($recipient); $giftCard->save($con); $this->transactionService->addRedeemGiftCardTransaction($con, $giftCard); $con->commit(); } catch (Exception $e) { $con->rollBack(); throw $e; } return $giftCard; }
/** * * Put the current country as the default one. * * @throws \RuntimeException * @throws \Exception * @throws \Propel\Runtime\Exception\PropelException */ public function toggleDefault() { if ($this->getId() === null) { throw new \RuntimeException("impossible to just uncheck default country, choose a new one"); } $con = Propel::getWriteConnection(CountryTableMap::DATABASE_NAME); $con->beginTransaction(); try { CountryQuery::create()->filterByByDefault(1)->update(array('ByDefault' => 0), $con); $this->setByDefault(1)->save($con); $con->commit(); } catch (PropelException $e) { $con->rollBack(); throw $e; } }
protected function createOrUpdate(AddressModel $addressModel, AddressCreateOrUpdateEvent $event) { $addressModel->setDispatcher($event->getDispatcher()); $con = Propel::getWriteConnection(AddressTableMap::DATABASE_NAME); $con->beginTransaction(); try { $addressModel->setLabel($event->getLabel())->setTitleId($event->getTitle())->setFirstname($event->getFirstname())->setLastname($event->getLastname())->setAddress1($event->getAddress1())->setAddress2($event->getAddress2())->setAddress3($event->getAddress3())->setZipcode($event->getZipcode())->setCity($event->getCity())->setCountryId($event->getCountry())->setStateId($event->getState())->setCellphone($event->getCellphone())->setPhone($event->getPhone())->setCompany($event->getCompany())->save(); if ($event->getIsDefault() && !$addressModel->getIsDefault()) { $addressModel->makeItDefault(); } $event->setAddress($addressModel); $con->commit(); } catch (PropelException $e) { $con->rollback(); throw $e; } }
/** * process update content * * @param ContentUpdateEvent $event */ public function update(ContentUpdateEvent $event) { if (null !== ($content = ContentQuery::create()->findPk($event->getContentId()))) { $con = Propel::getWriteConnection(ContentTableMap::DATABASE_NAME); $con->beginTransaction(); $content->setDispatcher($event->getDispatcher()); try { $content->setVisible($event->getVisible())->setLocale($event->getLocale())->setTitle($event->getTitle())->setDescription($event->getDescription())->setChapo($event->getChapo())->setPostscriptum($event->getPostscriptum())->save($con); $content->updateDefaultFolder($event->getDefaultFolder()); $event->setContent($content); $con->commit(); } catch (PropelException $e) { $con->rollBack(); throw $e; } } }
/** * Create a new content. * * Here pre and post insert event are fired * * @param $defaultFolderId * @throws \Exception */ public function create($defaultFolderId) { $con = Propel::getWriteConnection(ContentTableMap::DATABASE_NAME); $con->beginTransaction(); $this->dispatchEvent(TheliaEvents::BEFORE_CREATECONTENT, new ContentEvent($this)); try { $this->save($con); $cf = new ContentFolder(); $cf->setContentId($this->getId())->setFolderId($defaultFolderId)->setDefaultFolder(1)->save($con); $this->setPosition($this->getNextPosition())->save($con); $con->commit(); $this->dispatchEvent(TheliaEvents::AFTER_CREATECONTENT, new ContentEvent($this)); } catch (\Exception $ex) { $con->rollback(); throw $ex; } }
public function uploadFunds(Payment $payment) { $con = Propel::getWriteConnection(TransactionTableMap::DATABASE_NAME); $con->beginTransaction(); try { if ($payment->getTotalAmount()->isPositive()) { $this->transactionService->addUploadFundTransaction($con, $payment); } if ($payment->getDonationAmount()->isPositive()) { $this->transactionService->addDonation($con, $payment); } } catch (\Exception $e) { $con->rollback(); throw $e; } $con->commit(); }
public function importAction() { $i = 0; $con = Propel::getWriteConnection(OrderTableMap::DATABASE_NAME); $con->beginTransaction(); $form = $this->createForm('socolissimo.import'); try { $vForm = $this->validateForm($form); // Get file $importedFile = $vForm->getData()['import_file']; // Check extension if (strtolower($importedFile->getClientOriginalExtension()) != 'csv') { throw new FormValidationException(Translator::getInstance()->trans('Bad file format. CSV expected.', [], SoColissimo::DOMAIN)); } $csvData = file_get_contents($importedFile); $lines = explode(PHP_EOL, $csvData); // For each line, parse columns foreach ($lines as $line) { $parsedLine = str_getcsv($line, ";"); // Check if there are 2 columns : delivery ref & order ref if (count($parsedLine) == SoColissimo::IMPORT_NB_COLS) { // Get delivery and order ref $deliveryRef = $parsedLine[SoColissimo::IMPORT_DELIVERY_REF_COL]; $orderRef = $parsedLine[SoColissimo::IMPORT_ORDER_REF_COL]; // Save delivery ref if there is one if (!empty($deliveryRef)) { $this->importDeliveryRef($deliveryRef, $orderRef, $i); } } } $con->commit(); // Get number of affected rows to display $this->getSession()->getFlashBag()->add('import-result', Translator::getInstance()->trans('Operation successful. %i orders affected.', ['%i' => $i], SoColissimo::DOMAIN)); // Redirect return $this->generateRedirect(URL::getInstance()->absoluteUrl($form->getSuccessUrl(), ['current_tab' => 'import'])); } catch (FormValidationException $e) { $con->rollback(); $this->setupFormErrorContext(null, $e->getMessage(), $form); return $this->render('module-configure', ['module_code' => SoColissimo::getModuleCode(), 'current_tab' => 'import']); } }
public function deActivate($moduleModel = null) { if (null === $moduleModel) { $moduleModel = $this->getModuleModel(); } if ($moduleModel->getActivate() == self::IS_ACTIVATED) { $con = Propel::getWriteConnection(ModuleTableMap::DATABASE_NAME); $con->beginTransaction(); try { if ($this->preDeactivation($con)) { $moduleModel->setActivate(self::IS_NOT_ACTIVATED); $moduleModel->save($con); $this->postDeactivation($con); $con->commit(); } } catch (\Exception $e) { $con->rollBack(); throw $e; } } }
public static function transaction($closure, $retry = 3) { $con = Propel::getWriteConnection(UserTableMap::DATABASE_NAME); $con->beginTransaction(); $result = null; for ($i = 1; $i <= $retry; $i++) { try { $result = $closure($con); $con->commit(); break; } catch (\Exception $e) { $con->rollBack(); if ($i < $retry) { usleep($i * 100); } else { throw $e; } } } return $result; }
/** * Delete a product template entry * * @param \Thelia\Core\Event\Template\TemplateDeleteEvent $event * @throws \Exception */ public function delete(TemplateDeleteEvent $event) { if (null !== ($template = TemplateQuery::create()->findPk($event->getTemplateId()))) { // Check if template is used by a product $product_count = ProductQuery::create()->findByTemplateId($template->getId())->count(); if ($product_count <= 0) { $con = Propel::getWriteConnection(TemplateTableMap::DATABASE_NAME); $con->beginTransaction(); try { $template->setDispatcher($event->getDispatcher())->delete($con); // We have to also delete any reference of this template in category tables // We can't use a FK here, as the DefaultTemplateId column may be NULL // so let's take care of this. CategoryQuery::create()->filterByDefaultTemplateId($event->getTemplateId())->update(['DefaultTemplateId' => null], $con); $con->commit(); } catch (\Exception $ex) { $con->rollback(); throw $ex; } } $event->setTemplate($template); $event->setProductCount($product_count); } }
protected function parseImports(SimpleXMLElement $xml) { if (false === ($imports = $xml->xpath('//config:imports/config:import'))) { return; } $con = Propel::getWriteConnection(ImportTableMap::DATABASE_NAME); $con->beginTransaction(); try { /** @var SimpleXMLElement $import */ foreach ($imports as $import) { $id = (string) $import->getAttributeAsPhp("id"); $class = (string) $import->getAttributeAsPhp("class"); $categoryRef = (string) $import->getAttributeAsPhp("category_id"); if (!class_exists($class)) { throw new \ErrorException("The class \"{$class}\" doesn't exist"); } $category = ImportCategoryQuery::create()->findOneByRef($categoryRef); if (null === $category) { throw new \ErrorException("The import category \"{$categoryRef}\" doesn't exist"); } $importModel = ImportQuery::create()->findOneByRef($id); if (null === $importModel) { $importModel = new Import(); $importModel->setRef($id); } $importModel->setImportCategory($category)->setHandleClass($class)->save($con); /** @var SimpleXMLElement $descriptive */ foreach ($import->children() as $descriptive) { $locale = $descriptive->getAttributeAsPhp("locale"); $title = null; $description = null; /** @var SimpleXMLElement $row */ foreach ($descriptive->children() as $row) { switch ($row->getName()) { case "title": $title = (string) $row; break; case "description": $description = (string) $row; break; } } $importModel->setLocale($locale)->setTitle($title)->setDescription($description)->save($con); } } $con->commit(); } catch (\Exception $e) { $con->rollBack(); Tlog::getInstance()->error($e->getMessage()); } }
public function delete(ModuleDeleteEvent $event) { $con = Propel::getWriteConnection(ModuleTableMap::DATABASE_NAME); $con->beginTransaction(); if (null !== ($module = ModuleQuery::create()->findPk($event->getModuleId(), $con))) { try { if (null === $module->getFullNamespace()) { throw new \LogicException(Translator::getInstance()->trans('Cannot instantiate module "%name%": the namespace is null. Maybe the model is not loaded ?', ['%name%' => $module->getCode()])); } // If the module is referenced by an order, display a meaningful error // instead of 'delete cannot delete' caused by a constraint violation. // FIXME: we hav to find a way to delete modules used by order. if (OrderQuery::create()->filterByDeliveryModuleId($module->getId())->count() > 0 || OrderQuery::create()->filterByPaymentModuleId($module->getId())->count() > 0) { throw new \LogicException(Translator::getInstance()->trans('The module "%name%" is currently in use by at least one order, and can\'t be deleted.', ['%name%' => $module->getCode()])); } try { // First, try to create an instance $instance = $module->createInstance(); // Then, if module is activated, check if we can deactivate it if ($module->getActivate()) { // check for modules that depend of this one $this->checkDeactivation($module); } $instance->setContainer($this->container); $path = $module->getAbsoluteBaseDir(); $instance->destroy($con, $event->getDeleteData()); $fs = new Filesystem(); $fs->remove($path); } catch (\ReflectionException $ex) { // Happens probably because the module directory has been deleted. // Log a warning, and delete the database entry. Tlog::getInstance()->addWarning(Translator::getInstance()->trans('Failed to create instance of module "%name%" when trying to delete module. Module directory has probably been deleted', ['%name%' => $module->getCode()])); } catch (FileNotFoundException $fnfe) { // The module directory has been deleted. // Log a warning, and delete the database entry. Tlog::getInstance()->addWarning(Translator::getInstance()->trans('Module "%name%" directory was not found', ['%name%' => $module->getCode()])); } $module->delete($con); $con->commit(); $event->setModule($module); $this->cacheClear($event->getDispatcher()); } catch (\Exception $e) { $con->rollBack(); throw $e; } } }
/** * Update module information, and invoke install() for new modules (e.g. modules * just discovered), or update() modules for which version number ha changed. * * @param SplFileInfo $file the module.xml file descriptor * @param ContainerInterface $container the container * * @return Module * * @throws \Exception * @throws \Propel\Runtime\Exception\PropelException */ public function updateModule($file, ContainerInterface $container) { $descriptorValidator = $this->getDescriptorValidator(); $content = $descriptorValidator->getDescriptor($file->getRealPath()); $reflected = new \ReflectionClass((string) $content->fullnamespace); $code = basename(dirname($reflected->getFileName())); $version = (string) $content->version; $mandatory = intval($content->mandatory); $hidden = intval($content->hidden); $module = ModuleQuery::create()->filterByCode($code)->findOne(); if (null === $module) { $module = new Module(); $module->setActivate(0); $action = 'install'; } elseif ($version !== $module->getVersion()) { $currentVersion = $module->getVersion(); $action = 'update'; } else { $action = 'none'; } $con = Propel::getWriteConnection(ModuleTableMap::DATABASE_NAME); $con->beginTransaction(); try { $module->setCode($code)->setVersion($version)->setFullNamespace((string) $content->fullnamespace)->setType($this->getModuleType($reflected))->setCategory((string) $content->type)->setMandatory($mandatory)->setHidden($hidden)->save($con); // Update the module images, title and description when the module is installed, but not after // as these data may have been modified byt the administrator if ('install' === $action) { $this->saveDescription($module, $content, $con); if (isset($content->{"images-folder"}) && !$module->isModuleImageDeployed($con)) { /** @var \Thelia\Module\BaseModule $moduleInstance */ $moduleInstance = $reflected->newInstance(); $imagesFolder = THELIA_MODULE_DIR . $code . DS . (string) $content->{"images-folder"}; $moduleInstance->deployImageFolder($module, $imagesFolder, $con); } } // Tell the module to install() or update() $instance = $module->createInstance(); $instance->setContainer($container); if ($action == 'install') { $instance->install($con); } elseif ($action == 'update') { $instance->update($currentVersion, $version, $con); } if ($action !== 'none') { $instance->registerHooks(); } $con->commit(); } catch (\Exception $ex) { Tlog::getInstance()->addError("Failed to update module " . $module->getCode(), $ex); $con->rollBack(); throw $ex; } return $module; }