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; }
protected function setUp() { parent::setUp(); if (!class_exists('Propel\\Bundle\\PropelBundle\\Tests\\Fixtures\\DataFixtures\\Loader\\CoolBook')) { $schema = <<<XML <database name="default" package="vendor.bundles.Propel.Bundle.PropelBundle.Tests.Fixtures.DataFixtures.Loader" namespace="Propel\\Bundle\\PropelBundle\\Tests\\Fixtures\\DataFixtures\\Loader" defaultIdMethod="native"> <table name="cool_book"> <column name="id" type="integer" primaryKey="true" /> <column name="name" type="varchar" size="255" /> <column name="description" type="varchar" /> <column name="author_id" type="integer" required="false" defaultValue="null" /> <column name="complementary_infos" required="false" type="object" description="An object column" /> <foreign-key foreignTable="cool_book_author" onDelete="CASCADE" onUpdate="CASCADE"> <reference local="author_id" foreign="id" /> </foreign-key> </table> <table name="cool_book_author"> <column name="id" type="integer" primaryKey="true" /> <column name="name" type="varchar" size="255" /> </table> </database> XML; QuickBuilder::buildSchema($schema); } $this->con = Propel::getServiceContainer()->getConnection('default'); $this->con->beginTransaction(); }
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 __construct(LoggerInterface $alternativeLogger = null) { $con = Propel::getServiceContainer()->getConnection(\Thelia\Model\Map\ProductTableMap::DATABASE_NAME); $con->setLogger($this); $con->setLogMethods(array('exec', 'query', 'execute', 'beginTransaction', 'commit', 'rollBack')); $this->alternativeLogger = $alternativeLogger; }
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); }
/** * {@inheritDoc} */ public function register(Container $container) { // Append custom settings with missing params from default settings $container['settings']['database'] = self::mergeWithDefaultSettings($container['settings']['database']); $settings = $container['settings']['database']; $logLevel = $settings['logger']['level'] ?? null; $logPath = $settings['logger']['path'] ?? null; $className = $settings['classname'] ?? null; if (!$className) { $className = 'Propel\\Runtime\\Connection\\ConnectionWrapper'; if ($logLevel == Logger::DEBUG) { $className = 'Propel\\Runtime\\Connection\\ProfilerConnectionWrapper'; } } $manager = new ConnectionManagerSingle(); $manager->setConfiguration(['classname' => $className, 'dsn' => $settings['dsn'], 'user' => $settings['user'], 'password' => $settings['password'], 'settings' => $settings['settings']]); $manager->setName($settings['connection']); /** @var StandardServiceContainer $serviceContainer */ $serviceContainer = Propel::getServiceContainer(); $serviceContainer->checkVersion($settings['version']); $serviceContainer->setAdapterClass($settings['connection'], $settings['adapter']); $serviceContainer->setConnectionManager($settings['connection'], $manager); $serviceContainer->setDefaultDatasource($settings['connection']); if ($logPath && $logLevel) { $logger = new Logger('defaultLogger'); $logger->pushHandler(new StreamHandler($logPath, $logLevel)); $serviceContainer->setLogger('defaultLogger', $logger); if ($logLevel == Logger::DEBUG) { /** @var ConnectionWrapper $con */ $con = Propel::getConnection(); $con->useDebug(true); } } }
/** * @param Click $card */ public function deleteCard($card) { $delete = "\n DELETE FROM logintime t1\n JOIN\n (\n SELECT MAX(datetime)\n AS max_dt\n FROM logintime\n WHERE user_id = 1\n ) t2\nWHERE t1.datetime = t2.max_dt\n AND card = {$card->get}\n "; $con = Propel::getConnection(); $stmt = $con->prepare($delete); return $stmt->execute(); }
public function process() { $logger = Tlog::getInstance(); $logger->setLevel(Tlog::DEBUG); $updatedVersions = array(); $currentVersion = ConfigQuery::read('thelia_version'); $logger->debug("start update process"); if (true === $this->isLatestVersion($currentVersion)) { $logger->debug("You already have the latest version. No update available"); throw new UpToDateException('You already have the latest version. No update available'); } $index = array_search($currentVersion, self::$version); $con = Propel::getServiceContainer()->getWriteConnection(ProductTableMap::DATABASE_NAME); $con->beginTransaction(); $logger->debug("begin transaction"); $database = new Database($con->getWrappedConnection()); try { $size = count(self::$version); for ($i = ++$index; $i < $size; $i++) { $this->updateToVersion(self::$version[$i], $database, $logger); $updatedVersions[] = self::$version[$i]; } $con->commit(); $logger->debug('update successfully'); } catch (PropelException $e) { $con->rollBack(); $logger->error(sprintf('error during update process with message : %s', $e->getMessage())); throw $e; } $logger->debug('end of update processing'); return $updatedVersions; }
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]; }
protected function createOrUpdate(PopInCampaignEvent $event, PopInCampaign $model) { $con = Propel::getConnection(PopInCampaignTableMap::DATABASE_NAME); $con->beginTransaction(); try { if (null !== ($id = $event->getId())) { $model->setId($id); } if (null !== ($start = $event->getStart())) { $model->setStart($start); } if (null !== ($end = $event->getEnd())) { $model->setEnd($end); } if (null !== ($contentSourceType = $event->getContentSourceType())) { $model->setContentSourceType($contentSourceType); } if (null !== ($contentSourceId = $event->getContentSourceId())) { $model->setContentSourceId($contentSourceId); } $model->save($con); $con->commit(); } catch (\Exception $e) { $con->rollback(); throw $e; } $event->setPopInCampaign($model); }
/** * Register propel runtime configuration. * * @return void */ protected function registerRuntimeConfiguration() { $propel_conf = $this->app->config['propel.propel']; if (!isset($propel_conf['runtime']['connections'])) { throw new \InvalidArgumentException('Unable to guess Propel runtime config file. Please, initialize the "propel.runtime" parameter.'); } /** @var $serviceContainer \Propel\Runtime\ServiceContainer\StandardServiceContainer */ $serviceContainer = Propel::getServiceContainer(); $serviceContainer->closeConnections(); $serviceContainer->checkVersion('2.0.0-dev'); $runtime_conf = $propel_conf['runtime']; // set connections foreach ($runtime_conf['connections'] as $connection_name) { $config = $propel_conf['database']['connections'][$connection_name]; $serviceContainer->setAdapterClass($connection_name, $config['adapter']); $manager = new ConnectionManagerSingle(); $manager->setConfiguration($config + [$propel_conf['paths']]); $manager->setName($connection_name); $serviceContainer->setConnectionManager($connection_name, $manager); } $serviceContainer->setDefaultDatasource($runtime_conf['defaultConnection']); // set loggers $has_default_logger = false; if (isset($runtime_conf['log'])) { $has_default_logger = array_key_exists('defaultLogger', $runtime_conf['log']); foreach ($runtime_conf['log'] as $logger_name => $logger_conf) { $serviceContainer->setLoggerConfiguration($logger_name, $logger_conf); } } if (!$has_default_logger) { $serviceContainer->setLogger('defaultLogger', \Log::getMonolog()); } Propel::setServiceContainer($serviceContainer); }
/** * 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 install() { // install sql $files = ['sql/keeko.sql', 'data/static-data.sql', 'data/dummy-data.sql']; try { $repo = $this->getServiceContainer()->getResourceRepository(); $con = Propel::getConnection(); foreach ($files as $file) { if ($repo->contains('/iuf/junia/database/' . $file)) { $sql = $repo->get('/iuf/junia/database/' . $file)->getBody(); $stmt = $con->prepare($sql); $stmt->execute(); } } } catch (\Exception $e) { echo $e->getMessage(); } // install static data // $comp = new Competition(); // $comp->setLabel('Individual Freestyle'); // $comp->save(); // $comp = new Competition(); // $comp->setLabel('Pairs Freestyle'); // $comp->save(); // $comp = new Competition(); // $comp->setLabel('Small Group Freestyle'); // $comp->save(); // $comp = new Competition(); // $comp->setLabel('Large Group Freestyle'); // $comp->save(); }
public function testComputeWithSchema() { $con = Propel::getServiceContainer()->getConnection(BookstoreTableMap::DATABASE_NAME); BookstoreContestEntryQuery::create()->deleteAll(); BookstoreQuery::create()->deleteAll(); CustomerQuery::create()->deleteAll(); BookstoreContestQuery::create()->deleteAll(); $store = new Bookstore(); $store->setStoreName('FreeAgent Bookstore'); $store->save(); $this->assertEquals(0, $store->computeTotalContestEntries($con), 'The compute method returns 0 for objects with no related objects'); $contest = new BookstoreContest(); $contest->setBookstore($store); $contest->save(); $customer1 = new Customer(); $customer1->save(); $entry1 = new BookstoreContestEntry(); $entry1->setBookstore($store); $entry1->setBookstoreContest($contest); $entry1->setCustomer($customer1); $entry1->save(null, true); // skip reload to avoid #1151 for now $this->assertEquals(1, $store->computeTotalContestEntries($con), 'The compute method computes the aggregate function on related objects'); $customer2 = new Customer(); $customer2->save(); $entry2 = new BookstoreContestEntry(); $entry2->setBookstore($store); $entry2->setBookstoreContest($contest); $entry2->setCustomer($customer2); $entry2->save(null, true); // skip reload to avoid #1151 for now $this->assertEquals(2, $store->computeTotalContestEntries($con), 'The compute method computes the aggregate function on related objects'); $entry1->delete(); $this->assertEquals(1, $store->computeTotalContestEntries($con), 'The compute method computes the aggregate function on related objects'); }
public function updateOrCreateLinkAction($id) { // Check current user authorization if (null !== ($response = $this->checkAuth(AdminResources::MODULE, DealerTeam::getModuleCode(), AccessManager::CREATE))) { return $response; } $retour = []; $code = 200; $con = Propel::getConnection(); $con->beginTransaction(); try { $data = ['id' => $id]; $tempOption = $this->getRequest()->request->get("option_id"); $dafyDealer = []; foreach ($tempOption as $option) { $data["dealer_option_id"] = $option; $temp = $this->getService()->createFromArray($data); if ($temp) { $dafyDealer[] = $temp->toArray(); } } $con->commit(); $retour["data"] = $dafyDealer; } catch (\Exception $e) { $con->rollBack(); // Any other error Tlog::getInstance()->addError($e->getMessage()); $code = $e->getCode(); if ($code == 0) { $code = 500; } $retour["message"] = $e->getMessage(); } return JsonResponse::create($retour, $code); }
/** * {@inheritdoc} */ public function load($files = array(), $connectionName) { $nbFiles = 0; $this->deletedClasses = array(); $this->loadMapBuilders($connectionName); $this->con = Propel::getConnection($connectionName); try { $this->con->beginTransaction(); $datas = array(); foreach ($files as $file) { $content = $this->transformDataToArray($file); if (count($content) > 0) { $datas = array_merge_recursive($datas, $content); $nbFiles++; } } $this->deleteCurrentData($datas); $this->loadDataFromArray($datas); $this->con->commit(); } catch (\Exception $e) { $this->con->rollBack(); throw $e; } return $nbFiles; }
/** * This is run before each unit test; it populates the database. */ protected function setUp() { Propel::init(__DIR__ . '/../../../../Fixtures/bookstore/build/conf/bookstore-conf.php'); parent::setUp(); $this->con = Propel::getConnection(BookPeer::DATABASE_NAME); $this->con->beginTransaction(); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { if (!$input->getOption('force')) { $output->writeln('<error>You have to use the "--force" option to drop the database.</error>'); return; } if ('prod' === $this->getApplication()->getKernel()->getEnvironment()) { $this->writeSection($output, 'WARNING: you are about to drop a database in production !', 'bg=red;fg=white'); if (false === $this->askConfirmation($input, $output, 'Are you sure ? (y/n) ', false)) { $output->writeln('Aborted, nice decision !'); return -2; } } $connectionName = $input->getOption('connection') ?: $this->getDefaultConnection(); $config = $this->getConnectionData($connectionName); $connection = Propel::getConnection($connectionName); $dbName = $this->parseDbName($config['dsn']); if (null === $dbName) { return $output->writeln('<error>No database name found.</error>'); } else { $query = 'DROP DATABASE ' . $dbName . ';'; } $statement = $connection->prepare($query); $statement->execute(); $output->writeln(sprintf('<info>Database <comment>%s</comment> has been dropped.</info>', $dbName)); }
public function closeCursor() { $this->dataFetcher->close(); if ($this->enableInstancePoolingOnFinish) { Propel::enableInstancePooling(); } }
/** * 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; }
/** * Bootable Method * * @method boot * @param Application $app * @return void */ public function boot(Application $app) { if (!file_exists($app['propel.config_file'])) { throw new \InvalidArgumentException('Unable to guess Propel config file. Please, initialize the "propel.config_file" parameter.'); } Propel2::init($app['propel.config_file']); }
public function boot() { parent::boot(); $this->configure(); if (function_exists('ppm_log')) { //In an environment like PPM with several workers Propel's not distributed cache will //lead to inconsistent states across all workers, so we need to disable it here completely. //Jarves already caches using a distributed cache where all workers are notified when //a change changes, so we don't really need Propel's cache here. Propel::disableInstancePooling(); } if (!$this->booted) { /** @var ContainerInterface $container */ $container = $this->container; /** @var $jarves Jarves */ $jarves = $container->get('jarves'); /** @var JarvesConfig $jarvesConfig */ $jarvesConfig = $container->get('jarves.config'); $twig = $container->get('twig'); $twig->addGlobal('jarves_content_render', $container->get('jarves.content.render')); $twig->addGlobal('pageStack', $container->get('jarves.page_stack')); if ($jarvesConfig->getSystemConfig()->getLogs(true)->isActive()) { /** @var $logger \Symfony\Bridge\Monolog\Logger */ $logger = $container->get('logger'); $logger->pushHandler($container->get('jarves.logger.handler')); } } $this->booted = true; }
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 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 testInvalidCharset() { $this->markTestSkipped('Skipped because of weird behavior on some platforms'); $db = Propel::getServiceContainer()->getAdapter(BookPeer::DATABASE_NAME); if ($db instanceof SqliteAdapter) { $this->markTestSkipped(); } $a = new Author(); $a->setFirstName("Б."); $a->setLastName("АКУНИН"); $a->save(); $authorNameWindows1251 = iconv("utf-8", "windows-1251", $a->getLastName()); $a->setLastName($authorNameWindows1251); // Different databases seem to handle invalid data differently (no surprise, I guess...) if ($db instanceof PgsqlAdapter) { try { $a->save(); $this->fail("Expected an exception when saving non-UTF8 data to database."); } catch (Exception $x) { print $x; } } else { // No exception is thrown by MySQL ... (others need to be tested still) $a->save(); $a->reload(); $this->assertEquals("", $a->getLastName(), "Expected last_name to be empty (after inserting invalid charset data)"); } }
/** * @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; } }
/** * 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; } }
/** * @return \Propel\Runtime\Util\Profiler */ public function getProfiler() { if (null === $this->profiler) { $this->profiler = Propel::getServiceContainer()->getProfiler(); } return $this->profiler; }
function changeAppPhoto($params) { require 'session.php'; $con = Propel::getConnection('pos'); $con->beginTransaction(); $operationTime = time(); $unique = session_id() . time(); $file = $_FILES['photo']; $folder = $session->get('pos/folder') . '/resources/images/'; $ext = pathinfo($file['name'], PATHINFO_EXTENSION); $newfile = $unique . '.' . $ext; $newfile_full_path = $folder . $newfile; try { if ($file['name'] == '') { throw new Exception('Missing file'); } if ($file['error'] > 0) { throw new Exception($file['error']); } move_uploaded_file($file['tmp_name'], $newfile_full_path); $appPhoto = OptionQuery::create()->filterByName(['app_photo'])->findOne($con); $appPhoto->setValue($newfile)->save($con); $results['success'] = true; $results['photo'] = $newfile; $con->commit(); } catch (Exception $e) { $con->rollBack(); $results['success'] = false; $results['errmsg'] = $e->getMessage(); } return $results; }
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]; }