first commit

This commit is contained in:
2025-03-12 17:06:23 +01:00
commit 2241f7131f
13185 changed files with 1692479 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
<?php
class AllegroCommission
{
protected $config;
public function __construct()
{
$this->config = stConfig::getInstance('stAllegroBackend');
}
public function calculatePrice($price)
{
$commission = $this->config->get('offer_product_commission');
if ($commission && $commission['commission'] > 0)
{
$price = stPrice::calculate($price, $commission['commission']);
if ($commission['round_type'] == 'full_buck')
{
$price = stPrice::round($price, 0);
}
}
return stPrice::round($price);
}
}

View File

@@ -0,0 +1,30 @@
<?php
function st_allegro_delivery_times_select_tag($name, $value)
{
return select_tag($name, options_for_select(stAllegroApi::getDeliveryTimes(), $value));
}
function st_allegro_shippin_rates_select_tag($name, $value)
{
$options = array();
try
{
$api = stAllegroApi::getInstance();
foreach ($api->getShippingRates() as $rate)
{
$options[$rate->id] = $rate->name;
}
}
catch(Exception $e)
{
if (SF_ENVIRONMENT == 'dev')
{
sfLogger::getInstance()->crit('{stAllegro} st_allegro_shippin_rates_select_tag: '. $e->getMessage());
}
}
return select_tag($name, options_for_select($options, $value, array('include_custom' => __('Wybierz'))));
}

View File

@@ -0,0 +1,315 @@
<?php
sfLoader::loadHelpers(array('Helper', 'stProduct'), 'stProduct');
function st_allegro_selected_product($id)
{
if ($id)
{
$api = stAllegroApi::getInstance();
$product = $api->getProduct($id);
st_allegro_product($product);
}
}
function st_allegro_product($product)
{
$image = $product->images ? $product->images[0]->url : "https://assets.allegrostatic.com/metrum/placeholder/placeholder-2447b7d18a.svg";
echo '<div class="allegro-product" data-id="'.$product->id.'">';
echo ' <div class="image" style="background-image: url('.$image.');"></div>';
echo ' <div class="description">';
echo ' <h3>'.$product->name.'</h3>';
echo ' <ul class="parameters">';
foreach ($product->parameters as $index => $parameter)
{
if ($index > 4) break;
echo ' <li>'.$parameter->name.': <b>'.st_allegro_product_parameter_value($parameter).'</b></li>';
}
echo ' </ul>';
echo ' </div>';
echo '</div>';
}
function st_allegro_payment_type($type)
{
$payments = array(
'm' => 'mTransfer - mBank',
'mtex' => 'mTransfer mobilny - mBank',
'w' => 'BZWBK - Przelew24',
'o' => 'Pekao24Przelew - Bank Pekao',
'i' => 'Inteligo',
'p' => 'iPKO',
'pkex' => 'PayU Express Bank Pekao',
'g' => 'ING',
'gbx' => 'Getin Bank',
'gbex' => 'GetIn Bank PayU Express',
'nlx' => 'Noble Bank',
'nlex' => 'Noble Bank PayU Express',
'ib' => 'Paylink Idea - IdeaBank',
'l' => 'Credit Agricole',
'as' => 'T-mobile Usługi Bankowe dostarczane przez Alior Bank',
'exas' => 'PayU Express T-mobile Usługi Bankowe',
'u' => 'Eurobank',
'ab' => 'Alior Bankiem',
'exab' => 'PayU Express z Alior Bankiem',
'ps' => 'PBS',
'wm' => 'Przelew z Millennium',
'h' => 'Przelew z BPH',
'wd' => 'Przelew z Deutsche Banku',
'wc' => 'Przelew z Citi Handlowego',
'bo' => 'BOŚ',
'bnx' => 'BNP Paribas',
'bnex' => 'BNP Paribas PayU Express',
'orx' => 'Orange',
'orex' => 'PayU Express Orange',
'c' => 'Karta kredytowa',
'tt' => 'Karta kredytowa',
'b' => 'Przelew tradycyjny',
'ai' => 'Raty',
'blik' => 'Blik',
'ap' => 'Android Pay',
'neb' => 'Nest Bank',
'rap' => 'Raiffeisen R-Przelew',
'plb' => 'Plus Bank',
'bpo' => 'e-transfer Pocztowy24',
'collect_on_delivery' => 'Płacę przy odbiorze',
'cash_on_delivery' => 'Płacę przy odbiorze',
'wire_transfer' => 'Zwykły przelew (poza systemem Allegro Finanse)',
'p24' => 'Przelewy24',
'payu' => 'PayU'
);
if (isset($payments[$type]))
{
return $payments[$type];
}
return null;
}
function st_allegro_edit_row($title, $content, $options = null) {
$title = __($title, null, 'stAllegroBackend');
$labelClass = "";
$rowClass = "";
if (is_array($options)) {
if (isset($options['row'])) {
$rowClass = " ".$options['row'];
}
} elseif ($options) {
$labelClass = ' class="required"';
}
$content = <<<CONTENT
<div class="row{$rowClass}">
<label{$labelClass}>$title</label>
<div class="field">
<div class="field-container">$content</div>
<div class="clr"></div>
</div>
</div>
CONTENT;
return $content;
}
function st_allegro_edit_row_olny_title($title) {
$title = __($title, null, 'stAllegroBackend');
$content = <<<CONTENT
<div class="row">
$title
</div>
CONTENT;
return $content;
}
function st_allegro_get_tables($quantity, $content) {
$tables = array();
$tableElementsQuantity = ceil(count($content['tbody'])/$quantity);
for ($i = 1; $i <= $quantity; $i++) {
$data = array('thead' => $content['thead'], 'tbody' => array());
for ($j = 0; $j < $tableElementsQuantity; $j++)
if (count($content['tbody']))
$data['tbody'][] = array_shift($content['tbody']);
$tables[] = st_allegro_get_table($data);
}
return implode('', $tables);
}
function st_allegro_get_table($content) {
$thead = st_allegro_get_table_row('thead', $content);
$tbody = st_allegro_get_table_row('tbody', $content);
$content = <<<CONTENT
<table class="st_record_list st_record_manager st-allegro-edit-table-size" cellspacing="0">
$thead
$tbody
</table>
CONTENT;
return $content;
}
function st_allegro_get_table_row($type, $content) {
if (isset($content[$type]) && !empty($content[$type])) {
$result = '<'.$type.'>';
foreach ($content[$type] as $row) {
$result .= '<tr>';
foreach ($row as $record)
$result .= '<'.($type == 'tbody' ? 'td' : 'th').'>'.$record.'</'.($type == 'tbody' ? 'td' : 'th').'>';
$result .= '</tr>';
}
$result .= '</'.$type.'>';
return $result;
}
return null;
}
function st_allegro_show_category_status(stAllegroCategory $allegroObject) {
$categoryStatus = $allegroObject->checkStatus();
if ($categoryStatus === 1)
$msg = __('Brak nowych kategorii do pobrania.').' '.__('Data ostatniego pobierania').': '.$allegroObject->getDownloadedTime('d.m.Y H:i');
elseif ($categoryStatus === 0)
$msg = __('Dostępne są nowe kategorie do pobrania.').' '.__('Data ostatniego pobierania').': '.$allegroObject->getDownloadedTime('d.m.Y H:i');
elseif ($categoryStatus === -1)
$msg = __('Brak pobranych kategorii, należy pobrać kategorie.');
return $msg;
}
function st_allegro_get_auction_link(AllegroAuction $auction) {
if ($link = $auction->getAuctionLink()) {
return '<a href="'.$link.'" target="_blank">'.$auction->getAuctionId().'</a>';
} else
return '-';
}
function st_allegro_status_label($status)
{
$enum = stAllegroApi::getStatusList();
return isset($enum[$status]) ? $enum[$status] : '';
}
function st_allegro_implied_warranty_select_tag($name, $value)
{
$options = array();
try
{
$api = stAllegroApi::getInstance();
foreach ($api->getImpliedWarranties() as $warranty)
{
$options[$warranty->id] = $warranty->name;
}
}
catch(Exception $e)
{
if (SF_ENVIRONMENT == 'dev')
{
sfLogger::getInstance()->crit('{stAllegro} st_allegro_implied_warranty_select_tag: '. $e->getMessage());
}
}
return select_tag($name, options_for_select($options, $value, array('include_custom' => __('Wybierz'))), array('style' => 'width: 300px'));
}
function st_allegro_warranty_select_tag($name, $value)
{
$options = array();
try
{
$api = stAllegroApi::getInstance();
foreach ($api->getWarranties() as $warranty)
{
$options[$warranty->id] = $warranty->name;
}
}
catch(Exception $e)
{
if (SF_ENVIRONMENT == 'dev')
{
sfLogger::getInstance()->crit('{stAllegro} st_allegro_warranty_select_tag: '. $e->getMessage());
}
}
return select_tag($name, options_for_select($options, $value, array('include_custom' => __('Wybierz'))), array('style' => 'width: 300px'));
}
function st_allegro_return_policy_select_tag($name, $value)
{
$options = array();
try
{
$api = stAllegroApi::getInstance();
foreach ($api->getReturnPolicies() as $policy)
{
$options[$policy->id] = $policy->name;
}
}
catch(Exception $e)
{
if (SF_ENVIRONMENT == 'dev')
{
sfLogger::getInstance()->crit('{stAllegro} st_allegro_return_policy_select_tag: '. $e->getMessage());
}
}
return select_tag($name, options_for_select($options, $value, array('include_custom' => __('Wybierz'))), array('style' => 'width: 300px'));
}
function st_allegro_product_code(AllegroAuction $auction = null)
{
$product = null;
if ($auction)
{
$product = $auction->getProduct();
}
return $product ? '<a href="'.url_for('@stProduct?action=edit&id=' . $product->getId()).'">' . $product->getCode() . '</a>' : '';
}
function st_allegro_duration_time_select_tag($name, $value, array $params = array())
{
return select_tag($name, options_for_select(stAllegroApi::getDurationTimes(), $value), $params);
}
function st_allegro_payments_invoice_select_tag($name, $value, array $params = array())
{
return select_tag($name, options_for_select(stAllegroApi::getPaymentInvoiceList(), $value), $params);
}
function st_allegro_product_search($name, $value, $options = array())
{
$results_formatter = _token_input_product_results_formatter();
$token_formatter = _token_input_product_token_formatter();
$url = st_url_for('@stProductEdit?action=ajaxProductsToken&id=0');
$tokenizer = array_merge(array(
'preventDuplicates' => true,
'resultsFormatter' => $results_formatter,
'tokenFormatter' => $token_formatter,
'hintText' => __('Wpisz kod/nazwę szukanego produktu'),
'additionalDataFields' => array('code'),
'tokenLimit' => 1,
'sortable' => true,
), isset($options['tokenizer']) ? $options['tokenizer'] : array());
return st_tokenizer_input_tag($name, $url, $value, array('tokenizer' => $tokenizer));
}

View File

@@ -0,0 +1,262 @@
<?php
use_helper('stPrice');
function st_allegro_product_parameter_value($parameter)
{
if (isset($parameter->values))
{
$content = implode(", ", $parameter->values);
}
elseif (isset($parameter->valuesLabels))
{
$content = implode(", ", $parameter->valuesLabels);
}
else
{
$content = 'Brak';
}
if (isset($parameter->unit))
{
$content .= " ".$parameter->unit;
}
return $content;
}
function st_allegro_parameter($name, $parameter, array $values, &$dependencies)
{
// echo "<pre>".var_export($parameter, true)."</pre>";
$type = 'st_allegro_parameter_' . $parameter->type;
$value = isset($values[$parameter->id]) ? $values[$parameter->id] : null;
$required = $parameter->required;
$display = "flex";
if ($parameter->options->dependsOnParameterId)
{
$parameterValueIds = isset($values[$parameter->options->dependsOnParameterId]) ? $values[$parameter->options->dependsOnParameterId]->valuesIds : array();
if ($parameter->options->requiredDependsOnValueIds)
{
$intersect = array_intersect($parameter->options->requiredDependsOnValueIds, $parameterValueIds);
$required = count($intersect) > 0;
}
if ($parameter->options->displayDependsOnValueIds)
{
$intersect = array_intersect($parameter->options->displayDependsOnValueIds, $parameterValueIds);
$display = count($intersect) > 0 ? "flex" : "none";
}
$dependencies[$parameter->options->dependsOnParameterId][$parameter->id] = array(
'required' => $parameter->options->requiredDependsOnValueIds,
'display' => $parameter->options->displayDependsOnValueIds,
);
}
$options = array(
'required' => $required,
'parameter' => $parameter,
'postfix' => $parameter->unit ? '<span style="vertical-align: middle">'.$parameter->unit.'</span>' : null,
'row_attr' => array(
'style' => 'display: ' . $display
),
'id' => 'st_allegro_offer_parameter_' . $parameter->id,
);
if ($parameter->type == 'dictionary' && $parameter->restrictions->multipleChoices)
{
$options['row_attr']['data-selected-ids'] = json_encode($value ? $value->valuesIds : array());
}
if (isset($parameter->restrictions->min))
{
$options['help'] = __("Wartość minimalna: %min%, wartość mayksymalna: %max%", array('%min%' => $parameter->restrictions->min, '%max%' => $parameter->restrictions->max));
}
echo st_admin_get_form_field($name . '[' . $parameter->type . '][' . $parameter->id . ']', $parameter->name, $value, $type, $options);
}
function st_allegro_parameter_dictionary($name, $value, array $params)
{
$parameter = $params['parameter'];
if (!$parameter->restrictions->multipleChoices)
{
return st_allegro_parameter_dictionary_single($name, $value, $params);
}
else
{
return st_allegro_parameter_dictionary_multiple($name, $value, $params);
}
}
function st_allegro_parameter_dictionary_single($name, $value, array $params)
{
$parameter = $params['parameter'];
$options = array();
foreach ($parameter->dictionary as $dictionary)
{
$options[$dictionary->id] = array(
'label' => $dictionary->value,
'attr' => array(
'data-depends-on-value-ids' => $dictionary->dependsOnValueIds ? json_encode(array_values($dictionary->dependsOnValueIds)) : null,
),
);
}
$value_id = $value && $value->valuesIds ? $value->valuesIds[0] : null;
$options_for_select = options_for_select($options, $value_id, array('include_custom' => __("Wybierz")));
$content = select_tag($name.'[value]', $options_for_select, array(
'id' => $params['id'],
'class' => 'st_allegro_parameter_dictionary st_allegro_parameter',
'data-ambiguous-value-id' => $parameter->options->ambiguousValueId,
'data-custom-value-enabled' => $parameter->options->customValuesEnabled,
'data-parameter-id' => $parameter->id,
));
if ($parameter->options->ambiguousValueId && $parameter->options->customValuesEnabled)
{
$visible = $parameter->options->ambiguousValueId == $value_id;
$content .= " ".input_tag($name.'[custom]', $visible && $value && isset($value->values) && !empty($value->values) ? $value->values[0] : null, array(
'disabled' => !$visible,
'style' => !$visible ? 'display: none' : '',
'placeholder' => __('Wprowadź własną wartość'),
'size' => '40',
'class' => 'st_allegro_parameter_dictionary_custom'
));
}
return $content;
}
function st_allegro_parameter_dictionary_multiple($name, $value, array $params)
{
$parameter = $params['parameter'];
$values = $value ? $value->valuesIds : array();
ob_start();
foreach ($parameter->dictionary as $dictionary)
{
echo '<label class="bs-mt-1 bs-d-block">';
echo st_admin_checkbox_tag($name . '[value][]', $dictionary->id, in_array($dictionary->id, $values), array(
'id' => $params['id'] . '_' . $parameter->id,
'class' => 'st_allegro_parameter_dictionary st_allegro_parameter',
'data-depends-on-value-ids' => $dictionary->dependsOnValueIds ? json_encode($dictionary->dependsOnValueIds) : null,
'data-ambiguous-value-id' => $parameter->options->ambiguousValueId,
'data-custom-value-enabled' => $parameter->options->customValuesEnabled,
'data-parameter-id' => $parameter->id,
)) . ' ' . $dictionary->value;
if ($parameter->options->ambiguousValueId == $dictionary->id && $parameter->options->customValuesEnabled)
{
$visible = in_array($parameter->options->ambiguousValueId , $values);
echo " ".input_tag($name.'[custom]', $value && isset($value->values) && !empty($value->values) ? $value->values[0] : null, array(
'disabled' => !$visible,
'style' => !$visible ? 'display: none' : '',
'placeholder' => __('Wprowadź własną wartość'),
'size' => '40',
'class' => 'st_allegro_parameter_dictionary_custom'
));
}
echo '</label>';
}
return ob_get_clean();
}
function st_allegro_parameter_float($name, $value, array $params)
{
return st_allegro_parameter_numeric($name, $value, $params);
}
function st_allegro_parameter_integer($name, $value, array $params)
{
return st_allegro_parameter_numeric($name, $value, $params);
}
function st_allegro_parameter_numeric($name, $value, array $params)
{
$parameter = $params['parameter'];
if (!$parameter->restrictions->range)
{
return input_tag($name, $value && $value->values ? $value->values[0] : null, array(
'id' => $params['id'],
'class' => 'number-type st_allegro_parameter',
'size' => 10,
'data-min' => $parameter->restrictions->min,
'data-max' => $parameter->restrictions->max,
'data-precision' => isset($parameter->restrictions->precision) && $parameter->restrictions->precision ? $parameter->restrictions->precision : 0,
));
}
else
{
return input_tag($name . '[from]', $value && $value->rangeValue ? $value->rangeValue->from : null, array(
'id' => $params['id'] . '_from',
'class' => 'number-type st_allegro_parameter',
'size' => 10,
'data-min' => $parameter->restrictions->min,
'data-max' => $parameter->restrictions->max,
'data-precision' => isset($parameter->restrictions->precision) && $parameter->restrictions->precision ? $parameter->restrictions->precision : 0,
)) . ' - ' . input_tag($name . '[to]', $value && $value->rangeValue ? $value->rangeValue->to : null, array(
'id' => $params['id'] . '_to',
'class' => 'number-type st_allegro_parameter',
'size' => 10,
'data-min' => $parameter->restrictions->min,
'data-max' => $parameter->restrictions->max,
'data-precision' => isset($parameter->restrictions->precision) && $parameter->restrictions->precision ? $parameter->restrictions->precision : 0,
));
}
}
function st_allegro_parameter_string($name, $value, array $params)
{
$parameter = $params['parameter'];
if ($parameter->restrictions->allowedNumberOfValues == 1)
{
return st_allegro_parameter_string_single($name, $value, $params);
}
else
{
return st_allegro_parameter_string_multiple($name, $value, $params);
}
}
function st_allegro_parameter_string_single($name, $value, array $params)
{
$parameter = $params['parameter'];
return input_tag($name, $value && $value->values ? $value->values[0] : null, array(
'class' => 'string-type st_allegro_parameter',
'maxlength' => $parameter->restrictions->maxLength,
'size' => '40',
));
}
function st_allegro_parameter_string_multiple($name, $value, array $params)
{
$parameter = $params['parameter'];
$values = $value ? $value->values : array();
ob_start();
for ($i = 0; $i < $parameter->restrictions->allowedNumberOfValues; $i++)
{
echo '<div style="margin-bottom: 5px">';
echo input_tag($name . '[' . $i . ']', isset($values[$i]) ? $values[$i] : null, array('class' => 'string-type st_allegro_parameter', 'maxlength' => $parameter->restrictions->maxLength, 'size' => '40', 'placeholder' => __('Wartość %no%', array('%no%' => $i + 1))));
echo '</div>';
}
return ob_get_clean();
}

View File

@@ -0,0 +1,114 @@
<?php
class AllegroAuction extends BaseAllegroAuction {
protected $productPrice = null;
protected $productOptionsArray = null;
public function productHasOptions()
{
return $this->getProduct() && $this->getProduct()->getOptHasOptions() > 1;
}
public function addCommand($uuid, $type)
{
$commands = $this->getCommands() ? $this->getCommands() : array();
$commands[$type] = $uuid;
$this->setCommands($commands);
}
public function getCommands()
{
$commands = parent::getCommands();
return $commands ? $commands : array();
}
public function getCommand($type)
{
$commands = $this->getCommands();
return $commands && isset($commands[$type]) ? $commands[$type] : null;
}
public function getEnvironment()
{
return 'AllegroPl';
}
public function getAuctionLink()
{
return stAllegroApi::getOfferUrl($this->getAuctionId());
}
public function setProductOptions($v)
{
// throw new Exception($v);
parent::setProductOptions($v);
$this->productOptionsArray = null;
}
public function getProductOptionsArray()
{
if (null === $this->productOptionsArray)
{
$ids = array();
if ($this->productHasOptions())
{
$selected = $this->getProductOptions() ? explode(",", $this->getProductOptions()) : array();
$values = array();
$index = 0;
foreach ($selected as $id)
{
$option = ProductOptionsValuePeer::retrieveByPK($id);
if ($option)
{
$values[$index][trim($option->getOptValue())] = $option->getId();
}
$index++;
}
$product = $this->getProduct();
if (null === $this->productPrice)
{
$this->productPrice = $product->getPriceBrutto();
}
$ids = stNewProductOptions::updateProduct($product, $ids, $values, false);
$price = stPrice::computePriceModifiers($product, $this->productPrice, 'brutto');
$product->setPriceBrutto($price);
$product->resetModified();
stNewProductOptions::clearStaticPool();
}
$this->productOptionsArray = $ids;
}
return $this->productOptionsArray;
}
public function save($con = null)
{
if (!$this->productHasOptions())
{
$this->setProductOptions(null);
}
return parent::save($con);
}
}

View File

@@ -0,0 +1,33 @@
<?php
/**
* SOTESHOP/stAllegroPlugin
*
* Ten plik należy do aplikacji stAllegroPlugin opartej na licencji (Professional License SOTE).
* Nie zmieniaj tego pliku, jeśli chcesz korzystać z automatycznych aktualizacji oprogramowania.
* Jeśli chcesz wprowadzać swoje modyfikacje do programu, zapoznaj się z dokumentacją, jak zmieniać
* oprogramowanie bez zmiany kodu bazowego http://www.sote.pl/modifications
*
* @package stAllegroPlugin
* @subpackage libs
* @copyright SOTE (www.sote.pl)
* @license http://www.sote.pl/license/sote (Professional License SOTE)
* @version $Id: AllegroAuctionHasOrder.php 16339 2011-12-01 12:09:59Z piotr $
* @author Piotr Halas <piotr.halas@sote.pl>
*/
/**
* Klasa AllegroAuctionHasOrder
*
* @package stAllegroPlugin
* @subpackage libs
*/
class AllegroAuctionHasOrder extends BaseAllegroAuctionHasOrder
{
public function save($con = null)
{
parent::save($con);
$this->getOrder()->setOptAllegroAuctionId($this->getAllegroAuctionId());
$this->getOrder()->save();
}
}

View File

@@ -0,0 +1,32 @@
<?php
/**
* SOTESHOP/stAllegroPlugin
*
* Ten plik należy do aplikacji stAllegroPlugin opartej na licencji (Professional License SOTE).
* Nie zmieniaj tego pliku, jeśli chcesz korzystać z automatycznych aktualizacji oprogramowania.
* Jeśli chcesz wprowadzać swoje modyfikacje do programu, zapoznaj się z dokumentacją, jak zmieniać
* oprogramowanie bez zmiany kodu bazowego http://www.sote.pl/modifications
*
* @package stAllegroPlugin
* @subpackage libs
* @copyright SOTE (www.sote.pl)
* @license http://www.sote.pl/license/sote (Professional License SOTE)
* @version $Id: AllegroAuctionHasOrderPeer.php 4776 2010-04-28 08:58:48Z piotr $
* @author Piotr Halas <piotr.halas@sote.pl>
*/
/**
* Klasa AllegroAuctionHasOrderPeer
*
* @package stAllegroPlugin
* @subpackage libs
*/
class AllegroAuctionHasOrderPeer extends BaseAllegroAuctionHasOrderPeer {
public static function exists($trans_id, AllegroAuction $auction)
{
$c = new Criteria();
$c->add(self::TRANS_ID, $trans_id);
$c->add(self::ALLEGRO_AUCTION_ID, $auction->getAuctionId());
return self::doCount($c) > 0;
}
}

View File

@@ -0,0 +1,112 @@
<?php
class AllegroAuctionPeer extends BaseAllegroAuctionPeer {
public static function doSelectByProduct($productId, $environment) {
$c = new Criteria();
$c->add(self::PRODUCT_ID, $productId);
$c->add(self::SITE, $environment);
$c->addAscendingOrderByColumn(self::ID);
$c->setIgnoreCase(false);
return self::doSelect($c);
}
public static function getAuctionByOrder($order) {
$c = new Criteria();
$c->add(AllegroAuctionHasOrderPeer::ORDER_ID, $order->getId());
$auctionHasOrder = AllegroAuctionHasOrderPeer::doSelectOne($c);
if (is_object($auctionHasOrder)) {
$c = new Criteria();
$c->add(self::AUCTION_ID, $auctionHasOrder->getAllegroAuctionId());
return self::doSelectOne($c);
}
return null;
}
/**
* Pobiera aukcje dla danego zamówienia
*
* @param Order $order
* @return AllegroAuction[]
*/
public static function getAuctionsByOrder(Order $order) {
$c = new Criteria();
$c->add(AllegroAuctionHasOrderPeer::ORDER_ID, $order->getId());
$c->addJoin(self::AUCTION_ID, AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID);
return self::doSelect($c);
}
/**
* Pobiera aukcje po id/numerze oferty Allegro
*
* @param string $number
* @return AllegroAuction
*/
public static function retrieveByAuctionNumber($number)
{
$c = new Criteria();
$c->add(self::AUCTION_ID, $number);
return self::doSelectOne($c);
}
/**
* Pobiera aukcje po id
*
* @param Order $order
* @return AllegroAuction[]
*/
public static function doSelectByAuctionIds(array $ids)
{
$c = new Criteria();
$c->add(self::AUCTION_ID, $ids, Criteria::IN);
$offers = array();
foreach (self::doSelectJoinProduct($c) as $offer)
{
$offers[$offer->getAuctionId()] = $offer;
}
return $offers;
}
public static function doSelectAuctionIdsByOrder(Order $order)
{
$c = new Criteria();
$c->addSelectColumn(OrderProductPeer::ALLEGRO_AUCTION_ID);
$c->add(OrderProductPeer::ORDER_ID, $order->getId());
$rs = OrderProductPeer::doSelectRS($c);
$ids = array();
while($rs->next())
{
$ids[] = $rs->getInt(1);
}
return $ids;
}
public static function updateRequiresSync($productId = null, $optionId = null)
{
$selCriteria = new Criteria();
$selCriteria->add(AllegroAuctionPeer::ID, null, Criteria::ISNOTNULL);
if (null !== $productId)
{
$selCriteria->add(AllegroAuctionPeer::PRODUCT_ID, $productId);
}
if ($optionId)
{
$selCriteria->add(AllegroAuctionPeer::PRODUCT_OPTIONS, sprintf('(%1$s = \'%2$d\' OR %1$s LIKE \'%%,%2$d\')', AllegroAuctionPeer::PRODUCT_OPTIONS, $optionId), Criteria::CUSTOM);
}
$upCriteria = new Criteria();
$upCriteria->add(AllegroAuctionPeer::REQUIRES_SYNC, true);
BasePeer::doUpdate($selCriteria, $upCriteria, Propel::getConnection());
}
}

View File

@@ -0,0 +1,12 @@
<?php
/**
* Subclass for representing a row from the 'st_allegro_parcel_tracking_number_queue' table.
*
*
*
* @package plugins.stAllegroPlugin.lib.model
*/
class AllegroParcelTrackingNumberQueue extends BaseAllegroParcelTrackingNumberQueue
{
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* Subclass for performing query and update operations on the 'st_allegro_parcel_tracking_number_queue' table.
*
*
*
* @package plugins.stAllegroPlugin.lib.model
*/
class AllegroParcelTrackingNumberQueuePeer extends BaseAllegroParcelTrackingNumberQueuePeer
{
public static function addParcelTrackingNumber(Order $order)
{
$c = new Criteria();
$c->add(self::ORDER_ID, $order->getId());
if (!self::doCount($c))
{
$allegroParcelTrackingNumberQueue = new AllegroParcelTrackingNumberQueue();
$allegroParcelTrackingNumberQueue->setOrder($order);
$allegroParcelTrackingNumberQueue->save();
}
}
}

View File

@@ -0,0 +1,664 @@
<?php
class AllegroApiOffer extends BaseObject implements Persistent
{
/**
* Oferta allegro
*
* @var object|null
*/
protected $allegroOffer;
/**
* Wybrane opcje produktu
*
* @var array|null
*/
protected $selectedProductOptionsIds = null;
/**
* Oferta Allegro po stronie sklepu
*
* @var AllegroAuction
*/
protected $allegroAuction = null;
public function buildPkeyCriteria()
{
$c = new Criteria();
$c->add(constant($this->getPeer().'::ID'), $this->getId());
return $c;
}
public function getPeer()
{
return get_class($this).'Peer';
}
public function getPrimaryKeyFields($keyType = BasePeer::TYPE_FIELDNAME)
{
$fields = call_user_func(array($this->getPeer(), 'translateFieldName'), 'id', BasePeer::TYPE_FIELDNAME, $keyType);
return array($fields);
}
public function setAfterSalesServices(array $afterSalesServices)
{
foreach ($afterSalesServices as $index => $service)
{
if (empty($service['id']))
{
$service = null;
}
$afterSalesServices[$index] = $service;
}
$this->__call('setAfterSalesServices', [$afterSalesServices]);
}
public function __toString()
{
return $this->getAdminGeneratorTitle();
}
/**
* Undocumented function
*
* @param object|null $allegroOffer
*/
public function __construct($allegroOffer = null)
{
$this->allegroOffer = $allegroOffer;
if (null === $this->allegroOffer)
{
$this->allegroOffer = stAllegroApi::arrayToObject(array(
'product' => null,
'category' => null,
'parameters' => null,
'publication' => null,
'afterSalesServices' => null,
'sizeTable' => null,
'discounts' => null,
'location' => null,
'images' => null,
'tax' => null,
'name' => null,
'external' => null,
'sellingMode' => null,
'stock' => null,
'description' => null,
'delivery' => null,
'payments' => null,
));
}
try
{
if (!isset($allegroOffer->location))
{
$config = stConfig::getInstance('stAllegroBackend');
$this->setLocation(array(
'city' => $config->get('allegro_pl_city'),
'countryCode' => 'PL',
'postCode' => $config->get('allegro_pl_post_code'),
'province' => strtoupper($config->get('allegro_pl_state')),
));
}
}
catch (Exception $e)
{
}
}
public function getAdminGeneratorTitle()
{
return $this->getName() . ' ('.$this->getId().')';
}
public function __clone()
{
if (!$this->isNew())
{
$duration = $this->getPublication()->duration;
$this->allegroOffer->publication = null;
$this->setPublication(array(
'duration' => $duration,
'status' => stAllegroApi::STATUS_INACTIVE,
));
unset($this->allegroOffer->validation);
unset($this->allegroOffer->updatedAt);
unset($this->allegroOffer->createdAt);
$this->setNew(true);
$allegroAuction = new AllegroAuction();
$allegroAuction->fromArray($this->getAllegroAuction()->toArray());
$allegroAuction->setId(null);
$allegroAuction->setCreatedAt(null);
$allegroAuction->setUpdatedAt(null);
$allegroAuction->setCommands(null);
$allegroAuction->setEnded(null);
$allegroAuction->setEndedAt(null);
$this->allegroAuction = $allegroAuction;
$this->allegroOffer->id = null;
}
}
public function setFromArray(array $data)
{
foreach ($data as $name => $value)
{
$property = 'set'.lcfirst(sfInflector::camelize($name));
if ($name == 'description' && $value && !is_array($value))
{
$value = json_decode($value);
}
$this->$property($value);
}
}
public function getPrimaryKey()
{
return $this->getId();
}
public function setPrimaryKey($primaryKey)
{
$this->allegroOffer->id = $primaryKey;
}
/**
* Zwraca GUID oferty
*
* @return string
*/
public function getId()
{
return isset($this->allegroOffer->id) ? $this->allegroOffer->id : null;
}
public function getAllowSync()
{
return $this->getAllegroAuction()->getAllowSync();
}
public function setAllowSync($allowSync)
{
$this->getAllegroAuction()->setAllowSync($allowSync);
}
/**
* Zwraca ofertę Allegro po stronie sklepu
*
* @return AllegroAuction
*/
public function getAllegroAuction()
{
if (null === $this->allegroAuction)
{
$allegroAuction = $this->getId() ? AllegroAuctionPeer::retrieveByAuctionNumber($this->getId()) : null;
if (null === $allegroAuction)
{
$allegroAuction = new AllegroAuction();
$allegroAuction->setName($this->getName());
$allegroAuction->setAuctionId($this->getId());
}
$this->allegroAuction = $allegroAuction;
}
return $this->allegroAuction;
}
/**
* Wystaw ofertę
*
* @return $this
* @throws stAllegroException
* @throws PropelException
*/
public function publish()
{
$api = stAllegroApi::getInstance();
$response = $api->publishOffers(array($this->getId()));
$this->getAllegroAuction()->addCommand($response->id, 'publish');
$this->getAllegroAuction()->setEnded(null);
$this->getAllegroAuction()->setEndedAt(null);
$this->getAllegroAuction()->save();
return $this;
}
/**
* Zakończ ofertę
*
* @return $this
* @throws stAllegroException
* @throws PropelException
*/
public function end()
{
$api = stAllegroApi::getInstance();
$api->publishOffers(array($this->getId()), false);
$this->getAllegroAuction()->setAllowSync(false);
$this->getAllegroAuction()->save();
return $this;
}
public function getStatusLabel()
{
$enum = stAllegroApi::getStatusList();
return isset($enum[$this->getPublication()->status]) ? $enum[$this->getPublication()->status] : '';
}
public function getPrimaryImage()
{
return $this->allegroOffer->primaryImage ? $this->allegroOffer->primaryImage->url : null;
}
public function getStockSold()
{
return $this->getStock()->sold;
}
public function getStockAvailable()
{
return $this->getStock()->available;
}
public function getShopProductStock()
{
$stock = null;
if ($this->getShopProduct())
{
stNewProductOptions::clearCache($this->getShopProduct());
$this->getAllegroAuction()->getProductOptionsArray();
$stock = $this->getShopProduct()->getStock();
}
return $stock;
}
/**
* Ustawia powiązanie produktu z ofertą
*
* @param Product $product
* @return self
*/
public function setShopProduct(Product $product = null)
{
if (null !== $product)
{
$this->getAllegroAuction()->setProduct($product);
$this->setShopProductId($product->getId());
}
return $this;
}
/**
* Zwraca powiązany produkt z ofertą
*
* @return Product
*/
public function getShopProduct()
{
return $this->getAllegroAuction()->getProduct();
}
public function getShopProductCode()
{
return $this->getAllegroAuction()->getProduct() ? $this->getAllegroAuction()->getProduct()->getCode() : null;
}
public function setProductId($id)
{
$this->setShopProductId($id);
}
public function getProductId()
{
return $this->getShopProductId();
}
/**
* Ustawia id powiązanego produktu z ofertą
*
* @param int $id
* @return self
*/
public function setShopProductId($id)
{
$this->getAllegroAuction()->setProductId($id);
$this->setExternal(array('id' => $id));
return $this;
}
/**
* Zwraca id powiązanego produktu z ofertą
*
* @return int
*/
public function getShopProductId()
{
return $this->getShopProduct() ? $this->getShopProduct()->getId() : null;
}
/**
* Zwraca nazwę
*
* @return string|null
*/
public function getName()
{
return $this->allegroOffer ? $this->allegroOffer->name : null;
}
/**
* Ustawia nazwę
*
* @param string $name Nazwa oferty
*
* @return self
*/
public function setName(string $name)
{
$this->allegroOffer->name = $name;
return $this;
}
public function setParameters(array $parameters)
{
$this->allegroOffer->parameters = array();
if (is_numeric(key($parameters)))
{
foreach ($parameters as $parameter)
{
$this->allegroOffer->parameters[$parameter['id']] = stAllegroApi::arrayToObject($parameter);
}
}
else
{
$this->allegroOffer->parameters = $this->transformOfferParameters($parameters);
}
}
public function setShopProductOptions($v)
{
$this->getAllegroAuction()->setProductOptions($v);
}
public function getShopProductOptions()
{
return $this->getAllegroAuction()->getProductOptions();
}
public function isAdminGeneratorActionVisible($name)
{
return $name == 'preview' && $this->getPublication()->status == stAllegroApi::STATUS_ACTIVE ||
$name == 'duplicate' && ($this->getPublication()->status == stAllegroApi::STATUS_ACTIVE || $this->getPublication()->status == stAllegroApi::STATUS_ENDED) ||
$name == '_delete';
}
public function getIsSystemDefault()
{
return $this->getPublication()->status != stAllegroApi::STATUS_INACTIVE;
}
public function getOfferUrl()
{
return stAllegroApi::getOfferUrl($this->getId());
}
public function delete($con = null)
{
stAllegroApi::getInstance()->deleteDraftOffer($this->getId());
}
public function save($con = null)
{
$config = stConfig::getInstance('stAllegroBackend');
$productChanged = $this->getAllegroAuction()->isColumnModified(AllegroAuctionPeer::PRODUCT_ID) || $this->getAllegroAuction()->isColumnModified(AllegroAuctionPeer::PRODUCT_OPTIONS);
if ($this->isNew())
{
$response = stAllegroApi::getInstance()->createOffer($this->allegroOffer);
$this->allegroOffer = $response;
if (null === $this->allegroAuction)
{
$this->allegroAuction = new AllegroAuction();
$this->allegroAuction->setName($response->name);
}
$this->allegroAuction->setAuctionId($response->id);
$this->allegroAuction->save();
$this->setNew(false);
}
else
{
$this->allegroAuction->save();
$product = $this->getAllegroAuction()->getProduct();
if ($productChanged)
{
$this->getAllegroAuction()->getProductOptionsArray();
if ($config->get('offer_sync_product_price'))
{
$commision = new AllegroCommission();
$this->allegroOffer->sellingMode->price->amount = $commision->calculatePrice($product->getPriceBrutto());
}
}
$response = stAllegroApi::getInstance()->updateOffer($this->getId(), $this->allegroOffer);
if ($response->validation && $response->validation->errors)
{
$this->allegroOffer->validation = $response->validation;
}
else
{
$this->allegroOffer = $response;
if ($productChanged)
{
$priceModifiers = $product->getPriceModifiers();
/**
* @see BasketProduct::setPriceModifiers()
**/
foreach ($priceModifiers as $index => $value) {
if (isset($value['custom']['label'])) {
$label = $value['custom']['label'];
unset($value['custom']['label']);
$value['label'] = $label;
$priceModifiers[$index] = $value;
}
}
$stmt = Propel::getConnection()->prepareStatement(sprintf('UPDATE %s SET %s = ?, %s = ?, %s = ?, %s = ?, %s = ? WHERE %s = ?', OrderProductPeer::TABLE_NAME, OrderProductPeer::CODE, OrderProductPeer::IMAGE, OrderProductPeer::NAME, OrderProductPeer::PRODUCT_ID, OrderProductPeer::PRICE_MODIFIERS, OrderProductPeer::ALLEGRO_AUCTION_ID));
$stmt->setString(1, $product->getCode());
$stmt->setString(2, $product->getOptImage());
$stmt->setString(3, $config->get('import_product_name', 'offer') == 'offer' ? $this->getName() : $product->getName());
$stmt->setInt(4, $product->getId());
$stmt->setString(5, serialize($priceModifiers));
$stmt->setString(6, $this->getId());
$stmt->executeQuery();
}
}
}
return true;
}
public function __call($name, $arguments)
{
$type = substr($name, 0, 3);
$property = lcfirst(substr($name, 3));
if (property_exists($this->allegroOffer, $property))
{
if ($type == 'get')
{
return $this->allegroOffer->$property;
}
elseif ($type == 'set')
{
$this->setAllegroApiParameter($property, $arguments[0]);
return;
}
}
throw new \BadMethodCallException('Method does not exist.');
}
protected function setAllegroApiParameter($name, $value)
{
if (is_array($value))
{
if (!isset($value[0]))
{
$this->allegroOffer->$name = stAllegroApi::arrayToObject(array_merge((array)$this->allegroOffer->$name, $value), true);
}
else
{
$this->allegroOffer->$name = stAllegroApi::arrayToObject($value, true);
}
}
else
{
$this->allegroOffer->$name = !empty($value) ? $value : null;
}
}
protected function transformOfferParameters(array $data)
{
$parameters = array();
foreach ($data as $type => $values)
{
switch($type)
{
case 'dictionary':
foreach ($values as $id => $value)
{
if ($value && $value['value'])
{
$parameter = new stdClass();
$parameter->id = $id;
$parameter->valuesIds = is_array($value['value']) ? $value['value'] : array($value['value']);
if (isset($value['custom']) && !empty($value['custom']))
{
$parameter->values = array($value['custom']);
}
$parameters[$id] = $parameter;
}
}
break;
case 'float':
case 'integer':
foreach ($values as $id => $value)
{
$parameter = new stdClass();
$parameter->id = $id;
if (is_array($value))
{
$parameter->rangeValue = new stdClass();
$parameter->rangeValue->from = $value['from'];
$parameter->rangeValue->to = $value['to'];
if ($value['from'] !== "" || $value['to'] !== "")
{
$parameters[$id] = $parameter;
}
}
else
{
$parameter->values = array($value);
if ($value !== "")
{
$parameters[$id] = $parameter;
}
}
}
break;
case 'string':
foreach ($values as $id => $value)
{
$parameter = new stdClass();
$parameter->id = $id;
if (is_array($value))
{
$parameter->values = array();
foreach ($value as $v)
{
if ($v)
{
$parameter->values[] = $v;
}
}
if ($parameter->values)
{
$parameters[$id] = $parameter;
}
}
else
{
$parameter->values = array($value);
if ($value)
{
$parameters[$id] = $parameter;
}
}
}
break;
}
}
return $parameters;
}
}

View File

@@ -0,0 +1,53 @@
<?php
class AllegroApiOfferMapBuilder
{
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'plugins.stAllegroPlugin.lib.model.AllegroApiOfferMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap('propel');
$tMap = $this->dbMap->addTable('st_allegro_api_offer');
$tMap->setPhpName('AllegroApiOffer');
$tMap->addPrimaryKey('ID', 'Id', 'string', CreoleTypes::CHAR, true, 38);
$tMap->addColumn('NAME', 'Name', 'string', CreoleTypes::VARCHAR, true, 255);
} // doBuild()
}

View File

@@ -0,0 +1,190 @@
<?php
class AllegroApiOfferPeer
{
const TABLE_NAME = 'st_allegro_api_offer';
const ID = self::TABLE_NAME.'.id';
const NAME = self::TABLE_NAME.'.name';
const STATUS = self::TABLE_NAME.'.status';
const PRICE_AMOUNT_FROM = self::TABLE_NAME.'.price_amount_from';
const PRICE_AMOUNT_TO = self::TABLE_NAME.'.price_amount_to';
const PRODUCT_CODE = self::TABLE_NAME.'.product_code';
const SHOP_PRODUCT = self::TABLE_NAME.'.external_id';
const PRODUCT_ID = self::TABLE_NAME.'.product_id';
const ALLEGRO_FIELD_MAPPING = array(
self::ID => 'offer.id',
self::NAME => 'name',
self::STATUS => 'publication.status',
self::PRICE_AMOUNT_FROM => 'sellingMode.price.amount.gte',
self::PRICE_AMOUNT_TO => 'sellingMode.price.amount.lte',
self::SHOP_PRODUCT => 'external.id',
self::PRODUCT_ID => 'external.id',
);
public static function getAllegroField($field)
{
return isset(self::ALLEGRO_FIELD_MAPPING[$field]) ? self::ALLEGRO_FIELD_MAPPING[$field] : null;
}
/**
* Ostatnio wykonane kryteria
*
* @var Criteria
*/
protected static $lastCriteria = null;
protected static $lastResults = null;
/**
* Zwraca cennik dostawy według GUID
*
* @param string $id GUID
* @return AllegroApiOffer
*/
public static function retrieveByPK($id)
{
$response = stAllegroApi::getInstance()->getOffer($id);
// throw new Exception("<pre>".var_export($response, true)."</pre>");
$allegroApiOffer = new AllegroApiOffer($response);
$allegroApiOffer->setNew(false);
return $allegroApiOffer;
}
/**
* Zwraca cennik dostaw na podstawie przekazanych kryteriów
*
* @param Criteria $c Kryteria
* @return AllegroApiOffer
*/
public static function doSelectOne(Criteria $c)
{
$results = self::doSelect($c);
return $results ? $results[0] : null;
}
/**
* Zwraca tablicę cenników dostaw na podstawie przekazanych kryteriów
*
* @param Criteria $c Kryteria
* @return AllegroApiOffer[]
*/
public static function doSelect(Criteria $c)
{
if (null === self::$lastCriteria || !self::$lastCriteria->equals($c))
{
$results = array();
$response = self::getAllegroApiOffersResponse($c);
foreach ($response->offers as $offer)
{
$allegroApiOffer = new AllegroApiOffer($offer);
$allegroApiOffer->setNew(false);
$results[] = $allegroApiOffer;
}
self::$lastCriteria = $c;
self::$lastResults = $results;
}
return self::$lastResults;
}
public static function doCount(Criteria $c)
{
$c = clone $c;
$c->clearOrderByColumns();
$c->setOffset(0);
$c->setLimit(null);
$response = self::getAllegroApiOffersResponse($c);
return $response->totalCount;
}
/**
* Zwraca oferty z Allegro API
*
* @param Criteria $c Kryteria
* @return object
* @throws stAllegroException
*/
protected static function getAllegroApiOffersResponse(Criteria $c)
{
$params = array(
'limit' => $c->getLimit(),
'offset' => $c->getOffset(),
'sellingMode.format' => 'BUY_NOW'
);
if (null !== $c->get(self::STATUS) && "" !== $c->get(self::STATUS))
{
$params['publication.status'] = $c->get(self::STATUS);
}
if (null !== $c->get(self::ID) && "" !== $c->get(self::ID))
{
$params[self::getAllegroField(self::ID)] = $c->get(self::ID);
}
if (null !== $c->get(self::NAME) && "" !== $c->get(self::NAME))
{
$params[self::getAllegroField(self::NAME)] = trim($c->get(self::NAME), '%');
}
if (null !== $c->get(self::PRICE_AMOUNT_FROM) && "" !== $c->get(self::PRICE_AMOUNT_FROM))
{
$params[self::getAllegroField(self::PRICE_AMOUNT_FROM)] = $c->get(self::PRICE_AMOUNT_FROM);
}
if (null !== $c->get(self::PRICE_AMOUNT_TO) && "" !== $c->get(self::PRICE_AMOUNT_TO))
{
$params[self::getAllegroField(self::PRICE_AMOUNT_TO)] = $c->get(self::PRICE_AMOUNT_TO);
}
if (null !== $c->get(self::SHOP_PRODUCT) && "" !== $c->get(self::SHOP_PRODUCT))
{
$params[self::getAllegroField(self::SHOP_PRODUCT)] = $c->get(self::SHOP_PRODUCT);
}
if (null !== $c->get(self::PRODUCT_ID) && "" !== $c->get(self::PRODUCT_ID))
{
$params[self::getAllegroField(self::PRODUCT_ID)] = $c->get(self::PRODUCT_ID);
}
return stAllegroApi::getInstance()->getOffers($params);
}
public static function getMapBuilder()
{
return BasePeer::getMapBuilder(AllegroApiOfferMapBuilder::CLASS_NAME);
}
public static function translateFieldName($name, $fromType, $toType)
{
return $name;
}
}
// static code to register the map builder for this Peer with the main Propel class
if (Propel::isInit()) {
// the MapBuilder classes register themselves with Propel during initialization
// so we need to load them here.
try {
AllegroApiOfferPeer::getMapBuilder();
} catch (Exception $e) {
Propel::log('Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR);
}
} else {
// even if Propel is not yet initialized, the map builder class can be registered
// now and then it will be loaded when Propel initializes.
Propel::registerMapBuilder(AllegroApiOfferMapBuilder::CLASS_NAME);
}

View File

@@ -0,0 +1,195 @@
<?php
class AllegroApiShippingRate extends BaseObject implements Persistent
{
/**
* GUID cennika dostaw
*
* @var string
*/
protected $id;
/**
* Nazwa cennika dostaw
*
* @var string
*/
protected $name;
/**
* Data ostatniej modyfikacji cennika dostaw
*
* @var int|null
*/
protected $lastModified;
/**
* Lista stawek cennika dostaw
*
* @var array|null
*/
protected $rates;
public function buildPkeyCriteria()
{
$c = new Criteria();
$c->add(constant($this->getPeer().'::ID'), $this->getId());
return $c;
}
public function getPeer()
{
return get_class($this).'Peer';
}
public function getPrimaryKeyFields($keyType = BasePeer::TYPE_FIELDNAME)
{
$fields = call_user_func(array($this->getPeer(), 'translateFieldName'), 'id', BasePeer::TYPE_FIELDNAME, $keyType);
return array($fields);
}
public function getPrimaryKey()
{
return $this->id;
}
public function setPrimaryKey($primaryKey)
{
$this->id = $primaryKey;
}
/**
* Zwraca GUID cennika dostaw
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Ustawia GUID cennika dostaw
*
* @param string $id GUID cennika dostaw
*
* @return self
*/
public function setId(string $id)
{
$this->id = $id;
return $this;
}
/**
* Zwraca nazwę cennika dostaw
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Ustawia nazwę cennika dostaw
*
* @param string $name Nazwa cennika dostaw
*
* @return self
*/
public function setName(string $name)
{
$this->name = $name;
return $this;
}
/**
* Zwraca datę ostatniej modyfikacji cennika dostaw
*
* @return int|null
*/
public function getLastModified()
{
return $this->lastModified;
}
/**
* Ustawia datę ostatniej modyfikacji cennika dostaw
*
* @param int $lastModified Data ostatniej modyfikacji cennika dostaw
*
* @return self
*/
public function setLastModified(int $lastModified)
{
$this->lastModified = $lastModified;
return $this;
}
/**
* Zwraca listę stawek cennika dostaw
*
* @return array|null
*/
public function getRates()
{
return $this->rates;
}
/**
* Ustawia listę stawek cennika dostaw
*
* @param array $rates Lista stawek cennika dostaw
*
* @return self
*/
public function setRates(array $rates)
{
$this->rates = $rates;
return $this;
}
/**
* Zwraca stawkę cennika dostawy po GUID
*
* @param string $id GUID stawki
* @param string|null $default Wartość domyślna w przypadku braku stawki
* @return array
*/
public function getRate($id, $default = null)
{
return isset($this->rates[$id]) ? $this->rates[$id] : $default;
}
public function delete($con = null)
{
}
public function save($con = null)
{
if ($this->isNew())
{
$response = stAllegroApi::getInstance()->createShippingRate(array(
'name' => $this->name,
'rates' => $this->rates
));
$this->id = $response->id;
}
else
{
stAllegroApi::getInstance()->updateShippingRate($this->id, array(
'name' => $this->name,
'rates' => $this->rates,
));
}
return true;
}
}

View File

@@ -0,0 +1,54 @@
<?php
class AllegroApiShippingRateMapBuilder
{
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'plugins.stAllegroPlugin.lib.model.AllegroApiShippingRateMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap('propel');
$tMap = $this->dbMap->addTable('st_allegro_api_shipping_rate');
$tMap->setPhpName('AllegroApiShippingRate');
$tMap->addPrimaryKey('ID', 'Id', 'string', CreoleTypes::CHAR, true, 38);
$tMap->addColumn('NAME', 'Name', 'string', CreoleTypes::VARCHAR, true, 255);
$tMap->addColumn('LAST_MODIFIED', 'LastModified', 'int', CreoleTypes::TIMESTAMP);
} // doBuild()
}

View File

@@ -0,0 +1,142 @@
<?php
class AllegroApiShippingRatePeer
{
const TABLE_NAME = 'st_allegro_api_shipping_rate';
const ID = self::TABLE_NAME.'.id';
const NAME = self::TABLE_NAME.'.name';
const LAST_MODIFIED = self::TABLE_NAME.'.last_modified';
/**
* Ostatnio wykonane kryteria
*
* @var Criteria
*/
protected static $lastCriteria = null;
protected static $lastResults = null;
/**
* Zwraca cennik dostawy według GUID
*
* @param string $id GUID
* @return AllegroApiShippingRate
*/
public static function retrieveByPK($id)
{
$rates = array();
$shippingRate = stAllegroApi::getInstance()->getShippingRate($id);
foreach ($shippingRate->rates as $methodId => $rate)
{
$rates[$methodId] = array(
'first_item_rate' => array(
'amount' => $rate->firstItemRate->amount,
'currency' => $rate->firstItemRate->currency,
'default' => 0.00
),
'next_item_rate' => array(
'amount' => $rate->nextItemRate->amount,
'currency' => $rate->firstItemRate->currency,
'default' => 0.00
),
'max_quantity_per_package' => $rate->maxQuantityPerPackage,
);
}
$allegroApiShippingRate = new AllegroApiShippingRate();
$allegroApiShippingRate->setId($shippingRate->id);
$allegroApiShippingRate->setName($shippingRate->name);
$allegroApiShippingRate->setRates($rates);
$allegroApiShippingRate->setLastModified($shippingRate->lastModified ? strtotime($shippingRate->lastModified) : null);
$allegroApiShippingRate->setNew(false);
return $allegroApiShippingRate;
}
/**
* Zwraca cennik dostaw na podstawie przekazanych kryteriów
*
* @param Criteria $c Kryteria
* @return AllegroApiShippingRate
*/
public static function doSelectOne(Criteria $c)
{
$results = self::doSelect($c);
return $results ? $results[0] : null;
}
/**
* Zwraca tablicę cenników dostaw na podstawie przekazanych kryteriów
*
* @param Criteria $c Kryteria
* @return AllegroApiShippingRate[]
*/
public static function doSelect(Criteria $c)
{
if (null === self::$lastCriteria || !self::$lastCriteria->equals($c))
{
$results = array();
$query = trim($c->get(self::NAME), '%');
foreach (stAllegroApi::getInstance()->getShippingRates() as $shippingRate)
{
if (null === $query || "" === $query || false !== stripos($shippingRate->name, $query))
{
$allegroApiShippingRate = new AllegroApiShippingRate();
$allegroApiShippingRate->setId($shippingRate->id);
$allegroApiShippingRate->setName($shippingRate->name);
$allegroApiShippingRate->setNew(false);
$results[] = $allegroApiShippingRate;
}
}
self::$lastCriteria = $c;
self::$lastResults = array_slice($results, $c->getOffset(), $c->getLimit() > 0 ? $c->getLimit() : null);
}
return self::$lastResults;
}
public static function doCount(Criteria $c)
{
$c = clone $c;
$c->clearOrderByColumns();
$c->setOffset(0);
$c->setLimit(null);
$results = self::doSelect($c);
return count($results);
}
public static function getMapBuilder()
{
return BasePeer::getMapBuilder(AllegroApiShippingRateMapBuilder::CLASS_NAME);
}
public static function translateFieldName($name, $fromType, $toType)
{
return $name;
}
}
// static code to register the map builder for this Peer with the main Propel class
if (Propel::isInit()) {
// the MapBuilder classes register themselves with Propel during initialization
// so we need to load them here.
try {
AllegroApiShippingRatePeer::getMapBuilder();
} catch (Exception $e) {
Propel::log('Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR);
}
} else {
// even if Propel is not yet initialized, the map builder class can be registered
// now and then it will be loaded when Propel initializes.
Propel::registerMapBuilder(AllegroApiShippingRateMapBuilder::CLASS_NAME);
}

View File

@@ -0,0 +1,74 @@
<?php
/**
* This class adds structure of 'st_allegro_auction_has_order' table to 'propel' DatabaseMap object.
*
*
*
* These statically-built map classes are used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package plugins.stAllegroPlugin.lib.model.map
*/
class AllegroAuctionHasOrderMapBuilder {
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'plugins.stAllegroPlugin.lib.model.map.AllegroAuctionHasOrderMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap('propel');
$tMap = $this->dbMap->addTable('st_allegro_auction_has_order');
$tMap->setPhpName('AllegroAuctionHasOrder');
$tMap->setUseIdGenerator(false);
$tMap->addPrimaryKey('TRANS_ID', 'TransId', 'string', CreoleTypes::BIGINT, true, null);
$tMap->addPrimaryKey('ALLEGRO_AUCTION_ID', 'AllegroAuctionId', 'string', CreoleTypes::BIGINT, true, null);
$tMap->addForeignPrimaryKey('ORDER_ID', 'OrderId', 'int' , CreoleTypes::INTEGER, 'st_order', 'ID', true, null);
$tMap->addColumn('ALLEGRO_USER_ID', 'AllegroUserId', 'string', CreoleTypes::BIGINT, true, null);
} // doBuild()
} // AllegroAuctionHasOrderMapBuilder

View File

@@ -0,0 +1,92 @@
<?php
/**
* This class adds structure of 'st_allegro_auction' table to 'propel' DatabaseMap object.
*
*
*
* These statically-built map classes are used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package plugins.stAllegroPlugin.lib.model.map
*/
class AllegroAuctionMapBuilder {
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'plugins.stAllegroPlugin.lib.model.map.AllegroAuctionMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap('propel');
$tMap = $this->dbMap->addTable('st_allegro_auction');
$tMap->setPhpName('AllegroAuction');
$tMap->setUseIdGenerator(true);
$tMap->addColumn('CREATED_AT', 'CreatedAt', 'int', CreoleTypes::TIMESTAMP, false, null);
$tMap->addColumn('UPDATED_AT', 'UpdatedAt', 'int', CreoleTypes::TIMESTAMP, false, null);
$tMap->addPrimaryKey('ID', 'Id', 'int', CreoleTypes::INTEGER, true, null);
$tMap->addForeignKey('PRODUCT_ID', 'ProductId', 'int', CreoleTypes::INTEGER, 'st_product', 'ID', true, null);
$tMap->addColumn('PRODUCT_OPTIONS', 'ProductOptions', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('REQUIRES_SYNC', 'RequiresSync', 'int', CreoleTypes::INTEGER, false, null);
$tMap->addColumn('ALLOW_SYNC', 'AllowSync', 'boolean', CreoleTypes::BOOLEAN, false, null);
$tMap->addColumn('SITE', 'Site', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('NAME', 'Name', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('AUCTION_ID', 'AuctionId', 'string', CreoleTypes::BIGINT, false, null);
$tMap->addColumn('ENDED', 'Ended', 'boolean', CreoleTypes::BOOLEAN, false, null);
$tMap->addColumn('ENDED_AT', 'EndedAt', 'int', CreoleTypes::TIMESTAMP, false, null);
$tMap->addColumn('COMMANDS', 'Commands', 'array', CreoleTypes::VARCHAR, false, 1024);
} // doBuild()
} // AllegroAuctionMapBuilder

View File

@@ -0,0 +1,70 @@
<?php
/**
* This class adds structure of 'st_allegro_parcel_tracking_number_queue' table to 'propel' DatabaseMap object.
*
*
*
* These statically-built map classes are used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package plugins.stAllegroPlugin.lib.model.map
*/
class AllegroParcelTrackingNumberQueueMapBuilder {
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'plugins.stAllegroPlugin.lib.model.map.AllegroParcelTrackingNumberQueueMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap('propel');
$tMap = $this->dbMap->addTable('st_allegro_parcel_tracking_number_queue');
$tMap->setPhpName('AllegroParcelTrackingNumberQueue');
$tMap->setUseIdGenerator(false);
$tMap->addColumn('CREATED_AT', 'CreatedAt', 'int', CreoleTypes::TIMESTAMP, false, null);
$tMap->addForeignPrimaryKey('ORDER_ID', 'OrderId', 'int' , CreoleTypes::INTEGER, 'st_order', 'ID', true, null);
} // doBuild()
} // AllegroParcelTrackingNumberQueueMapBuilder

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,830 @@
<?php
/**
* Base class that represents a row from the 'st_allegro_auction_has_order' table.
*
*
*
* @package plugins.stAllegroPlugin.lib.model.om
*/
abstract class BaseAllegroAuctionHasOrder extends BaseObject implements Persistent {
protected static $dispatcher = null;
/**
* The value for the trans_id field.
* @var string
*/
protected $trans_id;
/**
* The value for the allegro_auction_id field.
* @var string
*/
protected $allegro_auction_id;
/**
* The value for the order_id field.
* @var int
*/
protected $order_id;
/**
* The value for the allegro_user_id field.
* @var string
*/
protected $allegro_user_id;
/**
* @var Order
*/
protected $aOrder;
/**
* Flag to prevent endless save loop, if this object is referenced
* by another object which falls in this transaction.
* @var boolean
*/
protected $alreadyInSave = false;
/**
* Flag to prevent endless validation loop, if this object is referenced
* by another object which falls in this transaction.
* @var boolean
*/
protected $alreadyInValidation = false;
/**
* Get the [trans_id] column value.
*
* @return string
*/
public function getTransId()
{
return $this->trans_id;
}
/**
* Get the [allegro_auction_id] column value.
*
* @return string
*/
public function getAllegroAuctionId()
{
return $this->allegro_auction_id;
}
/**
* Get the [order_id] column value.
*
* @return int
*/
public function getOrderId()
{
return $this->order_id;
}
/**
* Get the [allegro_user_id] column value.
*
* @return string
*/
public function getAllegroUserId()
{
return $this->allegro_user_id;
}
/**
* Set the value of [trans_id] column.
*
* @param string $v new value
* @return void
*/
public function setTransId($v)
{
if ($v !== null && !is_string($v)) {
$v = (string) $v;
}
if ($this->trans_id !== $v) {
$this->trans_id = $v;
$this->modifiedColumns[] = AllegroAuctionHasOrderPeer::TRANS_ID;
}
} // setTransId()
/**
* Set the value of [allegro_auction_id] column.
*
* @param string $v new value
* @return void
*/
public function setAllegroAuctionId($v)
{
if ($v !== null && !is_string($v)) {
$v = (string) $v;
}
if ($this->allegro_auction_id !== $v) {
$this->allegro_auction_id = $v;
$this->modifiedColumns[] = AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID;
}
} // setAllegroAuctionId()
/**
* Set the value of [order_id] column.
*
* @param int $v new value
* @return void
*/
public function setOrderId($v)
{
if ($v !== null && !is_int($v) && is_numeric($v)) {
$v = (int) $v;
}
if ($this->order_id !== $v) {
$this->order_id = $v;
$this->modifiedColumns[] = AllegroAuctionHasOrderPeer::ORDER_ID;
}
if ($this->aOrder !== null && $this->aOrder->getId() !== $v) {
$this->aOrder = null;
}
} // setOrderId()
/**
* Set the value of [allegro_user_id] column.
*
* @param string $v new value
* @return void
*/
public function setAllegroUserId($v)
{
if ($v !== null && !is_string($v)) {
$v = (string) $v;
}
if ($this->allegro_user_id !== $v) {
$this->allegro_user_id = $v;
$this->modifiedColumns[] = AllegroAuctionHasOrderPeer::ALLEGRO_USER_ID;
}
} // setAllegroUserId()
/**
* Hydrates (populates) the object variables with values from the database resultset.
*
* An offset (1-based "start column") is specified so that objects can be hydrated
* with a subset of the columns in the resultset rows. This is needed, for example,
* for results of JOIN queries where the resultset row includes columns from two or
* more tables.
*
* @param ResultSet $rs The ResultSet class with cursor advanced to desired record pos.
* @param int $startcol 1-based offset column which indicates which restultset column to start with.
* @return int next starting column
* @throws PropelException - Any caught Exception will be rewrapped as a PropelException.
*/
public function hydrate(ResultSet $rs, $startcol = 1)
{
try {
if ($this->getDispatcher()->getListeners('AllegroAuctionHasOrder.preHydrate')) {
$event = $this->getDispatcher()->notify(new sfEvent($this, 'AllegroAuctionHasOrder.preHydrate', array('resultset' => $rs, 'startcol' => $startcol)));
$startcol = $event['startcol'];
}
$this->trans_id = $rs->getString($startcol + 0);
$this->allegro_auction_id = $rs->getString($startcol + 1);
$this->order_id = $rs->getInt($startcol + 2);
$this->allegro_user_id = $rs->getString($startcol + 3);
$this->resetModified();
$this->setNew(false);
if ($this->getDispatcher()->getListeners('AllegroAuctionHasOrder.postHydrate')) {
$event = $this->getDispatcher()->notify(new sfEvent($this, 'AllegroAuctionHasOrder.postHydrate', array('resultset' => $rs, 'startcol' => $startcol + 4)));
return $event['startcol'];
}
// FIXME - using NUM_COLUMNS may be clearer.
return $startcol + 4; // 4 = AllegroAuctionHasOrderPeer::NUM_COLUMNS - AllegroAuctionHasOrderPeer::NUM_LAZY_LOAD_COLUMNS).
} catch (Exception $e) {
throw new PropelException("Error populating AllegroAuctionHasOrder object", $e);
}
}
/**
* Removes this object from datastore and sets delete attribute.
*
* @param Connection $con
* @return void
* @throws PropelException
* @see BaseObject::setDeleted()
* @see BaseObject::isDeleted()
*/
public function delete($con = null)
{
if ($this->isDeleted()) {
throw new PropelException("This object has already been deleted.");
}
if ($this->getDispatcher()->getListeners('AllegroAuctionHasOrder.preDelete')) {
$this->getDispatcher()->notify(new sfEvent($this, 'AllegroAuctionHasOrder.preDelete', array('con' => $con)));
}
if (sfMixer::hasCallables('BaseAllegroAuctionHasOrder:delete:pre'))
{
foreach (sfMixer::getCallables('BaseAllegroAuctionHasOrder:delete:pre') as $callable)
{
$ret = call_user_func($callable, $this, $con);
if ($ret)
{
return;
}
}
}
if ($con === null) {
$con = Propel::getConnection(AllegroAuctionHasOrderPeer::DATABASE_NAME);
}
try {
$con->begin();
AllegroAuctionHasOrderPeer::doDelete($this, $con);
$this->setDeleted(true);
$con->commit();
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
if ($this->getDispatcher()->getListeners('AllegroAuctionHasOrder.postDelete')) {
$this->getDispatcher()->notify(new sfEvent($this, 'AllegroAuctionHasOrder.postDelete', array('con' => $con)));
}
if (sfMixer::hasCallables('BaseAllegroAuctionHasOrder:delete:post'))
{
foreach (sfMixer::getCallables('BaseAllegroAuctionHasOrder:delete:post') as $callable)
{
call_user_func($callable, $this, $con);
}
}
}
/**
* Stores the object in the database. If the object is new,
* it inserts it; otherwise an update is performed. This method
* wraps the doSave() worker method in a transaction.
*
* @param Connection $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see doSave()
*/
public function save($con = null)
{
if ($this->isDeleted()) {
throw new PropelException("You cannot save an object that has been deleted.");
}
if (!$this->alreadyInSave) {
if ($this->getDispatcher()->getListeners('AllegroAuctionHasOrder.preSave')) {
$this->getDispatcher()->notify(new sfEvent($this, 'AllegroAuctionHasOrder.preSave', array('con' => $con)));
}
foreach (sfMixer::getCallables('BaseAllegroAuctionHasOrder:save:pre') as $callable)
{
$affectedRows = call_user_func($callable, $this, $con);
if (is_int($affectedRows))
{
return $affectedRows;
}
}
}
if ($con === null) {
$con = Propel::getConnection(AllegroAuctionHasOrderPeer::DATABASE_NAME);
}
try {
$con->begin();
$affectedRows = $this->doSave($con);
$con->commit();
if (!$this->alreadyInSave) {
if ($this->getDispatcher()->getListeners('AllegroAuctionHasOrder.postSave')) {
$this->getDispatcher()->notify(new sfEvent($this, 'AllegroAuctionHasOrder.postSave', array('con' => $con)));
}
foreach (sfMixer::getCallables('BaseAllegroAuctionHasOrder:save:post') as $callable)
{
call_user_func($callable, $this, $con, $affectedRows);
}
}
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Stores the object in the database.
*
* If the object is new, it inserts it; otherwise an update is performed.
* All related objects are also updated in this method.
*
* @param Connection $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see save()
*/
protected function doSave($con)
{
$affectedRows = 0; // initialize var to track total num of affected rows
if (!$this->alreadyInSave) {
$this->alreadyInSave = true;
// We call the save method on the following object(s) if they
// were passed to this object by their coresponding set
// method. This object relates to these object(s) by a
// foreign key reference.
if ($this->aOrder !== null) {
if ($this->aOrder->isModified()) {
$affectedRows += $this->aOrder->save($con);
}
$this->setOrder($this->aOrder);
}
// If this object has been modified, then save it to the database.
if ($this->isModified()) {
if ($this->isNew()) {
$pk = AllegroAuctionHasOrderPeer::doInsert($this, $con);
$affectedRows += 1; // we are assuming that there is only 1 row per doInsert() which
// should always be true here (even though technically
// BasePeer::doInsert() can insert multiple rows).
$this->setNew(false);
} else {
$affectedRows += AllegroAuctionHasOrderPeer::doUpdate($this, $con);
}
$this->resetModified(); // [HL] After being saved an object is no longer 'modified'
}
$this->alreadyInSave = false;
}
return $affectedRows;
} // doSave()
/**
* Array of ValidationFailed objects.
* @var array ValidationFailed[]
*/
protected $validationFailures = array();
/**
* Gets any ValidationFailed objects that resulted from last call to validate().
*
*
* @return array ValidationFailed[]
* @see validate()
*/
public function getValidationFailures()
{
return $this->validationFailures;
}
/**
* Validates the objects modified field values and all objects related to this table.
*
* If $columns is either a column name or an array of column names
* only those columns are validated.
*
* @param mixed $columns Column name or an array of column names.
* @return boolean Whether all columns pass validation.
* @see doValidate()
* @see getValidationFailures()
*/
public function validate($columns = null)
{
$res = $this->doValidate($columns);
if ($res === true) {
$this->validationFailures = array();
return true;
} else {
$this->validationFailures = $res;
return false;
}
}
/**
* This function performs the validation work for complex object models.
*
* In addition to checking the current object, all related objects will
* also be validated. If all pass then <code>true</code> is returned; otherwise
* an aggreagated array of ValidationFailed objects will be returned.
*
* @param array $columns Array of column names to validate.
* @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objets otherwise.
*/
protected function doValidate($columns = null)
{
if (!$this->alreadyInValidation) {
$this->alreadyInValidation = true;
$retval = null;
$failureMap = array();
// We call the validate method on the following object(s) if they
// were passed to this object by their coresponding set
// method. This object relates to these object(s) by a
// foreign key reference.
if ($this->aOrder !== null) {
if (!$this->aOrder->validate($columns)) {
$failureMap = array_merge($failureMap, $this->aOrder->getValidationFailures());
}
}
if (($retval = AllegroAuctionHasOrderPeer::doValidate($this, $columns)) !== true) {
$failureMap = array_merge($failureMap, $retval);
}
$this->alreadyInValidation = false;
}
return (!empty($failureMap) ? $failureMap : true);
}
/**
* Retrieves a field from the object by name passed in as a string.
*
* @param string $name name
* @param string $type The type of fieldname the $name is of:
* one of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return mixed Value of field.
*/
public function getByName($name, $type = BasePeer::TYPE_PHPNAME)
{
$pos = AllegroAuctionHasOrderPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
return $this->getByPosition($pos);
}
/**
* Retrieves a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @return mixed Value of field at $pos
*/
public function getByPosition($pos)
{
switch($pos) {
case 0:
return $this->getTransId();
break;
case 1:
return $this->getAllegroAuctionId();
break;
case 2:
return $this->getOrderId();
break;
case 3:
return $this->getAllegroUserId();
break;
default:
return null;
break;
} // switch()
}
/**
* Exports the object as an array.
*
* You can specify the key type of the array by passing one of the class
* type constants.
*
* @param string $keyType One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return an associative array containing the field names (as keys) and field values
*/
public function toArray($keyType = BasePeer::TYPE_PHPNAME)
{
$keys = AllegroAuctionHasOrderPeer::getFieldNames($keyType);
$result = array(
$keys[0] => $this->getTransId(),
$keys[1] => $this->getAllegroAuctionId(),
$keys[2] => $this->getOrderId(),
$keys[3] => $this->getAllegroUserId(),
);
return $result;
}
/**
* Sets a field from the object by name passed in as a string.
*
* @param string $name peer name
* @param mixed $value field value
* @param string $type The type of fieldname the $name is of:
* one of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return void
*/
public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME)
{
$pos = AllegroAuctionHasOrderPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
return $this->setByPosition($pos, $value);
}
/**
* Sets a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @param mixed $value field value
* @return void
*/
public function setByPosition($pos, $value)
{
switch($pos) {
case 0:
$this->setTransId($value);
break;
case 1:
$this->setAllegroAuctionId($value);
break;
case 2:
$this->setOrderId($value);
break;
case 3:
$this->setAllegroUserId($value);
break;
} // switch()
}
/**
* Populates the object using an array.
*
* This is particularly useful when populating an object from one of the
* request arrays (e.g. $_POST). This method goes through the column
* names, checking to see whether a matching key exists in populated
* array. If so the setByName() method is called for that column.
*
* You can specify the key type of the array by additionally passing one
* of the class type constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME,
* TYPE_NUM. The default key type is the column's phpname (e.g. 'authorId')
*
* @param array $arr An array to populate the object from.
* @param string $keyType The type of keys the array uses.
* @return void
*/
public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME)
{
$keys = AllegroAuctionHasOrderPeer::getFieldNames($keyType);
if (array_key_exists($keys[0], $arr)) $this->setTransId($arr[$keys[0]]);
if (array_key_exists($keys[1], $arr)) $this->setAllegroAuctionId($arr[$keys[1]]);
if (array_key_exists($keys[2], $arr)) $this->setOrderId($arr[$keys[2]]);
if (array_key_exists($keys[3], $arr)) $this->setAllegroUserId($arr[$keys[3]]);
}
/**
* Build a Criteria object containing the values of all modified columns in this object.
*
* @return Criteria The Criteria object containing all modified values.
*/
public function buildCriteria()
{
$criteria = new Criteria(AllegroAuctionHasOrderPeer::DATABASE_NAME);
if ($this->isColumnModified(AllegroAuctionHasOrderPeer::TRANS_ID)) $criteria->add(AllegroAuctionHasOrderPeer::TRANS_ID, $this->trans_id);
if ($this->isColumnModified(AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID)) $criteria->add(AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID, $this->allegro_auction_id);
if ($this->isColumnModified(AllegroAuctionHasOrderPeer::ORDER_ID)) $criteria->add(AllegroAuctionHasOrderPeer::ORDER_ID, $this->order_id);
if ($this->isColumnModified(AllegroAuctionHasOrderPeer::ALLEGRO_USER_ID)) $criteria->add(AllegroAuctionHasOrderPeer::ALLEGRO_USER_ID, $this->allegro_user_id);
return $criteria;
}
/**
* Builds a Criteria object containing the primary key for this object.
*
* Unlike buildCriteria() this method includes the primary key values regardless
* of whether or not they have been modified.
*
* @return Criteria The Criteria object containing value(s) for primary key(s).
*/
public function buildPkeyCriteria()
{
$criteria = new Criteria(AllegroAuctionHasOrderPeer::DATABASE_NAME);
$criteria->add(AllegroAuctionHasOrderPeer::TRANS_ID, $this->trans_id);
$criteria->add(AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID, $this->allegro_auction_id);
$criteria->add(AllegroAuctionHasOrderPeer::ORDER_ID, $this->order_id);
return $criteria;
}
/**
* Returns the composite primary key for this object.
* The array elements will be in same order as specified in XML.
* @return array
*/
public function getPrimaryKey()
{
return array($this->getTransId(), $this->getAllegroAuctionId(), $this->getOrderId());
}
/**
* Returns [composite] primary key fields
*
* @param string $keyType
* @return array
*/
public function getPrimaryKeyFields($keyType = BasePeer::TYPE_FIELDNAME)
{
return array(AllegroAuctionHasOrderPeer::translateFieldName('trans_id', BasePeer::TYPE_FIELDNAME, $keyType), AllegroAuctionHasOrderPeer::translateFieldName('allegro_auction_id', BasePeer::TYPE_FIELDNAME, $keyType), AllegroAuctionHasOrderPeer::translateFieldName('order_id', BasePeer::TYPE_FIELDNAME, $keyType));
}
/**
* Set the [composite] primary key.
*
* @param array $keys The elements of the composite key (order must match the order in XML file).
* @return void
*/
public function setPrimaryKey($keys)
{
$this->setTransId($keys[0]);
$this->setAllegroAuctionId($keys[1]);
$this->setOrderId($keys[2]);
}
/**
* Sets contents of passed object to values from current object.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param object $copyObj An object of AllegroAuctionHasOrder (or compatible) type.
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @throws PropelException
*/
public function copyInto($copyObj, $deepCopy = false)
{
$copyObj->setAllegroUserId($this->allegro_user_id);
$copyObj->setNew(true);
$copyObj->setTransId(NULL); // this is a pkey column, so set to default value
$copyObj->setAllegroAuctionId(NULL); // this is a pkey column, so set to default value
$copyObj->setOrderId(NULL); // this is a pkey column, so set to default value
}
/**
* Makes a copy of this object that will be inserted as a new row in table when saved.
* It creates a new object filling in the simple attributes, but skipping any primary
* keys that are defined for the table.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @return AllegroAuctionHasOrder Clone of current object.
* @throws PropelException
*/
public function copy($deepCopy = false)
{
// we use get_class(), because this might be a subclass
$clazz = get_class($this);
$copyObj = new $clazz();
$this->copyInto($copyObj, $deepCopy);
return $copyObj;
}
/**
* Returns a peer instance associated with this om.
*
* @return string Peer class name
*/
public function getPeer()
{
return 'AllegroAuctionHasOrderPeer';
}
/**
* Declares an association between this object and a Order object.
*
* @param Order $v
* @return void
* @throws PropelException
*/
public function setOrder($v)
{
if ($v === null) {
$this->setOrderId(NULL);
} else {
$this->setOrderId($v->getId());
}
$this->aOrder = $v;
}
/**
* Get the associated Order object
*
* @param Connection Optional Connection object.
* @return Order The associated Order object.
* @throws PropelException
*/
public function getOrder($con = null)
{
if ($this->aOrder === null && ($this->order_id !== null)) {
// include the related Peer class
$this->aOrder = OrderPeer::retrieveByPK($this->order_id, $con);
/* The following can be used instead of the line above to
guarantee the related object contains a reference
to this object, but this level of coupling
may be undesirable in many circumstances.
As it can lead to a db query with many results that may
never be used.
$obj = OrderPeer::retrieveByPK($this->order_id, $con);
$obj->addOrders($this);
*/
}
return $this->aOrder;
}
public function getDispatcher()
{
if (null === self::$dispatcher)
{
self::$dispatcher = stEventDispatcher::getInstance();
}
return self::$dispatcher;
}
public function __call($method, $arguments)
{
$event = $this->getDispatcher()->notifyUntil(new sfEvent($this, 'AllegroAuctionHasOrder.' . $method, array('arguments' => $arguments, 'method' => $method)));
if ($event->isProcessed())
{
return $event->getReturnValue();
}
if (!$callable = sfMixer::getCallable('BaseAllegroAuctionHasOrder:'.$method))
{
throw new sfException(sprintf('Call to undefined method BaseAllegroAuctionHasOrder::%s', $method));
}
array_unshift($arguments, $this);
return call_user_func_array($callable, $arguments);
}
} // BaseAllegroAuctionHasOrder

View File

@@ -0,0 +1,846 @@
<?php
/**
* Base static class for performing query and update operations on the 'st_allegro_auction_has_order' table.
*
*
*
* @package plugins.stAllegroPlugin.lib.model.om
*/
abstract class BaseAllegroAuctionHasOrderPeer {
/** the default database name for this class */
const DATABASE_NAME = 'propel';
/** the table name for this class */
const TABLE_NAME = 'st_allegro_auction_has_order';
/** A class that can be returned by this peer. */
const CLASS_DEFAULT = 'plugins.stAllegroPlugin.lib.model.AllegroAuctionHasOrder';
/** The total number of columns. */
const NUM_COLUMNS = 4;
/** The number of lazy-loaded columns. */
const NUM_LAZY_LOAD_COLUMNS = 0;
/** the column name for the TRANS_ID field */
const TRANS_ID = 'st_allegro_auction_has_order.TRANS_ID';
/** the column name for the ALLEGRO_AUCTION_ID field */
const ALLEGRO_AUCTION_ID = 'st_allegro_auction_has_order.ALLEGRO_AUCTION_ID';
/** the column name for the ORDER_ID field */
const ORDER_ID = 'st_allegro_auction_has_order.ORDER_ID';
/** the column name for the ALLEGRO_USER_ID field */
const ALLEGRO_USER_ID = 'st_allegro_auction_has_order.ALLEGRO_USER_ID';
/** The PHP to DB Name Mapping */
private static $phpNameMap = null;
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
private static $fieldNames = array (
BasePeer::TYPE_PHPNAME => array ('TransId', 'AllegroAuctionId', 'OrderId', 'AllegroUserId', ),
BasePeer::TYPE_COLNAME => array (AllegroAuctionHasOrderPeer::TRANS_ID, AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID, AllegroAuctionHasOrderPeer::ORDER_ID, AllegroAuctionHasOrderPeer::ALLEGRO_USER_ID, ),
BasePeer::TYPE_FIELDNAME => array ('trans_id', 'allegro_auction_id', 'order_id', 'allegro_user_id', ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, )
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
*/
private static $fieldKeys = array (
BasePeer::TYPE_PHPNAME => array ('TransId' => 0, 'AllegroAuctionId' => 1, 'OrderId' => 2, 'AllegroUserId' => 3, ),
BasePeer::TYPE_COLNAME => array (AllegroAuctionHasOrderPeer::TRANS_ID => 0, AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID => 1, AllegroAuctionHasOrderPeer::ORDER_ID => 2, AllegroAuctionHasOrderPeer::ALLEGRO_USER_ID => 3, ),
BasePeer::TYPE_FIELDNAME => array ('trans_id' => 0, 'allegro_auction_id' => 1, 'order_id' => 2, 'allegro_user_id' => 3, ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, )
);
protected static $hydrateMethod = null;
protected static $postHydrateMethod = null;
public static function setHydrateMethod($callback)
{
self::$hydrateMethod = $callback;
}
public static function setPostHydrateMethod($callback)
{
self::$postHydrateMethod = $callback;
}
/**
* @return MapBuilder the map builder for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getMapBuilder()
{
return BasePeer::getMapBuilder('plugins.stAllegroPlugin.lib.model.map.AllegroAuctionHasOrderMapBuilder');
}
/**
* Gets a map (hash) of PHP names to DB column names.
*
* @return array The PHP to DB name map for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @deprecated Use the getFieldNames() and translateFieldName() methods instead of this.
*/
public static function getPhpNameMap()
{
if (self::$phpNameMap === null) {
$map = AllegroAuctionHasOrderPeer::getTableMap();
$columns = $map->getColumns();
$nameMap = array();
foreach ($columns as $column) {
$nameMap[$column->getPhpName()] = $column->getColumnName();
}
self::$phpNameMap = $nameMap;
}
return self::$phpNameMap;
}
/**
* Translates a fieldname to another type
*
* @param string $name field name
* @param string $fromType One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @param string $toType One of the class type constants
* @return string translated name of the field.
*/
static public function translateFieldName($name, $fromType, $toType)
{
$toNames = self::getFieldNames($toType);
$key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null;
if ($key === null) {
throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true));
}
return $toNames[$key];
}
/**
* Returns an array of of field names.
*
* @param string $type The type of fieldnames to return:
* One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return array A list of field names
*/
static public function getFieldNames($type = BasePeer::TYPE_PHPNAME)
{
if (!array_key_exists($type, self::$fieldNames)) {
throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.');
}
return self::$fieldNames[$type];
}
/**
* Convenience method which changes table.column to alias.column.
*
* Using this method you can maintain SQL abstraction while using column aliases.
* <code>
* $c->addAlias("alias1", TablePeer::TABLE_NAME);
* $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
* </code>
* @param string $alias The alias for the current table.
* @param string $column The column name for current table. (i.e. AllegroAuctionHasOrderPeer::COLUMN_NAME).
* @return string
*/
public static function alias($alias, $column)
{
return str_replace(AllegroAuctionHasOrderPeer::TABLE_NAME.'.', $alias.'.', $column);
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param criteria object containing the columns to add.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns(Criteria $criteria)
{
$criteria->addSelectColumn(AllegroAuctionHasOrderPeer::TRANS_ID);
$criteria->addSelectColumn(AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID);
$criteria->addSelectColumn(AllegroAuctionHasOrderPeer::ORDER_ID);
$criteria->addSelectColumn(AllegroAuctionHasOrderPeer::ALLEGRO_USER_ID);
if (stEventDispatcher::getInstance()->getListeners('AllegroAuctionHasOrderPeer.postAddSelectColumns')) {
stEventDispatcher::getInstance()->notify(new sfEvent($criteria, 'AllegroAuctionHasOrderPeer.postAddSelectColumns'));
}
}
const COUNT = 'COUNT(st_allegro_auction_has_order.TRANS_ID)';
const COUNT_DISTINCT = 'COUNT(DISTINCT st_allegro_auction_has_order.TRANS_ID)';
/**
* Returns the number of rows matching criteria.
*
* @param Criteria $criteria
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCount(Criteria $criteria, $distinct = false, $con = null)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(AllegroAuctionHasOrderPeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(AllegroAuctionHasOrderPeer::COUNT);
}
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$rs = AllegroAuctionHasOrderPeer::doSelectRS($criteria, $con);
if ($rs->next()) {
return $rs->getInt(1);
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Method to select one object from the DB.
*
* @param Criteria $criteria object used to create the SELECT statement.
* @param Connection $con
* @return AllegroAuctionHasOrder
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectOne(Criteria $criteria, $con = null)
{
$critcopy = clone $criteria;
$critcopy->setLimit(1);
$objects = AllegroAuctionHasOrderPeer::doSelect($critcopy, $con);
if ($objects) {
return $objects[0];
}
return null;
}
/**
* Method to do selects.
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con
* @return AllegroAuctionHasOrder[]
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelect(Criteria $criteria, $con = null)
{
return AllegroAuctionHasOrderPeer::populateObjects(AllegroAuctionHasOrderPeer::doSelectRS($criteria, $con));
}
/**
* Prepares the Criteria object and uses the parent doSelect()
* method to get a ResultSet.
*
* Use this method directly if you want to just get the resultset
* (instead of an array of objects).
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return ResultSet The resultset object with numerically-indexed fields.
* @see BasePeer::doSelect()
*/
public static function doSelectRS(Criteria $criteria, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if (!$criteria->getSelectColumns()) {
$criteria = clone $criteria;
AllegroAuctionHasOrderPeer::addSelectColumns($criteria);
}
if (stEventDispatcher::getInstance()->getListeners('BasePeer.preDoSelectRs')) {
stEventDispatcher::getInstance()->notify(new sfEvent($criteria, 'BasePeer.preDoSelectRs'));
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
// BasePeer returns a Creole ResultSet, set to return
// rows indexed numerically.
$rs = BasePeer::doSelect($criteria, $con);
if (stEventDispatcher::getInstance()->getListeners('BasePeer.postDoSelectRs')) {
stEventDispatcher::getInstance()->notify(new sfEvent($rs, 'BasePeer.postDoSelectRs'));
}
return $rs;
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects(ResultSet $rs)
{
if (self::$hydrateMethod)
{
return call_user_func(self::$hydrateMethod, $rs);
}
$results = array();
// set the class once to avoid overhead in the loop
$cls = AllegroAuctionHasOrderPeer::getOMClass();
$cls = Propel::import($cls);
// populate the object(s)
while($rs->next()) {
$obj = new $cls();
$obj->hydrate($rs);
$results[] = self::$postHydrateMethod ? call_user_func(self::$postHydrateMethod, $obj) : $obj;
}
return $results;
}
/**
* Returns the number of rows matching criteria, joining the related Order table
*
* @param Criteria $c
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCountJoinOrder(Criteria $criteria, $distinct = false, $con = null)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(AllegroAuctionHasOrderPeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(AllegroAuctionHasOrderPeer::COUNT);
}
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$criteria->addJoin(AllegroAuctionHasOrderPeer::ORDER_ID, OrderPeer::ID);
$rs = AllegroAuctionHasOrderPeer::doSelectRS($criteria, $con);
if ($rs->next()) {
return $rs->getInt(1);
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Selects a collection of AllegroAuctionHasOrder objects pre-filled with their Order objects.
*
* @return AllegroAuctionHasOrder[] Array of AllegroAuctionHasOrder objects.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectJoinOrder(Criteria $c, $con = null)
{
$c = clone $c;
// Set the correct dbName if it has not been overridden
if ($c->getDbName() == Propel::getDefaultDB()) {
$c->setDbName(self::DATABASE_NAME);
}
AllegroAuctionHasOrderPeer::addSelectColumns($c);
OrderPeer::addSelectColumns($c);
$c->addJoin(AllegroAuctionHasOrderPeer::ORDER_ID, OrderPeer::ID);
$rs = AllegroAuctionHasOrderPeer::doSelectRs($c, $con);
if (self::$hydrateMethod)
{
return call_user_func(self::$hydrateMethod, $rs);
}
$results = array();
while($rs->next()) {
$obj1 = new AllegroAuctionHasOrder();
$startcol = $obj1->hydrate($rs);
if ($obj1->getOrderId())
{
$obj2 = new Order();
$obj2->hydrate($rs, $startcol);
$obj2->addAllegroAuctionHasOrder($obj1);
}
$results[] = self::$postHydrateMethod ? call_user_func(self::$postHydrateMethod, $obj1) : $obj1;;
}
return $results;
}
/**
* Returns the number of rows matching criteria, joining all related tables
*
* @param Criteria $c
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCountJoinAll(Criteria $criteria, $distinct = false, $con = null)
{
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(AllegroAuctionHasOrderPeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(AllegroAuctionHasOrderPeer::COUNT);
}
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$criteria->addJoin(AllegroAuctionHasOrderPeer::ORDER_ID, OrderPeer::ID);
$rs = AllegroAuctionHasOrderPeer::doSelectRS($criteria, $con);
if ($rs->next()) {
return $rs->getInt(1);
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Selects a collection of AllegroAuctionHasOrder objects pre-filled with all related objects.
*
* @return AllegroAuctionHasOrder[]
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectJoinAll(Criteria $c, $con = null)
{
$c = clone $c;
// Set the correct dbName if it has not been overridden
if ($c->getDbName() == Propel::getDefaultDB()) {
$c->setDbName(self::DATABASE_NAME);
}
AllegroAuctionHasOrderPeer::addSelectColumns($c);
$startcol2 = (AllegroAuctionHasOrderPeer::NUM_COLUMNS - AllegroAuctionHasOrderPeer::NUM_LAZY_LOAD_COLUMNS) + 1;
OrderPeer::addSelectColumns($c);
$startcol3 = $startcol2 + OrderPeer::NUM_COLUMNS;
$c->addJoin(AllegroAuctionHasOrderPeer::ORDER_ID, OrderPeer::ID);
$rs = BasePeer::doSelect($c, $con);
if (self::$hydrateMethod)
{
return call_user_func(self::$hydrateMethod, $rs);
}
$results = array();
while($rs->next()) {
$omClass = AllegroAuctionHasOrderPeer::getOMClass();
$cls = Propel::import($omClass);
$obj1 = new $cls();
$obj1->hydrate($rs);
// Add objects for joined Order rows
$omClass = OrderPeer::getOMClass();
$cls = Propel::import($omClass);
$obj2 = new $cls();
$obj2->hydrate($rs, $startcol2);
$newObject = true;
for ($j=0, $resCount=count($results); $j < $resCount; $j++) {
$temp_obj1 = $results[$j];
$temp_obj2 = $temp_obj1->getOrder(); // CHECKME
if (null !== $temp_obj2 && $temp_obj2->getPrimaryKey() === $obj2->getPrimaryKey()) {
$newObject = false;
$temp_obj2->addAllegroAuctionHasOrder($obj1); // CHECKME
break;
}
}
if ($newObject) {
$obj2->initAllegroAuctionHasOrders();
$obj2->addAllegroAuctionHasOrder($obj1);
}
$results[] = self::$postHydrateMethod ? call_user_func(self::$postHydrateMethod, $obj1) : $obj1;
}
return $results;
}
/**
* Returns the TableMap related to this peer.
* This method is not needed for general use but a specific application could have a need.
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap()
{
return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME);
}
/**
* The class that the Peer will make instances of.
*
* This uses a dot-path notation which is tranalted into a path
* relative to a location on the PHP include_path.
* (e.g. path.to.MyClass -> 'path/to/MyClass.php')
*
* @return string path.to.ClassName
*/
public static function getOMClass()
{
return AllegroAuctionHasOrderPeer::CLASS_DEFAULT;
}
/**
* Method perform an INSERT on the database, given a AllegroAuctionHasOrder or Criteria object.
*
* @param mixed $values Criteria or AllegroAuctionHasOrder object containing data that is used to create the INSERT statement.
* @param Connection $con the connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert($values, $con = null)
{
foreach (sfMixer::getCallables('BaseAllegroAuctionHasOrderPeer:doInsert:pre') as $callable)
{
$ret = call_user_func($callable, 'BaseAllegroAuctionHasOrderPeer', $values, $con);
if (false !== $ret)
{
return $ret;
}
}
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} else {
$criteria = $values->buildCriteria(); // build Criteria from AllegroAuctionHasOrder object
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
try {
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
$con->begin();
$pk = BasePeer::doInsert($criteria, $con);
$con->commit();
} catch(PropelException $e) {
$con->rollback();
throw $e;
}
foreach (sfMixer::getCallables('BaseAllegroAuctionHasOrderPeer:doInsert:post') as $callable)
{
call_user_func($callable, 'BaseAllegroAuctionHasOrderPeer', $values, $con, $pk);
}
return $pk;
}
/**
* Method perform an UPDATE on the database, given a AllegroAuctionHasOrder or Criteria object.
*
* @param mixed $values Criteria or AllegroAuctionHasOrder object containing data that is used to create the UPDATE statement.
* @param Connection $con The connection to use (specify Connection object to exert more control over transactions).
* @return int The number of affected rows (if supported by underlying database driver).
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doUpdate($values, $con = null)
{
foreach (sfMixer::getCallables('BaseAllegroAuctionHasOrderPeer:doUpdate:pre') as $callable)
{
$ret = call_user_func($callable, 'BaseAllegroAuctionHasOrderPeer', $values, $con);
if (false !== $ret)
{
return $ret;
}
}
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$selectCriteria = new Criteria(self::DATABASE_NAME);
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
$comparison = $criteria->getComparison(AllegroAuctionHasOrderPeer::TRANS_ID);
$selectCriteria->add(AllegroAuctionHasOrderPeer::TRANS_ID, $criteria->remove(AllegroAuctionHasOrderPeer::TRANS_ID), $comparison);
$comparison = $criteria->getComparison(AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID);
$selectCriteria->add(AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID, $criteria->remove(AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID), $comparison);
$comparison = $criteria->getComparison(AllegroAuctionHasOrderPeer::ORDER_ID);
$selectCriteria->add(AllegroAuctionHasOrderPeer::ORDER_ID, $criteria->remove(AllegroAuctionHasOrderPeer::ORDER_ID), $comparison);
} else { // $values is AllegroAuctionHasOrder object
$criteria = $values->buildCriteria(); // gets full criteria
$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
}
// set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
$ret = BasePeer::doUpdate($selectCriteria, $criteria, $con);
foreach (sfMixer::getCallables('BaseAllegroAuctionHasOrderPeer:doUpdate:post') as $callable)
{
call_user_func($callable, 'BaseAllegroAuctionHasOrderPeer', $values, $con, $ret);
}
return $ret;
}
/**
* Method to DELETE all rows from the st_allegro_auction_has_order table.
*
* @return int The number of affected rows (if supported by underlying database driver).
*/
public static function doDeleteAll($con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDeleteAll(AllegroAuctionHasOrderPeer::TABLE_NAME, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Method perform a DELETE on the database, given a AllegroAuctionHasOrder or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or AllegroAuctionHasOrder object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param Connection $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(AllegroAuctionHasOrderPeer::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} elseif ($values instanceof AllegroAuctionHasOrder) {
$criteria = $values->buildPkeyCriteria();
} else {
// it must be the primary key
$criteria = new Criteria(self::DATABASE_NAME);
// primary key is composite; we therefore, expect
// the primary key passed to be an array of pkey
// values
if(count($values) == count($values, COUNT_RECURSIVE))
{
// array is not multi-dimensional
$values = array($values);
}
$vals = array();
foreach($values as $value)
{
$vals[0][] = $value[0];
$vals[1][] = $value[1];
$vals[2][] = $value[2];
}
$criteria->add(AllegroAuctionHasOrderPeer::TRANS_ID, $vals[0], Criteria::IN);
$criteria->add(AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID, $vals[1], Criteria::IN);
$criteria->add(AllegroAuctionHasOrderPeer::ORDER_ID, $vals[2], Criteria::IN);
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDelete($criteria, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Validates all modified columns of given AllegroAuctionHasOrder object.
* If parameter $columns is either a single column name or an array of column names
* than only those columns are validated.
*
* NOTICE: This does not apply to primary or foreign keys for now.
*
* @param AllegroAuctionHasOrder $obj The object to validate.
* @param mixed $cols Column name or array of column names.
*
* @return mixed TRUE if all columns are valid or the error message of the first invalid column.
*/
public static function doValidate(AllegroAuctionHasOrder $obj, $cols = null)
{
$columns = array();
if ($cols) {
$dbMap = Propel::getDatabaseMap(AllegroAuctionHasOrderPeer::DATABASE_NAME);
$tableMap = $dbMap->getTable(AllegroAuctionHasOrderPeer::TABLE_NAME);
if (! is_array($cols)) {
$cols = array($cols);
}
foreach($cols as $colName) {
if ($tableMap->containsColumn($colName)) {
$get = 'get' . $tableMap->getColumn($colName)->getPhpName();
$columns[$colName] = $obj->$get();
}
}
} else {
}
$res = BasePeer::doValidate(AllegroAuctionHasOrderPeer::DATABASE_NAME, AllegroAuctionHasOrderPeer::TABLE_NAME, $columns);
if ($res !== true) {
$request = sfContext::getInstance()->getRequest();
foreach ($res as $failed) {
$col = AllegroAuctionHasOrderPeer::translateFieldname($failed->getColumn(), BasePeer::TYPE_COLNAME, BasePeer::TYPE_PHPNAME);
$request->setError($col, $failed->getMessage());
}
}
return $res;
}
/**
* Retrieve object using using composite pkey values.
* @param string $trans_id
@param string $allegro_auction_id
@param int $order_id
* @param Connection $con
* @return AllegroAuctionHasOrder
*/
public static function retrieveByPK( $trans_id, $allegro_auction_id, $order_id, $con = null) {
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$criteria = new Criteria();
$criteria->add(AllegroAuctionHasOrderPeer::TRANS_ID, $trans_id);
$criteria->add(AllegroAuctionHasOrderPeer::ALLEGRO_AUCTION_ID, $allegro_auction_id);
$criteria->add(AllegroAuctionHasOrderPeer::ORDER_ID, $order_id);
$v = AllegroAuctionHasOrderPeer::doSelect($criteria, $con);
return !empty($v) ? $v[0] : null;
}
} // BaseAllegroAuctionHasOrderPeer
// static code to register the map builder for this Peer with the main Propel class
if (Propel::isInit()) {
// the MapBuilder classes register themselves with Propel during initialization
// so we need to load them here.
try {
BaseAllegroAuctionHasOrderPeer::getMapBuilder();
} catch (Exception $e) {
Propel::log('Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR);
}
} else {
// even if Propel is not yet initialized, the map builder class can be registered
// now and then it will be loaded when Propel initializes.
Propel::registerMapBuilder('plugins.stAllegroPlugin.lib.model.map.AllegroAuctionHasOrderMapBuilder');
}

View File

@@ -0,0 +1,896 @@
<?php
/**
* Base static class for performing query and update operations on the 'st_allegro_auction' table.
*
*
*
* @package plugins.stAllegroPlugin.lib.model.om
*/
abstract class BaseAllegroAuctionPeer {
/** the default database name for this class */
const DATABASE_NAME = 'propel';
/** the table name for this class */
const TABLE_NAME = 'st_allegro_auction';
/** A class that can be returned by this peer. */
const CLASS_DEFAULT = 'plugins.stAllegroPlugin.lib.model.AllegroAuction';
/** The total number of columns. */
const NUM_COLUMNS = 13;
/** The number of lazy-loaded columns. */
const NUM_LAZY_LOAD_COLUMNS = 0;
/** the column name for the CREATED_AT field */
const CREATED_AT = 'st_allegro_auction.CREATED_AT';
/** the column name for the UPDATED_AT field */
const UPDATED_AT = 'st_allegro_auction.UPDATED_AT';
/** the column name for the ID field */
const ID = 'st_allegro_auction.ID';
/** the column name for the PRODUCT_ID field */
const PRODUCT_ID = 'st_allegro_auction.PRODUCT_ID';
/** the column name for the PRODUCT_OPTIONS field */
const PRODUCT_OPTIONS = 'st_allegro_auction.PRODUCT_OPTIONS';
/** the column name for the REQUIRES_SYNC field */
const REQUIRES_SYNC = 'st_allegro_auction.REQUIRES_SYNC';
/** the column name for the ALLOW_SYNC field */
const ALLOW_SYNC = 'st_allegro_auction.ALLOW_SYNC';
/** the column name for the SITE field */
const SITE = 'st_allegro_auction.SITE';
/** the column name for the NAME field */
const NAME = 'st_allegro_auction.NAME';
/** the column name for the AUCTION_ID field */
const AUCTION_ID = 'st_allegro_auction.AUCTION_ID';
/** the column name for the ENDED field */
const ENDED = 'st_allegro_auction.ENDED';
/** the column name for the ENDED_AT field */
const ENDED_AT = 'st_allegro_auction.ENDED_AT';
/** the column name for the COMMANDS field */
const COMMANDS = 'st_allegro_auction.COMMANDS';
/** The PHP to DB Name Mapping */
private static $phpNameMap = null;
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
private static $fieldNames = array (
BasePeer::TYPE_PHPNAME => array ('CreatedAt', 'UpdatedAt', 'Id', 'ProductId', 'ProductOptions', 'RequiresSync', 'AllowSync', 'Site', 'Name', 'AuctionId', 'Ended', 'EndedAt', 'Commands', ),
BasePeer::TYPE_COLNAME => array (AllegroAuctionPeer::CREATED_AT, AllegroAuctionPeer::UPDATED_AT, AllegroAuctionPeer::ID, AllegroAuctionPeer::PRODUCT_ID, AllegroAuctionPeer::PRODUCT_OPTIONS, AllegroAuctionPeer::REQUIRES_SYNC, AllegroAuctionPeer::ALLOW_SYNC, AllegroAuctionPeer::SITE, AllegroAuctionPeer::NAME, AllegroAuctionPeer::AUCTION_ID, AllegroAuctionPeer::ENDED, AllegroAuctionPeer::ENDED_AT, AllegroAuctionPeer::COMMANDS, ),
BasePeer::TYPE_FIELDNAME => array ('created_at', 'updated_at', 'id', 'product_id', 'product_options', 'requires_sync', 'allow_sync', 'site', 'name', 'auction_id', 'ended', 'ended_at', 'commands', ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, )
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
*/
private static $fieldKeys = array (
BasePeer::TYPE_PHPNAME => array ('CreatedAt' => 0, 'UpdatedAt' => 1, 'Id' => 2, 'ProductId' => 3, 'ProductOptions' => 4, 'RequiresSync' => 5, 'AllowSync' => 6, 'Site' => 7, 'Name' => 8, 'AuctionId' => 9, 'Ended' => 10, 'EndedAt' => 11, 'Commands' => 12, ),
BasePeer::TYPE_COLNAME => array (AllegroAuctionPeer::CREATED_AT => 0, AllegroAuctionPeer::UPDATED_AT => 1, AllegroAuctionPeer::ID => 2, AllegroAuctionPeer::PRODUCT_ID => 3, AllegroAuctionPeer::PRODUCT_OPTIONS => 4, AllegroAuctionPeer::REQUIRES_SYNC => 5, AllegroAuctionPeer::ALLOW_SYNC => 6, AllegroAuctionPeer::SITE => 7, AllegroAuctionPeer::NAME => 8, AllegroAuctionPeer::AUCTION_ID => 9, AllegroAuctionPeer::ENDED => 10, AllegroAuctionPeer::ENDED_AT => 11, AllegroAuctionPeer::COMMANDS => 12, ),
BasePeer::TYPE_FIELDNAME => array ('created_at' => 0, 'updated_at' => 1, 'id' => 2, 'product_id' => 3, 'product_options' => 4, 'requires_sync' => 5, 'allow_sync' => 6, 'site' => 7, 'name' => 8, 'auction_id' => 9, 'ended' => 10, 'ended_at' => 11, 'commands' => 12, ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, )
);
protected static $hydrateMethod = null;
protected static $postHydrateMethod = null;
public static function setHydrateMethod($callback)
{
self::$hydrateMethod = $callback;
}
public static function setPostHydrateMethod($callback)
{
self::$postHydrateMethod = $callback;
}
/**
* @return MapBuilder the map builder for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getMapBuilder()
{
return BasePeer::getMapBuilder('plugins.stAllegroPlugin.lib.model.map.AllegroAuctionMapBuilder');
}
/**
* Gets a map (hash) of PHP names to DB column names.
*
* @return array The PHP to DB name map for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @deprecated Use the getFieldNames() and translateFieldName() methods instead of this.
*/
public static function getPhpNameMap()
{
if (self::$phpNameMap === null) {
$map = AllegroAuctionPeer::getTableMap();
$columns = $map->getColumns();
$nameMap = array();
foreach ($columns as $column) {
$nameMap[$column->getPhpName()] = $column->getColumnName();
}
self::$phpNameMap = $nameMap;
}
return self::$phpNameMap;
}
/**
* Translates a fieldname to another type
*
* @param string $name field name
* @param string $fromType One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @param string $toType One of the class type constants
* @return string translated name of the field.
*/
static public function translateFieldName($name, $fromType, $toType)
{
$toNames = self::getFieldNames($toType);
$key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null;
if ($key === null) {
throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true));
}
return $toNames[$key];
}
/**
* Returns an array of of field names.
*
* @param string $type The type of fieldnames to return:
* One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return array A list of field names
*/
static public function getFieldNames($type = BasePeer::TYPE_PHPNAME)
{
if (!array_key_exists($type, self::$fieldNames)) {
throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.');
}
return self::$fieldNames[$type];
}
/**
* Convenience method which changes table.column to alias.column.
*
* Using this method you can maintain SQL abstraction while using column aliases.
* <code>
* $c->addAlias("alias1", TablePeer::TABLE_NAME);
* $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
* </code>
* @param string $alias The alias for the current table.
* @param string $column The column name for current table. (i.e. AllegroAuctionPeer::COLUMN_NAME).
* @return string
*/
public static function alias($alias, $column)
{
return str_replace(AllegroAuctionPeer::TABLE_NAME.'.', $alias.'.', $column);
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param criteria object containing the columns to add.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns(Criteria $criteria)
{
$criteria->addSelectColumn(AllegroAuctionPeer::CREATED_AT);
$criteria->addSelectColumn(AllegroAuctionPeer::UPDATED_AT);
$criteria->addSelectColumn(AllegroAuctionPeer::ID);
$criteria->addSelectColumn(AllegroAuctionPeer::PRODUCT_ID);
$criteria->addSelectColumn(AllegroAuctionPeer::PRODUCT_OPTIONS);
$criteria->addSelectColumn(AllegroAuctionPeer::REQUIRES_SYNC);
$criteria->addSelectColumn(AllegroAuctionPeer::ALLOW_SYNC);
$criteria->addSelectColumn(AllegroAuctionPeer::SITE);
$criteria->addSelectColumn(AllegroAuctionPeer::NAME);
$criteria->addSelectColumn(AllegroAuctionPeer::AUCTION_ID);
$criteria->addSelectColumn(AllegroAuctionPeer::ENDED);
$criteria->addSelectColumn(AllegroAuctionPeer::ENDED_AT);
$criteria->addSelectColumn(AllegroAuctionPeer::COMMANDS);
if (stEventDispatcher::getInstance()->getListeners('AllegroAuctionPeer.postAddSelectColumns')) {
stEventDispatcher::getInstance()->notify(new sfEvent($criteria, 'AllegroAuctionPeer.postAddSelectColumns'));
}
}
const COUNT = 'COUNT(st_allegro_auction.ID)';
const COUNT_DISTINCT = 'COUNT(DISTINCT st_allegro_auction.ID)';
/**
* Returns the number of rows matching criteria.
*
* @param Criteria $criteria
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCount(Criteria $criteria, $distinct = false, $con = null)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(AllegroAuctionPeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(AllegroAuctionPeer::COUNT);
}
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$rs = AllegroAuctionPeer::doSelectRS($criteria, $con);
if ($rs->next()) {
return $rs->getInt(1);
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Method to select one object from the DB.
*
* @param Criteria $criteria object used to create the SELECT statement.
* @param Connection $con
* @return AllegroAuction
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectOne(Criteria $criteria, $con = null)
{
$critcopy = clone $criteria;
$critcopy->setLimit(1);
$objects = AllegroAuctionPeer::doSelect($critcopy, $con);
if ($objects) {
return $objects[0];
}
return null;
}
/**
* Method to do selects.
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con
* @return AllegroAuction[]
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelect(Criteria $criteria, $con = null)
{
return AllegroAuctionPeer::populateObjects(AllegroAuctionPeer::doSelectRS($criteria, $con));
}
/**
* Prepares the Criteria object and uses the parent doSelect()
* method to get a ResultSet.
*
* Use this method directly if you want to just get the resultset
* (instead of an array of objects).
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return ResultSet The resultset object with numerically-indexed fields.
* @see BasePeer::doSelect()
*/
public static function doSelectRS(Criteria $criteria, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if (!$criteria->getSelectColumns()) {
$criteria = clone $criteria;
AllegroAuctionPeer::addSelectColumns($criteria);
}
if (stEventDispatcher::getInstance()->getListeners('BasePeer.preDoSelectRs')) {
stEventDispatcher::getInstance()->notify(new sfEvent($criteria, 'BasePeer.preDoSelectRs'));
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
// BasePeer returns a Creole ResultSet, set to return
// rows indexed numerically.
$rs = BasePeer::doSelect($criteria, $con);
if (stEventDispatcher::getInstance()->getListeners('BasePeer.postDoSelectRs')) {
stEventDispatcher::getInstance()->notify(new sfEvent($rs, 'BasePeer.postDoSelectRs'));
}
return $rs;
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects(ResultSet $rs)
{
if (self::$hydrateMethod)
{
return call_user_func(self::$hydrateMethod, $rs);
}
$results = array();
// set the class once to avoid overhead in the loop
$cls = AllegroAuctionPeer::getOMClass();
$cls = Propel::import($cls);
// populate the object(s)
while($rs->next()) {
$obj = new $cls();
$obj->hydrate($rs);
$results[] = self::$postHydrateMethod ? call_user_func(self::$postHydrateMethod, $obj) : $obj;
}
return $results;
}
/**
* Returns the number of rows matching criteria, joining the related Product table
*
* @param Criteria $c
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCountJoinProduct(Criteria $criteria, $distinct = false, $con = null)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(AllegroAuctionPeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(AllegroAuctionPeer::COUNT);
}
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$criteria->addJoin(AllegroAuctionPeer::PRODUCT_ID, ProductPeer::ID);
$rs = AllegroAuctionPeer::doSelectRS($criteria, $con);
if ($rs->next()) {
return $rs->getInt(1);
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Selects a collection of AllegroAuction objects pre-filled with their Product objects.
*
* @return AllegroAuction[] Array of AllegroAuction objects.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectJoinProduct(Criteria $c, $con = null)
{
$c = clone $c;
// Set the correct dbName if it has not been overridden
if ($c->getDbName() == Propel::getDefaultDB()) {
$c->setDbName(self::DATABASE_NAME);
}
AllegroAuctionPeer::addSelectColumns($c);
ProductPeer::addSelectColumns($c);
$c->addJoin(AllegroAuctionPeer::PRODUCT_ID, ProductPeer::ID);
$rs = AllegroAuctionPeer::doSelectRs($c, $con);
if (self::$hydrateMethod)
{
return call_user_func(self::$hydrateMethod, $rs);
}
$results = array();
while($rs->next()) {
$obj1 = new AllegroAuction();
$startcol = $obj1->hydrate($rs);
if ($obj1->getProductId())
{
$obj2 = new Product();
$obj2->hydrate($rs, $startcol);
$obj2->addAllegroAuction($obj1);
}
$results[] = self::$postHydrateMethod ? call_user_func(self::$postHydrateMethod, $obj1) : $obj1;;
}
return $results;
}
/**
* Returns the number of rows matching criteria, joining all related tables
*
* @param Criteria $c
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCountJoinAll(Criteria $criteria, $distinct = false, $con = null)
{
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(AllegroAuctionPeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(AllegroAuctionPeer::COUNT);
}
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$criteria->addJoin(AllegroAuctionPeer::PRODUCT_ID, ProductPeer::ID);
$rs = AllegroAuctionPeer::doSelectRS($criteria, $con);
if ($rs->next()) {
return $rs->getInt(1);
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Selects a collection of AllegroAuction objects pre-filled with all related objects.
*
* @return AllegroAuction[]
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectJoinAll(Criteria $c, $con = null)
{
$c = clone $c;
// Set the correct dbName if it has not been overridden
if ($c->getDbName() == Propel::getDefaultDB()) {
$c->setDbName(self::DATABASE_NAME);
}
AllegroAuctionPeer::addSelectColumns($c);
$startcol2 = (AllegroAuctionPeer::NUM_COLUMNS - AllegroAuctionPeer::NUM_LAZY_LOAD_COLUMNS) + 1;
ProductPeer::addSelectColumns($c);
$startcol3 = $startcol2 + ProductPeer::NUM_COLUMNS;
$c->addJoin(AllegroAuctionPeer::PRODUCT_ID, ProductPeer::ID);
$rs = BasePeer::doSelect($c, $con);
if (self::$hydrateMethod)
{
return call_user_func(self::$hydrateMethod, $rs);
}
$results = array();
while($rs->next()) {
$omClass = AllegroAuctionPeer::getOMClass();
$cls = Propel::import($omClass);
$obj1 = new $cls();
$obj1->hydrate($rs);
// Add objects for joined Product rows
$omClass = ProductPeer::getOMClass();
$cls = Propel::import($omClass);
$obj2 = new $cls();
$obj2->hydrate($rs, $startcol2);
$newObject = true;
for ($j=0, $resCount=count($results); $j < $resCount; $j++) {
$temp_obj1 = $results[$j];
$temp_obj2 = $temp_obj1->getProduct(); // CHECKME
if (null !== $temp_obj2 && $temp_obj2->getPrimaryKey() === $obj2->getPrimaryKey()) {
$newObject = false;
$temp_obj2->addAllegroAuction($obj1); // CHECKME
break;
}
}
if ($newObject) {
$obj2->initAllegroAuctions();
$obj2->addAllegroAuction($obj1);
}
$results[] = self::$postHydrateMethod ? call_user_func(self::$postHydrateMethod, $obj1) : $obj1;
}
return $results;
}
/**
* Returns the TableMap related to this peer.
* This method is not needed for general use but a specific application could have a need.
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap()
{
return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME);
}
/**
* The class that the Peer will make instances of.
*
* This uses a dot-path notation which is tranalted into a path
* relative to a location on the PHP include_path.
* (e.g. path.to.MyClass -> 'path/to/MyClass.php')
*
* @return string path.to.ClassName
*/
public static function getOMClass()
{
return AllegroAuctionPeer::CLASS_DEFAULT;
}
/**
* Method perform an INSERT on the database, given a AllegroAuction or Criteria object.
*
* @param mixed $values Criteria or AllegroAuction object containing data that is used to create the INSERT statement.
* @param Connection $con the connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert($values, $con = null)
{
foreach (sfMixer::getCallables('BaseAllegroAuctionPeer:doInsert:pre') as $callable)
{
$ret = call_user_func($callable, 'BaseAllegroAuctionPeer', $values, $con);
if (false !== $ret)
{
return $ret;
}
}
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} else {
$criteria = $values->buildCriteria(); // build Criteria from AllegroAuction object
}
$criteria->remove(AllegroAuctionPeer::ID); // remove pkey col since this table uses auto-increment
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
try {
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
$con->begin();
$pk = BasePeer::doInsert($criteria, $con);
$con->commit();
} catch(PropelException $e) {
$con->rollback();
throw $e;
}
foreach (sfMixer::getCallables('BaseAllegroAuctionPeer:doInsert:post') as $callable)
{
call_user_func($callable, 'BaseAllegroAuctionPeer', $values, $con, $pk);
}
return $pk;
}
/**
* Method perform an UPDATE on the database, given a AllegroAuction or Criteria object.
*
* @param mixed $values Criteria or AllegroAuction object containing data that is used to create the UPDATE statement.
* @param Connection $con The connection to use (specify Connection object to exert more control over transactions).
* @return int The number of affected rows (if supported by underlying database driver).
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doUpdate($values, $con = null)
{
foreach (sfMixer::getCallables('BaseAllegroAuctionPeer:doUpdate:pre') as $callable)
{
$ret = call_user_func($callable, 'BaseAllegroAuctionPeer', $values, $con);
if (false !== $ret)
{
return $ret;
}
}
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$selectCriteria = new Criteria(self::DATABASE_NAME);
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
$comparison = $criteria->getComparison(AllegroAuctionPeer::ID);
$selectCriteria->add(AllegroAuctionPeer::ID, $criteria->remove(AllegroAuctionPeer::ID), $comparison);
} else { // $values is AllegroAuction object
$criteria = $values->buildCriteria(); // gets full criteria
$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
}
// set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
$ret = BasePeer::doUpdate($selectCriteria, $criteria, $con);
foreach (sfMixer::getCallables('BaseAllegroAuctionPeer:doUpdate:post') as $callable)
{
call_user_func($callable, 'BaseAllegroAuctionPeer', $values, $con, $ret);
}
return $ret;
}
/**
* Method to DELETE all rows from the st_allegro_auction table.
*
* @return int The number of affected rows (if supported by underlying database driver).
*/
public static function doDeleteAll($con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDeleteAll(AllegroAuctionPeer::TABLE_NAME, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Method perform a DELETE on the database, given a AllegroAuction or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or AllegroAuction object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param Connection $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(AllegroAuctionPeer::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} elseif ($values instanceof AllegroAuction) {
$criteria = $values->buildPkeyCriteria();
} else {
// it must be the primary key
$criteria = new Criteria(self::DATABASE_NAME);
$criteria->add(AllegroAuctionPeer::ID, (array) $values, Criteria::IN);
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDelete($criteria, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Validates all modified columns of given AllegroAuction object.
* If parameter $columns is either a single column name or an array of column names
* than only those columns are validated.
*
* NOTICE: This does not apply to primary or foreign keys for now.
*
* @param AllegroAuction $obj The object to validate.
* @param mixed $cols Column name or array of column names.
*
* @return mixed TRUE if all columns are valid or the error message of the first invalid column.
*/
public static function doValidate(AllegroAuction $obj, $cols = null)
{
$columns = array();
if ($cols) {
$dbMap = Propel::getDatabaseMap(AllegroAuctionPeer::DATABASE_NAME);
$tableMap = $dbMap->getTable(AllegroAuctionPeer::TABLE_NAME);
if (! is_array($cols)) {
$cols = array($cols);
}
foreach($cols as $colName) {
if ($tableMap->containsColumn($colName)) {
$get = 'get' . $tableMap->getColumn($colName)->getPhpName();
$columns[$colName] = $obj->$get();
}
}
} else {
}
$res = BasePeer::doValidate(AllegroAuctionPeer::DATABASE_NAME, AllegroAuctionPeer::TABLE_NAME, $columns);
if ($res !== true) {
$request = sfContext::getInstance()->getRequest();
foreach ($res as $failed) {
$col = AllegroAuctionPeer::translateFieldname($failed->getColumn(), BasePeer::TYPE_COLNAME, BasePeer::TYPE_PHPNAME);
$request->setError($col, $failed->getMessage());
}
}
return $res;
}
/**
* Retrieve a single object by pkey.
*
* @param mixed $pk the primary key.
* @param Connection $con the connection to use
* @return AllegroAuction
*/
public static function retrieveByPK($pk, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$criteria = new Criteria(AllegroAuctionPeer::DATABASE_NAME);
$criteria->add(AllegroAuctionPeer::ID, $pk);
$v = AllegroAuctionPeer::doSelect($criteria, $con);
return !empty($v) > 0 ? $v[0] : null;
}
/**
* Retrieve multiple objects by pkey.
*
* @param array $pks List of primary keys
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return AllegroAuction[]
*/
public static function retrieveByPKs($pks, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$objs = null;
if (empty($pks)) {
$objs = array();
} else {
$criteria = new Criteria();
$criteria->add(AllegroAuctionPeer::ID, $pks, Criteria::IN);
$objs = AllegroAuctionPeer::doSelect($criteria, $con);
}
return $objs;
}
} // BaseAllegroAuctionPeer
// static code to register the map builder for this Peer with the main Propel class
if (Propel::isInit()) {
// the MapBuilder classes register themselves with Propel during initialization
// so we need to load them here.
try {
BaseAllegroAuctionPeer::getMapBuilder();
} catch (Exception $e) {
Propel::log('Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR);
}
} else {
// even if Propel is not yet initialized, the map builder class can be registered
// now and then it will be loaded when Propel initializes.
Propel::registerMapBuilder('plugins.stAllegroPlugin.lib.model.map.AllegroAuctionMapBuilder');
}

View File

@@ -0,0 +1,748 @@
<?php
/**
* Base class that represents a row from the 'st_allegro_parcel_tracking_number_queue' table.
*
*
*
* @package plugins.stAllegroPlugin.lib.model.om
*/
abstract class BaseAllegroParcelTrackingNumberQueue extends BaseObject implements Persistent {
protected static $dispatcher = null;
/**
* The value for the created_at field.
* @var int
*/
protected $created_at;
/**
* The value for the order_id field.
* @var int
*/
protected $order_id;
/**
* @var Order
*/
protected $aOrder;
/**
* Flag to prevent endless save loop, if this object is referenced
* by another object which falls in this transaction.
* @var boolean
*/
protected $alreadyInSave = false;
/**
* Flag to prevent endless validation loop, if this object is referenced
* by another object which falls in this transaction.
* @var boolean
*/
protected $alreadyInValidation = false;
/**
* Get the [optionally formatted] [created_at] column value.
*
* @param string $format The date/time format string (either date()-style or strftime()-style).
* If format is NULL, then the integer unix timestamp will be returned.
* @return mixed Formatted date/time value as string or integer unix timestamp (if format is NULL).
* @throws PropelException - if unable to convert the date/time to timestamp.
*/
public function getCreatedAt($format = 'Y-m-d H:i:s')
{
if ($this->created_at === null || $this->created_at === '') {
return null;
} elseif (!is_int($this->created_at)) {
// a non-timestamp value was set externally, so we convert it
$ts = strtotime($this->created_at);
if ($ts === -1 || $ts === false) { // in PHP 5.1 return value changes to FALSE
throw new PropelException("Unable to parse value of [created_at] as date/time value: " . var_export($this->created_at, true));
}
} else {
$ts = $this->created_at;
}
if ($format === null) {
return $ts;
} elseif (strpos($format, '%') !== false) {
return strftime($format, $ts);
} else {
return date($format, $ts);
}
}
/**
* Get the [order_id] column value.
*
* @return int
*/
public function getOrderId()
{
return $this->order_id;
}
/**
* Set the value of [created_at] column.
*
* @param int $v new value
* @return void
*/
public function setCreatedAt($v)
{
if ($v !== null && !is_int($v)) {
$ts = strtotime($v);
if ($ts === -1 || $ts === false) { // in PHP 5.1 return value changes to FALSE
throw new PropelException("Unable to parse date/time value for [created_at] from input: " . var_export($v, true));
}
} else {
$ts = $v;
}
if ($this->created_at !== $ts) {
$this->created_at = $ts;
$this->modifiedColumns[] = AllegroParcelTrackingNumberQueuePeer::CREATED_AT;
}
} // setCreatedAt()
/**
* Set the value of [order_id] column.
*
* @param int $v new value
* @return void
*/
public function setOrderId($v)
{
if ($v !== null && !is_int($v) && is_numeric($v)) {
$v = (int) $v;
}
if ($this->order_id !== $v) {
$this->order_id = $v;
$this->modifiedColumns[] = AllegroParcelTrackingNumberQueuePeer::ORDER_ID;
}
if ($this->aOrder !== null && $this->aOrder->getId() !== $v) {
$this->aOrder = null;
}
} // setOrderId()
/**
* Hydrates (populates) the object variables with values from the database resultset.
*
* An offset (1-based "start column") is specified so that objects can be hydrated
* with a subset of the columns in the resultset rows. This is needed, for example,
* for results of JOIN queries where the resultset row includes columns from two or
* more tables.
*
* @param ResultSet $rs The ResultSet class with cursor advanced to desired record pos.
* @param int $startcol 1-based offset column which indicates which restultset column to start with.
* @return int next starting column
* @throws PropelException - Any caught Exception will be rewrapped as a PropelException.
*/
public function hydrate(ResultSet $rs, $startcol = 1)
{
try {
if ($this->getDispatcher()->getListeners('AllegroParcelTrackingNumberQueue.preHydrate')) {
$event = $this->getDispatcher()->notify(new sfEvent($this, 'AllegroParcelTrackingNumberQueue.preHydrate', array('resultset' => $rs, 'startcol' => $startcol)));
$startcol = $event['startcol'];
}
$this->created_at = $rs->getTimestamp($startcol + 0, null);
$this->order_id = $rs->getInt($startcol + 1);
$this->resetModified();
$this->setNew(false);
if ($this->getDispatcher()->getListeners('AllegroParcelTrackingNumberQueue.postHydrate')) {
$event = $this->getDispatcher()->notify(new sfEvent($this, 'AllegroParcelTrackingNumberQueue.postHydrate', array('resultset' => $rs, 'startcol' => $startcol + 2)));
return $event['startcol'];
}
// FIXME - using NUM_COLUMNS may be clearer.
return $startcol + 2; // 2 = AllegroParcelTrackingNumberQueuePeer::NUM_COLUMNS - AllegroParcelTrackingNumberQueuePeer::NUM_LAZY_LOAD_COLUMNS).
} catch (Exception $e) {
throw new PropelException("Error populating AllegroParcelTrackingNumberQueue object", $e);
}
}
/**
* Removes this object from datastore and sets delete attribute.
*
* @param Connection $con
* @return void
* @throws PropelException
* @see BaseObject::setDeleted()
* @see BaseObject::isDeleted()
*/
public function delete($con = null)
{
if ($this->isDeleted()) {
throw new PropelException("This object has already been deleted.");
}
if ($this->getDispatcher()->getListeners('AllegroParcelTrackingNumberQueue.preDelete')) {
$this->getDispatcher()->notify(new sfEvent($this, 'AllegroParcelTrackingNumberQueue.preDelete', array('con' => $con)));
}
if (sfMixer::hasCallables('BaseAllegroParcelTrackingNumberQueue:delete:pre'))
{
foreach (sfMixer::getCallables('BaseAllegroParcelTrackingNumberQueue:delete:pre') as $callable)
{
$ret = call_user_func($callable, $this, $con);
if ($ret)
{
return;
}
}
}
if ($con === null) {
$con = Propel::getConnection(AllegroParcelTrackingNumberQueuePeer::DATABASE_NAME);
}
try {
$con->begin();
AllegroParcelTrackingNumberQueuePeer::doDelete($this, $con);
$this->setDeleted(true);
$con->commit();
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
if ($this->getDispatcher()->getListeners('AllegroParcelTrackingNumberQueue.postDelete')) {
$this->getDispatcher()->notify(new sfEvent($this, 'AllegroParcelTrackingNumberQueue.postDelete', array('con' => $con)));
}
if (sfMixer::hasCallables('BaseAllegroParcelTrackingNumberQueue:delete:post'))
{
foreach (sfMixer::getCallables('BaseAllegroParcelTrackingNumberQueue:delete:post') as $callable)
{
call_user_func($callable, $this, $con);
}
}
}
/**
* Stores the object in the database. If the object is new,
* it inserts it; otherwise an update is performed. This method
* wraps the doSave() worker method in a transaction.
*
* @param Connection $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see doSave()
*/
public function save($con = null)
{
if ($this->isDeleted()) {
throw new PropelException("You cannot save an object that has been deleted.");
}
if (!$this->alreadyInSave) {
if ($this->getDispatcher()->getListeners('AllegroParcelTrackingNumberQueue.preSave')) {
$this->getDispatcher()->notify(new sfEvent($this, 'AllegroParcelTrackingNumberQueue.preSave', array('con' => $con)));
}
foreach (sfMixer::getCallables('BaseAllegroParcelTrackingNumberQueue:save:pre') as $callable)
{
$affectedRows = call_user_func($callable, $this, $con);
if (is_int($affectedRows))
{
return $affectedRows;
}
}
}
if ($this->isNew() && !$this->isColumnModified(AllegroParcelTrackingNumberQueuePeer::CREATED_AT))
{
$this->setCreatedAt(time());
}
if ($con === null) {
$con = Propel::getConnection(AllegroParcelTrackingNumberQueuePeer::DATABASE_NAME);
}
try {
$con->begin();
$affectedRows = $this->doSave($con);
$con->commit();
if (!$this->alreadyInSave) {
if ($this->getDispatcher()->getListeners('AllegroParcelTrackingNumberQueue.postSave')) {
$this->getDispatcher()->notify(new sfEvent($this, 'AllegroParcelTrackingNumberQueue.postSave', array('con' => $con)));
}
foreach (sfMixer::getCallables('BaseAllegroParcelTrackingNumberQueue:save:post') as $callable)
{
call_user_func($callable, $this, $con, $affectedRows);
}
}
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Stores the object in the database.
*
* If the object is new, it inserts it; otherwise an update is performed.
* All related objects are also updated in this method.
*
* @param Connection $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see save()
*/
protected function doSave($con)
{
$affectedRows = 0; // initialize var to track total num of affected rows
if (!$this->alreadyInSave) {
$this->alreadyInSave = true;
// We call the save method on the following object(s) if they
// were passed to this object by their coresponding set
// method. This object relates to these object(s) by a
// foreign key reference.
if ($this->aOrder !== null) {
if ($this->aOrder->isModified()) {
$affectedRows += $this->aOrder->save($con);
}
$this->setOrder($this->aOrder);
}
// If this object has been modified, then save it to the database.
if ($this->isModified()) {
if ($this->isNew()) {
$pk = AllegroParcelTrackingNumberQueuePeer::doInsert($this, $con);
$affectedRows += 1; // we are assuming that there is only 1 row per doInsert() which
// should always be true here (even though technically
// BasePeer::doInsert() can insert multiple rows).
$this->setNew(false);
} else {
$affectedRows += AllegroParcelTrackingNumberQueuePeer::doUpdate($this, $con);
}
$this->resetModified(); // [HL] After being saved an object is no longer 'modified'
}
$this->alreadyInSave = false;
}
return $affectedRows;
} // doSave()
/**
* Array of ValidationFailed objects.
* @var array ValidationFailed[]
*/
protected $validationFailures = array();
/**
* Gets any ValidationFailed objects that resulted from last call to validate().
*
*
* @return array ValidationFailed[]
* @see validate()
*/
public function getValidationFailures()
{
return $this->validationFailures;
}
/**
* Validates the objects modified field values and all objects related to this table.
*
* If $columns is either a column name or an array of column names
* only those columns are validated.
*
* @param mixed $columns Column name or an array of column names.
* @return boolean Whether all columns pass validation.
* @see doValidate()
* @see getValidationFailures()
*/
public function validate($columns = null)
{
$res = $this->doValidate($columns);
if ($res === true) {
$this->validationFailures = array();
return true;
} else {
$this->validationFailures = $res;
return false;
}
}
/**
* This function performs the validation work for complex object models.
*
* In addition to checking the current object, all related objects will
* also be validated. If all pass then <code>true</code> is returned; otherwise
* an aggreagated array of ValidationFailed objects will be returned.
*
* @param array $columns Array of column names to validate.
* @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objets otherwise.
*/
protected function doValidate($columns = null)
{
if (!$this->alreadyInValidation) {
$this->alreadyInValidation = true;
$retval = null;
$failureMap = array();
// We call the validate method on the following object(s) if they
// were passed to this object by their coresponding set
// method. This object relates to these object(s) by a
// foreign key reference.
if ($this->aOrder !== null) {
if (!$this->aOrder->validate($columns)) {
$failureMap = array_merge($failureMap, $this->aOrder->getValidationFailures());
}
}
if (($retval = AllegroParcelTrackingNumberQueuePeer::doValidate($this, $columns)) !== true) {
$failureMap = array_merge($failureMap, $retval);
}
$this->alreadyInValidation = false;
}
return (!empty($failureMap) ? $failureMap : true);
}
/**
* Retrieves a field from the object by name passed in as a string.
*
* @param string $name name
* @param string $type The type of fieldname the $name is of:
* one of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return mixed Value of field.
*/
public function getByName($name, $type = BasePeer::TYPE_PHPNAME)
{
$pos = AllegroParcelTrackingNumberQueuePeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
return $this->getByPosition($pos);
}
/**
* Retrieves a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @return mixed Value of field at $pos
*/
public function getByPosition($pos)
{
switch($pos) {
case 0:
return $this->getCreatedAt();
break;
case 1:
return $this->getOrderId();
break;
default:
return null;
break;
} // switch()
}
/**
* Exports the object as an array.
*
* You can specify the key type of the array by passing one of the class
* type constants.
*
* @param string $keyType One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return an associative array containing the field names (as keys) and field values
*/
public function toArray($keyType = BasePeer::TYPE_PHPNAME)
{
$keys = AllegroParcelTrackingNumberQueuePeer::getFieldNames($keyType);
$result = array(
$keys[0] => $this->getCreatedAt(),
$keys[1] => $this->getOrderId(),
);
return $result;
}
/**
* Sets a field from the object by name passed in as a string.
*
* @param string $name peer name
* @param mixed $value field value
* @param string $type The type of fieldname the $name is of:
* one of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return void
*/
public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME)
{
$pos = AllegroParcelTrackingNumberQueuePeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
return $this->setByPosition($pos, $value);
}
/**
* Sets a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @param mixed $value field value
* @return void
*/
public function setByPosition($pos, $value)
{
switch($pos) {
case 0:
$this->setCreatedAt($value);
break;
case 1:
$this->setOrderId($value);
break;
} // switch()
}
/**
* Populates the object using an array.
*
* This is particularly useful when populating an object from one of the
* request arrays (e.g. $_POST). This method goes through the column
* names, checking to see whether a matching key exists in populated
* array. If so the setByName() method is called for that column.
*
* You can specify the key type of the array by additionally passing one
* of the class type constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME,
* TYPE_NUM. The default key type is the column's phpname (e.g. 'authorId')
*
* @param array $arr An array to populate the object from.
* @param string $keyType The type of keys the array uses.
* @return void
*/
public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME)
{
$keys = AllegroParcelTrackingNumberQueuePeer::getFieldNames($keyType);
if (array_key_exists($keys[0], $arr)) $this->setCreatedAt($arr[$keys[0]]);
if (array_key_exists($keys[1], $arr)) $this->setOrderId($arr[$keys[1]]);
}
/**
* Build a Criteria object containing the values of all modified columns in this object.
*
* @return Criteria The Criteria object containing all modified values.
*/
public function buildCriteria()
{
$criteria = new Criteria(AllegroParcelTrackingNumberQueuePeer::DATABASE_NAME);
if ($this->isColumnModified(AllegroParcelTrackingNumberQueuePeer::CREATED_AT)) $criteria->add(AllegroParcelTrackingNumberQueuePeer::CREATED_AT, $this->created_at);
if ($this->isColumnModified(AllegroParcelTrackingNumberQueuePeer::ORDER_ID)) $criteria->add(AllegroParcelTrackingNumberQueuePeer::ORDER_ID, $this->order_id);
return $criteria;
}
/**
* Builds a Criteria object containing the primary key for this object.
*
* Unlike buildCriteria() this method includes the primary key values regardless
* of whether or not they have been modified.
*
* @return Criteria The Criteria object containing value(s) for primary key(s).
*/
public function buildPkeyCriteria()
{
$criteria = new Criteria(AllegroParcelTrackingNumberQueuePeer::DATABASE_NAME);
$criteria->add(AllegroParcelTrackingNumberQueuePeer::ORDER_ID, $this->order_id);
return $criteria;
}
/**
* Returns the primary key for this object (row).
* @return int
*/
public function getPrimaryKey()
{
return $this->getOrderId();
}
/**
* Returns [composite] primary key fields
*
* @param string $keyType
* @return array
*/
public function getPrimaryKeyFields($keyType = BasePeer::TYPE_FIELDNAME)
{
return array(AllegroParcelTrackingNumberQueuePeer::translateFieldName('order_id', BasePeer::TYPE_FIELDNAME, $keyType));
}
/**
* Generic method to set the primary key (order_id column).
*
* @param int $key Primary key.
* @return void
*/
public function setPrimaryKey($key)
{
$this->setOrderId($key);
}
/**
* Sets contents of passed object to values from current object.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param object $copyObj An object of AllegroParcelTrackingNumberQueue (or compatible) type.
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @throws PropelException
*/
public function copyInto($copyObj, $deepCopy = false)
{
$copyObj->setCreatedAt($this->created_at);
$copyObj->setNew(true);
$copyObj->setOrderId(NULL); // this is a pkey column, so set to default value
}
/**
* Makes a copy of this object that will be inserted as a new row in table when saved.
* It creates a new object filling in the simple attributes, but skipping any primary
* keys that are defined for the table.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @return AllegroParcelTrackingNumberQueue Clone of current object.
* @throws PropelException
*/
public function copy($deepCopy = false)
{
// we use get_class(), because this might be a subclass
$clazz = get_class($this);
$copyObj = new $clazz();
$this->copyInto($copyObj, $deepCopy);
return $copyObj;
}
/**
* Returns a peer instance associated with this om.
*
* @return string Peer class name
*/
public function getPeer()
{
return 'AllegroParcelTrackingNumberQueuePeer';
}
/**
* Declares an association between this object and a Order object.
*
* @param Order $v
* @return void
* @throws PropelException
*/
public function setOrder($v)
{
if ($v === null) {
$this->setOrderId(NULL);
} else {
$this->setOrderId($v->getId());
}
$this->aOrder = $v;
}
/**
* Get the associated Order object
*
* @param Connection Optional Connection object.
* @return Order The associated Order object.
* @throws PropelException
*/
public function getOrder($con = null)
{
if ($this->aOrder === null && ($this->order_id !== null)) {
// include the related Peer class
$this->aOrder = OrderPeer::retrieveByPK($this->order_id, $con);
/* The following can be used instead of the line above to
guarantee the related object contains a reference
to this object, but this level of coupling
may be undesirable in many circumstances.
As it can lead to a db query with many results that may
never be used.
$obj = OrderPeer::retrieveByPK($this->order_id, $con);
$obj->addOrders($this);
*/
}
return $this->aOrder;
}
public function getDispatcher()
{
if (null === self::$dispatcher)
{
self::$dispatcher = stEventDispatcher::getInstance();
}
return self::$dispatcher;
}
public function __call($method, $arguments)
{
$event = $this->getDispatcher()->notifyUntil(new sfEvent($this, 'AllegroParcelTrackingNumberQueue.' . $method, array('arguments' => $arguments, 'method' => $method)));
if ($event->isProcessed())
{
return $event->getReturnValue();
}
if (!$callable = sfMixer::getCallable('BaseAllegroParcelTrackingNumberQueue:'.$method))
{
throw new sfException(sprintf('Call to undefined method BaseAllegroParcelTrackingNumberQueue::%s', $method));
}
array_unshift($arguments, $this);
return call_user_func_array($callable, $arguments);
}
} // BaseAllegroParcelTrackingNumberQueue

View File

@@ -0,0 +1,839 @@
<?php
/**
* Base static class for performing query and update operations on the 'st_allegro_parcel_tracking_number_queue' table.
*
*
*
* @package plugins.stAllegroPlugin.lib.model.om
*/
abstract class BaseAllegroParcelTrackingNumberQueuePeer {
/** the default database name for this class */
const DATABASE_NAME = 'propel';
/** the table name for this class */
const TABLE_NAME = 'st_allegro_parcel_tracking_number_queue';
/** A class that can be returned by this peer. */
const CLASS_DEFAULT = 'plugins.stAllegroPlugin.lib.model.AllegroParcelTrackingNumberQueue';
/** The total number of columns. */
const NUM_COLUMNS = 2;
/** The number of lazy-loaded columns. */
const NUM_LAZY_LOAD_COLUMNS = 0;
/** the column name for the CREATED_AT field */
const CREATED_AT = 'st_allegro_parcel_tracking_number_queue.CREATED_AT';
/** the column name for the ORDER_ID field */
const ORDER_ID = 'st_allegro_parcel_tracking_number_queue.ORDER_ID';
/** The PHP to DB Name Mapping */
private static $phpNameMap = null;
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
private static $fieldNames = array (
BasePeer::TYPE_PHPNAME => array ('CreatedAt', 'OrderId', ),
BasePeer::TYPE_COLNAME => array (AllegroParcelTrackingNumberQueuePeer::CREATED_AT, AllegroParcelTrackingNumberQueuePeer::ORDER_ID, ),
BasePeer::TYPE_FIELDNAME => array ('created_at', 'order_id', ),
BasePeer::TYPE_NUM => array (0, 1, )
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
*/
private static $fieldKeys = array (
BasePeer::TYPE_PHPNAME => array ('CreatedAt' => 0, 'OrderId' => 1, ),
BasePeer::TYPE_COLNAME => array (AllegroParcelTrackingNumberQueuePeer::CREATED_AT => 0, AllegroParcelTrackingNumberQueuePeer::ORDER_ID => 1, ),
BasePeer::TYPE_FIELDNAME => array ('created_at' => 0, 'order_id' => 1, ),
BasePeer::TYPE_NUM => array (0, 1, )
);
protected static $hydrateMethod = null;
protected static $postHydrateMethod = null;
public static function setHydrateMethod($callback)
{
self::$hydrateMethod = $callback;
}
public static function setPostHydrateMethod($callback)
{
self::$postHydrateMethod = $callback;
}
/**
* @return MapBuilder the map builder for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getMapBuilder()
{
return BasePeer::getMapBuilder('plugins.stAllegroPlugin.lib.model.map.AllegroParcelTrackingNumberQueueMapBuilder');
}
/**
* Gets a map (hash) of PHP names to DB column names.
*
* @return array The PHP to DB name map for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @deprecated Use the getFieldNames() and translateFieldName() methods instead of this.
*/
public static function getPhpNameMap()
{
if (self::$phpNameMap === null) {
$map = AllegroParcelTrackingNumberQueuePeer::getTableMap();
$columns = $map->getColumns();
$nameMap = array();
foreach ($columns as $column) {
$nameMap[$column->getPhpName()] = $column->getColumnName();
}
self::$phpNameMap = $nameMap;
}
return self::$phpNameMap;
}
/**
* Translates a fieldname to another type
*
* @param string $name field name
* @param string $fromType One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @param string $toType One of the class type constants
* @return string translated name of the field.
*/
static public function translateFieldName($name, $fromType, $toType)
{
$toNames = self::getFieldNames($toType);
$key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null;
if ($key === null) {
throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true));
}
return $toNames[$key];
}
/**
* Returns an array of of field names.
*
* @param string $type The type of fieldnames to return:
* One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return array A list of field names
*/
static public function getFieldNames($type = BasePeer::TYPE_PHPNAME)
{
if (!array_key_exists($type, self::$fieldNames)) {
throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.');
}
return self::$fieldNames[$type];
}
/**
* Convenience method which changes table.column to alias.column.
*
* Using this method you can maintain SQL abstraction while using column aliases.
* <code>
* $c->addAlias("alias1", TablePeer::TABLE_NAME);
* $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
* </code>
* @param string $alias The alias for the current table.
* @param string $column The column name for current table. (i.e. AllegroParcelTrackingNumberQueuePeer::COLUMN_NAME).
* @return string
*/
public static function alias($alias, $column)
{
return str_replace(AllegroParcelTrackingNumberQueuePeer::TABLE_NAME.'.', $alias.'.', $column);
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param criteria object containing the columns to add.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns(Criteria $criteria)
{
$criteria->addSelectColumn(AllegroParcelTrackingNumberQueuePeer::CREATED_AT);
$criteria->addSelectColumn(AllegroParcelTrackingNumberQueuePeer::ORDER_ID);
if (stEventDispatcher::getInstance()->getListeners('AllegroParcelTrackingNumberQueuePeer.postAddSelectColumns')) {
stEventDispatcher::getInstance()->notify(new sfEvent($criteria, 'AllegroParcelTrackingNumberQueuePeer.postAddSelectColumns'));
}
}
const COUNT = 'COUNT(st_allegro_parcel_tracking_number_queue.ORDER_ID)';
const COUNT_DISTINCT = 'COUNT(DISTINCT st_allegro_parcel_tracking_number_queue.ORDER_ID)';
/**
* Returns the number of rows matching criteria.
*
* @param Criteria $criteria
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCount(Criteria $criteria, $distinct = false, $con = null)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(AllegroParcelTrackingNumberQueuePeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(AllegroParcelTrackingNumberQueuePeer::COUNT);
}
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$rs = AllegroParcelTrackingNumberQueuePeer::doSelectRS($criteria, $con);
if ($rs->next()) {
return $rs->getInt(1);
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Method to select one object from the DB.
*
* @param Criteria $criteria object used to create the SELECT statement.
* @param Connection $con
* @return AllegroParcelTrackingNumberQueue
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectOne(Criteria $criteria, $con = null)
{
$critcopy = clone $criteria;
$critcopy->setLimit(1);
$objects = AllegroParcelTrackingNumberQueuePeer::doSelect($critcopy, $con);
if ($objects) {
return $objects[0];
}
return null;
}
/**
* Method to do selects.
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con
* @return AllegroParcelTrackingNumberQueue[]
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelect(Criteria $criteria, $con = null)
{
return AllegroParcelTrackingNumberQueuePeer::populateObjects(AllegroParcelTrackingNumberQueuePeer::doSelectRS($criteria, $con));
}
/**
* Prepares the Criteria object and uses the parent doSelect()
* method to get a ResultSet.
*
* Use this method directly if you want to just get the resultset
* (instead of an array of objects).
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return ResultSet The resultset object with numerically-indexed fields.
* @see BasePeer::doSelect()
*/
public static function doSelectRS(Criteria $criteria, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if (!$criteria->getSelectColumns()) {
$criteria = clone $criteria;
AllegroParcelTrackingNumberQueuePeer::addSelectColumns($criteria);
}
if (stEventDispatcher::getInstance()->getListeners('BasePeer.preDoSelectRs')) {
stEventDispatcher::getInstance()->notify(new sfEvent($criteria, 'BasePeer.preDoSelectRs'));
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
// BasePeer returns a Creole ResultSet, set to return
// rows indexed numerically.
$rs = BasePeer::doSelect($criteria, $con);
if (stEventDispatcher::getInstance()->getListeners('BasePeer.postDoSelectRs')) {
stEventDispatcher::getInstance()->notify(new sfEvent($rs, 'BasePeer.postDoSelectRs'));
}
return $rs;
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects(ResultSet $rs)
{
if (self::$hydrateMethod)
{
return call_user_func(self::$hydrateMethod, $rs);
}
$results = array();
// set the class once to avoid overhead in the loop
$cls = AllegroParcelTrackingNumberQueuePeer::getOMClass();
$cls = Propel::import($cls);
// populate the object(s)
while($rs->next()) {
$obj = new $cls();
$obj->hydrate($rs);
$results[] = self::$postHydrateMethod ? call_user_func(self::$postHydrateMethod, $obj) : $obj;
}
return $results;
}
/**
* Returns the number of rows matching criteria, joining the related Order table
*
* @param Criteria $c
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCountJoinOrder(Criteria $criteria, $distinct = false, $con = null)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(AllegroParcelTrackingNumberQueuePeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(AllegroParcelTrackingNumberQueuePeer::COUNT);
}
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$criteria->addJoin(AllegroParcelTrackingNumberQueuePeer::ORDER_ID, OrderPeer::ID);
$rs = AllegroParcelTrackingNumberQueuePeer::doSelectRS($criteria, $con);
if ($rs->next()) {
return $rs->getInt(1);
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Selects a collection of AllegroParcelTrackingNumberQueue objects pre-filled with their Order objects.
*
* @return AllegroParcelTrackingNumberQueue[] Array of AllegroParcelTrackingNumberQueue objects.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectJoinOrder(Criteria $c, $con = null)
{
$c = clone $c;
// Set the correct dbName if it has not been overridden
if ($c->getDbName() == Propel::getDefaultDB()) {
$c->setDbName(self::DATABASE_NAME);
}
AllegroParcelTrackingNumberQueuePeer::addSelectColumns($c);
OrderPeer::addSelectColumns($c);
$c->addJoin(AllegroParcelTrackingNumberQueuePeer::ORDER_ID, OrderPeer::ID);
$rs = AllegroParcelTrackingNumberQueuePeer::doSelectRs($c, $con);
if (self::$hydrateMethod)
{
return call_user_func(self::$hydrateMethod, $rs);
}
$results = array();
while($rs->next()) {
$obj1 = new AllegroParcelTrackingNumberQueue();
$startcol = $obj1->hydrate($rs);
if ($obj1->getOrderId())
{
$obj2 = new Order();
$obj2->hydrate($rs, $startcol);
$obj2->addAllegroParcelTrackingNumberQueue($obj1);
}
$results[] = self::$postHydrateMethod ? call_user_func(self::$postHydrateMethod, $obj1) : $obj1;;
}
return $results;
}
/**
* Returns the number of rows matching criteria, joining all related tables
*
* @param Criteria $c
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCountJoinAll(Criteria $criteria, $distinct = false, $con = null)
{
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(AllegroParcelTrackingNumberQueuePeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(AllegroParcelTrackingNumberQueuePeer::COUNT);
}
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$criteria->addJoin(AllegroParcelTrackingNumberQueuePeer::ORDER_ID, OrderPeer::ID);
$rs = AllegroParcelTrackingNumberQueuePeer::doSelectRS($criteria, $con);
if ($rs->next()) {
return $rs->getInt(1);
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Selects a collection of AllegroParcelTrackingNumberQueue objects pre-filled with all related objects.
*
* @return AllegroParcelTrackingNumberQueue[]
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectJoinAll(Criteria $c, $con = null)
{
$c = clone $c;
// Set the correct dbName if it has not been overridden
if ($c->getDbName() == Propel::getDefaultDB()) {
$c->setDbName(self::DATABASE_NAME);
}
AllegroParcelTrackingNumberQueuePeer::addSelectColumns($c);
$startcol2 = (AllegroParcelTrackingNumberQueuePeer::NUM_COLUMNS - AllegroParcelTrackingNumberQueuePeer::NUM_LAZY_LOAD_COLUMNS) + 1;
OrderPeer::addSelectColumns($c);
$startcol3 = $startcol2 + OrderPeer::NUM_COLUMNS;
$c->addJoin(AllegroParcelTrackingNumberQueuePeer::ORDER_ID, OrderPeer::ID);
$rs = BasePeer::doSelect($c, $con);
if (self::$hydrateMethod)
{
return call_user_func(self::$hydrateMethod, $rs);
}
$results = array();
while($rs->next()) {
$omClass = AllegroParcelTrackingNumberQueuePeer::getOMClass();
$cls = Propel::import($omClass);
$obj1 = new $cls();
$obj1->hydrate($rs);
// Add objects for joined Order rows
$omClass = OrderPeer::getOMClass();
$cls = Propel::import($omClass);
$obj2 = new $cls();
$obj2->hydrate($rs, $startcol2);
$newObject = true;
for ($j=0, $resCount=count($results); $j < $resCount; $j++) {
$temp_obj1 = $results[$j];
$temp_obj2 = $temp_obj1->getOrder(); // CHECKME
if (null !== $temp_obj2 && $temp_obj2->getPrimaryKey() === $obj2->getPrimaryKey()) {
$newObject = false;
$temp_obj2->addAllegroParcelTrackingNumberQueue($obj1); // CHECKME
break;
}
}
if ($newObject) {
$obj2->initAllegroParcelTrackingNumberQueues();
$obj2->addAllegroParcelTrackingNumberQueue($obj1);
}
$results[] = self::$postHydrateMethod ? call_user_func(self::$postHydrateMethod, $obj1) : $obj1;
}
return $results;
}
/**
* Returns the TableMap related to this peer.
* This method is not needed for general use but a specific application could have a need.
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap()
{
return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME);
}
/**
* The class that the Peer will make instances of.
*
* This uses a dot-path notation which is tranalted into a path
* relative to a location on the PHP include_path.
* (e.g. path.to.MyClass -> 'path/to/MyClass.php')
*
* @return string path.to.ClassName
*/
public static function getOMClass()
{
return AllegroParcelTrackingNumberQueuePeer::CLASS_DEFAULT;
}
/**
* Method perform an INSERT on the database, given a AllegroParcelTrackingNumberQueue or Criteria object.
*
* @param mixed $values Criteria or AllegroParcelTrackingNumberQueue object containing data that is used to create the INSERT statement.
* @param Connection $con the connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert($values, $con = null)
{
foreach (sfMixer::getCallables('BaseAllegroParcelTrackingNumberQueuePeer:doInsert:pre') as $callable)
{
$ret = call_user_func($callable, 'BaseAllegroParcelTrackingNumberQueuePeer', $values, $con);
if (false !== $ret)
{
return $ret;
}
}
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} else {
$criteria = $values->buildCriteria(); // build Criteria from AllegroParcelTrackingNumberQueue object
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
try {
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
$con->begin();
$pk = BasePeer::doInsert($criteria, $con);
$con->commit();
} catch(PropelException $e) {
$con->rollback();
throw $e;
}
foreach (sfMixer::getCallables('BaseAllegroParcelTrackingNumberQueuePeer:doInsert:post') as $callable)
{
call_user_func($callable, 'BaseAllegroParcelTrackingNumberQueuePeer', $values, $con, $pk);
}
return $pk;
}
/**
* Method perform an UPDATE on the database, given a AllegroParcelTrackingNumberQueue or Criteria object.
*
* @param mixed $values Criteria or AllegroParcelTrackingNumberQueue object containing data that is used to create the UPDATE statement.
* @param Connection $con The connection to use (specify Connection object to exert more control over transactions).
* @return int The number of affected rows (if supported by underlying database driver).
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doUpdate($values, $con = null)
{
foreach (sfMixer::getCallables('BaseAllegroParcelTrackingNumberQueuePeer:doUpdate:pre') as $callable)
{
$ret = call_user_func($callable, 'BaseAllegroParcelTrackingNumberQueuePeer', $values, $con);
if (false !== $ret)
{
return $ret;
}
}
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$selectCriteria = new Criteria(self::DATABASE_NAME);
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
$comparison = $criteria->getComparison(AllegroParcelTrackingNumberQueuePeer::ORDER_ID);
$selectCriteria->add(AllegroParcelTrackingNumberQueuePeer::ORDER_ID, $criteria->remove(AllegroParcelTrackingNumberQueuePeer::ORDER_ID), $comparison);
} else { // $values is AllegroParcelTrackingNumberQueue object
$criteria = $values->buildCriteria(); // gets full criteria
$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
}
// set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
$ret = BasePeer::doUpdate($selectCriteria, $criteria, $con);
foreach (sfMixer::getCallables('BaseAllegroParcelTrackingNumberQueuePeer:doUpdate:post') as $callable)
{
call_user_func($callable, 'BaseAllegroParcelTrackingNumberQueuePeer', $values, $con, $ret);
}
return $ret;
}
/**
* Method to DELETE all rows from the st_allegro_parcel_tracking_number_queue table.
*
* @return int The number of affected rows (if supported by underlying database driver).
*/
public static function doDeleteAll($con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDeleteAll(AllegroParcelTrackingNumberQueuePeer::TABLE_NAME, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Method perform a DELETE on the database, given a AllegroParcelTrackingNumberQueue or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or AllegroParcelTrackingNumberQueue object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param Connection $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(AllegroParcelTrackingNumberQueuePeer::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} elseif ($values instanceof AllegroParcelTrackingNumberQueue) {
$criteria = $values->buildPkeyCriteria();
} else {
// it must be the primary key
$criteria = new Criteria(self::DATABASE_NAME);
$criteria->add(AllegroParcelTrackingNumberQueuePeer::ORDER_ID, (array) $values, Criteria::IN);
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
$affectedRows += BasePeer::doDelete($criteria, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Validates all modified columns of given AllegroParcelTrackingNumberQueue object.
* If parameter $columns is either a single column name or an array of column names
* than only those columns are validated.
*
* NOTICE: This does not apply to primary or foreign keys for now.
*
* @param AllegroParcelTrackingNumberQueue $obj The object to validate.
* @param mixed $cols Column name or array of column names.
*
* @return mixed TRUE if all columns are valid or the error message of the first invalid column.
*/
public static function doValidate(AllegroParcelTrackingNumberQueue $obj, $cols = null)
{
$columns = array();
if ($cols) {
$dbMap = Propel::getDatabaseMap(AllegroParcelTrackingNumberQueuePeer::DATABASE_NAME);
$tableMap = $dbMap->getTable(AllegroParcelTrackingNumberQueuePeer::TABLE_NAME);
if (! is_array($cols)) {
$cols = array($cols);
}
foreach($cols as $colName) {
if ($tableMap->containsColumn($colName)) {
$get = 'get' . $tableMap->getColumn($colName)->getPhpName();
$columns[$colName] = $obj->$get();
}
}
} else {
}
$res = BasePeer::doValidate(AllegroParcelTrackingNumberQueuePeer::DATABASE_NAME, AllegroParcelTrackingNumberQueuePeer::TABLE_NAME, $columns);
if ($res !== true) {
$request = sfContext::getInstance()->getRequest();
foreach ($res as $failed) {
$col = AllegroParcelTrackingNumberQueuePeer::translateFieldname($failed->getColumn(), BasePeer::TYPE_COLNAME, BasePeer::TYPE_PHPNAME);
$request->setError($col, $failed->getMessage());
}
}
return $res;
}
/**
* Retrieve a single object by pkey.
*
* @param mixed $pk the primary key.
* @param Connection $con the connection to use
* @return AllegroParcelTrackingNumberQueue
*/
public static function retrieveByPK($pk, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$criteria = new Criteria(AllegroParcelTrackingNumberQueuePeer::DATABASE_NAME);
$criteria->add(AllegroParcelTrackingNumberQueuePeer::ORDER_ID, $pk);
$v = AllegroParcelTrackingNumberQueuePeer::doSelect($criteria, $con);
return !empty($v) > 0 ? $v[0] : null;
}
/**
* Retrieve multiple objects by pkey.
*
* @param array $pks List of primary keys
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return AllegroParcelTrackingNumberQueue[]
*/
public static function retrieveByPKs($pks, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$objs = null;
if (empty($pks)) {
$objs = array();
} else {
$criteria = new Criteria();
$criteria->add(AllegroParcelTrackingNumberQueuePeer::ORDER_ID, $pks, Criteria::IN);
$objs = AllegroParcelTrackingNumberQueuePeer::doSelect($criteria, $con);
}
return $objs;
}
} // BaseAllegroParcelTrackingNumberQueuePeer
// static code to register the map builder for this Peer with the main Propel class
if (Propel::isInit()) {
// the MapBuilder classes register themselves with Propel during initialization
// so we need to load them here.
try {
BaseAllegroParcelTrackingNumberQueuePeer::getMapBuilder();
} catch (Exception $e) {
Propel::log('Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR);
}
} else {
// even if Propel is not yet initialized, the map builder class can be registered
// now and then it will be loaded when Propel initializes.
Propel::registerMapBuilder('plugins.stAllegroPlugin.lib.model.map.AllegroParcelTrackingNumberQueueMapBuilder');
}

View File

@@ -0,0 +1,97 @@
<?php
class stAllegroCategoriesBar {
protected $allegro = null;
protected $i18n;
public function __construct() {
$this->i18n = sfContext::getInstance()->getI18n();
$this->initAllegro();
}
public function initAllegro() {
if ($this->allegro == null) {
$request = sfContext::getInstance()->getRequest();
if ($request->hasParameter('environment'))
$environment = $request->getParameter('environment');
else
list(, $environment) = explode('-', $request->getParameter('name'), 2);
$this->allegro = new stAllegro($environment);
}
}
public function getCategories($offset = 0) {
if ($offset == 0)
{
$con = Propel::getConnection();
$c = new Criteria();
$c->add(AllegroCategoryPeer::SITE, $this->allegro->getEnvironment());
$cu = new Criteria();
$cu->add(AllegroCategoryPeer::IS_OLD, 1);
BasePeer::doUpdate($c, $cu, $con);
}
$this->msg = $this->i18n->__('Pobrano %count% z %countAll% kategorii.', array('%count%' => ($offset * 500), '%countAll%' => $this->allegro->getCategoryCount()), 'stAllegroBackend');
$categories = $this->allegro->getCategories($offset, 500);
$this->saveCategories($categories);
return $offset+1;
}
public function saveCategories($categories) {
$ids = array();
foreach ($categories as $category) {
if (is_array($category)) {
$ids[] = $category['catId'];
}
}
$c = new Criteria();
$c->add(AllegroCategoryPeer::CAT_ID, $ids, Criteria::IN);
$c->add(AllegroCategoryPeer::SITE, $this->allegro->getEnvironment());
$selected = array();
foreach (AllegroCategoryPeer::doSelect($c) as $category)
{
$selected[$category->getCatId()] = $category;
}
foreach ($categories as $category) {
if (is_array($category)) {
$allegroCategory = isset($selected[$category['catId']]) ? $selected[$category['catId']] : null;
if (!$allegroCategory) {
$allegroCategory = new AllegroCategory();
$allegroCategory->setCatId($category['catId']);
$allegroCategory->setSite($this->allegro->getEnvironment());
}
$allegroCategory->setName($category['catName']);
$allegroCategory->setParent($category['catParent']);
$allegroCategory->setPosition($category['catPosition']);
$allegroCategory->setIsOld(0);
$allegroCategory->save();
}
}
}
public function getTitle() {
return ' ';
}
public function getMessage() {
return $this->msg;
}
public function close() {
$this->msg = sprintf($this->i18n->__('Kategorie zostały pobrane. Ilość pobranych kategorii wynosi %d.', null, 'stAllegroBackend'), $this->allegro->getCategoryCount());
$ac = new stAllegroCategory($this->allegro);
$ac->saveCategoryVersion();
}
}

View File

@@ -0,0 +1,61 @@
<?php
class stAllegroCreateAuctionsBar {
protected $i18n;
protected $msg = null;
protected $auctionIds = array();
public function __construct() {
$this->i18n = sfContext::getInstance()->getI18n();
$this->auctionIds = sfContext::getInstance()->getUser()->getAttribute('auctionsIds', array(), 'stAllegroPlugin');
}
public function init() {
sfContext::getInstance()->getUser()->setAttribute('auctionsInformations', array(), 'stAllegroPlugin');
}
public function getTitle() {
return $this->i18n->__('Wystawianie aukcji w serwisie aukcyjnym', null, 'stAllegroBackend');
}
public function getMessage() {
return $this->msg;
}
public function createAuction($step = 0) {
if (isset($this->auctionIds[$step])) {
$auction = AllegroAuctionPeer::retrieveByPK($this->auctionIds[$step]);
if (is_object($auction)) {
$this->msg = $this->i18n->__('Wystawianie aukcji', null, 'stAllegroBackend').': '.$auction->getName();
if (!$auction->getAuctionId()) {
try {
$stAllegro =stAllegro::getInstance($auction->getEnvironment());
$response = $stAllegro->createAuction($auction);
if ($response === false)
$response = $stAllegro->getLastError();
} catch(Exception $e) {
$response = $e->getMessage();
}
} else {
$response = $this->i18n->__('Aukcja została wystawiona wcześniej. Proszę utworzyć kopie aukcji i wystawić ją ponownie.', null, 'stAllegroBackend');
}
$messages = sfContext::getInstance()->getUser()->getAttribute('auctionsInformations', array(), 'stAllegroPlugin');
$messages[$auction->getId()] = $response;
sfContext::getInstance()->getUser()->setAttribute('auctionsInformations', $messages, 'stAllegroPlugin');
}
}
return ($step+1);
}
public function close() {
sfLoader::loadHelpers(array('Helper', 'stPartial', 'stAdminGenerator'));
$this->msg = st_get_partial('stAllegroBackend/createManyAuction', array('messages' => sfContext::getInstance()->getUser()->getAttribute('auctionsInformations', array(), 'stAllegroPlugin')));
}
}

View File

@@ -0,0 +1,75 @@
<?php
class stAllegroProductUpdateBar {
protected $i18n;
protected $msg;
public function __construct() {
$this->i18n = sfContext::getInstance()->getI18n();
}
public function execute($offset = 0) {
$c = new Criteria();
$c->setOffset($offset);
$c->setLimit(5);
$api = stAllegroApi::getInstance();
foreach (AllegroAuctionPeer::doSelect($c) as $auction)
{
try {
// throw new Exception("test");
$offer = $api->getOffer($auction->getAuctionId());
// throw new Exception("test");
$offer->external = stAllegroApi::arrayToObject(array(
'id' => $auction->getProductId(),
));
$api->updateOffer($offer->id, $offer);
}
catch(stAllegroException $e)
{
}
$auction->setName($offer->name);
$auction->save();
$offset++;
}
sleep(1);
return $offset;
}
public function getTitle() {
return $this->i18n->__('Aktualizacja ofert - Proszę czekać');
}
public function getMessage() {
return $this->msg;
}
public function close() {
$message = $this->i18n->__('Wszystie oferty zostały zaktualizowane pomyślnie', null, 'stAllegroBackend');
$link = $this->i18n->__('Przejdź do ofert');
$html =<<<HTML
<p style="text-align: center">$message</p>
<p style="text-align: center"><a href="#" onclick="location.reload(); return false">$link</a></p>
HTML;
$this->msg = $html;
$config = stConfig::getInstance('stAllegroBackend');
$config->set('offers_updated', true);
$config->save(true);
}
}

View File

@@ -0,0 +1,6 @@
<?php
class stAllegroException extends Exception
{
}

View File

@@ -0,0 +1,549 @@
<?php
/**
* Object PHP interface for Allegro REST API
*
* This class allows you to call any resource
* with correct request
*
* It also implements some features which
* will save you a lot of time
*
* Example:
* <pre>
* // Register your application here:
* // https://apps.developer.allegro.pl
*
* // Creating auth URL using client id and redirect_uri
* var_dump(
* AllegroRestApi::getAuthLink($clientId, $redirectUri)
* );
*
* // After clicking the link and granting permission you
* // will be redirected to $redirectUri with "code"
* //
* // Use given code to finally generate access token
* $tokens = AllegroRestApi::generateToken(
* $_GET['code'],
* $clientId,
* $clientSecret,
* $redirectUri
* );
*
* // Above token will be active for 12 hours and you can
* // refresh it indefinitely (in example using cron)
* AllegroRestApi::refreshToken(
* $tokens->refresh_token,
* $clientId,
* $clientSecret,
* $redirectUri
* );
*
* // Creating an instance of RestApi
* $restApi = new AllegroRestApi($tokens->access_token);
*
* // Getting our comments
* $response = $restApi->get('/sale/user-ratings?user.id=' . $yourUserId)
* </pre>
*
* @see https://developer.allegro.pl/about/
* @author Maciej Strączkowski <m.straczkowski@gmail.com>
* @copyright ZOONDO.EU Maciej Strączkowski
* @version 2.0.0
*/
class AllegroRestApi
{
/**
* An url address for production API
*/
const URL = 'https://api.allegro.pl';
/**
* An url address for sandbox API
*/
const SANDBOX_URL = 'https://api.allegro.pl.allegrosandbox.pl';
const AUTH_URL = 'https://allegro.pl/auth/oauth';
const SANDBOX_AUTH_URL = 'https://allegro.pl.allegrosandbox.pl/auth/oauth';
const UPLOAD_URL = 'https://upload.allegro.pl';
const SANDBOX_UPLOAD_URL = 'https://upload.allegro.pl.allegrosandbox.pl';
/**
* Allegro REST API access token
*
* @var string
*/
protected $token = null;
/**
* Should we use sandbox mode?
*
* @var boolean
*/
protected $sandbox = false;
/**
* Last error response from Allegro REST API
*
* @var stdClass
*/
protected static $lastErrors = null;
protected static $lastHttpCode = null;
protected static $lastRequestInfo = null;
protected static $lastHeaders = array();
/**
* Saves given token and sandbox boolean
* value into class properties
*
* @param string $token
* @param boolean $sandbox
*/
public function __construct($token, $sandbox = false)
{
$this->setToken($token);
$this->setSandbox($sandbox);
}
/**
* Returns an authorization link which user
* should click to give access
*
* @param string $clientId
* @param string $redirectUri
* @return string
*/
public static function getAuthLink($clientId, $redirectUri, $sandbox = false)
{
$api = new AllegroRestApi(null, $sandbox);
$redirectUri = rawurlencode($redirectUri);
return $api->getAuthUrl() . "/authorize"
. "?response_type=code"
. "&client_id=$clientId"
. "&redirect_uri=$redirectUri";
}
/**
* Generates access token using given
* credentials and code
*
* @param string $code Code from allegro
* @param string $clientId Client ID
* @param string $redirectUri Client secret
* @return object
*/
public static function generateToken($code, $clientId, $clientSecret, $redirectUri, $sandbox = false)
{
// Creating an instance of class
$api = new AllegroRestApi(null, $sandbox);
// Returning response
$response = $api->sendRequest($api->getAuthUrl() . "/token"
. "?grant_type=authorization_code"
. "&code=$code"
. "&redirect_uri=$redirectUri",
'POST',
array(),
array(
'Authorization' => 'Basic ' . base64_encode("$clientId:$clientSecret")
)
);
if (is_object($response) && isset($response->access_token)) {
$api = new AllegroRestApi($response->access_token, $sandbox);
$me = $api->get('/me');
$response->seller_id = $me->id;
}
return $response;
}
/**
* Refreshes access token using given
* credentials
*
* @param string $code Code from allegro
* @param string $clientId Client ID
* @param string $redirectUri Client secret
* @return object
*/
public static function refreshToken($refreshToken, $clientId, $clientSecret, $redirectUri, $sandbox = false)
{
// Creating an instance of class
$api = new AllegroRestApi(null, $sandbox);
$query = http_build_query(array(
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
'redirect_uri' => $redirectUri,
), null, '&');
// Returning response
$response = $api->sendRequest($api->getAuthUrl() . "/token?".$query,
'POST',
array(),
array(
'Authorization' => 'Basic ' . base64_encode("$clientId:$clientSecret")
)
);
if (is_object($response) && isset($response->access_token)) {
$api = new AllegroRestApi($response->access_token, $sandbox);
$me = $api->get('/me');
$response->seller_id = $me->id;
}
return $response;
}
/**
* Stores token in class property to
* use it in requests
*
* @param string $value Access token
* @return AllegroRestApi
*/
public function setToken($value)
{
$this->token = $value;
return $this;
}
/**
* Returns api access token from property
*
* @return string Access token
*/
public function getToken()
{
return $this->token;
}
/**
* Stores boolean in class property to
* determine which environment should we use
*
* @param boolean $value True or false
* @return AllegroRestApi
*/
public function setSandbox($value)
{
$this->sandbox = (boolean)$value;
return $this;
}
/**
* Returns boolean value which determines
* which environment should we use
*
* @return boolean True or false
*/
public function getSandbox()
{
return $this->sandbox;
}
/**
* Returns REST API basic URL depending
* on current sandbox setting
*
* @return string An URL address
*/
public function getUrl()
{
// Returning correct URL depending on sandbox setting
return $this->getSandbox()
? AllegroRestApi::SANDBOX_URL
: AllegroRestApi::URL;
}
/**
* Returns REST API AUTH URL depending
* on current sandbox setting
*
* @return string An URL address
*/
public function getAuthUrl()
{
// Returning correct URL depending on sandbox setting
return $this->getSandbox()
? AllegroRestApi::SANDBOX_AUTH_URL
: AllegroRestApi::AUTH_URL;
}
/**
* Returns REST API UPLOAD URL depending
* on current sandbox setting
*
* @return string An URL address
*/
public function getUploadUrl()
{
// Returning correct URL depending on sandbox setting
return $this->getSandbox()
? AllegroRestApi::SANDBOX_UPLOAD_URL
: AllegroRestApi::UPLOAD_URL;
}
/**
* Generates UUID which can be used in
* some actions
*
* @return string UUID
*/
public function getUuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff)
);
}
/**
* Sends GET request to Allegro REST API
* and returns response
*
* @param string $resource Resource path
* @param array $headers Request headers
* @return object
*/
public function get($resource)
{
return $this->sendRequest($resource, 'GET', array());
}
/**
* Sends POST request to Allegro REST API
* and returns response
*
* @param string $resource Resource path
* @param array $data Request body
* @param array $headers Request headers
* @return object
*/
public function post($resource, array $data)
{
return $this->sendRequest($resource, 'POST', $data);
}
/**
* Sends PUT request to Allegro REST API
* and returns response
*
* @param string $resource Resource path
* @param array $data Request body
* @param array $headers Request headers
* @return object
*/
public function put($resource, array $data)
{
return $this->sendRequest($resource, 'PUT', $data);
}
/**
* Sends DELETE request to Allegro REST API
* and returns response
*
* @param string $resource Resource path
* @param array $headers Request headers
* @return object
*/
public function delete($resource)
{
return $this->sendRequest($resource, 'DELETE', array());
}
/**
* Sends request to Allegro REST API
* using given arguments
*
* Returns API response as JSON object
*
* @param string $resource Resource path
* @param string $method Request method
* @param array|string $data Request body
* @return object
*/
public function sendRequest(string $resource, string $method, $data = array(), array $headers = array())
{
self::$lastErrors = array();
$headers = array_merge(array(
'Authorization' => 'Bearer ' . $this->getToken(),
'Content-Type' => 'application/vnd.allegro.public.v1+json',
'Accept' => 'application/vnd.allegro.public.v1+json',
'Accept-Language' => 'pl-PL',
), $headers);
stCommunication::forceSocketConnectionTime();
self::$lastHeaders = array();
$httpHeaders = self::parseHeaders($headers);
$ch = curl_init(stristr($resource, 'http') !== false ? $resource : $this->getUrl() . '/' . ltrim($resource, '/'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, array('AllegroRestApi', 'setCurlHeaders'));
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
if (!empty($data))
{
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($data) ? json_encode($data) : $data);
}
if ($data)
{
stPayment::log('allegro', sprintf("Calling %s (method: %s, headers: %s, data: %s)", $resource, strtoupper($method), json_encode($headers, JSON_UNESCAPED_UNICODE), json_encode($data, JSON_UNESCAPED_UNICODE)));
}
else
{
stPayment::log('allegro', sprintf("Calling %s (method: %s, headers: %s)", $resource, strtoupper($method), json_encode($headers, JSON_UNESCAPED_UNICODE)));
}
$response = curl_exec($ch);
if (false === $response)
{
$error = curl_error($ch);
self::$lastErrors = array(new stdClass());
self::$lastErrors[0]->code = curl_errno($ch);
self::$lastErrors[0]->message = $error;
self::$lastErrors[0]->path = null;
self::$lastErrors[0]->details = null;
self::$lastErrors[0]->userMessage = $error;
$e = new stAllegroException($error);
$trace = str_replace("\n", ", ", $e->getTraceAsString());
stPayment::log('allegro', sprintf("Got exception \"%s\" (headers: %s, trace: %s)", $e->getMessage(), json_encode(self::$lastHeaders, JSON_UNESCAPED_UNICODE), $trace));
throw $e;
}
if ($response)
{
$response = json_decode($response);
}
$info = curl_getinfo($ch);
self::$lastHttpCode = $info['http_code'];
self::$lastRequestInfo = $info;
if (self::$lastHttpCode >= 400)
{
if (isset($response->errors))
{
self::$lastErrors = $response->errors;
}
if (isset($response->error))
{
self::$lastErrors = array(new stdClass());
self::$lastErrors[0]->code = $response->error;
self::$lastErrors[0]->message = $response->error_description;
self::$lastErrors[0]->path = null;
self::$lastErrors[0]->details = null;
self::$lastErrors[0]->userMessage = $response->error_description;
}
$traceId = isset(self::$lastHeaders['trace-id']) ? self::$lastHeaders['trace-id'] : 'none';
$e = new stAllegroException(self::$lastErrors ? self::$lastErrors[0]->message : (is_object($response) ? json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) : $response). " (trace-id: $traceId)", self::$lastHttpCode);
$trace = str_replace("\n", ", ", $e->getTraceAsString());
stPayment::log('allegro', sprintf("Got exception \"%s\" (headers: %s, trace: %s)", $e->getMessage(), json_encode(self::$lastHeaders, JSON_UNESCAPED_UNICODE), $trace));
throw $e;
}
stCommunication::restoreSocketConnectionTime();
return $response;
}
/**
* Last Error response from Allegro REST API
*
* @return stdClass
*/
public static function getLastErrors()
{
return self::$lastErrors;
}
public static function getLastErrorsAsString($delimiter = "\n")
{
$messages = array();
$errors = self::getLastErrors();
foreach ($errors as $error)
{
$messages[] = $error->userMessage ? $error->userMessage : $error->message;
}
return implode($delimiter, $messages);
}
public static function getLastRequestInfo()
{
return self::$lastRequestInfo;
}
public static function getLastHttpCode()
{
return self::$lastHttpCode;
}
protected static function setCurlHeaders($handle, $header)
{
$details = explode(':', $header, 2);
if (count($details) == 2)
{
$key = trim($details[0]);
$value = trim($details[1]);
self::$lastHeaders[$key] = $value;
}
return strlen($header);
}
protected static function parseHeaders(array $headers)
{
$result = array();
foreach ($headers as $header => $value)
{
$result[] = "$header: $value";
}
return $result;
}
}

View File

@@ -0,0 +1,832 @@
<?php
class stAllegroApi
{
const ALLEGRO_URL = 'https://allegro.pl';
const ALLEGRO_ARCHIVE_URL = 'https://archiwum.allegro.pl';
const ALLEGRO_SANDBOX_URL = 'https://allegro.pl.allegrosandbox.pl';
/**
* offer is visible on site and available for purchase, occurs when offer status changes from ACTIVATING to ACTIVE.
*/
const OFFER_ACTIVATED = 'OFFER_ACTIVATED';
/**
* occurs when offer's fields has been changed e.g. description or photos.
*/
const OFFER_CHANGED = 'OFFER_CHANGED';
/**
* offer is no longer available for purchase, occurs when offer status changes from ACTIVE to ENDED.
*/
const OFFER_ENDED = 'OFFER_ENDED';
/**
* stock in an offer was changed either via purchase or by seller.
*/
const OFFER_STOCK_CHANGED = 'OFFER_STOCK_CHANGED';
/**
* occurs when price in an offer was changed.
*/
const OFFER_PRICE_CHANGED = 'OFFER_PRICE_CHANGED';
/**
* offer is no longer available on listing and has been archived
*/
const OFFER_ARCHIVED = 'OFFER_ARCHIVED';
/**
* bid was placed on the offer
*/
const OFFER_BID_PLACED = 'OFFER_BID_PLACED';
/**
* bid for offer was canceled
*/
const OFFER_BID_CANCELED = 'OFFER_BID_CANCELED';
const FILTER_SINGLE = 'SINGLE';
const FILTER_MULTI = 'MULTI';
const FILTER_NUMERIC = 'NUMERIC';
const FILTER_NUMERIC_SINGLE = 'NUMERIC_SINGLE';
const STATUS_INACTIVE = "INACTIVE";
const STATUS_ACTIVATING = "ACTIVATING";
const STATUS_ACTIVE = "ACTIVE";
const STATUS_ENDED = "ENDED";
protected static $instance = null;
/**
* AllegroRestApi instance
*
* @var AllegroRestApi
*/
protected $api = null;
/**
* stConfig instance
*
* @var stConfig
*/
protected $config = null;
/**
* Bazowy język wystawianej oferty
*
* @var string
*/
protected $language;
/**
* Get stAllegroApi instance
*
* @return self
*/
public static function getInstance()
{
if (null === self::$instance)
{
self::$instance = new static();
self::$instance->initialize();
}
return self::$instance;
}
public static function redirectAuthUri()
{
return sfContext::getInstance()->getController()->genUrl('@stAllegroPlugin?action=config', true);
}
public function initialize()
{
$this->config = stConfig::getInstance('stAllegroBackend');
try
{
$this->refreshToken();
}
catch(stAllegroException $e)
{
$this->api = new AllegroRestApi($this->config->get('access_token'), $this->config->get('sandbox'));
throw $e;
}
$this->api = new AllegroRestApi($this->config->get('access_token'), $this->config->get('sandbox'));
$this->language = stLanguage::getOptLanguage() == 'pl_PL' ? 'pl-PL' : 'en-EN';
}
public function refreshToken()
{
if (time() >= $this->config->get('expires'))
{
$response = AllegroRestApi::refreshToken($this->config->get('refresh_token'), $this->config->get('client_id'), $this->config->get('client_secret'), self::redirectAuthUri(), $this->config->get('sandbox'));
if ($response)
{
if (isset($response->error))
{
throw new stAllegroException($response->error);
}
$this->config->set('access_token', $response->access_token);
$this->config->set('refresh_token', $response->refresh_token);
$this->config->set('expires', $response->expires_in + time());
$this->config->set('seller_id', $response->seller_id);
$this->config->save(true);
}
}
}
public function getBasicInfoAboutUser()
{
return $this->apiCall('get', '/me');
}
public function getDeliveryMethods()
{
$response = $this->apiCall('get', '/sale/delivery-methods?marketplace=allegro-pl');
if ($response)
{
return $response->deliveryMethods;
}
return null;
}
public function getShippingRates()
{
$response = $this->apiCall('get', '/sale/shipping-rates?seller.id=' . $this->config->get('seller_id'));
if (isset($response->shippingRates))
{
return $response->shippingRates;
}
return null;
}
public function getShippingRate($id)
{
$response = $this->apiCall('get', '/sale/shipping-rates/'.$id);
if ($response)
{
$rates = array();
foreach ($response->rates as $rate)
{
$rates[$rate->deliveryMethod->id] = $rate;
}
$response->rates = $rates;
}
return $response;
}
public function updateShippingRate($id, $data)
{
$rates = array();
foreach ($data['rates'] as $methodId => $rate)
{
$rates[] = array(
'deliveryMethod' => array('id' => $methodId),
'maxQuantityPerPackage' => $rate['max_quantity_per_package'],
'firstItemRate' => $rate['first_item_rate'],
'nextItemRate' => $rate['next_item_rate'],
);
}
$request = array(
'id' => $id,
'name' => $data['name'],
'rates' => $rates,
);
return $this->apiCall('put', '/sale/shipping-rates/'.$id, $request);
}
public function createShippingRate($data)
{
$rates = array();
if ($data['rates'])
{
foreach ($data['rates'] as $methodId => $rate)
{
$rates[] = array(
'deliveryMethod' => array('id' => $methodId),
'maxQuantityPerPackage' => $rate['max_quantity_per_package'],
'firstItemRate' => $rate['first_item_rate'],
'nextItemRate' => $rate['next_item_rate'],
);
}
}
$request = array(
'name' => $data['name'],
'rates' => $rates,
);
return $this->apiCall('post', '/sale/shipping-rates', $request);
}
public function getProducts(array $params)
{
$filterquerystring = array();
if (isset($params['filters']))
{
foreach ($params['filters'] as $name => $filter)
{
switch ($filter['type'])
{
case self::FILTER_SINGLE:
case self::FILTER_NUMERIC_SINGLE:
$filterquerystring[] = $name . '=' . rawurlencode($filter['value']);
break;
case self::FILTER_MULTI:
foreach ($filter['value'] as $name => $value)
{
$filterquerystring[] = $name . '=' . rawurlencode($value);
}
break;
case self::FILTER_NUMERIC:
$filterquerystring[] = $name . '.from=' . rawurlencode($filter['value']['from']);
$filterquerystring[] = $name . '.to=' . rawurlencode($filter['value']['to']);
break;
}
}
unset($params['filters']);
}
$query = $params ? '?' . http_build_query($params, '', '&') : '';
if ($filterquerystring)
{
$query = $query ? '&'.implode("&", $filterquerystring) : '?'.implode("&", $filterquerystring);
}
return $this->apiCall('get', '/sale/products' . $query);
}
public function getProduct($id)
{
return $this->apiCall('get', '/sale/products/' . rawurlencode($id));
}
public function getOffers($params = array())
{
$externalId = [];
$params['publication.marketplace'] = 'allegro-pl';
if (isset($params['external.id']) && is_array($params['external.id'])) {
foreach ($params['external.id'] as $id)
{
$externalId[] = 'external.id='.$id;
}
unset($params['external.id']);
}
$query = $params ? '?' . http_build_query($params, '', '&') : '';
return $this->apiCall('get', '/sale/offers'.$query.($query ? '&'.implode("&", $externalId) : '?'.implode("&", $externalId)));
}
public function getOffer($id)
{
$response = $this->apiCall('get', '/sale/offers/'.$id);
if ($response->parameters)
{
$parameters = array();
foreach ($response->parameters as $parameter)
{
$parameters[$parameter->id] = $parameter;
}
$response->parameters = $parameters;
}
return $response;
}
public function getCategoryParameters($categoryId)
{
$response = $this->apiCall('get', '/sale/categories/' . $categoryId . '/parameters');
return $response->parameters;
}
public function getCategories($parentId = null)
{
if ($parentId)
{
$response = $this->apiCall('get', '/sale/categories?parent.id=' . $parentId);
}
else
{
$response = $this->apiCall('get', '/sale/categories');
}
if ($response)
{
return $response->categories;
}
return array();
}
public function getCategory($categoryId)
{
return $this->apiCall('get', '/sale/categories/'.$categoryId);
}
public function getMatchingCategories($searchPhrase)
{
$query = http_build_query(array(
'name' => $searchPhrase
), null, '&');
$response = $this->apiCall('get', '/sale/matching-categories?'.$query);
return $response ? $response->matchingCategories : array();
}
public function getCategoryPath($parentId)
{
$path = array();
$response = $this->getCategory($parentId);
$path[] = $response;
while($response && null !== $response->parent)
{
$response = $this->getCategory($response->parent->id);
$path[] = $response;
}
return $path ? array_reverse($path) : array();
}
public function deleteDraftOffer($id)
{
return $this->apiCall('delete', '/sale/offers/'.$id);
}
public static function getOfferUrl($offerNumber)
{
return self::getAllegroUrl() . '/oferta/' . $offerNumber;
}
public static function getArchiveOfferUrl($offerNumber)
{
return self::ALLEGRO_ARCHIVE_URL . '/oferta/' . $offerNumber;
}
public static function getOrderUrl($checkoutFormId)
{
return self::getAllegroUrl() . '/moje-allegro/sprzedaz/zamowienia/' . $checkoutFormId;
}
public static function getAllegroUrl()
{
$config = stConfig::getInstance('stAllegroBackend');
return $config->get('sandbox') ? self::ALLEGRO_SANDBOX_URL : self::ALLEGRO_URL;
}
public function updateOffer($id, stdClass $offer)
{
if (property_exists($offer, 'ean'))
{
unset($offer->ean);
}
if (!isset($offer->language) || empty($offer->language) && $offer->publication->status == self::STATUS_INACTIVE)
{
$offer->language = $this->language;
}
$data = self::objectToArray($offer);
$data['parameters'] = array_values($data['parameters']);
return $this->apiCall('put', '/sale/offers/'.$id, $data);
}
public function createOffer(stdClass $offer)
{
if (!isset($offer->language) || empty($offer->language))
{
$offer->language = $this->language;
}
$data = self::objectToArray($offer);
foreach ($data as $name => $value)
{
if (null === $value)
{
unset($data[$name]);
}
}
$data['parameters'] = array_values($data['parameters']);
// throw new Exception("<pre>".var_export($data, true)."</pre>");
$response = $this->apiCall('post', '/sale/offers', $data);
// throw new Exception("<pre>".var_export($response, true)."</pre>");
if ($response->parameters)
{
$parameters = array();
foreach ($response->parameters as $parameter)
{
$parameters[$parameter->id] = $parameter;
}
$response->parameters = $parameters;
}
return $response;
}
public function addParcelTrackingNumber($checkoutFormId, $carrierId, $trackingNumber, array $lineItems = [])
{
$params = [
'carrierId' => $carrierId,
'waybill' => $trackingNumber,
];
if (!empty($lineItems))
{
$params['lineItems'] = array_map(function($value) {
return ['id' => $value];
}, $lineItems);
}
return $this->api->post("/order/checkout-forms/$checkoutFormId/shipments", $params);
}
public function getAvailableShippingCarriers()
{
$response = $this->api->get('/order/carriers');
return $response ? $response->carriers : array();
}
public function getAccountAdditionalEmails()
{
return $this->apiCall('get', '/account/additional-emails/');
}
public function getImpliedWarranties()
{
$response = $this->apiCall('get', '/after-sales-service-conditions/implied-warranties?seller.id=' . $this->config->get('seller_id'));
return $response && $response->impliedWarranties ? $response->impliedWarranties : array();
}
public function getWarranties()
{
$response = $this->apiCall('get', '/after-sales-service-conditions/warranties?seller.id=' . $this->config->get('seller_id'));
return $response && $response->warranties ? $response->warranties : array();
}
public function getReturnPolicies()
{
$response = $this->apiCall('get', '/after-sales-service-conditions/return-policies?seller.id=' . $this->config->get('seller_id'));
return $response && $response->returnPolicies ? $response->returnPolicies : array();
}
public function uploadImage($imageFile)
{
$fileMimeType = mime_content_type($imageFile);
$data = file_get_contents($imageFile);
return $this->apiCall('post', $this->api->getUploadUrl() . '/sale/images', $data, array(
'Content-Type' => $fileMimeType,
));
}
public function getPricingFeePreview(array $params)
{
return $this->apiCall('post', '/pricing/fee-preview', $params);
}
public function getOfferQuotes($id)
{
return $this->apiCall('get', '/pricing/offer-quotes?offer.id=' . $id);
}
public function publishOffers(array $offers, $activate = true)
{
$params = array('offerCriteria' => array(array(
'offers' => array_map(function($id) {
return array('id' => intval($id));
}, $offers),
'type' => 'CONTAINS_OFFERS',
)),
'publication' => array(
'action' => $activate ? 'ACTIVATE' : 'END',
));
$response = $this->apiCall('put', '/sale/offer-publication-commands/' . $this->api->getUuid(), $params);
return $response;
}
public function getPublishOffersReport($commandId)
{
$response = $this->apiCall('get', "/sale/offer-publication-commands/$commandId/tasks");
if ($response)
{
return $response->tasks;
}
return null;
}
public function getPaymentMapping($paymentId)
{
$response = $this->apiCall('get', '/payments/payment-id-mappings?paymentId=' . $paymentId);
if ($response)
{
return $response->transactionId;
}
return null;
}
public function getOrderCheckoutForms($offset = null, $fromDate = null, $type = "READY_FOR_PROCESSING", $limit = 10)
{
$params = array(
'status' => $type,
'limit' => $limit,
'marketplace.id' => 'allegro-pl'
);
if (null !== $fromDate)
{
$params['updatedAt.gte'] = $fromDate;
}
if (null !== $offset)
{
$params['offset'] = $offset;
}
$query = http_build_query($params, null, '&');
return $this->apiCall('get', "/order/checkout-forms?" . $query);
}
public function getOrderCheckoutForm($checkoutFormId)
{
return $this->api->get("/order/checkout-forms/$checkoutFormId");
}
public function getOfferEvents($from = null, $type = null, $limit = 100)
{
$params = array(
'limit' => $limit,
);
if (null !== $from)
{
$params['from'] = $from;
}
$query = http_build_query($params, null, '&');
if (null !== $type)
{
$query .= is_array($type) ? '&type='.implode('&type=', $type) : '&type='.$type;
}
$response = $this->api->get("/sale/offer-events?".$query);
return $response ? $response->offerEvents : array();
}
public function getOrderEvents($from = null, $type = "READY_FOR_PROCESSING", $limit = 10)
{
$params = array(
'status' => $type,
'limit' => $limit,
);
if (null !== $from)
{
$params['offset'] = $from;
}
$query = http_build_query($params, null, '&');
$response = $this->apiCall('get', "/order/events?" . $query);
if ($response && isset($response->events))
{
return $response->events;
}
return null;
}
public function getOrderEventStats()
{
$response = $this->apiCall('get', "/order/event-stats");
if ($response && isset($response->latestEvent))
{
return $response->latestEvent;
}
return null;
}
/**
* Wywołuje adres zasobu API
*
* @param string $method Metoda GET, POST, PUT, DELETE
* @param string $url Adres zasobu
* @param array|string $data Dane
* @param array $headers Dodatkowe nagłówki
* @return void
*/
public function apiCall(string $method, string $url, $data = array(), array $headers = array())
{
$this->refreshToken();
return $this->api->sendRequest($url, $method, $data, $headers);
}
public static function objectToArray($data) {
if (is_object($data)) {
// Gets the properties of the given object
// with get_object_vars function
$data = get_object_vars($data);
}
if (is_array($data)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(array('stAllegroApi', 'objectToArray'), $data);
}
else {
// Return array
return $data;
}
}
public static function arrayToObject($data, $camelize = false)
{
if (is_array($data))
{
if (!isset($data[0]) && !empty($data))
{
$results = array();
foreach ($data as $index => $value)
{
$results[$camelize ? lcfirst(sfInflector::camelize($index)) : $index] = self::arrayToObject($value, $camelize);
}
return (object)$results;
}
else
{
$results = array();
foreach ($data as $index => $value)
{
$results[$index] = self::arrayToObject($value, $camelize);
}
return $results;
}
}
else {
// Return object
return !empty($data) ? $data : null;
}
}
public static function getErrorByHttpCode($code)
{
$errors = array(
400 => 'Wysłano niepoprawne dane JSON.',
401 => 'Użytkownik nie jest uwierzytelniony - Proszę ponownie zalogować się w Allegro.',
403 => 'Nie masz praw dostępu do danego zasobu.',
404 => 'Odpytywany zasób nie istnieje w API.',
406 => 'W nagłówku Accept przekazany został nieobsługiwany przez zasób typ danych.',
415 => 'W nagłówku Accept przekazany został nieobsługiwany przez zasób typ danych.',
422 => 'Wysłano niepoprawne wartości pól, np. walidacja obiektu zwróciła błąd, albo któreś z pól nie spełnia kryteriów nałożonych na nie przez zasób.',
429 => 'Klient przekroczył limit liczby żądań.',
503 => 'Połączenie z serwisem nie jest możliwe.',
);
return isset($errors[$code]) ? $errors[$code] : null;
}
public static function getDeliveryTimes()
{
return array(
'PT0S' => 'natychmiast',
'PT24H' => '24 godziny',
'PT48H' => '2 dni',
'PT72H' => '3 dni',
'PT96H' => '4 dni',
'PT120H' => '5 dni',
'PT168H' => '7 dni',
'PT240H' => '10 dni',
'PT336H' => '14 dni',
'PT504H' => '21 dni',
'PT720H' => '30 dni',
'PT1440H' => '60 dni',
);
}
public static function getDurationTimes()
{
return array(
'' => 'Do wyczerpania przedmiotów',
'PT72H' => '3 dni',
'PT120H' => '5 dni',
'PT168H' => '7 dni',
'PT240H' => '10 dni',
'PT480H' => '20 dni',
'PT720H' => '30 dni',
);
}
public static function getStatusList()
{
return array(
self::STATUS_INACTIVE => "Szkic",
self::STATUS_ACTIVE => "Aktywna",
self::STATUS_ACTIVATING => "W trakcie aktywacji",
self::STATUS_ENDED => "Zakończona",
);
}
public static function getPaymentInvoiceList()
{
return array(
"NO_INVOICE" => "Nie wystawiam faktury",
"VAT" => "Faktura VAT",
"VAT_MARGIN" => "Faktura VAT-marża",
"WITHOUT_VAT" => "Faktura bez VAT",
);
}
public static function getIntervalToDays($interval)
{
$interval = new DateInterval($interval);
$seconds = ($interval->d * 24 * 60 * 60) +
($interval->h * 60 * 60) +
($interval->i * 60) +
$interval->s;
return $seconds / (60 * 60 * 24);
}
public static function formatDate($date, $format = "d-m-Y")
{
$time = strtotime($date);
return date($format, $time);
}
public static function getLastErrors()
{
return AllegroRestApi::getLastErrors();
}
public static function getLastErrorsAsString($delimiter = "\n")
{
return AllegroRestApi::getLastErrorsAsString($delimiter);
}
public static function getLastHttpCode()
{
return AllegroRestApi::getLastHttpCode();
}
}

View File

@@ -0,0 +1,333 @@
<?php
class stAllegroListener {
public static function generateStProduct(sfEvent $event) {
$event->getSubject()->attachAdminGeneratorFile('stAllegroPlugin', 'stProductAllegro.yml');
}
public static function generateStOrder(sfEvent $event) {
$event->getSubject()->attachAdminGeneratorFile('stAllegroPlugin', 'stOrderAllegro.yml');
}
public static function postExecuteAllegroCustom(sfEvent $event) {
$productId = $event->getSubject()->forward_parameters['product_id'];
$c = new Criteria();
$c->add(AllegroAuctionPeer::PRODUCT_ID, $productId);
$hasAuctions = (bool) AllegroAuctionPeer::doCount($c);
if (!$hasAuctions) {
$config = stConfig::getInstance('stAllegroPlugin');
if ($config->get('allegro_pl_api_key', null) && (!$config->get('sandbox_api_key') || !$config->get('sandbox_enabled'))) {
$category = new stAllegroCategory('AllegroPl');
if ($category->checkStatus() == 1)
return $event->getSubject()->redirect('stProduct/allegroEdit?product_id='.$productId.'&environment=allegro-pl');
}
}
}
public static function preExecuteAllegroEdit(sfEvent $event) {
$auction = null;
if ($id = $event->getSubject()->getRequestParameter('id')) {
$auction = AllegroAuctionPeer::retrieveByPK($id);
}
$env = (is_object($auction) && $auction->getEnvironment() != '') ? $auction->getEnvironment() : $event->getSubject()->getRequestParameter('environment');
if (stAllegro::getInstance($env)->testConnection() == false)
return $event->getSubject()->redirect('stAllegroBackend/connectionError?environment='.$env);
}
public static function preDeleteAllegro(sfEvent $event) {
$productId = $event->getSubject()->allegro_auction->getProductId();
$event->getSubject()->allegro_auction->delete();
return $event->getSubject()->redirect('stProduct/allegroCustom?product_id='.$productId);
}
public static function addTaskScheluderTasks(sfEvent $event)
{
$config = stConfig::getInstance('stAllegroBackend');
if ($config->get('enable') && !empty($config->get('access_token')))
{
stTaskConfiguration::addTask(
'allegro_order_import',
stAllegroOrderImportTask::class,
'Allegro - Import zamówień',
array(
'time_interval' => stTaskConfiguration::TIME_INTERVAL_10MIN,
'priority' => stTaskConfiguration::PRIORITY_FIRST,
'is_active' => true,
)
);
stTaskConfiguration::addTask(
'allegro_sync',
stAllegroSyncTask::class,
'Allegro - Synchronizacja ofert',
array(
'time_interval' => stTaskConfiguration::TIME_INTERVAL_10MIN,
'priority' => stTaskConfiguration::PRIORITY_FIRST + 1,
'is_active' => true,
)
);
stTaskConfiguration::addTask(
'allegro_send_tracking_number',
stAllegroSendTackingNumberTask::class,
'Allegro - Nadanie numeru paczki w ofercie',
array(
'time_interval' => stTaskConfiguration::TIME_INTERVAL_10MIN,
'priority' => stTaskConfiguration::PRIORITY_FIRST + 2,
'is_active' => true,
)
);
stTaskConfiguration::addTask(
'allegro_event',
stAllegroEventTask::class,
'Allegro - Dziennik zdarzeń',
array(
'time_interval' => stTaskConfiguration::TIME_INTERVAL_10MIN,
'priority' => stTaskConfiguration::PRIORITY_FIRST + 3,
'is_active' => true,
)
);
}
}
public static function validateAllegroEdit(sfEvent $event, $ok)
{
$action = $event->getSubject();
$i18n = $action->getContext()->getI18N();
if ($action->getRequest()->getMethod() != sfRequest::POST)
{
$id = $action->getRequestParameter('id');
$auction = AllegroAuctionPeer::retrieveByPK($id);
if (null !== $auction && $auction->getAllegroCategoryId())
{
$allegro = stAllegro::getInstance($auction->getSite());
$allegro->doLogin();
try
{
$response = $allegro->call('doGetCategoryPath', array(
'sessionId' => $allegro->getSessionHandle(),
'categoryId' => $auction->getAllegroCategory()->getCatId(),
));
$response = stAllegroHelper::objectToArray($response);
$last = $response['categoryPath'] ? end($response['categoryPath']['item']) : array();
if (!$last)
{
$action->getRequest()->setError('allegro_auction{allegro_category_id}', $i18n->__('Wybrana kategoria nie istnieje już na allegro lub zmieniła swoją lokalizacje (Wykonaj import kategorii z allegro i wybierz nową kategorię)', null, 'stAllegroBackend'));
$ok = false;
}
elseif (!$last['catIsLeaf'])
{
$action->getRequest()->setError('allegro_auction{allegro_category_id}', $i18n->__('Wybrana kategoria zawiera dodatkowe podkategorie (Jeżeli nie widzisz dodatkowych podkategorii wykonaj import kategorii z allegro wybierz nową podkategorię)', null, 'stAllegroBackend'));
$ok = false;
}
}
catch (Exception $e)
{
$action->getRequest()->setError('allegro_auction{allegro_category_id}', $e->getMessage());
$ok = false;
}
}
}
else
{
$data = $action->getRequest()->getParameter('allegro_auction');
$text = stJQueryToolsHelper::parseTokensFromRequest($data['text']);
if (empty($text))
{
$action->getRequest()->setError('allegro_auction{text}', $i18n->__('Uzupełnij opis', null, 'stAllegroBackend'));
}
else
{
$error = false;
foreach ($text as $section)
{
foreach ($section['content'] as $content)
{
if (empty($content['value']))
{
$error = true;
}
}
}
if ($error)
{
$action->getRequest()->setError('allegro_auction{text}', $i18n->__('Uzupełnij opis', null, 'stAllegroBackend'));
$ok = false;
}
}
}
return $ok;
}
public static function GetAllegroOrCreate(sfEvent $event) {
if (!$event->getSubject()->getRequestParameter('id')) {
$auction = $event->getSubject()->allegro_auction;
$productId = $event->getSubject()->getRequestParameter('product_id');
$environment = $event->getSubject()->getRequestParameter('environment');
$environment = stAllegro::parseEnvironment($environment);
$product = ProductPeer::retrieveByPK($productId);
if ($product) {
$auction->setProductId($productId);
$auction->setEan($product->getManCode());
$auction->setAllegroCategoryId(0);
$auction->setName($product->getName());
$auction->setText(preg_replace('/<\/?(html|body|meta|head|!doctype).*>/i', '', $product->getDescription()));
$auction->setShortText(preg_replace('/<\/?(html|body|meta|head|!doctype).*>/i', '', $product->getShortDescription()));
$auction->setSite($environment);
$auction->setAuctionType(0);
$auction->setWhoPay(1);
$auction->setPriceBuyNow($product->getOptPriceBrutto());
$auction->setStock(1);
$auction->setHowLong(7);
}
}
}
public static function postUpdateAllegroFromRequest(sfEvent $event) {
$auction = $event->getSubject()->allegro_auction;
$request = $event->getSubject()->getRequestParameter('allegro_auction');
$fields = array('auction_type', 'price_buy_now', 'price_start', 'price_min', 'stock', 'stock_type', 'how_long', 'allegro_template_id', 'shipping_time',
'who_pay', 'other_text', 'short_text', 'attributes', 'depository_on_sale', 'resumption', 'ean');
foreach ($fields as $field)
if (isset($request[$field])) {
$auction->{sfInflector::camelize('set_'.$field)}($request[$field]);
}
if ($request['text'])
{
if ($auction->hasNewDescriptionFormat())
{
$auction->setText(stJQueryToolsHelper::parseTokensFromRequest($request['text']));
}
else
{
$auction->setText($request['text']);
}
}
if (!isset($request['depository_on_sale'])) {
$auction->setDepositoryOnSale(false);
}
if (isset($request['allegro_category_id'])) {
$category = json_decode(json_decode($request['allegro_category_id']), true);
if (isset($category[0]['id'])) {
$category = AllegroCategoryPeer::doSelectByCatId($category[0]['id'], $auction->getEnvironment());
if (is_object($category))
$auction->setAllegroCategoryId($category->getId());
}
}
if (isset($request['15'])) {
$options = 0;
foreach ($request['15']['value'] as $v)
$options = $options+$v;
$auction->setOtherOption($options);
} else {
$auction->setOtherOption(0);
}
if (isset($request['14'])) {
$options = 0;
foreach ($request['14']['value'] as $v)
$options = $options+$v;
$auction->setPayOption($options);
} else {
$auction->setPayOption(0);
}
if (isset($request['delivery']))
{
foreach ($request['delivery'] as $key => $value)
if (!isset($request['delivery'][$key]['enabled']))
$request['delivery'][$key]['enabled'] = false;
else
$request['delivery'][$key]['enabled'] = true;
$auction->setDelivery($request['delivery']);
}
}
public static function postSaveAllegro(sfEvent $event) {
$t = $event->getSubject();
if ($t->getRequest()->getMethod() == sfRequest::POST) {
$auction = $event['modelInstance'];
if (stAllegro::getInstance($auction->getEnvironment())->testConnection()) {
if ($t->getRequestParameter('validate_auction')) {
try {
$response = stAllegro::getInstance($auction->getEnvironment())->checkAuction($auction);
if (is_object($response))
$event->getSubject()->setFlash('allegro-validate-message', stAllegroHelper::objectToArray($response));
else
$event->getSubject()->setFlash('allegro-validate-error', stAllegro::getInstance($auction->getEnvironment())->getLastError());
} catch (AllegroValidationException $e) {
$event->getSubject()->setFlash('allegro-error', $e->getMessage());
} catch (AllegroException $e) {
$event->getSubject()->setFlash('allegro-validate-error', $e->getMessage());
}
}
if ($t->getRequestParameter('create_auction')) {
return $t->redirect('stAllegroBackend/sale?id='.$auction->getId());
}
}
}
}
public static function addAllegroFiltersCriteria(sfEvent $event) {
$action = $event->getSubject();
/**
* @var Criteria $c
*/
$c = $event['criteria'];
if ((!isset($action->filters['order_auctions']) || "" === $action->filters['order_auctions']) && (!isset($action->filters['opt_allegro_checkout_form_id']) || "" === $action->filters['opt_allegro_checkout_form_id']))
{
$c->addJoin(OrderPeer::ID, AllegroAuctionHasOrderPeer::ORDER_ID, Criteria::LEFT_JOIN);
$cc = $c->getNewCriterion(OrderPeer::OPT_ALLEGRO_CHECKOUT_FORM_ID, null, Criteria::ISNOTNULL);
$cc->addOr($c->getNewCriterion(AllegroAuctionHasOrderPeer::ORDER_ID, null, Criteria::ISNOTNULL));
$c->add($cc);
$c->addGroupByColumn(OrderPeer::ID);
}
elseif (isset($action->filters['order_auctions']) && "" !== $action->filters['order_auctions'])
{
$c->addJoin(OrderProductPeer::ORDER_ID, OrderPeer::ID, Criteria::LEFT_JOIN);
$c->add(OrderProductPeer::ALLEGRO_AUCTION_ID, $action->filters['order_auctions']);
}
}
}

View File

@@ -0,0 +1,36 @@
<?php
class stAllegroPager extends sfPager
{
public function __construct($page = 1, $maxPerPage = 20)
{
$this->setPage($page);
$this->setMaxPerPage($maxPerPage);
}
public function setTotalCount($count)
{
$this->setNbResults($count);
$this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage()));
}
public function getOffset()
{
return ($this->getPage() - 1) * $this->getMaxPerPage();
}
public function init()
{
}
public function getResults()
{
}
protected function retrieveObject($offset)
{
}
}

View File

@@ -0,0 +1,108 @@
<?php
class stAllegroEventTask extends stTask
{
public function count(): int
{
if (!$this->getParameter('event_count'))
{
$this->setParameter('event_count', 1000);
}
return $this->getParameter('event_count');
}
public function execute(int $offset): int
{
try
{
$events = $this->getEvents();
if (empty($events))
{
return $this->doCount();
}
}
catch (Throwable $e)
{
$this->getLogger()->error("Wystąpił błąd podczas pobierania informacji o zdarzeniach:\n%error%", array('%error%' => stAllegroApi::getLastErrorsAsString()));
return $this->doCount();
}
foreach ($events as $event)
{
switch ($event->type)
{
case stAllegroApi::OFFER_ACTIVATED:
$auction = AllegroAuctionPeer::retrieveByAuctionNumber($event->offer->id);
if (null !== $auction)
{
$auction->setEnded(false);
$auction->save();
$this->getLogger()->info("Oferta %offer% została oznaczona jako aktywna", array(
'%offer%' => sprintf('[%s](%s)', $event->offer->id, stAllegroApi::getOfferUrl($event->offer->id)),
));
}
break;
case stAllegroApi::OFFER_ENDED:
$auction = AllegroAuctionPeer::retrieveByAuctionNumber($event->offer->id);
if (null !== $auction)
{
$auction->setEnded(true);
$auction->save();
$this->getLogger()->info("Oferta %offer% została oznaczona jako zakończona", array(
'%offer%' => sprintf('[%s](%s)', $event->offer->id, stAllegroApi::getOfferUrl($event->offer->id)),
));
}
break;
case stAllegroApi::OFFER_ARCHIVED:
$auction = AllegroAuctionPeer::retrieveByAuctionNumber($event->offer->id);
if (null !== $auction)
{
$auction->delete();
$this->getLogger()->info("Oferta %offer% została usunięta ze sklepu, ponieważ nie istnieje już na allegro", array(
'%offer%' => $event->offer->id,
));
}
break;
}
$offset++;
usleep(250000);
}
$this->updateLastEventId($event->id);
if ($offset >= $this->doCount())
{
$this->setParameter('event_count', $offset + 200);
$this->doCount(true);
}
return $offset;
}
protected function getEvents(): array
{
$api = stAllegroApi::getInstance();
$config = stConfig::getInstance('stAllegroBackend');
return $api->getOfferEvents($config->get('last_offer_event_id', null), [stAllegroApi::OFFER_ACTIVATED, stAllegroApi::OFFER_ARCHIVED, stAllegroApi::OFFER_ENDED], 100);
}
protected function updateLastEventId($id)
{
$config = stConfig::getInstance('stAllegroBackend');
$config->set('last_offer_event_id', $id);
$config->save();
}
}

View File

@@ -0,0 +1,533 @@
<?php
class stAllegroOrderImportTask extends stTask
{
/**
* Allegro config instance
*
* @var stConfig
*/
protected $config = null;
/**
* Allegro API instance
*
* @var stAllegroApi
*/
protected $api = null;
/**
* Default Tax instance
*
* @var Tax
*/
protected $tax = null;
/**
* Default OrderStatus instance
*
* @var OrderStatus
*/
protected $orderStatus = null;
protected $allegroPaymentType = null;
/**
* @var stEventDispatcher
*/
protected $dispatcher;
/**
* Domyślny status dla nowego zamówienia
*
* @var OrderStatus
*/
protected $defaultOrderStatus;
protected static $userGroup = null;
public function count(): int
{
$count = 0;
if (!stConfig::getInstance('stAllegroBackend')->get('access_token'))
{
return 0;
}
try
{
$fromDate = gmdate('Y-m-d\TH:i:s\Z', time() - 60*60*24 * stConfig::getInstance('stAllegroBackend')->get('import_offset'));
$api = stAllegroApi::getInstance();
$forms = $api->getOrderCheckoutForms(null, $fromDate);
$count = $forms->totalCount;
$this->setParameter('from_date', $fromDate);
}
catch (stAllegroException $e)
{
$errors = stAllegroApi::getLastErrors();
if ($errors)
{
foreach ($errors as $error)
{
$this->getLogger()->error($error->message);
}
}
else
{
$this->getLogger()->exception($e);
}
}
return $count;
}
public function finished()
{
$this->clearCache();
}
public function execute(int $offset): int
{
sfLoader::loadHelpers(array('Helper', 'I18N', 'stUrl', 'stOrder', 'stDate'));
$response = $this->getApi()->getOrderCheckoutForms($offset, $this->getParameter('from_date'));
foreach ($response->checkoutForms as $form)
{
$order = $this->getOrder($form);
if (null === $order)
{
$order = new Order();
$order->setClientCulture('pl_PL');
$order->setOptAllegroCheckoutFormId($form->id);
$order->setOptAllegroNick($form->buyer->login);
$order->setOptClientEmail($form->buyer->email);
$order->setOrderCurrency($this->getOrderCurrency());
$order->setOrderStatus($this->getDefaultOrderStatus());
$this->addProducts($order, $form->lineItems);
$this->addOrderUserDataBilling($order, $form);
$this->addOrderUserDataDelivery($order, $form);
$this->addOrderDelivery($order, $form->delivery);
}
if ($form->messageToSeller)
{
$order->setDescription($this->replace4Bytes($form->messageToSeller));
}
$isNew = $order->isNew();
if (!$isNew && !trim($order->getOrderUserDataDelivery()->getFullName()))
{
$address = $form->delivery->address;
$order->getOrderUserDataDelivery()->setFullName($address->firstName . ' ' . $address->lastName);
$order->getOrderUserDataDelivery()->save();
}
if ($order->isModified())
{
$order->save();
}
if ($isNew)
{
$order->setNumber(OrderPeer::updateOrderNumber($order->getId(), $order->getCreatedAt()));
$this->addOrderPayment($order, $form->payment);
$this->addOrderInvoice($order, $form->invoice);
$this->updateStock($order);
$this->logImportedOrder($order, $form);
}
usleep(100000);
stNewProductOptions::clearStaticPool();
$offset++;
}
return $offset;
}
protected function replace4Bytes($string)
{
return preg_replace('%(?:
\xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)%xs', '', $string);
}
protected function addOrderDelivery(Order $order, $delivery)
{
$orderDelivery = new OrderDelivery();
$orderDelivery->setName('Dostawa Allegro - ' . $delivery->method->name);
$orderDelivery->setTax($this->getDefaultProductTax());
$orderDelivery->setCostBrutto($delivery->cost->amount);
$orderDelivery->setOptAllegroDeliveryMethodId($delivery->method->id);
$orderDelivery->setOptAllegroDeliverySmart($delivery->smart);
if (isset($delivery->pickupPoint) && !empty($delivery->pickupPoint))
{
$orderDelivery->setPickupPoint($delivery->pickupPoint->id);
}
$order->setOrderDelivery($orderDelivery);
}
protected function updateStock(Order $order)
{
$config = stConfig::getInstance('stProduct');
if ($config->get('depository_enabled') && $config->get('get_depository') == 'order')
{
$c = new Criteria();
$items = $order->getOrderProducts($c);
stDepositoryPluginListener::decreaseAll($items);
}
}
protected function addOrderInvoice(Order $order, $invoice)
{
if ($invoice->required && $invoice->address) {
$userData = $order->getOrderUserDataBilling();
if (isset($invoice->address->naturalPerson) && $invoice->address->naturalPerson) {
$userData->setFullName($invoice->address->naturalPerson->firstName . ' ' . $invoice->address->naturalPerson->lastName);
} else {
$userData->setFullName('');
}
$userData->setAddress($invoice->address->street);
$userData->setTown($invoice->address->city);
$country = CountriesPeer::retrieveByIsoA2($invoice->address->countryCode);
$userData->setCountries($country);
if (isset($invoice->address->company) && $invoice->address->company) {
if ($invoice->address->company->name)
{
$userData->setCompany($invoice->address->company->name);
}
if ($invoice->address->company->taxId)
{
$userData->setVatNumber($invoice->address->company->taxId);
}
}
$userData->setCode($invoice->address->zipCode);
$userData->save();
}
$proforma = stInvoice::createInvoiceProforma($order);
if ($invoice->required) {
stInvoice::createInvoiceRequest($order, $proforma);
}
}
protected function addOrderPayment(Order $order, $payment)
{
$c = new Criteria();
$c->add(PaymentTypePeer::MODULE_NAME, 'stAllegro');
$c->add(PaymentTypePeer::HIDE_MODULE, 1);
$paymentType = PaymentTypePeer::doSelectOne($c);
if (null === $paymentType) {
$paymentType = new PaymentType();
$paymentType->setHideModule(true);
$paymentType->setModuleName('stAllegro');
$paymentType->setActive(false);
$paymentType->setCulture('pl_PL');
$paymentType->setName("Płatność w serwisie Allegro");
$paymentType->save();
}
$paymentInstance = stPayment::newPaymentInstance($paymentType->getId(), $order->getOptTotalAmount());
if ($payment->type == "ONLINE") {
$paymentInstance->setAllegroPaymentType(strtolower($payment->provider));
} else {
$paymentInstance->setAllegroPaymentType(strtolower($payment->type));
}
$paymentInstance->setTransactionId($payment->id);
$ohp = new OrderHasPayment();
$ohp->setOrder($order);
$ohp->setPayment($paymentInstance);
$ohp->save();
$order->setOrderPayment($paymentInstance);
if (null !== $payment->paidAmount && $payment->type == "ONLINE") {
$paymentInstance->setStatus(true);
$paymentInstance->setPayedAt(strtotime($payment->finishedAt));
}
$paymentInstance->save();
}
protected function addOrderUserDataBilling(Order $order, $form)
{
$userData = new OrderUserDataBilling();
if ($form->buyer->guest) {
$address = $form->delivery->address;
$userData->setFullName($address->firstName . ' ' . $address->lastName);
$userData->setAddress($address->street);
$userData->setTown($address->city);
$country = CountriesPeer::retrieveByIsoA2($address->countryCode);
$userData->setCountries($country);
$userData->setCompany($address->companyName);
$userData->setPhone($address->phoneNumber);
$userData->setCode($address->zipCode);
} else {
$userData->setFullName($form->buyer->firstName . ' ' . $form->buyer->lastName);
$userData->setAddress($form->buyer->address->street);
$userData->setTown($form->buyer->address->city);
$country = CountriesPeer::retrieveByIsoA2($form->buyer->address->countryCode);
$userData->setCountries($country);
$userData->setCompany($form->buyer->companyName);
$userData->setPhone($form->buyer->phoneNumber);
$userData->setCode($form->buyer->address->postCode);
}
$this->getEventDispatcher()->notify(new sfEvent($this, 'stAllegroOrderBar.addOrderUserDataBilling', array('order_user_data_billing' => $userData, 'order' => $order, 'allegro_form' => $form)));
$order->setOrderUserDataBilling($userData);
}
protected function addOrderUserDataDelivery(Order $order, $form)
{
$userData = new OrderUserDataDelivery();
$address = $form->delivery->address;
if (isset($form->delivery->pickupPoint) && $form->delivery->pickupPoint)
{
$pickupPoint = $form->delivery->pickupPoint;
$userData->setFullName($address->firstName . ' ' . $address->lastName);
$userData->setAddress($pickupPoint->address->street);
$userData->setTown($pickupPoint->address->city);
$country = CountriesPeer::retrieveByIsoA2('PL');
$userData->setCountries($country);
$userData->setCompany($pickupPoint->name);
$userData->setPhone($form->delivery->address->phoneNumber);
$userData->setCode($pickupPoint->address->zipCode);
}
else
{
$userData->setFullName($address->firstName . ' ' . $address->lastName);
$userData->setAddress($address->street);
$userData->setTown($address->city);
$country = CountriesPeer::retrieveByIsoA2($address->countryCode);
$userData->setCountries($country);
$userData->setCompany($address->companyName);
$userData->setPhone($address->phoneNumber);
$userData->setCode($address->zipCode);
}
$this->getEventDispatcher()->notify(new sfEvent($this, 'stAllegroOrderBar.addOrderUserDataDelivery', array('order_user_data_delivery' => $userData, 'order' => $order, 'allegro_form' => $form)));
$order->setOrderUserDataDelivery($userData);
}
protected function addProducts(Order $order, $items)
{
$offerIds = array();
$createdAt = 0;
foreach ($items as $item) {
$offerIds[] = $item->offer->id;
}
$offers = AllegroAuctionPeer::doSelectByAuctionIds($offerIds);
foreach ($items as $item) {
$offer = isset($offers[$item->offer->id]) ? $offers[$item->offer->id] : null;
$product = null;
if ($offer) {
$product = $offer->getProduct();
}
$orderProduct = new OrderProduct();
$orderProduct->setVersion(2);
if ($product) {
$orderProduct->setProduct($product);
$offer->getProductOptionsArray();
$priceModifiers = $product->getPriceModifiers();
/**
* @see BasketProduct::setPriceModifiers()
**/
foreach ($priceModifiers as $index => $value) {
if (isset($value['custom']['label'])) {
$label = $value['custom']['label'];
unset($value['custom']['label']);
$value['label'] = $label;
$priceModifiers[$index] = $value;
}
}
$orderProduct->setPriceModifiers($priceModifiers);
}
$orderProduct->setQuantity($item->quantity);
$orderProduct->setCode($product ? $product->getCode() : $item->offer->id);
$orderProduct->setName($this->getConfig()->get('import_product_name', 'offer') == 'offer' || !$product ? $item->offer->name : $product->getName());
$orderProduct->setPriceNetto(null);
$orderProduct->setAllegroAuctionId($item->offer->id);
$orderProduct->setPriceBrutto($item->price->amount);
if ($product) {
$orderProduct->setImage($product->getOptImage());
}
$orderProduct->setTax($product ? $product->getTax() : $this->getDefaultProductTax());
$this->getEventDispatcher()->notify(new sfEvent($this, 'stAllegroOrderBar.addProducts', array('order_product' => $orderProduct, 'order' => $order, 'auction' => $offer, 'allegro_item' => $item)));
$order->addOrderProduct($orderProduct);
$time = strtotime($item->boughtAt);
if ($createdAt < $time) {
$createdAt = $time;
}
}
$order->setCreatedAt($time);
}
public function logImportedOrder(Order $order, $form)
{
$offers = array();
foreach ($form->lineItems as $item) {
$offers[] = $item->offer->id;
}
$this->getLogger()->info('Nowe zamówienie %order% (oferty: %offers%) złożone %created_at% na kwotę %amount%', array(
'%order%' => sprintf('[%s](%s)', $order->getNumber(), st_url_for('@stOrder?action=edit&id=' . $order->getId())),
'%offers%' => implode(', ', $offers),
'%created_at%' => st_format_date($order->getCreatedAt()),
'%amount%' => st_order_price($order->getOptTotalAmount(), $order->getOrderCurrency()),
));
}
/**
* Pobiera zamówienia na podstawie formularza pozakupowego Allegro
*
* @param stdClass $form
* @return Order
*/
protected function getOrder($form)
{
$c = new Criteria();
$c->add(OrderPeer::OPT_ALLEGRO_CHECKOUT_FORM_ID, $form->id);
return OrderPeer::doSelectOne($c);
}
public function getOrderCurrency()
{
$orderCurrency = new OrderCurrency();
$orderCurrency->setName('Polski złoty');
$orderCurrency->setShortcut('PLN');
$orderCurrency->setExchange(1);
$orderCurrency->setFrontSymbol(null);
$orderCurrency->setBackSymbol('zł');
$orderCurrency->save();
return $orderCurrency;
}
protected static function getUserGroup()
{
if (null === self::$userGroup) {
$c = new Criteria();
$c->add(sfGuardGroupPeer::NAME, 'user');
self::$userGroup = sfGuardGroupPeer::doSelectOne($c);
}
return self::$userGroup;
}
protected function getAllegroPaymentType()
{
if (null === $this->allegroPaymentType) {
$c = new Criteria();
$c->add(PaymentTypePeer::MODULE_NAME, 'stAllegro');
$c->add(PaymentTypePeer::HIDE_MODULE, 1);
$paymentType = PaymentTypePeer::doSelectOne($c);
if (null === $paymentType) {
$paymentType = new PaymentType();
$paymentType->setHideModule(true);
$paymentType->setModuleName('stAllegro');
$paymentType->setActive(false);
$paymentType->setCulture('pl_PL');
$paymentType->setName("Płatność w serwisie Allegro");
$paymentType->save();
}
$this->allegroPaymentType = $paymentType;
}
return $this->allegroPaymentType;
}
protected function getApi(): stAllegroApi
{
return stAllegroApi::getInstance();
}
public function getConfig(): stConfig
{
return stConfig::getInstance('stAllegroBackend');
}
public function getDefaultOrderStatus(): OrderStatus
{
if (null === $this->defaultOrderStatus)
{
$this->defaultOrderStatus = OrderStatusPeer::retrieveDefaultPendingStatus();
}
return $this->defaultOrderStatus;
}
public function getDefaultProductTax(): Tax
{
return TaxPeer::retrieveByTax(23);
}
public function getEventDispatcher(): stEventDispatcher
{
return stEventDispatcher::getInstance();
}
}

View File

@@ -0,0 +1,188 @@
<?php
class stAllegroSendTackingNumberTask extends stTask
{
const LIMIT = 25;
protected $carriers = null;
public function started(): void
{
$this->setParameter('last_id', null);
}
public function count(): int
{
$c = $this->getCriteria();
return AllegroParcelTrackingNumberQueuePeer::doCount($c);
}
public function execute(int $offset): int
{
$c = $this->getCriteria();
$c->setLimit(self::LIMIT);
$lastId = $this->getParameter('last_id');
if ($lastId)
{
$c->add(AllegroParcelTrackingNumberQueuePeer::ORDER_ID, $lastId, Criteria::GREATER_THAN);
}
$api = stAllegroApi::getInstance();
$controller = sfContext::getInstance()->getController();
/**
* @var AllegroParcelTrackingNumberQueue $trackingNumberQueue
*/
foreach (AllegroParcelTrackingNumberQueuePeer::doSelectJoinOrder($c) as $trackingNumberQueue)
{
$this->setParameter('last_id', $trackingNumberQueue->getOrderId());
$order = $trackingNumberQueue->getOrder();
$numbers = $order->getOrderDelivery()->getNumbers();
if (empty($numbers)) {
$trackingNumberQueue->delete();
$offset++;
continue;
}
$deliveryName = $order->getOrderDelivery()->getName();
$allegroDeliveryId = $order->getOrderDelivery()->getOptAllegroDeliveryMethodId();
$orderLink = sprintf('[%s](%s)', $order->getNumber(), $controller->genUrl('@stOrder?action=edit&id='.$order->getId()));
if (null !== stPocztaPolskaClient::getServiceByAllegroDeliveryMethodId($allegroDeliveryId))
{
$carrierId = "POCZTA_POLSKA";
}
else
{
$carrierId = $this->getCarrierId($deliveryName);
if (false === $carrierId)
{
return $this->doCount();
}
}
if (!$carrierId)
{
$this->getLogger()->error("Wystąpił błąd podczas dodawania numeru przesyłki %number% dla zamówienia %order%:\n%error%", array(
"%number%" => implode(', ', $numbers),
"%error%" => "Nie znaleziono pasującego identyfikatora przewoźnika",
'%order%' => $orderLink,
));
$trackingNumberQueue->delete();
$offset++;
continue;
}
foreach ($numbers as $number)
{
if (strpos($number, ' ') !== false)
{
$this->getLogger()->error("Wystąpił błąd podczas dodawania numeru przesyłki %number% dla zamówienia %order%:\n%error%", array(
"%number%" => $number,
"%error%" => "Nieprawidłowy format numeru przesyłki",
'%order%' => $orderLink,
));
$offset++;
continue;
}
$this->getLogger()->info("Wysyłanie numeru przesyłki \"%number%\" dla zamówienia %order%", array(
"%number%" => $number,
'%order%' => $orderLink,
));
try
{
if ($carrierId)
{
$api->addParcelTrackingNumber($order->getOptAllegroCheckoutFormId(), $carrierId, $number);
}
else
{
$this->getLogger()->error("Wystąpił błąd podczas dodawania numeru przesyłki %number% dla zamówienia %order%:\n%error%", array(
"%number%" => $number,
"%error%" => "Nie znaleziono pasującego identyfikatora przewoźnika",
'%order%' => $orderLink,
));
}
}
catch (Throwable $e)
{
$error = stAllegroApi::getLastErrorsAsString();
$this->getLogger()->error("Wystąpił błąd podczas dodawania numeru przesyłki %number% dla zamówienia %order%:\n%error%", array(
"%number%" => $number,
"%error%" => $error ? $error : $e->getMessage(),
"%order%" => $orderLink,
));
}
}
$trackingNumberQueue->delete();
$offset++;
usleep(300000);
}
sleep(1);
return $offset;
}
protected function getCriteria()
{
$c = new Criteria();
$c->addAscendingOrderByColumn(AllegroParcelTrackingNumberQueuePeer::ORDER_ID);
return $c;
}
protected function getCarriers()
{
$api = stAllegroApi::getInstance();
if (null === $this->carriers)
{
$this->carriers = $api->getAvailableShippingCarriers();
}
return $this->carriers;
}
public function getCarrierId($deliveryName)
{
$deliveryName = str_replace('Dostawa Allegro - ', '', $deliveryName);
try
{
$carriers = $this->getCarriers();
}
catch(Throwable $e)
{
$error = stAllegroApi::getLastErrorsAsString();
$this->getLogger()->error("Wystąpił błąd podczas pobierania dostępnych identyfikatorów przewoźników:\n%error%", array(
"%error%" => $error ? $error : $e->getMessage(),
));
return false;
}
foreach ($carriers as $carrier)
{
if (!in_array($carrier->id, array('OTHER', 'ALLEGRO')) && false !== strpos($deliveryName, $carrier->name))
{
return $carrier->id;
}
}
return null;
}
}

View File

@@ -0,0 +1,220 @@
<?php
class stAllegroSyncTask extends stTask
{
const LIMIT = 50;
/**
* Kontroler
*
* @var sfWebController
*/
protected $controller;
public function initialize(): void
{
$this->controller = sfContext::getInstance()->getController();
}
public function started(): void
{
$this->setParameter('last_id', null);
}
public function count(): int
{
if (!stConfig::getInstance('stAllegroBackend')->get('access_token'))
{
return 0;
}
return AllegroAuctionPeer::doCount($this->getCriteria());
}
public function execute(int $offset): int
{
$c = $this->getCriteria();
$lastId = $this->getParameter('last_id');
if ($lastId)
{
$c->add(AllegroAuctionPeer::ID, $lastId, Criteria::GREATER_THAN);
}
$c->setLimit(self::LIMIT);
$publish = array();
$unpublish = array();
$api = stAllegroApi::getInstance();
/**
* @var AllegroAuction $auction
*/
foreach (AllegroAuctionPeer::doSelect($c) as $auction)
{
stNewProductOptions::clearStaticPool();
$this->setParameter('last_id', $auction->getId());
$offerLink = $this->getOfferLink($auction->getAuctionId());
try
{
if (null === $auction->getAuctionId() || null === $auction->getProduct())
{
$auction->delete();
$offer = null;
} else
{
try
{
$offer = $api->getOffer($auction->getAuctionId());
} catch (stAllegroException $e)
{
$errors = stAllegroApi::getLastErrors();
if ($errors[0]->code == 'NOT_FOUND')
{
$messages = array();
foreach ($errors as $error)
{
$messages[] = $error->userMessage;
}
$auction->delete();
$this->getLogger()->error("Oferta %offer% nie została znaleziona", array(
"%offer%" => $offerLink,
));
$offer = null;
}
}
}
if ($auction->getAllowSync() && $offer)
{
if ($offer->publication->status == 'ACTIVE' || $offer->publication->status == 'ENDED')
{
$auction->getProductOptionsArray();
$stock = $auction->getProduct()->getStock();
$config = stConfig::getInstance('stAllegroBackend');
$ok = true;
if ($stock > 0)
{
if ($config->get('offer_sync_product_price'))
{
$allegroCommission = new AllegroCommission();
$price = $allegroCommission->calculatePrice($auction->getProduct()->getPriceBrutto());
$offer->sellingMode->price->amount = $price;
}
$offer->stock->available = ceil($stock);
$this->getLogger()->info('Synchronizacja oferty %offer%', array('%offer%' => $offerLink));
$response = $api->updateOffer($auction->getAuctionId(), $offer);
if ($response->validation->errors)
{
$ok = false;
$messages = array();
foreach ($response->validation->errors as $error)
{
$messages[] = $error->userMessage;
}
$this->getLogger()->error("Wystąpił błąd podczas synchronizacji oferty %offer%:\n%error%", array(
"%offer%" => $offerLink,
"%error%" => implode("\n", $messages),
));
}
}
if ($ok)
{
if ($offer->publication->status == 'ENDED' && $stock > 0)
{
$publish[$auction->getAuctionId()] = $offerLink;
} elseif ($offer->publication->status == 'ACTIVE' && !$stock)
{
$unpublish[$auction->getAuctionId()] = $offerLink;
}
}
}
}
} catch (Exception $e)
{
$messages = array();
foreach (stAllegroApi::getLastErrors() as $error)
{
$messages[] = $error->userMessage;
}
$this->getLogger()->error("Wystąpił błąd podczas synchronizacji oferty %offer%:\n%error%", array(
"%offer%" => $offerLink,
"%error%" => implode("\n", $messages),
));
}
if (!$auction->isDeleted())
{
if ($offer)
{
$auction->setEnded(($offer->publication->status == 'ENDED' || isset($unpublish[$auction->getAuctionId()])) && !isset($publish[$auction->getAuctionId()]));
}
$auction->setRequiresSync(false);
$auction->save();
}
$offset++;
stNewProductOptions::clearStaticPool();
usleep(250000);
}
if ($unpublish)
{
$this->getLogger()->info("Zakończenie ofert %offers% z powodu braku produktów na magazynie", array('%offers%' => implode(", ", $unpublish)));
$api->publishOffers(array_keys($unpublish), false);
}
if ($publish)
{
$this->getLogger()->info("Wznowienie ofert %offers% z powodu ponownej dostępności produktów na magazynie", array('%offers%' => implode(", ", $publish)));
$api->publishOffers(array_keys($publish), true);
}
sleep(1);
return $offset;
}
private function getCriteria(): Criteria
{
$c = new Criteria();
$c->add(AllegroAuctionPeer::REQUIRES_SYNC, true);
$c->addAscendingOrderByColumn(AllegroAuctionPeer::ID);
return $c;
}
private function getOfferLink($offerId): string
{
$url = $this->controller->genUrl('@stAllegroPlugin?action=edit&id='.$offerId);
return sprintf('[%s](%s)', $offerId, $url);
}
}

View File

@@ -0,0 +1,18 @@
<?php
class stAllegroImageValidator extends sfValidator {
public function execute(&$value, &$error) {
if (isset($value['selected']) && count($value['selected']) > 16) {
$error = $this->getParameter('msg');
return false;
}
return true;
}
public function initialize($context, $parameters = null) {
parent::initialize($context);
$this->getParameterHolder()->add($parameters);
return true;
}
}

View File

@@ -0,0 +1,22 @@
<?php
class stAllegroProductOptionsValidator extends sfValidator {
public function execute(&$value, &$error) {
$product = ProductPeer::retrieveByPk($this->getContext()->getRequest()->getParameter('product_id', null));
if (is_object($product)) {
if (empty($value) && $product->getOptHasOptions() > 1) {
$error = $this->getParameter('msg');
return false;
}
}
return true;
}
public function initialize($context, $parameters = null) {
parent::initialize($context);
$this->getParameterHolder()->add($parameters);
return true;
}
}

View File

@@ -0,0 +1,44 @@
<?php
class stAllegroStockValidator extends sfValidator {
public function execute(&$value, &$error) {
if (empty($value)) {
$error = $this->getParameter('zero_msg');
return false;
}
$auction = $this->getContext()->getRequest()->getParameter('allegro_auction', null);
$product = ProductPeer::retrieveByPk($this->getContext()->getRequest()->getParameter('product_id', null));
if (is_object($product)) {
if ($product->getOptHasOptions() > 1) {
if (!isset($auction['product_options'])) {
$error = $this->getParameter('null_options');
return false;
}
$ids = explode(',', $auction['product_options']);
$options = ProductOptionsValuePeer::retrieveByPKs($ids);
stNewProductOptions::updateProductBySelectedOptions($product, $options);
}
$stock = (int) $product->getStock();
$productConfig = stConfig::getInstance('stProduct');
if ($productConfig->get('depository_enabled'))
if ($value > $stock) {
$error = $this->getParameter('stock_msg');
return false;
}
}
return true;
}
public function initialize($context, $parameters = null) {
parent::initialize($context);
$this->getParameterHolder()->add($parameters);
return true;
}
}

View File

@@ -0,0 +1,76 @@
<?php
class stAllegroVariantsValidator extends sfValidator {
public function execute(&$value, &$error) {
$product = ProductPeer::retrieveByPk($this->getContext()->getRequest()->getParameter('product_id', null));
$i18n = $this->getContext()->getI18n();
$variant = null;
foreach ($value['attributes'] as $attributeId => $attribute) {
$attributeJson = json_decode($attribute['attribute'], true);
if ($attributeJson['sellFormTitle'] == 'Rozmiar') {
$variant = $attribute;
break;
}
}
if ($variant !== null) {
$size = array_combine(explode('|', $attributeJson['sellFormOptsValues']), explode('|', $attributeJson['sellFormDesc']));
if ($product->getOptHasOptions() > 1) {
if (!isset($variant['value']) || empty($variant['value'])) {
$error = $i18n->__('<b>(Rozmiar)</b> - proszę wybrać minimuj jedną opcje.');
return false;
}
$variant['options'];
foreach ($variant['value'] as $id) {
if (empty($variant['quantity'][$id])) {
$error = $i18n->__('<b>(Rozmiar: %size%)</b> - ilość produktów do wystawienia musi być większa od 0.', array('%size%' => $size[$id]));
return false;
}
if (!isset($variant['options'][$id]) && empty($variant['options'][$id])) {
$error = $i18n->__('<b>(Rozmiar: %size%)</b> - każda opcja musi mieć wybraną opcje produktów.', array('%size%' => $size[$id]));
return false;
}
$options = ProductOptionsValuePeer::retrieveByPKs(explode(',', $variant['options'][$id]));
stNewProductOptions::updateProductBySelectedOptions($product, $options);
if ($variant['quantity'][$id] > $product->getStock()) {
$error = $i18n->__('<b>(Rozmiar: %size%)</b> - brak dostępnej ilości produktów w magazynie.', array('%size%' => $size[$id]));
return false;
}
}
} else {
$sumStock = 0;
foreach ($variant['quantity'] as $key => $quantity) {
if (isset($variant['value'][$key])) {
$sumStock += (int) $quantity;
if ((int) $quantity == 0) {
$error = $i18n->__('<b>(Rozmiar: %size%)</b> - ilość produktów do wystawienia musi być większa od 0.', array('%size%' => $size[$id]));
return false;
}
}
}
if ($sumStock > $product->getStock()) {
$error = $i18n->__('<b>(Rozmiar: %size%)</b> - brak dostępnej ilości produktów w magazynie.', array('%size%' => $size[$id]));
return false;
}
}
}
return true;
}
public function initialize($context, $parameters = null) {
parent::initialize($context);
$this->getParameterHolder()->add($parameters);
return true;
}
}