本文整理汇总了PHP中ActiveRecord::beginTransaction方法的典型用法代码示例。如果您正苦于以下问题:PHP ActiveRecord::beginTransaction方法的具体用法?PHP ActiveRecord::beginTransaction怎么用?PHP ActiveRecord::beginTransaction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ActiveRecord
的用法示例。
在下文中一共展示了ActiveRecord::beginTransaction方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: save
/**
* @role update
*/
public function save()
{
$taxes = Tax::getAllTaxes();
$classes = TaxClass::getAllClasses();
if (($zoneID = (int) $this->request->get('id')) <= 0) {
$taxRates = TaxRate::getRecordSetByDeliveryZone(null);
$deliveryZone = DeliveryZone::getDefaultZoneInstance();
} else {
$deliveryZone = DeliveryZone::getInstanceByID($zoneID, true);
$taxRates = $deliveryZone->getTaxRates();
}
ActiveRecord::beginTransaction();
// delete all rates
foreach ($taxRates as $rate) {
$rate->delete();
}
foreach ($taxes as $tax) {
$this->saveRate($deliveryZone, $tax, null);
foreach ($classes as $class) {
$this->saveRate($deliveryZone, $tax, $class);
}
}
ActiveRecord::commit();
return new JSONResponse(false, 'success', $this->translate('_tax_rates_have_been_successfully_saved'));
}
示例2: process
public function process($loadReferencedRecords = array())
{
set_time_limit(0);
ignore_user_abort(true);
$this->deleteCancelFile();
$filter = $this->grid->getFilter();
$filter->setLimit(0);
$ids = array();
foreach (ActiveRecordModel::getFieldValues($this->grid->getModelClass(), $filter, array('ID'), ActiveRecordModel::LOAD_REFERENCES) as $row) {
$ids[] = $row['ID'];
}
$totalCount = count($ids);
$progress = 0;
$response = new JSONResponse(array('act' => $this->request->get('act')), 'success', $this->completionMessage);
ActiveRecord::beginTransaction();
$chunkSize = count($ids) / self::MASS_ACTION_CHUNK_SIZE > 5 ? self::MASS_ACTION_CHUNK_SIZE : ceil(count($ids) / 5);
foreach (array_chunk($ids, $chunkSize) as $chunk) {
$response->flush('|' . base64_encode(json_encode(array('total' => $totalCount, 'progress' => $progress, 'pid' => $this->pid))));
$this->processSet(ActiveRecordModel::getRecordSet($this->grid->getModelClass(), new ARSelectFilter(new INCond(new ARFieldHandle($this->grid->getModelClass(), 'ID'), $chunk)), $loadReferencedRecords));
$progress += count($chunk);
}
ActiveRecord::commit();
$response->flush('|');
return $response;
}
示例3: import
public function import()
{
//ignore_user_abort(true);
set_time_limit(0);
$validator = $this->buildValidator();
if (!$validator->isValid()) {
return new JSONResponse(array('errors' => $validator->getErrorList()));
}
$dsn = $this->request->get('dbType') . '://' . $this->request->get('dbUser') . ($this->request->get('dbPass') ? ':' . $this->request->get('dbPass') : '') . '@' . $this->request->get('dbServer') . '/' . $this->request->get('dbName');
try {
$cart = $this->request->get('cart');
ClassLoader::import('library.import.driver.' . $cart);
$driver = new $cart($dsn, $this->request->get('filePath'));
} catch (SQLException $e) {
$validator->triggerError('dbServer', $e->getNativeError());
$validator->saveState();
return new JSONResponse(array('errors' => $validator->getErrorList()));
}
if (!$driver->isDatabaseValid()) {
$validator->triggerError('dbName', $this->maketext('_invalid_database', $driver->getName()));
$validator->saveState();
return new JSONResponse(array('errors' => $validator->getErrorList()));
}
if (!$driver->isPathValid()) {
$validator->triggerError('filePath', $this->maketext('_invalid_path', $driver->getName()));
$validator->saveState();
return new JSONResponse(array('errors' => $validator->getErrorList()));
}
$importer = new LiveCartImporter($driver);
$response = new JSONResponse(null);
// get importable data types
$response->flush($this->getResponse(array('types' => $importer->getItemTypes())));
ActiveRecord::beginTransaction();
// process import
try {
while (true) {
$result = $importer->process();
$response->flush($this->getResponse($result));
//echo '|' . round(memory_get_usage() / (1024*1024), 1) . " ($result[type] : " . array_shift(array_shift(ActiveRecord::getDataBySQL("SELECT COUNT(*) FROM " . $result['type']))) . ")<br> \n";
if (is_null($result)) {
break;
}
}
} catch (Exception $e) {
print_r($e->getMessage());
ActiveRecord::rollback();
}
if (!$this->application->isDevMode() || 1) {
ActiveRecord::commit();
} else {
ActiveRecord::rollback();
}
$importer->reset();
return $response;
}
示例4: setDefault
/**
* Sets default currency.
* @role status
* @return ActionRedirectResponse
*/
public function setDefault()
{
try {
$r = ActiveRecord::getInstanceByID('Currency', $this->request->get('id'), true);
} catch (ARNotFoundException $e) {
return new ActionRedirectResponse('backend.currency', 'index');
}
ActiveRecord::beginTransaction();
$update = new ARUpdateFilter();
$update->addModifier('isDefault', 0);
ActiveRecord::updateRecordSet('Currency', $update);
$r->setAsDefault(true);
$r->save();
ActiveRecord::commit();
return new ActionRedirectResponse('backend.currency', 'index');
}
示例5: save
public function save()
{
ActiveRecord::beginTransaction();
$image = null;
try {
$image = ActiveRecord::getInstanceById($this->getModelClass(), $this->request->get('imageId'), true);
$multilingualFields = array("title");
$image->setValueArrayByLang($multilingualFields, $this->application->getDefaultLanguageCode(), $this->application->getLanguageArray(true), $this->request);
$image->save();
if ($_FILES['image']['tmp_name']) {
$resizer = new ImageManipulator($_FILES['image']['tmp_name']);
if (!$resizer->isValidImage()) {
throw new InvalidImageException();
}
if (!$image->resizeImage($resizer)) {
throw new ImageResizeException();
}
}
} catch (InvalidImageException $exc) {
$error = $this->translate('_err_not_image');
} catch (ImageResizeException $exc) {
$error = $this->translate('_err_resize');
} catch (Exception $exc) {
$error = $this->translate('_err_not_found ' . get_class($exc));
}
$response = new ActionResponse();
if (isset($error)) {
ActiveRecord::rollback();
$result = array('error' => $error);
} else {
ActiveRecord::commit();
$result = $image->toArray();
}
$this->setLayout('iframeJs');
$response->set('ownerId', $this->request->get('ownerId'));
$response->set('imageId', $this->request->get('imageId'));
$response->set('result', @json_encode($result));
return $response;
}
示例6: saveTaxRates
private function saveTaxRates(Tax $tax)
{
$zones = DeliveryZone::getAll();
$zones->add(DeliveryZone::getDefaultZoneInstance());
$classes = TaxClass::getAllClasses();
ActiveRecord::beginTransaction();
foreach ($zones as $zone) {
// delete all zone tax rates
$taxRates = $zone->getTaxRates();
foreach ($taxRates as $rate) {
if ($rate->taxID->get()->getID() == $tax->getID()) {
$rate->delete();
}
}
$this->saveRate($zone, $tax);
foreach ($classes as $class) {
$this->saveRate($zone, $tax, $class);
}
}
ActiveRecord::commit();
}
示例7: import
public function import()
{
$options = unserialize(base64_decode($this->request->get('options')));
$response = new JSONResponse(null);
if (file_exists($this->getCancelFile())) {
unlink($this->getCancelFile());
}
if (!$this->request->get('continue')) {
$this->clearCacheProgress();
}
$import = $this->getImportInstance();
set_time_limit(0);
ignore_user_abort(true);
$profile = new CsvImportProfile($import->getClassName());
// map CSV fields to LiveCart fields
$params = $this->request->get('params');
foreach ($this->request->get('column') as $key => $value) {
if ($value) {
$fieldParams = !empty($params[$key]) ? $params[$key] : array();
$profile->setField($key, $value, array_filter($fieldParams));
}
}
$profile->setParam('isHead', $this->request->get('firstHeader'));
if ($this->request->get('saveProfile')) {
$path = $this->getProfileDirectory($import) . $this->request->get('profileName') . '.ini';
$profile->setFileName($path);
$profile->save();
}
// get import root category
if ($import->isRootCategory()) {
$profile->setParam('category', $this->request->get('category'));
}
$import->beforeImport($profile);
$csv = new CsvFile($this->request->get('file'), $this->request->get('delimiter'));
$total = $csv->getRecordCount();
if ($this->request->get('firstHeader')) {
$total -= 1;
}
if ($this->request->get('firstHeader')) {
$import->skipHeader($csv);
$import->skipHeader($csv);
}
$progress = 0;
$processed = 0;
if ($this->request->get('continue')) {
$import->setImportPosition($csv, $this->getCacheProgress() + 1);
$progress = $this->getCacheProgress();
} else {
if (!empty($options['transaction'])) {
ActiveRecord::beginTransaction();
}
}
if (empty($options['transaction'])) {
$this->request->set('continue', true);
}
$import->setOptions($options);
if ($uid = $this->request->get('uid')) {
$import->setUID($uid);
}
do {
$progress += $import->importFileChunk($csv, $profile, 1);
// continue timed-out import
if ($this->request->get('continue')) {
$this->setCacheProgress($progress);
}
ActiveRecord::clearPool();
if ($progress % self::PROGRESS_FLUSH_INTERVAL == 0 || $total == $progress) {
$response->flush($this->getResponse(array('progress' => $progress, 'total' => $total, 'uid' => $import->getUID(), 'lastName' => $import->getLastImportedRecordName())));
//echo '|' . round(memory_get_usage() / (1024*1024), 1) . '|' . count($categories) . "\n";
}
// test non-transactional mode
//if (!$this->request->get('continue')) exit;
if (connection_aborted()) {
if ($this->request->get('continue')) {
exit;
} else {
$this->cancel();
}
}
} while (!$import->isCompleted($csv));
if (!empty($options['missing']) && 'keep' != $options['missing']) {
$filter = $import->getMissingRecordFilter($profile);
if ('disable' == $options['missing']) {
$import->disableRecords($filter);
} else {
if ('delete' == $options['missing']) {
$import->deleteRecords($filter);
}
}
}
$import->afterImport();
if (!$this->request->get('continue')) {
//ActiveRecord::rollback();
ActiveRecord::commit();
}
$response->flush($this->getResponse(array('progress' => 0, 'total' => $total)));
//echo '|' . round(memory_get_usage() / (1024*1024), 1);
exit;
}
示例8: setDatabase
public function setDatabase()
{
set_time_limit(0);
if (!$this->buildDatabaseValidator()->isValid()) {
return new ActionRedirectResponse('install', 'database');
}
$type = function_exists('mysql_connect') ? 'mysql' : 'mysqli';
$dsn = $type . '://' . $this->request->get('username') . ($this->request->get('password') ? ':' . $this->request->get('password') : '') . '@' . $this->request->get('server') . '/' . $this->request->get('name');
ClassLoader::import('library.activerecord.ActiveRecord');
ActiveRecord::resetDBConnection();
ActiveRecord::setDSN($dsn);
try {
$conn = ActiveRecord::getDBConnection();
// test if InnoDB tables can be created
$table = 'TestInnoDB';
$create = 'CREATE TABLE ' . $table . ' (ID INTEGER) ENGINE = INNODB';
$drop = 'DROP TABLE ' . $table;
ActiveRecord::executeUpdate($create);
$data = ActiveRecord::getDataBySQL('SHOW TABLE STATUS');
ActiveRecord::executeUpdate($drop);
foreach ($data as $row) {
if (strtolower($row['Name']) == strtolower($table)) {
if (strtolower($row['Engine']) != 'innodb') {
throw new SQLException('', $this->translate('_err_innodb_not_available'));
}
}
}
$dsnFile = $this->getDsnFile();
if (!file_exists(dirname($dsnFile))) {
mkdir(dirname($dsnFile), 0777, true);
}
ActiveRecord::beginTransaction();
//ActiveRecord::executeUpdate('SET FOREIGN_KEY_CHECKS = 0');
//ActiveRecord::executeUpdate('DROP TABLE `AccessControlAssociation`, `AdAdvertiser`, `AdAdvertiserUser`, `AdBanner`, `AdBannerStats`, `AdCampaign`, `AdCampaignCondition`, `AdZone`, `Author`, `AuthorImage`, `BillingAddress`, `Category`, `CategoryImage`, `CategoryPresentation`, `CategorySubscribeCategory`, `CategorySubscribeQueue`, `CategorySubscribeUser`, `Currency`, `CustomerOrder`, `DeliveryZone`, `DeliveryZoneAddressMask`, `DeliveryZoneCityMask`, `DeliveryZoneCountry`, `DeliveryZoneRealTimeService`, `DeliveryZoneState`, `DeliveryZoneWarehouse`, `DeliveryZoneZipMask`, `Discount`, `DiscountAction`, `DiscountCondition`, `DiscountConditionRecord`, `EavDateValue`, `EavField`, `EavFieldGroup`, `EavItem`, `EavNumericValue`, `EavObject`, `EavStringValue`, `EavValue`, `ExpressCheckout`, `Filter`, `FilterGroup`, `HelpComment`, `Language`, `Manufacturer`, `ManufacturerImage`, `NewsletterMessage`, `NewsletterSentMessage`, `NewsletterSubscriber`, `NewsPost`, `OrderCoupon`, `OrderDiscount`, `OrderedItem`, `OrderedItemOption`, `OrderLog`, `OrderNote`, `PostalCode`, `Product`, `ProductBundle`, `ProductCategory`, `ProductFile`, `ProductFileGroup`, `ProductImage`, `ProductList`, `ProductListItem`, `ProductOption`, `ProductOptionChoice`, `ProductPrice`, `ProductRating`, `ProductRatingSummary`, `ProductRatingType`, `ProductRelationship`, `ProductRelationshipGroup`, `ProductReview`, `ProductVariation`, `ProductVariationTemplate`, `ProductVariationType`, `ProductVariationValue`, `ProductWarehouse`, `PurchasePointsItemOrder`, `PurchasePointsOrder`, `PurchasePointsUser`, `RecurringProductPeriod`, `RewardPointsOrder`, `RewardPointsUser`, `Role`, `SearchLog`, `SessionData`, `Shipment`, `ShipmentTax`, `ShipmentWarehouse`, `ShippingAddress`, `ShippingRate`, `ShippingService`, `SpecField`, `SpecFieldGroup`, `SpecFieldValue`, `SpecificationDateValue`, `SpecificationItem`, `SpecificationNumericValue`, `SpecificationStringValue`, `State`, `StaticPage`, `Tax`, `TaxRate`, `Transaction`, `User`, `UserAddress`, `UserGroup`, `Warehouse`');
// import schema
Installer::loadDatabaseDump(file_get_contents(ClassLoader::getRealPath('installdata.sql') . '/create.sql'), true);
// create root category
Installer::loadDatabaseDump(file_get_contents(ClassLoader::getRealPath('installdata.sql') . '/initialData.sql'), true);
// states
Installer::loadDatabaseDump(file_get_contents(ClassLoader::getRealPath('installdata.sql.state') . '/all.sql'), true);
file_put_contents($dsnFile, '<?php return ' . var_export($dsn, true) . '; ?>');
ActiveRecord::commit();
return new ActionResponse();
//return new ActionRedirectResponse('install', 'admin');
} catch (SQLException $e) {
$validator = $this->buildDatabaseValidator();
$validator->triggerError('connect', $e->getNativeError());
$validator->saveState();
return new ActionResponse('step', 'database');
//return new ActionRedirectResponse('install', 'database');
}
}
示例9: processMass
/**
* @role mass
*/
public function processMass()
{
$filter = $this->getSelectFilter();
$act = $this->request->get('act');
$field = array_pop(explode('_', $act, 2));
if ('move' == $act) {
new ActiveGrid($this->application, $filter, $this->getClassName());
$cat = Category::getInstanceById($this->request->get('categoryID'), Category::LOAD_DATA);
$update = new ARUpdateFilter();
$update->setCondition($filter->getCondition());
$update->addModifier('Product.categoryID', $cat->getID());
$update->joinTable('ProductPrice', 'Product', 'productID AND (ProductPrice.currencyID = "' . $this->application->getDefaultCurrencyCode() . '")', 'ID');
ActiveRecord::beginTransaction();
ActiveRecord::updateRecordSet('Product', $update, Product::LOAD_REFERENCES);
Category::recalculateProductsCount();
ActiveRecord::commit();
return new JSONResponse(array('act' => $this->request->get('act')), 'success', $this->translate('_move_succeeded'));
}
// remove design themes
if ('theme' == $act && !$this->request->get('theme')) {
ClassLoader::import('application.model.presentation.CategoryPresentation');
ActiveRecord::deleteRecordSet('CategoryPresentation', new ARDeleteFilter($filter->getCondition()), null, array('Product', 'Category'));
return new JSONResponse(array('act' => $this->request->get('act')), 'success', $this->translate('_themes_removed'));
}
$params = array();
if ('manufacturer' == $act) {
$params['manufacturer'] = Manufacturer::getInstanceByName($this->request->get('manufacturer'));
} else {
if ('price' == $act || 'inc_price' == $act) {
$params['baseCurrency'] = $this->application->getDefaultCurrencyCode();
$params['price'] = $this->request->get($act);
$params['currencies'] = $this->application->getCurrencySet();
$params['inc_price_value'] = $this->request->get('inc_price_value');
$params['inc_quant_price'] = $this->request->get('inc_quant_price');
} else {
if ('addRelated' == $act) {
$params['relatedProduct'] = Product::getInstanceBySKU($this->request->get('related'));
if (!$params['relatedProduct']) {
return new JSONResponse(0);
}
} else {
if ($this->request->get('categoryID')) {
$params['category'] = Category::getInstanceById($this->request->get('categoryID'), Category::LOAD_DATA);
} else {
if ('theme' == $act) {
ClassLoader::import('application.model.presentation.CategoryPresentation');
$params['theme'] = $this->request->get('theme');
} else {
if ('shippingClass' == $act) {
$params['shippingClass'] = $this->request->get('shippingClass');
} else {
if ('taxClass' == $act) {
$params['taxClass'] = $this->request->get('taxClass');
}
}
}
}
}
}
}
$response = parent::processMass($params);
if ($this->request->get('categoryID')) {
Category::recalculateProductsCount();
}
return $response;
}
示例10: setDefault
/**
* Sets default currency.
* @role status
* @return ActionRedirectResponse
*/
public function setDefault()
{
try {
$r = ActiveRecord::getInstanceByID('Currency', $this->request->get('id'), true);
} catch (ARNotFoundException $e) {
return new ActionRedirectResponse('backend.currency', 'index');
}
ActiveRecord::beginTransaction();
$update = new ARUpdateFilter();
$update->addModifier('isDefault', 0);
ActiveRecord::updateRecordSet('Currency', $update);
$r->setAsDefault(true);
$r->save();
$config = $this->getApplication()->getConfig();
if ($config->get('CURRENCY_RATE_UPDATE')) {
$source = CurrencyRateSource::getInstance($this->application, $r->getID());
foreach ($source->getAllCurrencyCodes() as $currencyCode) {
$rate = $source->getRate($currencyCode);
if ($rate != null) {
$currency = Currency::getInstanceById($currencyCode);
$currency->rate->set($rate);
$currency->lastUpdated->set(date('Y-m-d H:i:s', time()));
$currency->save();
}
}
}
ActiveRecord::commit();
return new ActionRedirectResponse('backend.currency', 'index');
}
示例11: create
/**
* @role create
*/
public function create()
{
ActiveRecord::beginTransaction();
$user = User::getInstanceByID((int) $this->request->get('customerID'), true, true);
$user->loadAddresses();
$order = CustomerOrder::getNewInstance($user);
$status = CustomerOrder::STATUS_NEW;
$order->status->set($status);
$order->isFinalized->set(0);
$order->capturedAmount->set(0);
$order->totalAmount->set(0);
$order->dateCompleted->set(new ARSerializableDateTime());
$order->currency->set($this->application->getDefaultCurrency());
foreach (array('billingAddress' => 'defaultBillingAddress', 'shippingAddress' => 'defaultShippingAddress') as $orderField => $userField) {
if ($user->{$userField}->get()) {
$user->{$userField}->get()->userAddress->get()->load();
$address = clone $user->{$userField}->get()->userAddress->get();
$address->save();
$order->{$orderField}->set($address);
}
}
$response = $this->save($order);
ActiveRecord::commit();
return $response;
}
示例12: registerAnonUser
protected function registerAnonUser()
{
if ($this->user->isAnonymous()) {
$this->order->loadAll();
ActiveRecord::beginTransaction();
$this->user->setPassword($this->session->get('password'));
$this->user->resetModifiedStatus(true);
$this->user->defaultBillingAddress->resetModifiedStatus();
$this->user->defaultShippingAddress->resetModifiedStatus();
if ($this->user->getSpecification()) {
$this->user->setSpecification(clone $this->user->getSpecification());
}
$this->user->save();
foreach (array('billingAddress' => 'defaultBillingAddress', 'shippingAddress' => 'defaultShippingAddress') as $order => $key) {
$address = $this->user->{$key}->get();
if ($address) {
$newAddress = clone $address;
$newAddress->userAddress->set(clone $newAddress->userAddress->get());
$newAddress->user->set($this->user);
$this->user->{$key}->set($newAddress);
$newAddress->save();
$this->order->{$order}->set($newAddress->userAddress->get());
}
}
$this->order->resetArrayData();
// shipping and billing addresses the same? save only the billing address
if ($this->order->shippingAddress->get() && $this->order->billingAddress->get()->toString() == $this->order->shippingAddress->get()->toString()) {
$this->user->defaultShippingAddress->get()->delete();
$this->user->defaultShippingAddress->setNull();
}
$this->user->save();
$this->order->user->set($this->user);
$this->order->user->setAsModified();
SessionUser::setUser($this->user);
$this->session->set('checkoutUser', null);
ActiveRecord::commit();
$this->getUserController()->sendWelcomeEmail($this->user);
}
}
示例13: reindex
/**
* Reindex traversal tree left and right indexes using parentNodesID of the same tree
*
* @todo This method does nothing
*/
public static function reindex($className)
{
$tableName = self::getSchemaInstance($className)->getName();
ActiveRecord::beginTransaction();
self::reindexBratch($className, $tableName, self::ROOT_ID, 1);
ActiveRecord::commit();
}