diff --git a/CHANGELOG.md b/CHANGELOG.md index 435a9f309..ad7250484 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - Update SwiftMailer - Fix bugs on customer change password form and module "order by title" - Add the ability to place a firewall on forms. To use this in a module, extend Thelia\Form\FirewallForm instead of BaseForm +- Add Exports and Imports management #2.0.2 - Coupon UI has been redesigned. diff --git a/core/lib/Thelia/Action/Export.php b/core/lib/Thelia/Action/Export.php new file mode 100644 index 000000000..bdea9f360 --- /dev/null +++ b/core/lib/Thelia/Action/Export.php @@ -0,0 +1,88 @@ + + */ +class Export extends BaseAction implements EventSubscriberInterface +{ + protected $environment; + + public function __construct($environment) + { + $this->environment = $environment; + } + + public function changeCategoryPosition(UpdatePositionEvent $event) + { + $this->genericUpdatePosition(new ExportCategoryQuery(), $event); + + $this->cacheClear($event->getDispatcher()); + } + + public function changeExportPosition(UpdatePositionEvent $event) + { + $this->genericUpdatePosition(new ExportQuery(), $event); + + $this->cacheClear($event->getDispatcher()); + } + + protected function cacheClear(EventDispatcherInterface $dispatcher) + { + $cacheEvent = new CacheEvent( + $this->environment + ); + + $dispatcher->dispatch(TheliaEvents::CACHE_CLEAR, $cacheEvent); + } + + /** + * Returns an array of event names this subscriber wants to listen to. + * + * The array keys are event names and the value can be: + * + * * The method name to call (priority defaults to 0) + * * An array composed of the method name to call and the priority + * * An array of arrays composed of the method names to call and respective + * priorities, or 0 if unset + * + * For instance: + * + * * array('eventName' => 'methodName') + * * array('eventName' => array('methodName', $priority)) + * * array('eventName' => array(array('methodName1', $priority), array('methodName2')) + * + * @return array The event names to listen to + * + * @api + */ + public static function getSubscribedEvents() + { + return array( + TheliaEvents::EXPORT_CATEGORY_CHANGE_POSITION => array("changeCategoryPosition", 128), + TheliaEvents::EXPORT_CHANGE_POSITION => array("changeExportPosition", 128), + ); + } + +} diff --git a/core/lib/Thelia/Action/Import.php b/core/lib/Thelia/Action/Import.php new file mode 100644 index 000000000..e0aef97b5 --- /dev/null +++ b/core/lib/Thelia/Action/Import.php @@ -0,0 +1,88 @@ + + */ +class Import extends BaseAction implements EventSubscriberInterface +{ + protected $environment; + + public function __construct($environment) + { + $this->environment = $environment; + } + + public function changeCategoryPosition(UpdatePositionEvent $event) + { + $this->genericUpdatePosition(new ImportCategoryQuery(), $event); + + $this->cacheClear($event->getDispatcher()); + } + + public function changeImportPosition(UpdatePositionEvent $event) + { + $this->genericUpdatePosition(new ImportQuery(), $event); + + $this->cacheClear($event->getDispatcher()); + } + + protected function cacheClear(EventDispatcherInterface $dispatcher) + { + $cacheEvent = new CacheEvent( + $this->environment + ); + + $dispatcher->dispatch(TheliaEvents::CACHE_CLEAR, $cacheEvent); + } + + /** + * Returns an array of event names this subscriber wants to listen to. + * + * The array keys are event names and the value can be: + * + * * The method name to call (priority defaults to 0) + * * An array composed of the method name to call and the priority + * * An array of arrays composed of the method names to call and respective + * priorities, or 0 if unset + * + * For instance: + * + * * array('eventName' => 'methodName') + * * array('eventName' => array('methodName', $priority)) + * * array('eventName' => array(array('methodName1', $priority), array('methodName2')) + * + * @return array The event names to listen to + * + * @api + */ + public static function getSubscribedEvents() + { + return array( + TheliaEvents::IMPORT_CATEGORY_CHANGE_POSITION => array("changeCategoryPosition", 128), + TheliaEvents::IMPORT_CHANGE_POSITION => array("changeImportPosition", 128), + ); + } + +} diff --git a/core/lib/Thelia/Command/Skeleton/Module/config.xml b/core/lib/Thelia/Command/Skeleton/Module/config.xml index 39341f344..97639928c 100644 --- a/core/lib/Thelia/Command/Skeleton/Module/config.xml +++ b/core/lib/Thelia/Command/Skeleton/Module/config.xml @@ -27,4 +27,16 @@ --> + + + + diff --git a/core/lib/Thelia/Config/Resources/action.xml b/core/lib/Thelia/Config/Resources/action.xml index f8ea66a4f..18dc627b2 100644 --- a/core/lib/Thelia/Config/Resources/action.xml +++ b/core/lib/Thelia/Config/Resources/action.xml @@ -163,6 +163,16 @@ + + + %kernel.cache_dir% + + + + + %kernel.cache_dir% + + diff --git a/core/lib/Thelia/Config/Resources/config.xml b/core/lib/Thelia/Config/Resources/config.xml index 81ffc3333..6e001e18a 100644 --- a/core/lib/Thelia/Config/Resources/config.xml +++ b/core/lib/Thelia/Config/Resources/config.xml @@ -34,6 +34,8 @@ Thelia\Model\BrandImage + /admin/import + /admin/export @@ -135,6 +137,47 @@ - + + + + %kernel.environment% + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/lib/Thelia/Config/Resources/export.xml b/core/lib/Thelia/Config/Resources/export.xml new file mode 100644 index 000000000..c8d6152c3 --- /dev/null +++ b/core/lib/Thelia/Config/Resources/export.xml @@ -0,0 +1,118 @@ + + + + + + + Customers + Clients + + + Products + Produits + + + Content + Contenu + + + + Orders + Commandes + + + + + + + Mailing + Exporter le nom, prénom et adresse mail des clients inscrits et des abonnées à la newsletter + + + Mailing + Export the last name, first name and email address of the customers and the newsletter subscribers + + + + + + Clients + Exporter toutes les informations à propos de vos clients + + + Customers + Export all the information about your customers + + + + + + Prix des produits Hors-Taxes + Expotez le prix hors taxes de vos produits + + + Product prices excluding taxes + Export the prices of the products excluding taxes + + + + + + Prix des produits TTC + Expotez le prix TTC de vos produits + + + Product prices including taxes + Export the prices of the products including taxes + + + + + + Product SEO information + + Export the SEO information ( rewritten url, meta description and keywords, page title ) of your products + + + + Informations SEO des produits + + Exportez les informations SEO de vos produits + ( url réécrites, meta description et mots clés, titre ) de vos produits + + + + + + + Contents and folder + + Export your contents and their related folders + + + + Contenus et dossiers + + Exportez vos contenus et les dossiers associés + + + + + + + Full orders + + Export your orders. + + + + Commandes complètes + + Exportez vos commandes + + + + + diff --git a/core/lib/Thelia/Config/Resources/form.xml b/core/lib/Thelia/Config/Resources/form.xml index 758f2c926..39dc27f55 100644 --- a/core/lib/Thelia/Config/Resources/form.xml +++ b/core/lib/Thelia/Config/Resources/form.xml @@ -133,6 +133,9 @@
+ + + diff --git a/core/lib/Thelia/Config/Resources/import.xml b/core/lib/Thelia/Config/Resources/import.xml new file mode 100644 index 000000000..4a57d7da8 --- /dev/null +++ b/core/lib/Thelia/Config/Resources/import.xml @@ -0,0 +1,81 @@ + + + + + + Produits + Products + + + + + + + Importez votre stock + + +
  • ref: The reference of your product Attribute Combinations
  • +
  • stock: The quantity of product you have
  • + + ]]> +
    +
    + + Import your stock + + +
  • ref: The reference of your product attribute combinations
  • +
  • stock: The quantity of product you have
  • + + It can have the column "ean" that defines the product's EAN code. + ]]> +
    +
    +
    + + + + Importez vos prix Hors-Taxes + + +
  • ref: La reférénce de votre déclinaison de combinaison de produit
  • +
  • price: Le prix Hors-Taxes de votre déclinaison de combinaison de produit
  • + + Il peut aussi optionnellement avoir ces colonnes: +
      +
    • currency: Le code de la monnaie (exemple: EUR, USD)
    • +
    • promo_price: Le prix promotionnel Hors-Taxes de votre déclinaison de combinaison de produit
    • +
    • promo: Si cette valeur est a 0, désactive la promotion, si elle est a 1, l'active
    • +
    + ]]> +
    +
    + + Import your prices excluding taxes + + +
  • ref: The reference of the product attribute combinations
  • +
  • price: The price excluding taxes of the product attribute combinations
  • + + It may also optionally have those columns: +
      +
    • currency: the currency code (example: EUR, USD)
    • +
    • promo_price: the promo price excluding taxes of the product attribute combinations
    • +
    • promo: If this value is 0, set the product not in promo, if 1, it sets the product in promo
    • +
    + ]]> +
    +
    +
    +
    +
    diff --git a/core/lib/Thelia/Config/Resources/loop.xml b/core/lib/Thelia/Config/Resources/loop.xml index 743f33853..bca98a6f3 100644 --- a/core/lib/Thelia/Config/Resources/loop.xml +++ b/core/lib/Thelia/Config/Resources/loop.xml @@ -55,6 +55,12 @@ + + + + + + diff --git a/core/lib/Thelia/Config/Resources/routing/admin.xml b/core/lib/Thelia/Config/Resources/routing/admin.xml index 42696a22c..a2a4b7838 100644 --- a/core/lib/Thelia/Config/Resources/routing/admin.xml +++ b/core/lib/Thelia/Config/Resources/routing/admin.xml @@ -1158,17 +1158,6 @@ Thelia\Controller\Admin\TranslationsController::updateAction - - - - Thelia\Controller\Admin\ExportController::indexAction - - - - Thelia\Controller\Admin\CustomerExportController::newsletterExportAction - - - @@ -1205,6 +1194,54 @@ Thelia\Controller\Admin\BrandController::deleteAction + + + + Thelia\Controller\Admin\ExportController::indexAction + + + + Thelia\Controller\Admin\ExportController::changePosition + + + + Thelia\Controller\Admin\ExportController::changeCategoryPosition + + + + Thelia\Controller\Admin\ExportController::export + \d+ + + + + Thelia\Controller\Admin\ExportController::exportView + \d+ + + + + + + Thelia\Controller\Admin\ImportController::indexAction + + + + Thelia\Controller\Admin\ImportController::changePosition + + + + Thelia\Controller\Admin\ImportController::changeCategoryPosition + + + + Thelia\Controller\Admin\ImportController::import + \d+ + + + + Thelia\Controller\Admin\ImportController::importView + \d+ + + diff --git a/core/lib/Thelia/Controller/Admin/CustomerExportController.php b/core/lib/Thelia/Controller/Admin/CustomerExportController.php deleted file mode 100644 index 0036f2d53..000000000 --- a/core/lib/Thelia/Controller/Admin/CustomerExportController.php +++ /dev/null @@ -1,66 +0,0 @@ - - */ -class CustomerExportController extends BaseAdminController -{ - - public function newsletterExportAction() - { - if (null !== $response = $this->checkAuth([AdminResources::EXPORT_CUSTOMER_NEWSLETTER], [], [AccessManager::VIEW])) { - return $response; - } - - $data = NewsletterQuery::create() - ->select([ - 'email', - 'firstname', - 'lastname', - 'locale' - ]) - ->find(); - - $handle = fopen('php://memory', 'r+'); - - fputcsv($handle, ['email','firstname','lastname','locale'], ';', '"'); - - foreach ($data->toArray() as $customer) { - fputcsv($handle, $customer, ';', '"'); - } - - rewind($handle); - $content = stream_get_contents($handle); - fclose($handle); - - return Response::create( - $content, - 200, - array( - "Content-Type"=>"application/csv-tab-delimited-table", - "Content-disposition"=>"filename=export_customer_newsletter.csv" - ) - ); - - } - -} diff --git a/core/lib/Thelia/Controller/Admin/ExportController.php b/core/lib/Thelia/Controller/Admin/ExportController.php index 279ed8b4c..8a993759b 100644 --- a/core/lib/Thelia/Controller/Admin/ExportController.php +++ b/core/lib/Thelia/Controller/Admin/ExportController.php @@ -12,8 +12,27 @@ namespace Thelia\Controller\Admin; +use Thelia\Core\Event\UpdatePositionEvent; +use Thelia\Core\FileFormat\Archive\ArchiveBuilderManagerTrait; +use Thelia\Core\FileFormat\Formatting\FormatterManagerTrait; use Thelia\Core\Security\AccessManager; use Thelia\Core\Security\Resource\AdminResources; +use Thelia\Core\Template\Element\LoopResult; +use Thelia\Core\Template\Loop\Export as ExportLoop; +use Thelia\Core\Event\ImportExport as ImportExportEvent; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\FileFormat\Archive\AbstractArchiveBuilder; +use Thelia\Core\FileFormat\Formatting\AbstractFormatter; +use Thelia\Core\HttpFoundation\Response; +use Thelia\Form\Exception\FormValidationException; +use Thelia\Form\ExportForm; +use Thelia\ImportExport\Export\DocumentsExportInterface; +use Thelia\ImportExport\Export\ExportHandler; +use Thelia\ImportExport\Export\ImagesExportInterface; +use Thelia\Model\ExportCategoryQuery; +use Thelia\Model\ExportQuery; +use Thelia\Model\Lang; +use Thelia\Model\LangQuery; /** * Class ExportController @@ -22,6 +41,8 @@ use Thelia\Core\Security\Resource\AdminResources; */ class ExportController extends BaseAdminController { + use ArchiveBuilderManagerTrait; + use FormatterManagerTrait; public function indexAction() { @@ -29,6 +50,394 @@ class ExportController extends BaseAdminController return $response; } + $this->setOrders(); + return $this->render('export'); } + + /** + * @param integer $id + * @return Response + * + * This method is called when the route /admin/export/{id} + * is called with a POST request. + */ + public function export($id) + { + if (null === $export = $this->getExport($id)) { + return $this->render("404"); + } + + /** + * Get needed services + */ + $archiveBuilderManager = $this->getArchiveBuilderManager($this->container); + $formatterManager = $this->getFormatterManager($this->container); + + /** + * Get the archive builders + */ + $archiveBuilders = []; + foreach ($archiveBuilderManager->getNames() as $archiveBuilder) { + $archiveBuilders[$archiveBuilder] = $archiveBuilder; + } + + /** + * Define and validate the form + */ + $form = new ExportForm($this->getRequest()); + $errorMessage = null; + + try { + $boundForm = $this->validateForm($form); + + $lang = LangQuery::create()->findPk( + $boundForm->get("language")->getData() + ); + + $archiveBuilder = null; + + /** + * Get the formatter and the archive builder if we have to compress the file(s) + */ + + /** @var \Thelia\Core\FileFormat\Formatting\AbstractFormatter $formatter */ + $formatter = $formatterManager->get( + $boundForm->get("formatter")->getData() + ); + + if ($boundForm->get("do_compress")->getData()) { + /** @var \Thelia\Core\FileFormat\Archive\ArchiveBuilderInterface $archiveBuilder */ + $archiveBuilder = $archiveBuilderManager->get( + $boundForm->get("archive_builder")->getData() + ); + } + + /** + * Return the generated Response + */ + + return $this->processExport( + $formatter, + $export->getHandleClassInstance($this->container), + $archiveBuilder, + $lang, + $boundForm->get("images")->getData(), + $boundForm->get("documents")->getData() + ); + + } catch (FormValidationException $e) { + $errorMessage = $this->createStandardFormValidationErrorMessage($e); + } catch (\Exception $e) { + $errorMessage = $e->getMessage(); + } + + /** + * If has an error, display it + */ + if (null !== $errorMessage) { + $form->setErrorMessage($errorMessage); + + $this->getParserContext() + ->addForm($form) + ->setGeneralError($errorMessage) + ; + } + + return $this->exportView($id); + } + + /** + * @param AbstractFormatter $formatter + * @param ExportHandler $handler + * @param AbstractArchiveBuilder $archiveBuilder + * @param bool $includeImages + * @param bool $includeDocuments + * @return Response + * + * Processes an export by returning a response with the export's content. + */ + protected function processExport( + AbstractFormatter $formatter, + ExportHandler $handler, + AbstractArchiveBuilder $archiveBuilder = null, + Lang $lang, + $includeImages = false, + $includeDocuments = false + ) { + /** + * Build an event containing the formatter and the handler. + * Used for specific configuration (e.g: XML node names) + */ + + $event = new ImportExportEvent($formatter, $handler); + + $filename = $formatter::FILENAME . "." . $formatter->getExtension(); + + if ($archiveBuilder === null) { + $data = $handler->buildData($lang); + + $event->setData($data); + $this->dispatch(TheliaEvents::EXPORT_BEFORE_ENCODE, $event); + + $formattedContent = $formatter + ->setOrder($handler->getOrder()) + ->encode($data) + ; + + $this->dispatch(TheliaEvents::EXPORT_AFTER_ENCODE, $event->setContent($formattedContent)); + + return new Response( + $event->getContent(), + 200, + [ + "Content-Type" => $formatter->getMimeType(), + "Content-Disposition" => + "attachment; filename=\"" . $filename . "\"", + ] + ); + } else { + $event->setArchiveBuilder($archiveBuilder); + + if ($includeImages && $handler instanceof ImagesExportInterface) { + $this->processExportImages($handler, $archiveBuilder); + + $handler->setImageExport(true); + } + + if ($includeDocuments && $handler instanceof DocumentsExportInterface) { + $this->processExportDocuments($handler, $archiveBuilder); + + $handler->setDocumentExport(true); + } + + $data = $handler + ->buildData($lang) + ->setLang($lang) + ; + + $this->dispatch(TheliaEvents::EXPORT_BEFORE_ENCODE, $event); + + $formattedContent = $formatter + ->setOrder($handler->getOrder()) + ->encode($data) + ; + + $this->dispatch(TheliaEvents::EXPORT_AFTER_ENCODE, $event->setContent($formattedContent)); + + + $archiveBuilder->addFileFromString( + $event->getContent(), $filename + ); + + return $archiveBuilder->buildArchiveResponse($formatter::FILENAME); + } + } + + /** + * @param ImagesExportInterface $handler + * @param AbstractArchiveBuilder $archiveBuilder + * + * Procedure that add images in the export's archive + */ + protected function processExportImages(ImagesExportInterface $handler, AbstractArchiveBuilder $archiveBuilder) + { + foreach ($handler->getImagesPaths() as $name => $documentPath) { + $archiveBuilder->addFile( + $documentPath, + $handler::IMAGES_DIRECTORY, + is_integer($name) ? null : $name + ); + } + } + + /** + * @param DocumentsExportInterface $handler + * @param AbstractArchiveBuilder $archiveBuilder + * + * Procedure that add documents in the export's archive + */ + protected function processExportDocuments(DocumentsExportInterface $handler, AbstractArchiveBuilder $archiveBuilder) + { + foreach ($handler->getDocumentsPaths() as $name => $documentPath) { + $archiveBuilder->addFile( + $documentPath, + $handler::DOCUMENTS_DIRECTORY, + is_integer($name) ? null : $name + ); + } + } + + /** + * @param integer $id + * @return Response + * + * This method is called when the route /admin/export/{id} + * is called with a GET request. + * + * It returns a modal view if the request is an AJAX one, + * otherwise it generates a "normal" back-office page + */ + public function exportView($id) + { + if (null === $export = $this->getExport($id)) { + return $this->render("404"); + } + + /** + * Use the loop to inject the same vars in Smarty + */ + $loop = new ExportLoop($this->container); + + $loop->initializeArgs([ + "id" => $export->getId() + ]); + + $query = $loop->buildModelCriteria(); + $result= $query->find(); + + $results = $loop->parseResults( + new LoopResult($result) + ); + + $parserContext = $this->getParserContext(); + + /** @var \Thelia\Core\Template\Element\LoopResultRow $row */ + foreach ($results as $row) { + foreach ($row->getVarVal() as $name=>$value) { + $parserContext->set($name, $value); + } + } + + /** + * Inject conditions in smarty, + * It is used to display or not the checkboxes "Include images" + * and "Include documents" + */ + $this->getParserContext() + ->set("HAS_IMAGES", $export->hasImages($this->container)) + ->set("HAS_DOCUMENTS", $export->hasDocuments($this->container)) + ->set("CURRENT_LANG_ID", $this->getSession()->getLang()->getId()) + ; + + /** Then render the form */ + if ($this->getRequest()->isXmlHttpRequest()) { + return $this->render("ajax/export-modal"); + } else { + return $this->render("export-page"); + } + } + + + public function changePosition() + { + if (null !== $response = $this->checkAuth([AdminResources::EXPORT], [], [AccessManager::UPDATE])) { + return $response; + } + + $query = $this->getRequest()->query; + + $mode = $query->get("mode"); + $id = $query->get("id"); + $value = $query->get("value"); + + $this->getExport($id); + + $event = new UpdatePositionEvent($id, $this->getMode($mode), $value); + $this->dispatch(TheliaEvents::EXPORT_CHANGE_POSITION, $event); + + $this->setOrders(null, "manual"); + + return $this->render('export'); + } + + public function changeCategoryPosition() + { + if (null !== $response = $this->checkAuth([AdminResources::EXPORT], [], [AccessManager::UPDATE])) { + return $response; + } + + $query = $this->getRequest()->query; + + $mode = $query->get("mode"); + $id = $query->get("id"); + $value = $query->get("value"); + + $this->getCategory($id); + + $event = new UpdatePositionEvent($id, $this->getMode($mode), $value); + $this->dispatch(TheliaEvents::EXPORT_CATEGORY_CHANGE_POSITION, $event); + + $this->setOrders("manual"); + + return $this->render('export'); + } + + public function getMode($action) + { + if ($action === "up") { + $mode = UpdatePositionEvent::POSITION_UP; + } elseif ($action === "down") { + $mode = UpdatePositionEvent::POSITION_DOWN; + } else { + $mode = UpdatePositionEvent::POSITION_ABSOLUTE; + } + + return $mode; + } + + protected function setOrders($category = null, $export = null) + { + if ($category === null) { + $category = $this->getRequest()->query->get("category_order", "manual"); + } + + if ($export === null) { + $export = $this->getRequest()->query->get("export_order", "manual"); + } + + $this->getParserContext() + ->set("category_order", $category) + ; + + $this->getParserContext() + ->set("export_order", $export) + ; + } + + protected function getExport($id) + { + $export = ExportQuery::create()->findPk($id); + + if (null === $export) { + throw new \ErrorException( + $this->getTranslator()->trans( + "There is no id \"%id\" in the exports", + [ + "%id" => $id + ] + ) + ); + } + + return $export; + } + + protected function getCategory($id) + { + $category = ExportCategoryQuery::create()->findPk($id); + + if (null === $category) { + throw new \ErrorException( + $this->getTranslator()->trans( + "There is no id \"%id\" in the export categories", + [ + "%id" => $id + ] + ) + ); + } + + return $category; + } } diff --git a/core/lib/Thelia/Controller/Admin/ImportController.php b/core/lib/Thelia/Controller/Admin/ImportController.php new file mode 100644 index 000000000..2847e6116 --- /dev/null +++ b/core/lib/Thelia/Controller/Admin/ImportController.php @@ -0,0 +1,519 @@ + + */ +class ImportController extends BaseAdminController +{ + use FormatterManagerTrait; + use ArchiveBuilderManagerTrait; + + public function indexAction() + { + if (null !== $response = $this->checkAuth([AdminResources::IMPORT], [], [AccessManager::VIEW])) { + return $response; + } + + $this->setOrders(); + + return $this->render('import'); + } + + /** + * @param integer $id + * @return Response + * + * This method is called when the route /admin/import/{id} + * is called with a POST request. + */ + public function import($id) + { + if (null === $import = $this->getImport($id)) { + return $this->render("404"); + } + + $archiveBuilderManager = $this->getArchiveBuilderManager($this->container); + $formatterManager = $this->getFormatterManager($this->container); + $handler = $import->getHandleClassInstance($this->container); + + /** + * Get needed services + */ + $form = new ImportForm($this->getRequest()); + $errorMessage = null; + $successMessage = null; + + try { + $boundForm = $this->validateForm($form); + + $lang = LangQuery::create()->findPk( + $boundForm->get("language")->getData() + ); + + /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $file */ + $file = $boundForm->get("file_upload")->getData(); + + /** + * We have to check the extension manually because of composed file formats as tar.gz or tar.bz2 + */ + $name = $file->getClientOriginalName(); + + $tools = $this->retrieveFormatTools( + $name, + $handler, + $formatterManager, + $archiveBuilderManager + ); + + /** @var AbstractArchiveBuilder $archiveBuilder */ + $archiveBuilder = $tools["archive_builder"]; + + /** @var AbstractFormatter $formatter */ + $formatter = $tools["formatter"]; + + if ($archiveBuilder !== null) { + /** + * If the file is an archive, load it and try to find the file. + */ + $archiveBuilder = $archiveBuilder->loadArchive($file->getPathname()); + + $contentAndFormat = $this->getFileContentInArchive( + $archiveBuilder, + $formatterManager, + $tools["types"] + ); + + $formatter = $contentAndFormat["formatter"]; + $content = $contentAndFormat["content"]; + } elseif ($formatter !== null) { + /** + * If the file isn't an archive + */ + $content = file_get_contents($file->getPathname()); + + } else { + throw new \ErrorException( + $this->getTranslator()->trans( + "There's a problem, the extension \"%ext\" has been found, ". + "but has no formatters nor archive builder", + [ + "%ext" => $tools["extension"], + ] + ) + ); + } + + /** + * Process the import: dispatch events, format the file content and let the handler do it's job. + */ + $successMessage = $this->processImport( + $content, + $handler, + $formatter, + $archiveBuilder, + $lang + ); + + } catch (FormValidationException $e) { + $errorMessage = $this->createStandardFormValidationErrorMessage($e); + } catch (\Exception $e) { + $errorMessage = $e->getMessage(); + } + + if ($successMessage !== null) { + $this->getParserContext()->set("success_message", $successMessage); + } + + if ($errorMessage !== null) { + $form->setErrorMessage($errorMessage); + + $this->getParserContext() + ->addForm($form) + ->setGeneralError($errorMessage) + ; + } + + return $this->importView($id); + } + + public function getFileContentInArchive( + AbstractArchiveBuilder $archiveBuilder, + FormatterManager $formatterManager, + array $types + ) { + $content = null; + + /** + * Check expected file names for each formatter + */ + + $fileNames = []; + /** @var \Thelia\Core\FileFormat\Formatting\AbstractFormatter $formatter */ + foreach ($formatterManager->getFormattersByTypes($types) as $formatter) { + $fileName = $formatter::FILENAME . "." . $formatter->getExtension(); + $fileNames[] = $fileName; + + if ($archiveBuilder->hasFile($fileName)) { + $content = $archiveBuilder->getFileContent($fileName); + break; + } + } + + if ($content === null) { + throw new FileNotFoundException( + $this->getTranslator()->trans( + "Your archive must contain one of these file and doesn't: %files", + [ + "%files" => implode(", ", $fileNames), + ] + ) + ); + } + + return array( + "formatter" => $formatter, + "content" => $content, + ); + } + + public function retrieveFormatTools( + $fileName, + ImportHandler $handler, + FormatterManager $formatterManager, + ArchiveBuilderManager $archiveBuilderManager + ) { + $nameLength = strlen($fileName); + + $types = $handler->getHandledTypes(); + + $formats = + $formatterManager->getExtensionsByTypes($types, true) + + $archiveBuilderManager->getExtensions(true) + ; + + $uploadFormat = null; + + /** @var \Thelia\Core\FileFormat\Formatting\AbstractFormatter $formatter */ + $formatter = null; + + /** @var \Thelia\Core\FileFormat\Archive\AbstractArchiveBuilder $archiveBuilder */ + $archiveBuilder = null; + + foreach ($formats as $objectName => $format) { + $formatLength = strlen($format); + $formatExtension = substr($fileName, -$formatLength); + + if ($nameLength >= $formatLength && $formatExtension === $format) { + $uploadFormat = $format; + + + try { + $formatter = $formatterManager->get($objectName); + } catch (\OutOfBoundsException $e) {} + + try { + $archiveBuilder = $archiveBuilderManager->get($objectName); + } catch (\OutOfBoundsException $e) {} + + break; + } + } + + $this->checkFileExtension($fileName, $uploadFormat); + + return array( + "formatter" => $formatter, + "archive_builder" => $archiveBuilder, + "extension" => $uploadFormat, + "types" => $types, + ); + } + + public function checkFileExtension($fileName, $uploadFormat) + { + if ($uploadFormat === null) { + $splitName = explode(".", $fileName); + $ext = ""; + + if (1 < $limit = count($splitName)) { + $ext = "." . $splitName[$limit-1]; + } + + throw new FormValidationException( + $this->getTranslator()->trans( + "The extension \"%ext\" is not allowed", + [ + "%ext" => $ext + ] + ) + ); + } + } + + public function processImport( + $content, + ImportHandler $handler, + AbstractFormatter $formatter = null, + AbstractArchiveBuilder $archiveBuilder = null, + Lang $lang = null + ) { + $event = new ImportExportEvent($formatter, $handler, null, $archiveBuilder); + $event->setContent($content); + + $this->dispatch(TheliaEvents::IMPORT_AFTER_DECODE, $event); + + $data = $formatter + ->decode($event->getContent()) + ->setLang($lang) + ; + + $event->setContent(null)->setData($data); + $this->dispatch(TheliaEvents::IMPORT_AFTER_DECODE, $event); + + $errors = $handler->retrieveFromFormatterData($data); + + if (!empty($errors)) { + throw new \Exception( + $this->getTranslator()->trans( + "Errors occurred while importing the file: %errors", + [ + "%errors" => implode(", ", $errors), + ] + ) + ); + } + + return $this->getTranslator()->trans( + "Import successfully done, %numb row(s) have been changed", + [ + "%numb" => $handler->getImportedRows(), + ] + ); + } + + /** + * @param integer $id + * @return Response + * + * This method is called when the route /admin/import/{id} + * is called with a GET request. + * + * It returns a modal view if the request is an AJAX one, + * otherwise it generates a "normal" back-office page + */ + public function importView($id) + { + if (null === $import = $this->getImport($id)) { + return $this->render("404"); + } + + /** + * Use the loop to inject the same vars in Smarty + */ + $loop = new ImportLoop($this->container); + + $loop->initializeArgs([ + "id" => $id + ]); + + $query = $loop->buildModelCriteria(); + $result= $query->find(); + + $results = $loop->parseResults( + new LoopResult($result) + ); + + $parserContext = $this->getParserContext(); + + /** @var \Thelia\Core\Template\Element\LoopResultRow $row */ + foreach ($results as $row) { + foreach ($row->getVarVal() as $name=>$value) { + $parserContext->set($name, $value); + } + } + + /** + * Get allowed formats + */ + /** @var \Thelia\ImportExport\AbstractHandler $handler */ + $handler = $import->getHandleClassInstance($this->container); + $types = $handler->getHandledTypes(); + + $formatterManager = $this->getFormatterManager($this->container); + $archiveBuilderManager = $this->getArchiveBuilderManager($this->container); + + $formats = + $formatterManager->getExtensionsByTypes($types, true) + + $archiveBuilderManager->getExtensions(true) + ; + + /** + * Get allowed mime types (used for the "Search a file" window + */ + $mimeTypes = + $formatterManager->getMimeTypesByTypes($types) + + $archiveBuilderManager->getMimeTypes() + ; + + /** + * Inject them in smarty + */ + $parserContext + ->set("ALLOWED_MIME_TYPES", implode(",", $mimeTypes)) + ->set("ALLOWED_EXTENSIONS", implode(", ", $formats)) + ->set("CURRENT_LANG_ID", $this->getSession()->getLang()->getId()) + ; + + /** Then render the form */ + if ($this->getRequest()->isXmlHttpRequest()) { + return $this->render("ajax/import-modal"); + } else { + return $this->render("import-page"); + } + } + + protected function setOrders($category = null, $import = null) + { + if ($category === null) { + $category = $this->getRequest()->query->get("category_order", "manual"); + } + + if ($import === null) { + $import = $this->getRequest()->query->get("import_order", "manual"); + } + + $this->getParserContext() + ->set("category_order", $category) + ; + + $this->getParserContext() + ->set("import_order", $import) + ; + } + + public function changePosition() + { + if (null !== $response = $this->checkAuth([AdminResources::IMPORT], [], [AccessManager::UPDATE])) { + return $response; + } + + $query = $this->getRequest()->query; + + $mode = $query->get("mode"); + $id = $query->get("id"); + $value = $query->get("value"); + + $this->getImport($id); + + $event = new UpdatePositionEvent($id, $this->getMode($mode), $value); + $this->dispatch(TheliaEvents::IMPORT_CHANGE_POSITION, $event); + + } + + public function changeCategoryPosition() + { + if (null !== $response = $this->checkAuth([AdminResources::IMPORT], [], [AccessManager::UPDATE])) { + return $response; + } + + $query = $this->getRequest()->query; + + $mode = $query->get("mode"); + $id = $query->get("id"); + $value = $query->get("value"); + + $this->getCategory($id); + + $event = new UpdatePositionEvent($id, $this->getMode($mode), $value); + $this->dispatch(TheliaEvents::IMPORT_CATEGORY_CHANGE_POSITION, $event); + + $this->setOrders("manual"); + + return $this->render('import'); + } + + public function getMode($action) + { + if ($action === "up") { + $mode = UpdatePositionEvent::POSITION_UP; + } elseif ($action === "down") { + $mode = UpdatePositionEvent::POSITION_DOWN; + } else { + $mode = UpdatePositionEvent::POSITION_ABSOLUTE; + } + + return $mode; + } + + protected function getImport($id) + { + $import = ImportQuery::create()->findPk($id); + + if (null === $import) { + throw new \ErrorException( + $this->getTranslator()->trans( + "There is no id \"%id\" in the imports", + [ + "%id" => $id + ] + ) + ); + } + + return $import; + } + + protected function getCategory($id) + { + $category = ImportCategoryQuery::create()->findPk($id); + + if (null === $category) { + throw new \ErrorException( + $this->getTranslator()->trans( + "There is no id \"%id\" in the import categories", + [ + "%id" => $id + ] + ) + ); + } + + return $category; + } +} diff --git a/core/lib/Thelia/Core/Bundle/TheliaBundle.php b/core/lib/Thelia/Core/Bundle/TheliaBundle.php index bb476c402..69065eccc 100644 --- a/core/lib/Thelia/Core/Bundle/TheliaBundle.php +++ b/core/lib/Thelia/Core/Bundle/TheliaBundle.php @@ -17,7 +17,9 @@ use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Scope; +use Thelia\Core\DependencyInjection\Compiler\RegisterArchiveBuilderPass; use Thelia\Core\DependencyInjection\Compiler\RegisterCouponPass; +use Thelia\Core\DependencyInjection\Compiler\RegisterFormatterPass; use Thelia\Core\DependencyInjection\Compiler\RegisterListenersPass; use Thelia\Core\DependencyInjection\Compiler\RegisterParserPluginPass; use Thelia\Core\DependencyInjection\Compiler\RegisterRouterPass; @@ -57,6 +59,8 @@ class TheliaBundle extends Bundle ->addCompilerPass(new RegisterRouterPass()) ->addCompilerPass(new RegisterCouponPass()) ->addCompilerPass(new RegisterCouponConditionPass()) + ->addCompilerPass(new RegisterArchiveBuilderPass()) + ->addCompilerPass(new RegisterFormatterPass()) ; } } diff --git a/core/lib/Thelia/Core/DependencyInjection/Compiler/RegisterArchiveBuilderPass.php b/core/lib/Thelia/Core/DependencyInjection/Compiler/RegisterArchiveBuilderPass.php new file mode 100644 index 000000000..fc49bb4fc --- /dev/null +++ b/core/lib/Thelia/Core/DependencyInjection/Compiler/RegisterArchiveBuilderPass.php @@ -0,0 +1,54 @@ + + */ +class RegisterArchiveBuilderPass implements CompilerPassInterface +{ + const MANAGER_DEFINITION = "thelia.manager.archive_builder_manager"; + + const SERVICE_TAG = "thelia.archive_builder"; + + /** + * You can modify the container here before it is dumped to PHP code. + * + * @param ContainerBuilder $container Container + * + * @api + */ + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition(static::MANAGER_DEFINITION)) { + return; + } + + $manager = $container->getDefinition(static::MANAGER_DEFINITION); + $services = $container->findTaggedServiceIds(static::SERVICE_TAG); + + foreach ($services as $id => $condition) { + $manager->addMethodCall( + 'add', + array( + new Reference($id) + ) + ); + } + } +} diff --git a/core/lib/Thelia/Core/DependencyInjection/Compiler/RegisterFormatterPass.php b/core/lib/Thelia/Core/DependencyInjection/Compiler/RegisterFormatterPass.php new file mode 100644 index 000000000..2e66ed8f6 --- /dev/null +++ b/core/lib/Thelia/Core/DependencyInjection/Compiler/RegisterFormatterPass.php @@ -0,0 +1,54 @@ + + */ +class RegisterFormatterPass implements CompilerPassInterface +{ + const MANAGER_DEFINITION = "thelia.manager.formatter_manager"; + + const SERVICE_TAG = "thelia.formatter"; + + /** + * You can modify the container here before it is dumped to PHP code. + * + * @param ContainerBuilder $container Container + * + * @api + */ + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition(static::MANAGER_DEFINITION)) { + return; + } + + $manager = $container->getDefinition(static::MANAGER_DEFINITION); + $services = $container->findTaggedServiceIds(static::SERVICE_TAG); + + foreach ($services as $id => $condition) { + $manager->addMethodCall( + 'add', + array( + new Reference($id) + ) + ); + } + } +} diff --git a/core/lib/Thelia/Core/DependencyInjection/Loader/XmlFileLoader.php b/core/lib/Thelia/Core/DependencyInjection/Loader/XmlFileLoader.php index a8808372d..7d92be2f5 100644 --- a/core/lib/Thelia/Core/DependencyInjection/Loader/XmlFileLoader.php +++ b/core/lib/Thelia/Core/DependencyInjection/Loader/XmlFileLoader.php @@ -12,6 +12,7 @@ namespace Thelia\Core\DependencyInjection\Loader; +use Propel\Runtime\Propel; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Config\Util\XmlUtils; use Symfony\Component\DependencyInjection\DefinitionDecorator; @@ -24,6 +25,18 @@ use Symfony\Component\DependencyInjection\SimpleXMLElement; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Loader\FileLoader; +use Thelia\Model\Export; +use Thelia\Model\ExportCategory; +use Thelia\Model\ExportCategoryQuery; +use Thelia\Model\ExportQuery; +use Thelia\Model\Import; +use Thelia\Model\ImportCategory; +use Thelia\Model\ImportCategoryQuery; +use Thelia\Model\ImportQuery; +use Thelia\Model\Map\ExportCategoryTableMap; +use Thelia\Model\Map\ExportTableMap; +use Thelia\Model\Map\ImportCategoryTableMap; +use Thelia\Model\Map\ImportTableMap; /** * @@ -35,6 +48,7 @@ use Symfony\Component\DependencyInjection\Loader\FileLoader; */ class XmlFileLoader extends FileLoader { + /** * Loads an XML file. * @@ -63,6 +77,44 @@ class XmlFileLoader extends FileLoader $this->parseForms($xml); $this->parseDefinitions($xml, $path); + + $this->propelOnlyRun( + [$this, "parseExportCategories"], + $xml, + ExportCategoryTableMap::DATABASE_NAME + ); + + $this->propelOnlyRun( + [$this, "parseExports"], + $xml, + ExportTableMap::DATABASE_NAME + ); + + $this->propelOnlyRun( + [$this, "parseExportCategories"], + $xml, + ImportCategoryTableMap::DATABASE_NAME + ); + + $this->propelOnlyRun( + [$this, "parseExports"], + $xml, + ImportTableMap::DATABASE_NAME + ); + } + + public function propelOnlyRun(callable $method, $arg, $name) + { + $doRun = false; + + try { + Propel::getConnection($name); + $doRun = true; + } catch (\ErrorException $e) {} + + if ($doRun) { + call_user_func($method, $arg); + } } protected function parseCommands(SimpleXMLElement $xml) @@ -276,6 +328,259 @@ class XmlFileLoader extends FileLoader $this->container->setDefinition($id, $definition); } + protected function parseExportCategories(SimpleXMLElement $xml) + { + if (false === $exportCategories = $xml->xpath('//config:export_categories/config:export_category')) { + return; + } + + $con = Propel::getWriteConnection(ExportCategoryTableMap::DATABASE_NAME); + $con->beginTransaction(); + + try { + /** @var SimpleXMLElement $exportCategory */ + foreach ($exportCategories as $exportCategory) { + $id = (string) $exportCategory->getAttributeAsPhp("id"); + + $exportCategoryModel = ExportCategoryQuery::create()->findOneByRef($id); + + if ($exportCategoryModel === null) { + $exportCategoryModel = new ExportCategory(); + $exportCategoryModel + ->setRef($id) + ->save($con) + ; + } + + /** @var SimpleXMLElement $child */ + foreach ($exportCategory->children() as $child) { + $locale = (string) $child->getAttributeAsPhp("locale"); + $value = (string) $child; + + $exportCategoryModel + ->setLocale($locale) + ->setTitle($value) + ->save($con); + ; + } + } + + $con->commit(); + } catch (\Exception $e) { + $con->rollBack(); + + throw $e; + } + } + + protected function parseExports(SimpleXMLElement $xml) + { + if (false === $exports = $xml->xpath('//config:exports/config:export')) { + return; + } + + $con = Propel::getWriteConnection(ExportTableMap::DATABASE_NAME); + $con->beginTransaction(); + + try { + + /** @var SimpleXMLElement $export */ + foreach ($exports as $export) { + $id = (string) $export->getAttributeAsPhp("id"); + $class = (string) $export->getAttributeAsPhp("class"); + $categoryRef = (string) $export->getAttributeAsPhp("category_id"); + + if (!class_exists($class)) { + throw new \ErrorException( + "The class \"$class\" doesn't exist" + ); + } + + $category = ExportCategoryQuery::create()->findOneByRef($categoryRef); + + if (null === $category) { + throw new \ErrorException( + "The export category \"$categoryRef\" doesn't exist" + ); + } + + $exportModel = ExportQuery::create()->findOneByRef($id); + + if (null === $exportModel) { + $exportModel = new Export(); + $exportModel + ->setRef($id) + ; + } + + $exportModel + ->setExportCategory($category) + ->setHandleClass($class) + ->save($con) + ; + + /** @var SimpleXMLElement $descriptive */ + foreach ($export->children() as $descriptive) { + $locale = $descriptive->getAttributeAsPhp("locale"); + $title = null; + $description = null; + + /** @var SimpleXMLElement $row */ + foreach ($descriptive->children() as $row) { + switch ($row->getName()) { + case "title": + $title = (string) $row; + break; + case "description": + $description = (string) $row; + break; + } + } + + $exportModel + ->setLocale($locale) + ->setTitle($title) + ->setDescription($description) + ->save($con) + ; + } + } + + $con->commit(); + } catch (\Exception $e) { + $con->rollBack(); + + throw $e; + } + } + + protected function parseImportCategories(SimpleXMLElement $xml) + { + if (false === $importCategories = $xml->xpath('//config:import_categories/config:import_category')) { + return; + } + + $con = Propel::getWriteConnection(ImportCategoryTableMap::DATABASE_NAME); + $con->beginTransaction(); + + try { + + /** @var SimpleXMLElement $importCategory */ + foreach ($importCategories as $importCategory) { + $id = (string) $importCategory->getAttributeAsPhp("id"); + + $importCategoryModel = ImportCategoryQuery::create()->findOneByRef($id); + + if ($importCategoryModel === null) { + $importCategoryModel = new ImportCategory(); + $importCategoryModel + ->setRef($id) + ->save($con) + ; + } + + /** @var SimpleXMLElement $child */ + foreach ($importCategory->children() as $child) { + $locale = (string) $child->getAttributeAsPhp("locale"); + $value = (string) $child; + + $importCategoryModel + ->setLocale($locale) + ->setTitle($value) + ->save($con); + ; + } + + } + + $con->commit(); + } catch (\Exception $e) { + $con->rollBack(); + + throw $e; + } + } + + protected function parseImports(SimpleXMLElement $xml) + { + if (false === $imports = $xml->xpath('//config:imports/config:import')) { + return; + } + + $con = Propel::getWriteConnection(ImportTableMap::DATABASE_NAME); + $con->beginTransaction(); + + try { + /** @var SimpleXMLElement $import */ + foreach ($imports as $import) { + $id = (string) $import->getAttributeAsPhp("id"); + $class = (string) $import->getAttributeAsPhp("class"); + $categoryRef = (string) $import->getAttributeAsPhp("category_id"); + + if (!class_exists($class)) { + throw new \ErrorException( + "The class \"$class\" doesn't exist" + ); + } + + $category = ImportCategoryQuery::create()->findOneByRef($categoryRef); + + if (null === $category) { + throw new \ErrorException( + "The import category \"$categoryRef\" doesn't exist" + ); + } + + $importModel = ImportQuery::create()->findOneByRef($id); + + if (null === $importModel) { + $importModel = new Import(); + $importModel + ->setRef($id) + ; + } + + $importModel + ->setImportCategory($category) + ->setHandleClass($class) + ->save($con) + ; + + /** @var SimpleXMLElement $descriptive */ + foreach ($import->children() as $descriptive) { + $locale = $descriptive->getAttributeAsPhp("locale"); + $title = null; + $description = null; + + /** @var SimpleXMLElement $row */ + foreach ($descriptive->children() as $row) { + switch ($row->getName()) { + case "title": + $title = (string) $row; + break; + case "description": + $description = (string) $row; + break; + } + } + + $importModel + ->setLocale($locale) + ->setTitle($title) + ->setDescription($description) + ->save($con) + ; + } + } + + $con->commit(); + } catch (\Exception $e) { + $con->rollBack(); + + throw $e; + } + } + /** * Parses a XML file. * diff --git a/core/lib/Thelia/Core/DependencyInjection/Loader/schema/dic/config/thelia-1.0.xsd b/core/lib/Thelia/Core/DependencyInjection/Loader/schema/dic/config/thelia-1.0.xsd index 43c0eff65..5dfb98aea 100644 --- a/core/lib/Thelia/Core/DependencyInjection/Loader/schema/dic/config/thelia-1.0.xsd +++ b/core/lib/Thelia/Core/DependencyInjection/Loader/schema/dic/config/thelia-1.0.xsd @@ -17,6 +17,10 @@ + + + + @@ -212,4 +216,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/lib/Thelia/Core/Event/ImportExport.php b/core/lib/Thelia/Core/Event/ImportExport.php new file mode 100644 index 000000000..66db62669 --- /dev/null +++ b/core/lib/Thelia/Core/Event/ImportExport.php @@ -0,0 +1,153 @@ + + */ +class ImportExport extends ActionEvent +{ + /** @var \Thelia\ImportExport\AbstractHandler */ + protected $handler; + + /** @var \Thelia\Core\FileFormat\Formatting\AbstractFormatter */ + protected $formatter; + + /** @var FormatterData */ + protected $data; + + /** @var \Thelia\Core\FileFormat\Archive\AbstractArchiveBuilder */ + protected $archiveBuilder; + + /** @var mixed */ + protected $content; + + public function __construct( + AbstractFormatter $formatter = null, + AbstractHandler $handler = null, + FormatterData $data = null, + AbstractArchiveBuilder $archiveBuilder = null + ) { + $this->archiveBuilder = $archiveBuilder; + $this->formatter = $formatter; + $this->handler = $handler; + $this->data = $data; + } + + /** + * @param AbstractArchiveBuilder $archiveBuilder + * @return $this + */ + public function setArchiveBuilder(AbstractArchiveBuilder $archiveBuilder) + { + $this->archiveBuilder = $archiveBuilder; + + return $this; + } + + /** + * @return \Thelia\Core\FileFormat\Archive\AbstractArchiveBuilder + */ + public function getArchiveBuilder() + { + return $this->archiveBuilder; + } + + /** + * @param AbstractFormatter $formatter + * @return $this + */ + public function setFormatter(AbstractFormatter $formatter) + { + $this->formatter = $formatter; + + return $this; + } + + /** + * @return \Thelia\Core\FileFormat\Formatting\AbstractFormatter + */ + public function getFormatter() + { + return $this->formatter; + } + + /** + * @param \Thelia\ImportExport\Export\ExportHandler $handler + * @return $this + */ + public function setHandler(ExportHandler $handler) + { + $this->handler = $handler; + + return $this; + } + + /** + * @return \Thelia\ImportExport\Export\ExportHandler + */ + public function getHandler() + { + return $this->handler; + } + + /** + * @param FormatterData $data + * @return $this + */ + public function setData(FormatterData $data) + { + $this->data = $data; + + return $this; + } + + /** + * @return \Thelia\Core\FileFormat\Formatting\FormatterData + */ + public function getData() + { + return $this->data; + } + + /** + * @param $content + * @return $this + */ + public function setContent($content) + { + $this->content = $content; + + return $this; + } + + /** + * @return mixed + */ + public function getContent() + { + return $this->content; + } + + public function isArchive() + { + return $this->archiveBuilder !== null; + } +} diff --git a/core/lib/Thelia/Core/Event/TheliaEvents.php b/core/lib/Thelia/Core/Event/TheliaEvents.php index 9c2962801..3fdb34512 100644 --- a/core/lib/Thelia/Core/Event/TheliaEvents.php +++ b/core/lib/Thelia/Core/Event/TheliaEvents.php @@ -766,4 +766,18 @@ final class TheliaEvents const BEFORE_UPDATEBRAND = "action.before_updateBrand"; const AFTER_UPDATEBRAND = "action.after_updateBrand"; + + // -- Export ---------------------------------------------- + + const EXPORT_BEFORE_ENCODE = "Thelia.export.encode.before"; + const EXPORT_AFTER_ENCODE = "Thelia.export.encode.after"; + + const EXPORT_CATEGORY_CHANGE_POSITION = "Thelia.export.change_category_position"; + const EXPORT_CHANGE_POSITION = "Thelia.export.change_position"; + + const IMPORT_BEFORE_DECODE = "Thelia.import.decode.before"; + const IMPORT_AFTER_DECODE = "Thelia.import.decode.after"; + + const IMPORT_CATEGORY_CHANGE_POSITION = "Thelia.import.change_category_position"; + const IMPORT_CHANGE_POSITION = "Thelia.import.change_position"; } diff --git a/core/lib/Thelia/Core/FileFormat/Archive/AbstractArchiveBuilder.php b/core/lib/Thelia/Core/FileFormat/Archive/AbstractArchiveBuilder.php new file mode 100644 index 000000000..e873d74ef --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Archive/AbstractArchiveBuilder.php @@ -0,0 +1,214 @@ + + */ +abstract class AbstractArchiveBuilder implements FormatInterface, ArchiveBuilderInterface +{ + use FileDownloaderAwareTrait; + + const TEMP_DIRECTORY_NAME = "archive_builder"; + + /** @var string */ + protected $cacheFile; + + /** @var \Thelia\Core\Translation\Translator */ + protected $translator; + + /** @var \Thelia\Log\Tlog */ + protected $logger; + + /** @var string */ + protected $cacheDir; + + /** @var string */ + protected $environment; + + public function __construct() + { + $this->translator = Translator::getInstance(); + + $this->logger = Tlog::getNewInstance(); + } + + public function getArchiveBuilderCacheDirectory($environment) + { + $theliaCacheDir = THELIA_CACHE_DIR . $environment . DS; + + if (!is_writable($theliaCacheDir)) { + throw new \ErrorException( + $this->translator->trans( + "The cache directory \"%env\" is not writable", + [ + "%env" => $environment + ] + ) + ); + } + + $archiveBuilderCacheDir = $this->cacheDir = $theliaCacheDir . static::TEMP_DIRECTORY_NAME; + + if (!is_dir($archiveBuilderCacheDir) && !mkdir($archiveBuilderCacheDir, 0755)) { + throw new \ErrorException( + $this->translator->trans( + "Error while creating the directory \"%directory\"", + [ + "%directory" => static::TEMP_DIRECTORY_NAME + ] + ) + ); + } + + return $archiveBuilderCacheDir; + } + + /** + * @param $pathToFile + * @param $destination + * @param $isOnline + * @return $this + * @throws \ErrorException + */ + public function copyFile($pathToFile, $destination, $isOnline) + { + if ($isOnline) { + /** + * It's an online file + */ + $this->getFileDownloader() + ->download($pathToFile, $destination) + ; + } else { + /** + * It's a local file + */ + if (!is_file($pathToFile)) { + $this->throwFileNotFound($pathToFile); + } elseif (!is_readable($pathToFile)) { + throw new FileNotReadableException( + $this->translator + ->trans( + "The file %file is not readable", + [ + "%file" => $pathToFile, + ] + ) + ); + } + + if (!copy($pathToFile, $destination)) { + $translatedErrorMessage = $this->translator->trans( + "An error happend while copying %prev to %dest", + [ + "%prev" => $pathToFile, + "%dest" => $destination, + ] + ); + + $this->logger + ->error($translatedErrorMessage) + ; + + throw new \ErrorException($translatedErrorMessage); + } + } + + return $this; + } + + /** + * @return string + */ + public function generateCacheFile($environment) + { + $cacheFileName = md5(uniqid()); + + $cacheFile = $this->getArchiveBuilderCacheDirectory($environment) . DS; + $cacheFile .= $cacheFileName . "." . $this->getExtension(); + + return $cacheFile; + } + + public function throwFileNotFound($file) + { + + throw new FileNotFoundException( + $this->translator + ->trans( + "The file %file is missing or is not readable", + [ + "%file" => $file, + ] + ) + ); + } + + /** + * @param $path + * @return $this + */ + public function setCacheFile($path) + { + $this->cacheFile = $path; + + return $this; + } + + public function getCacheDir() + { + return $this->cacheDir; + } + + /** + * @return Tlog + */ + public function getLogger() + { + return $this->logger; + } + + /** + * @return Translator + */ + public function getTranslator() + { + return $this->translator; + } + + public function getCacheFile() + { + return $this->cacheFile; + } + + /** + * @param string $environment + * @return $this + * + * Sets the execution environment of the Kernel, + * used to know which cache is used. + */ + public function setEnvironment($environment) + { + $this->environment = $environment; + } +} diff --git a/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/Exception/TarArchiveException.php b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/Exception/TarArchiveException.php new file mode 100644 index 000000000..3e2d583d6 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/Exception/TarArchiveException.php @@ -0,0 +1,23 @@ + + */ +class TarArchiveException extends \Exception +{ + +} diff --git a/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/Exception/ZipArchiveException.php b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/Exception/ZipArchiveException.php new file mode 100644 index 000000000..f69375dec --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/Exception/ZipArchiveException.php @@ -0,0 +1,23 @@ + + */ +class ZipArchiveException extends \ErrorException +{ + +} diff --git a/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/TarArchiveBuilder.php b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/TarArchiveBuilder.php new file mode 100644 index 000000000..00e4fe838 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/TarArchiveBuilder.php @@ -0,0 +1,506 @@ + + */ +class TarArchiveBuilder extends AbstractArchiveBuilder +{ + const PHAR_FORMAT = \Phar::TAR; + + /** @var string */ + protected $environment; + + /** @var null|string */ + protected $compression; + + /** @var string */ + protected $tarCacheFile; + + /** @var \PharData */ + protected $tar; + + /** @var \Thelia\Core\Translation\Translator */ + protected $translator; + + /** @var \Thelia\Log\Tlog */ + protected $logger; + + public function __destruct() + { + if ($this->tar instanceof \PharData) { + if (file_exists($this->cacheFile)) { + unlink($this->cacheFile); + } + } + } + + /** + * @param string $filePath It is the path to access the file. + * @param string $directoryInArchive This is the directory where it will be stored in the archive + * @param null|string $name The name of the file in the archive. if it null or empty, it keeps the same name + * @param bool $isOnline + * @return $this + * @throws \Thelia\Exception\FileNotFoundException + * @throws \Thelia\Exception\FileNotReadableException + * @throws \ErrorException + * + * This methods adds a file in the archive. + * If the file is local, $isOnline must be false, + * If the file online, $filePath must be an URL. + */ + public function addFile($filePath, $directoryInArchive = "/", $name = null, $isOnline = false) + { + if (!empty($name)) { + $dirName = dirname($name); + if ($dirName == ".") { + $dirName = ""; + } + $directoryInArchive .= DS . $dirName; + } + + if (empty($name) || !is_scalar($name)) { + $name = basename($filePath); + } else { + $name = basename($name); + } + + /** + * Download the file if it is online + * If it's local check if the file exists and if it is redable + */ + $fileDownloadCache = $this->cacheDir . DS . md5(uniqid()) . ".tmp"; + $this->copyFile($filePath, $fileDownloadCache, $isOnline); + + /** + * Then write the file in the archive + */ + $directoryInArchive = $this->formatDirectoryPath($directoryInArchive); + + if (!empty($directoryInArchive)) { + $name = $this->formatFilePath( + $directoryInArchive . $name + ); + } + + $this->tar->addFile($filePath, $name); + + /** + * And clear the download temp file + */ + unlink($fileDownloadCache); + + return $this; + } + + /** + * @param $content + * @param $name + * @param string $directoryInArchive + * @return mixed + * @throws \ErrorException + * + * This method creates a file in the archive with its content + */ + public function addFileFromString($content, $name, $directoryInArchive = "/") + { + if (empty($name) || !is_scalar($name)) { + throw new \ErrorException( + $this->translator->trans( + "The file name must be valid" + ) + ); + } + + $directoryInArchive = $this->formatDirectoryPath($directoryInArchive); + + if (!empty($directoryInArchive)) { + $name = $this->formatFilePath( + $directoryInArchive . $name + ); + } + try { + $this->tar->addFromString($name, $content); + } catch (\Exception $e) { + throw new \ErrorException( + $this->translator->trans( + "Error while writing the file into the archive, error message: %errmes", + [ + "%errmes" => $e->getMessage() + ] + ) + ); + } + } + + /** + * @param $directoryPath + * @return $this + * @throws \ErrorException + * + * This method creates an empty directory + */ + public function addDirectory($directoryPath) + { + $directoryInArchive = $this->formatDirectoryPath($directoryPath); + + if (!empty($directoryInArchive)) { + + try { + $this->tar->addEmptyDir($directoryInArchive); + } catch (\Exception $e) { + throw new \ErrorException( + $this->translator->trans( + "The directory %dir has not been created in the archive", + [ + "%dir" => $directoryInArchive + ] + ) + ); + } + } + + return $this; + } + + /** + * @param string $pathToFile + * @return null|string + * @throws \Thelia\Exception\FileNotFoundException + * @throws \Thelia\Exception\FileNotReadableException + * @throws \ErrorException + * + * This method returns a file content + */ + public function getFileContent($pathToFile) + { + $pathToFile = $this->formatFilePath($pathToFile); + + if (!$this->hasFile($pathToFile)) { + $this->throwFileNotFound($pathToFile); + } + + /** @var \PharFileInfo $fileInfo*/ + $fileInfo = $this->tar[$pathToFile]; + + /** @var \SplFileObject $file */ + $file = $fileInfo->openFile(); + $content = ""; + + while (false !== ($char = $file->fgetc())) { + $content .= $char; + } + + return $content; + } + + /** + * @param $pathInArchive + * @return $this + * @throws \Thelia\Exception\FileNotFoundException + * @throws \ErrorException + * + * This method deletes a file in the archive + */ + public function deleteFile($pathInArchive) + { + if (!$this->hasFile($pathInArchive)) { + $this->throwFileNotFound($pathInArchive); + } + + if (false === $this->tar->delete($pathInArchive)) { + throw new \ErrorException( + $this->translator->trans( + "Unknown error while deleting the file %file", + [ + "%file" => $pathInArchive + ] + ) + ); + } + } + + /** + * @return \Thelia\Core\HttpFoundation\Response + * + * This method return an instance of a Response with the archive as content. + */ + public function buildArchiveResponse($filename) + { + if (!is_file($this->cacheFile)) { + $this->throwFileNotFound($this->cacheFile); + } + + if (!is_readable($this->cacheFile)) { + throw new FileNotReadableException( + $this->translator->trans( + "The file %file is not readable", + [ + "%file" => $this->cacheFile + ] + ) + ); + } + + $content = file_get_contents($this->cacheFile); + + return new Response( + $content, + 200, + [ + "Content-Type" => $this->getMimeType(), + "Content-Disposition" => "attachment; filename=\"".$filename . "." . $this->getExtension() ."\"", + ] + ); + } + + /** + * @param string $pathToArchive + * @param string $environment + * @param bool $isOnline + * @param FileDownloaderInterface $fileDownloader + * @return $this + * @throws \Thelia\Exception\FileNotFoundException + * @throws \Thelia\Exception\HttpUrlException + * @throws TarArchiveException + * + * Loads an archive + */ + public function loadArchive($pathToArchive, $isOnline = false) + { + $tar = clone $this; + + $tar + ->setCacheFile($tar->generateCacheFile($this->environment)) + ->copyFile($pathToArchive, $tar->getCacheFile(), $isOnline); + + /** + * This throws TarArchiveBuilderException if + * the archive is not valid. + */ + + return $tar->setEnvironment($tar->environment); + } + + /** + * @param $pathToFile + * @return bool + * + * Checks if the archive has a file. + * In \PharData, if you call it as a array, + * the keys are the files in the archive. + */ + public function hasFile($pathToFile) + { + $isFile = false; + + $pathToFile = $this->formatFilePath($pathToFile); + try { + /** @var \PharFileInfo $fileInfo */ + $fileInfo = $this->tar[$pathToFile]; + + if ($fileInfo->isFile()) { + $isFile = true; + } + /** + * Catch the exception to avoid its displaying. + */ + } catch (\BadMethodCallException $e) {} + + return $isFile; + } + + /** + * @param string $directory + * @return bool + * + * Check if the archive has a directory + */ + public function hasDirectory($directory) + { + $isDir = false; + + $pathToDir = $this->formatDirectoryPath($directory); + try { + /** @var \PharFileInfo $fileInfo */ + $fileInfo = $this->tar[$pathToDir]; + + if ($fileInfo->isDir()) { + $isDir = true; + } + /** + * Catch the exception to avoid its displaying. + */ + } catch (\BadMethodCallException $e) {} + + return $isDir; + } + + /** + * @param string $environment + * @return $this + * + * Sets the execution environment of the Kernel, + * used to know which cache is used. + */ + public function setEnvironment($environment) + { + if (empty($environment)) { + throw new \ErrorException( + $this->translator->trans( + "You must define an environment when you use an archive builder" + ) + ); + } + + if ($this->cacheFile === null) { + $cacheFile = $this->generateCacheFile($environment); + + if (file_exists($cacheFile)) { + unlink($cacheFile); + } + } else { + $cacheFile = $this->cacheFile; + } + + $errorMessage = null; + + try { + $this->tar = new \PharData($cacheFile, null, null, static::PHAR_FORMAT); + + $this->compressionEntryPoint(); + + } catch (\BadMethodCallException $e) { + /** + * This should not happen + */ + $errorMessage = "You have badly called the method setEnvironment twice for %file"; + } catch (\UnexpectedValueException $e) { + $errorMessage = "The file %file is corrupted"; + } + + if ($errorMessage !== null) { + throw new TarArchiveException( + $this->translator->trans( + $errorMessage, + [ + "%file" => $cacheFile + ] + ) + ); + } + + $this->cacheFile = $cacheFile; + $this->environment = $environment; + + return $this; + } + + /** + * @param string $initialString + * @return string + * + * Gives a valid file path for \ZipArchive + */ + public function formatFilePath($initialString) + { + /** + * Remove the / at the beginning and the end. + */ + $initialString = trim($initialString, "/"); + + /** + * Remove the double, triple, ... slashes + */ + $initialString = preg_replace("#\/{2,}#", "/", $initialString); + + return $initialString; + } + + /** + * @param string $initialString + * @return string + * + * Gives a valid directory path for \ZipArchive + */ + public function formatDirectoryPath($initialString) + { + $initialString = $this->formatFilePath($initialString); + + return $initialString . "/"; + } + + /** + * @return string + * + * This method must return a string, the name of the format. + * + * example: + * return "XML"; + */ + public function getName() + { + return "tar"; + } + + /** + * @return string + * + * This method must return a string, the extension of the file format, without the ".". + * The string should be lowercase. + * + * example: + * return "xml"; + */ + public function getExtension() + { + return "tar"; + } + + /** + * @return string + * + * This method must return a string, the mime type of the file format. + * + * example: + * return "application/json"; + */ + public function getMimeType() + { + return "application/x-tar"; + } + + protected function compressionEntryPoint() + { + /** + * This method must be overwritten if you want to do some + * stuff to compress you archive + */ + } + + public function getCompression() + { + return $this->compression; + } +} diff --git a/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/TarBz2ArchiveBuilder.php b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/TarBz2ArchiveBuilder.php new file mode 100644 index 000000000..eb6790711 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/TarBz2ArchiveBuilder.php @@ -0,0 +1,47 @@ + + */ +class TarBz2ArchiveBuilder extends TarArchiveBuilder +{ + public function getName() + { + return "tar.bz2"; + } + + public function getMimeType() + { + return "application/x-bzip2"; + } + + public function getExtension() + { + return "tbz2"; + } + + protected function compressionEntryPoint() + { + if ($this->compression != \Phar::BZ2) { + $this->tar = $this->tar->compress(\Phar::BZ2, $this->getExtension()); + } + + $this->compression = \Phar::BZ2; + + return $this; + } +} diff --git a/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/TarGzArchiveBuilder.php b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/TarGzArchiveBuilder.php new file mode 100644 index 000000000..581e4a3b2 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/TarGzArchiveBuilder.php @@ -0,0 +1,48 @@ + + */ +class TarGzArchiveBuilder extends TarArchiveBuilder +{ + public function getName() + { + return "tar.gz"; + } + + public function getMimeType() + { + return "application/x-gzip"; + } + + public function getExtension() + { + return "tgz"; + } + + protected function compressionEntryPoint() + { + if ($this->compression != \Phar::GZ) { + $this->tar = $this->tar->compress(\Phar::GZ, $this->getExtension()); + } + + $this->compression = \Phar::GZ; + + return $this; + } + +} diff --git a/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/ZipArchiveBuilder.php b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/ZipArchiveBuilder.php new file mode 100644 index 000000000..dcaac183e --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilder/ZipArchiveBuilder.php @@ -0,0 +1,613 @@ + + * + * This class is a driver defined by AbstractArchiveBuilder, + * it's goal is to manage Zip archives. + * + * You can create a new archive by creating a new instance, + * or load an existing zip with the static method loadArchive. + */ +class ZipArchiveBuilder extends AbstractArchiveBuilder +{ + /** + * @var \ZipArchive + */ + protected $zip; + + public function __construct() + { + parent::__construct(); + + $this->zip = new \ZipArchive(); + } + + /** + * On the destruction of the class, + * remove the temporary file. + */ + public function __destruct() + { + if ($this->zip instanceof \ZipArchive) { + @$this->zip->close(); + + if (file_exists($this->cacheFile)) { + unlink($this->cacheFile); + } + } + } + + /** + * @param string $filePath It is the path to access the file. + * @param string $directoryInArchive This is the directory where it will be stored in the archive + * @param null|string $name The name of the file in the archive. if it null or empty, it keeps the same name + * @param bool $isOnline + * @return $this + * @throws \Thelia\Exception\FileNotFoundException + * @throws \Thelia\Exception\FileNotReadableException + * @throws \ErrorException + * + * This methods adds a file in the archive. + * If the file is local, $isOnline must be false, + * If the file online, $filePath must be an URL. + */ + public function addFile($filePath, $directoryInArchive = null, $name = null, $isOnline = false) + { + if (!empty($name)) { + $directoryInArchive .= DS . dirname($name) ; + } + + $directoryInArchive = $this->formatDirectoryPath($directoryInArchive); + + /** + * Add empty directory if it doesn't exist + */ + + if (!empty($directoryInArchive)) { + $this->addDirectory($directoryInArchive); + } + + if (empty($name) || !is_scalar($name)) { + $name = basename($filePath); + } else { + $name = basename($name); + } + + /** + * Download the file if it is online + * If it's local check if the file exists and if it is redable + */ + $fileDownloadCache = $this->cacheDir . DS . md5(uniqid()) . ".tmp"; + $this->copyFile($filePath, $fileDownloadCache, $isOnline); + + /** + * Then write the file in the archive and commit the changes + */ + $destination = $directoryInArchive . $name; + + if (!$this->zip->addFile($fileDownloadCache, $destination)) { + $translatedErrorMessage = $this->translator->trans( + "An error occurred while adding this file to the archive: %file", + [ + "%file" => $fileDownloadCache + ] + ); + + $this->logger->error($translatedErrorMessage); + + // if error delete the cache file + unlink($fileDownloadCache); + + throw new \ErrorException($translatedErrorMessage); + } + + $this->commit(); + + // Delete the temp file + unlink($fileDownloadCache); + + return $this; + } + + /** + * @param $content + * @param $name + * @param string $directoryInArchive + * @return mixed + * @throws \ErrorException + * + * This method creates a file in the archive with its content + */ + public function addFileFromString($content, $name, $directoryInArchive = "/") + { + $directoryInArchive = $this->formatDirectoryPath($directoryInArchive); + + if (!empty($directoryInArchive) && $directoryInArchive !== "/") { + $this->addDirectory($directoryInArchive); + } + + if (empty($name) || !is_scalar($name)) { + throw new \ErrorException( + $this->translator->trans( + "The filename is not correct" + ) + ); + } + + $filePath = $this->getFilePath($directoryInArchive . DS . $name); + + if (!$this->zip->addFromString($filePath, $content)) { + throw new \ErrorException( + $this->translator->trans( + "Unable to write the file %file into the archive", + [ + "%file" => $filePath, + ] + ) + ); + } + + $this->commit(); + } + + + /** + * @param $directoryPath + * @return $this + * @throws \ErrorException + * + * This method creates an empty directory + */ + public function addDirectory($directoryPath) + { + $directoryInArchive = $this->formatDirectoryPath($directoryPath); + + if (!empty($directoryInArchive)) { + $this->zip->addEmptyDir($directoryInArchive); + $this->commit(); + + if (!$this->hasDirectory($directoryInArchive)) { + throw new \ErrorException( + $this->translator->trans( + "The directory %dir has not been created in the archive", + [ + "%dir" => $directoryInArchive + ] + ) + ); + } + } + + return $this; + } + + /** + * @param string $pathToFile + * @return null|string + * @throws \Thelia\Exception\FileNotFoundException + * @throws \Thelia\Exception\FileNotReadableException + * @throws \ErrorException + * + * This method returns a file content + */ + public function getFileContent($pathToFile) + { + $pathToFile = $this->formatFilePath($pathToFile); + + if (!$this->hasFile($pathToFile)) { + $this->throwFileNotFound($pathToFile); + } + + $stream = $this->zip->getStream($pathToFile); + $content = ""; + + while (!feof($stream)) { + $content .= fread($stream, 2); + } + + fclose($stream); + + return $content; + } + + + /** + * @param string $initialString + * @return string + * + * Gives a valid file path for \ZipArchive + */ + public function getFilePath($initialString) + { + /** + * Remove the / at the beginning and the end. + */ + $initialString = trim($initialString, "/"); + + /** + * Remove the double, triple, ... slashes + */ + $initialString = preg_replace("#\/{2,}#", "/", $initialString); + + if (preg_match("#\/?[^\/]+\/[^\/]+\/?#", $initialString)) { + $initialString = "/" . $initialString; + } + + return $initialString; + } + + /** + * @param string $initialString + * @return string + * + * Gives a valid directory path for \ZipArchive + */ + public function getDirectoryPath($initialString) + { + $initialString = $this->getFilePath($initialString); + + if ($initialString[0] !== "/") { + $initialString = "/" . $initialString; + } + + return $initialString . "/"; + } + + /** + * @param $pathInArchive + * @return $this + * @throws \Thelia\Exception\FileNotFoundException + * @throws \ErrorException + * + * This method deletes a file in the archive + */ + public function deleteFile($pathInArchive) + { + $pathInArchive = $this->formatFilePath($pathInArchive); + + if (!$this->hasFile($pathInArchive)) { + $this->throwFileNotFound($pathInArchive); + } + + $deleted = $this->zip->deleteName($pathInArchive); + + if (!$deleted) { + throw new \ErrorException( + $this->translator->trans( + "The file %file has not been deleted", + [ + "%file" => $pathInArchive, + ] + ) + ); + } + + return $this; + } + + /** + * @return \Thelia\Core\HttpFoundation\Response + * + * This method return an instance of a Response with the archive as content. + */ + public function buildArchiveResponse($filename) + { + $this->zip->comment = "Generated by Thelia v" . Thelia::THELIA_VERSION; + + $this->commit(); + + if (!file_exists($this->cacheFile)) { + $this->throwFileNotFound($this->cacheFile); + } + + if (!is_readable($this->cacheFile)) { + throw new FileNotReadableException( + $this->translator->trans( + "The cache file %file is not readable", + [ + "%file" => $this->cacheFile + ] + ) + ); + } + + $content = file_get_contents($this->cacheFile); + + $this->zip->close(); + + return new Response( + $content, + 200, + [ + "Content-Type" => $this->getMimeType(), + "Content-Disposition" => "attachment; filename=\"". $filename . "." . $this->getExtension() ."\"", + ] + ); + } + + /** + * @param string $pathToArchive + * @param bool $isOnline + * @param FileDownloaderInterface $fileDownloader + * @return ZipArchiveBuilder + * @throws \Thelia\Exception\FileNotFoundException + * @throws \Thelia\Exception\HttpUrlException + * + * Loads an archive + */ + public function loadArchive($pathToArchive, $isOnline = false) + { + $back = $this->zip; + $this->zip = new \ZipArchive(); + $zip = clone $this; + $this->zip = $back; + + $zip->setEnvironment($this->environment); + + $zip->copyFile( + $pathToArchive, + $zip->getCacheFile(), + $isOnline + ); + + if (true !== $return = $zip->getRawZipArchive()->open($zip->getCacheFile())) { + throw new ZipArchiveException( + $zip->getZipErrorMessage($return) + ); + } + + return $zip; + } + + /** + * @param $pathToFile + * @return bool + * + * Checks if the archive has a file + */ + public function hasFile($pathToFile) + { + return $this->zip + ->locateName($this->formatFilePath($pathToFile)) !== false + ; + } + + /** + * @param string $directory + * @return bool + * + * Checks if the link $directory exists and if it's not a file. + */ + public function hasDirectory($directory) + { + $link = $this->zip->locateName($this->formatDirectoryPath($directory)); + + return $link !== false; + } + + /** + * @param string $environment + * @return $this + * + * Sets the execution environment of the Kernel, + * used to know which cache is used. + */ + public function setEnvironment($environment) + { + parent::setEnvironment($environment); + + $cacheFile = $this->generateCacheFile($environment); + + if (file_exists($cacheFile)) { + unlink($cacheFile); + } + + $opening = $this->zip->open( + $cacheFile, + \ZipArchive::CREATE + ); + + if ($opening !== true) { + throw new \ErrorException( + $this->translator->trans( + "An unknown error append" + ) + ); + } + + $this->cacheFile = $cacheFile; + + return $this; + } + + /** + * @param $errorCode + * @return string + * + * Give the error message of a \ZipArchive error code + */ + public function getZipErrorMessage($errorCode) + { + switch ($errorCode) { + case \ZipArchive::ER_EXISTS: + $message = "The archive already exists"; + break; + + case \ZipArchive::ER_INCONS: + $message = "The archive is inconsistent"; + break; + + case \ZipArchive::ER_INVAL: + $message = "Invalid argument"; + break; + + case \ZipArchive::ER_MEMORY: + $message = "Memory error"; + break; + + case \ZipArchive::ER_NOENT: + $message = "The file doesn't exist"; + break; + + case \ZipArchive::ER_NOZIP: + $message = "The file is not a zip archive"; + break; + + case \ZipArchive::ER_OPEN: + $message = "The file could not be open"; + break; + + case \ZipArchive::ER_READ: + $message = "The file could not be read"; + break; + + case \ZipArchive::ER_SEEK: + $message = "Position error"; + break; + + default: + $message = "Unknown error on the ZIP archive"; + break; + } + + $zipMessageHead = $this->translator->trans( + "Zip Error" + ); + + $message = $this->translator->trans( + "[%zip_head] " . $message, + [ + "%zip_head" => $zipMessageHead + ] + ); + + return $message; + } + + public function commit() + { + $this->zip->close(); + $result = $this->zip->open($this->getCacheFile()); + + if ($result !== true) { + throw new \ErrorException( + $this->translator->trans( + "The changes could on the Zip Archive not be commited" + ) + ); + } + + return $this; + } + + /** + * @param string $initialString + * @return string + * + * Gives a valid file path for \ZipArchive + */ + public function formatFilePath($initialString) + { + /** + * Remove the / at the beginning and the end. + */ + $initialString = trim($initialString, "/"); + + /** + * Remove the double, triple, ... slashes + */ + $initialString = preg_replace("#\/{2,}#", "/", $initialString); + + if (preg_match("#\/?[^\/]+\/[^/]+\/?#", $initialString)) { + $initialString = "/" . $initialString; + } + + return $initialString; + } + + /** + * @param string $initialString + * @return string + * + * Gives a valid directory path for \ZipArchive + */ + public function formatDirectoryPath($initialString) + { + $initialString = $this->formatFilePath($initialString); + + if ($initialString !== "" && $initialString[0] !== "/") { + $initialString = "/" . $initialString; + } + + return $initialString . "/"; + } + + /** + * @return string + * + * This method must return a string, the name of the format. + * + * example: + * return "XML"; + */ + public function getName() + { + return "ZIP"; + } + + /** + * @return string + * + * This method must return a string, the extension of the file format, without the ".". + * The string should be lowercase. + * + * example: + * return "xml"; + */ + public function getExtension() + { + return "zip"; + } + + /** + * @return string + * + * This method must return a string, the mime type of the file format. + * + * example: + * return "application/json"; + */ + public function getMimeType() + { + return "application/zip"; + } + + /** + * @return \ZipArchive + */ + public function getRawZipArchive() + { + return $this->zip; + } +} diff --git a/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilderInterface.php b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilderInterface.php new file mode 100644 index 000000000..0ff882ae5 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilderInterface.php @@ -0,0 +1,115 @@ + + * + * This interface defines the methods that an archive builder must have. + */ +interface ArchiveBuilderInterface +{ + /** + * @param string $filePath It is the path to access the file. + * @param string $directoryInArchive This is the directory where it will be stored in the archive + * @param null|string $name The name of the file in the archive. if it null or empty, it keeps the same name + * @param bool $isOnline + * @return $this + * @throws \Thelia\Exception\FileNotFoundException + * @throws \Thelia\Exception\FileNotReadableException + * @throws \ErrorException + * + * This methods adds a file in the archive. + * If the file is local, $isOnline must be false, + * If the file online, $filePath must be an URL. + */ + public function addFile($filePath, $directoryInArchive = "/", $name = null, $isOnline = false); + + /** + * @param $content + * @param $name + * @param string $directoryInArchive + * @return mixed + * @throws \ErrorException + * + * This method creates a file in the archive with its content + */ + public function addFileFromString($content, $name, $directoryInArchive = "/"); + + /** + * @param string $pathToFile + * @return null|string + * @throws \Thelia\Exception\FileNotFoundException + * @throws \Thelia\Exception\FileNotReadableException + * @throws \ErrorException + * + * This method returns a file content + */ + public function getFileContent($pathToFile); + /** + * @param $pathInArchive + * @return $this + * @throws \Thelia\Exception\FileNotFoundException + * @throws \ErrorException + * + * This method deletes a file in the archive + */ + public function deleteFile($pathInArchive); + + /** + * @param $directoryPath + * @return $this + * @throws \ErrorException + * + * This method creates an empty directory + */ + public function addDirectory($directoryPath); + + /** + * @params string $filename + * @return \Thelia\Core\HttpFoundation\Response + * + * This method return an instance of a Response with the archive as content. + */ + public function buildArchiveResponse($filename); + + /** + * @param string $pathToArchive + * @param bool $isOnline + * @return $this + * @throws \Thelia\Exception\FileNotFoundException + * @throws \Thelia\Exception\HttpUrlException + * + * Loads an archive + */ + public function loadArchive($pathToArchive, $isOnline = false); + + /** + * @param $pathToFile + * @return bool + * + * Checks if the archive has a file + */ + public function hasFile($pathToFile); + + /** + * @param string $directory + * @return bool + * + * Check if the archive has a directory + */ + public function hasDirectory($directory); + +} diff --git a/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilderManager.php b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilderManager.php new file mode 100644 index 000000000..176531670 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilderManager.php @@ -0,0 +1,155 @@ + + */ +class ArchiveBuilderManager +{ + /** @var array */ + protected $archiveBuilders = array(); + + protected $environment; + + public function __construct($environment) + { + $this->environment = $environment; + } + /** + * @param AbstractArchiveBuilder $archiveBuilder + * @return $this + */ + public function add(AbstractArchiveBuilder $archiveBuilder) + { + if (null !== $archiveBuilder) { + $archiveBuilder->setEnvironment($this->environment); + + $this->archiveBuilders[$archiveBuilder->getName()] = $archiveBuilder; + } + + return $this; + } + + /** + * @param $name + * @return $this + * @throws \OutOfBoundsException + */ + public function delete($name) + { + if (!array_key_exists($name, $this->archiveBuilders)) { + $this->throwOutOfBounds($name); + } + + unset($this->archiveBuilders[$name]); + + return $this; + } + + /** + * @return array + */ + public function getAll() + { + return $this->archiveBuilders; + } + + /** + * @return array + */ + public function getNames() + { + $names = []; + + /** @var AbstractArchiveBuilder $builder */ + foreach ($this->archiveBuilders as $builder) { + $names[] = $builder->getName(); + } + + return $names; + } + + public function get($name) + { + if (!array_key_exists($name, $this->archiveBuilders)) { + $this->throwOutOfBounds($name); + } + + return $this->archiveBuilders[$name]; + } + + protected function throwOutOfBounds($name) + { + throw new \OutOfBoundsException( + Translator::getInstance()->trans( + "The archive builder \"%name\" doesn't exist", + [ + "%name" => $name + ] + ) + ); + } + + /** + * @return array + * + * Return the extensions handled by archive builders + */ + public function getExtensions($withDot = false) + { + $extensions = []; + + /** @var AbstractArchiveBuilder $archiveBuilder */ + foreach ($this->archiveBuilders as $archiveBuilder) { + $extensionName = $withDot ? ".": ""; + $extensionName .= $archiveBuilder->getExtension(); + $extensions[$archiveBuilder->getName()] = $extensionName; + } + + return $extensions; + } + + /** + * @param $extension + * @return bool|AbstractArchiveBuilder + */ + public function getArchiveBuilderByExtension($extension) + { + $extensions = $this->getExtensions(); + + if (!in_array($extension, $extensions)) { + return false; + } else { + $flip = array_flip($extensions); + $archiveBuilderName = $flip[$extension]; + + return $this->archiveBuilders[$archiveBuilderName]; + } + } + + public function getMimeTypes() + { + $mimeTypes = []; + + /** @var AbstractArchiveBuilder $formatter */ + foreach ($this->archiveBuilders as $formatter) { + $mimeTypes[$formatter->getName()] = $formatter->getMimeType(); + } + + return $mimeTypes; + } +} diff --git a/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilderManagerTrait.php b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilderManagerTrait.php new file mode 100644 index 000000000..24c365203 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Archive/ArchiveBuilderManagerTrait.php @@ -0,0 +1,31 @@ + + */ +trait ArchiveBuilderManagerTrait +{ + /** + * @param ContainerInterface $container + * @return \Thelia\Core\FileFormat\Archive\ArchiveBuilderManager + */ + public function getArchiveBuilderManager(ContainerInterface $container) + { + return $container->get("thelia.manager.archive_builder_manager"); + } +} diff --git a/core/lib/Thelia/Core/FileFormat/FormatInterface.php b/core/lib/Thelia/Core/FileFormat/FormatInterface.php new file mode 100644 index 000000000..4b327271d --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/FormatInterface.php @@ -0,0 +1,58 @@ + + * + * This interface defines what a formatter must have: + * - A name ( example: XML, JSON, yaml ) + * - An extension ( example: xml, json, yml ) + * - A mime type ( example: application/xml, application/json, ... ) + */ +interface FormatInterface +{ + + /** + * @return string + * + * This method must return a string, the name of the format. + * + * example: + * return "XML"; + */ + public function getName(); + + /** + * @return string + * + * This method must return a string, the extension of the file format, without the ".". + * The string should be lowercase. + * + * example: + * return "xml"; + */ + public function getExtension(); + + /** + * @return string + * + * This method must return a string, the mime type of the file format. + * + * example: + * return "application/json"; + */ + public function getMimeType(); +} diff --git a/core/lib/Thelia/Core/FileFormat/FormatType.php b/core/lib/Thelia/Core/FileFormat/FormatType.php new file mode 100644 index 000000000..37b3988ce --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/FormatType.php @@ -0,0 +1,33 @@ + + */ +class FormatType +{ + /** + * This type is for unbounded formats, in general serialization formats + * example: XML, json, yaml + */ + const UNBOUNDED = "export.unbounded"; + + /** + * This type is for tabled format ( matrix ), most used by spreadsheet application. + * example: CSV, ODS, XLS + */ + const TABLE = "export.table"; +} diff --git a/core/lib/Thelia/Core/FileFormat/Formatting/AbstractFormatter.php b/core/lib/Thelia/Core/FileFormat/Formatting/AbstractFormatter.php new file mode 100644 index 000000000..f8c9993a6 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Formatting/AbstractFormatter.php @@ -0,0 +1,70 @@ + + */ +abstract class AbstractFormatter implements FormatInterface, FormatterInterface +{ + const FILENAME = "data"; + + /** @var \Thelia\Core\Translation\Translator */ + protected $translator; + + /** @var \Thelia\Log\Tlog */ + protected $logger; + + /** @var array */ + protected $order = array(); + + public function __construct() + { + $this->translator = Translator::getInstance(); + + $this->logger = Tlog::getInstance(); + } + + public function getOrder() + { + return $this->order; + } + + public function setOrder(array $order) + { + $this->order = $order; + + return $this; + } + + public function checkOrders(array $values) + { + foreach ($this->getOrder() as $order) { + if (!array_key_exists($order, $values)) { + throw new \ErrorException( + $this->translator->trans( + "The column %column that you want to sort doesn't exist", + [ + "%column" => $order + ] + ) + ); + } + } + } +} diff --git a/core/lib/Thelia/Core/FileFormat/Formatting/Exception/BadFormattedStringException.php b/core/lib/Thelia/Core/FileFormat/Formatting/Exception/BadFormattedStringException.php new file mode 100644 index 000000000..0935ed07c --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Formatting/Exception/BadFormattedStringException.php @@ -0,0 +1,23 @@ + + */ +class BadFormattedStringException extends \ErrorException +{ + +} diff --git a/core/lib/Thelia/Core/FileFormat/Formatting/Formatter/CSVFormatter.php b/core/lib/Thelia/Core/FileFormat/Formatting/Formatter/CSVFormatter.php new file mode 100644 index 000000000..654db35f7 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Formatting/Formatter/CSVFormatter.php @@ -0,0 +1,206 @@ + + */ +class CSVFormatter extends AbstractFormatter +{ + public $delimiter = ";"; + public $lineReturn = "\n"; + public $stringDelimiter = "\""; + + /** + * @return string + * + * This method must return a string, the name of the format. + * + * example: + * return "XML"; + */ + public function getName() + { + return "CSV"; + } + + /** + * @return string + * + * This method must return a string, the extension of the file format, without the ".". + * The string should be lowercase. + * + * example: + * return "xml"; + */ + public function getExtension() + { + return "csv"; + } + + /** + * @return string + * + * This method must return a string, the mime type of the file format. + * + * example: + * return "application/json"; + */ + public function getMimeType() + { + return "text/csv"; + } + + /** + * @param FormatterData $data + * @return mixed + * + * This method must use a FormatterData object and output + * a formatted value. + */ + public function encode(FormatterData $data) + { + $string = ""; + + /** + * Get the first row and delimiters lengths + */ + $firstRow = $data->getRow(); + $delimiterLength = strlen($this->delimiter); + $lineReturnLength = strlen($this->lineReturn); + + if ($firstRow === false) { + return ""; + } + + /** + * check if $this->order doesn't have non-existing rows + */ + $this->checkOrders($firstRow); + + $rawKeys = array_keys($firstRow); + $keys = []; + + foreach ($rawKeys as $key) { + $keys[$key] = $key; + } + + $values = $data->getData(); + array_unshift($values, $keys); + + while (null !== $row = array_shift($values)) { + /** + * First put the sorted ones + */ + foreach ($this->order as $order) { + $string .= $this->formatField($row[$order]); + unset($row[$order]); + } + + /** + * Then place the fields, + * order by name + */ + ksort($row); + + foreach ($keys as $key) { + if (array_key_exists($key, $row)) { + $string .= $this->formatField($row[$key]); + } + } + + $string = substr($string,0, -$delimiterLength) . $this->lineReturn; + } + + return substr($string, 0, -$lineReturnLength); + } + + protected function formatField($value) + { + if ($value === null) { + $value = ""; + } elseif (!is_scalar($value)) { + $value = serialize($value); + } + + $value = str_replace($this->stringDelimiter, "\\" . $this->stringDelimiter, $value); + + return $this->stringDelimiter . $value . $this->stringDelimiter . $this->delimiter; + } + + /** + * @param $rawData + * @return FormatterData + * + * This must takes raw data as argument and outputs + * a FormatterData object. + */ + public function decode($rawData) + { + $raw = explode($this->lineReturn, $rawData); + $decoded = []; + + if (count($raw) > 0) { + $keys = explode($this->delimiter, array_shift($raw)); + $keysLength = count($keys); + + foreach ($keys as &$key) { + $key = trim($key, $this->stringDelimiter); + } + + $columns = count ($keys); + + while (null !== $row = array_shift($raw)) { + $newRow = []; + $row = explode($this->delimiter, $row); + + if (count($row) >= $keysLength) { + for ($i = 0; $i < $columns; ++$i) { + $value = trim($row[$i], $this->stringDelimiter); + + if (false !== $unserialized = @unserialize($row[$i])) { + $value = $unserialized; + } + + $newRow[$keys[$i]] = $value; + } + + $decoded[] = $newRow; + } + } + } + + return (new FormatterData())->setData($decoded); + } + + /** + * @return string + * + * return a string that defines the handled format type. + * + * Thelia types are defined in \Thelia\Core\FileFormat\FormatType + * + * examples: + * return FormatType::TABLE; + * return FormatType::UNBOUNDED; + */ + public function getHandledType() + { + return FormatType::TABLE; + } +} diff --git a/core/lib/Thelia/Core/FileFormat/Formatting/Formatter/JsonFormatter.php b/core/lib/Thelia/Core/FileFormat/Formatting/Formatter/JsonFormatter.php new file mode 100644 index 000000000..2744fb60b --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Formatting/Formatter/JsonFormatter.php @@ -0,0 +1,95 @@ + + */ +class JsonFormatter extends AbstractFormatter +{ + /** + * @return string + * + * This method must return a string, the name of the format. + * + * example: + * return "XML"; + */ + public function getName() + { + return "Json"; + } + + /** + * @return string + * + * This method must return a string, the extension of the file format, without the ".". + * The string should be lowercase. + * + * example: + * return "xml"; + */ + public function getExtension() + { + return "json"; + } + + /** + * @return string + * + * This method must return a string, the mime type of the file format. + * + * example: + * return "application/json"; + */ + public function getMimeType() + { + return "application/json"; + } + + /** + * @param FormatterData $data + * @return mixed + * + * This method must use a FormatterData object and output + * a formatted value. + */ + public function encode(FormatterData $data) + { + return json_encode($data->getData()); + } + + /** + * @param $rawData + * @return FormatterData + * + * This must takes raw data as argument and outputs + * a FormatterData object. + */ + public function decode($rawData) + { + return (new FormatterData())->setData( + json_decode($rawData, true) + ); + } + + public function getHandledType() + { + return FormatType::UNBOUNDED; + } +} diff --git a/core/lib/Thelia/Core/FileFormat/Formatting/Formatter/XMLFormatter.php b/core/lib/Thelia/Core/FileFormat/Formatting/Formatter/XMLFormatter.php new file mode 100644 index 000000000..8d8945d94 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Formatting/Formatter/XMLFormatter.php @@ -0,0 +1,239 @@ + + */ +class XMLFormatter extends AbstractFormatter +{ + public $root = "data"; + public $rowName = "row"; + public $nodeName = "entry"; + + /** + * @return string + * + * This method must return a string, the name of the format. + * + * example: + * return "XML"; + */ + public function getName() + { + return "XML"; + } + + /** + * @return string + * + * This method must return a string, the extension of the file format, without the ".". + * The string should be lowercase. + * + * example: + * return "xml"; + */ + public function getExtension() + { + return "xml"; + } + + /** + * @return string + * + * This method must return a string, the mime type of the file format. + * + * example: + * return "application/json"; + */ + public function getMimeType() + { + return "application/xml"; + } + + /** + * @param FormatterData $data + * @return mixed + * + * This method must use a FormatterData object and output + * a formatted value. + */ + public function encode(FormatterData $data) + { + $arrayData = $data->getData(); + + $domDocument = new \DOMDocument("1.0"); + $container = $domDocument->appendChild(new \DOMElement($this->root)); + + foreach ($arrayData as $key=>$entry) { + if (is_array($entry)) { + $node = $container->appendChild(new \DOMElement($this->rowName)); + $this->recursiveBuild($entry, $node); + } else { + $node = new \DOMElement($this->nodeName); + $container->appendChild($node); + + /** @var \DOMElement $lastChild */ + $lastChild = $container->lastChild; + $lastChild->setAttribute("name",$key); + $lastChild->setAttribute("value", $entry); + } + } + + $domDocument->preserveWhiteSpace = false; + $domDocument->formatOutput = true; + + return $domDocument->saveXML(); + } + + protected function recursiveBuild(array $data, \DOMNode $node) + { + foreach ($data as $key=>$entry) { + if (is_array($entry)) { + $newNode = $node->appendChild(new \DOMElement($key)); + $this->recursiveBuild($entry, $newNode); + } else { + $inputNode = new \DOMElement($this->nodeName); + $node->appendChild($inputNode); + + /** @var \DOMElement $lastChild */ + $lastChild = $node->lastChild; + $lastChild->setAttribute("name",$key); + $lastChild->setAttribute("value", $entry); + } + } + } + + /** + * @param $rawData + * @return FormatterData + * + * This must takes raw data as argument and outputs + * a FormatterData object. + */ + public function decode($rawData) + { + $raw = $this->rawDecode($rawData); + + return (new FormatterData())->setData($this->recursiveDecode($raw)); + } + + public function recursiveDecode(array &$data, array &$parent = null) + { + $row = []; + + foreach ($data as $name => &$child) { + if (is_array($child)) { + $data = $this->recursiveDecode($child, $data); + } + + if ($name === "name" || $name === "value") { + $row[$name] = $this->getValue($name, $data); + } + + if (count($row) == 2) { + reset($parent); + + if (is_int($key = key($parent))) { + $parent[$row["name"]] = $row["value"]; + unset($parent[$key]); + } else { + $data[$row["name"]] = $row["value"]; + } + + $row=[]; + } + } + + return $parent === null ? $data : $parent; + } + + public function getValue($name, array &$data) + { + $value = $data[$name]; + unset ($data[$name]); + + return $value; + } + + /** + * @param $rawData + * @return array + * @throws \Thelia\Core\FileFormat\Formatting\Exception\BadFormattedStringException + */ + public function rawDecode($rawData) + { + try { + $xml = new SimpleXMLElement($rawData); + } catch (\Exception $e) { + $errorMessage = $this->translator->trans( + "You tried to load a bad formatted XML" + ); + + $this->logger->error( + $errorMessage .": ". $e->getMessage() + ); + + throw new BadFormattedStringException( + $errorMessage + ); + } + + $array = []; + + foreach ($xml->children() as $child) { + $this->recursiveRawDecode($array, $child); + } + + return $array; + } + + protected function recursiveRawDecode(array &$data, \SimpleXMLElement $node) + { + if ($node->count()) { + if (!array_key_exists($node->getName(), $data)) { + $data[$node->getName()] = []; + } + $row = &$data[$node->getName()]; + + foreach ($node->children() as $child) { + $this->recursiveRawDecode($row, $child); + } + } else { + $newRow = array(); + + /** @var SimpleXMLElement $attribute */ + foreach ($node->attributes() as $attribute) { + $newRow[$attribute->getName()] = $node->getAttributeAsPhp($attribute->getName()); + } + + if ($node->getName() === $this->nodeName) { + $data[] = $newRow; + } else { + $data[$node->getName()] = $newRow; + } + } + } + + public function getHandledType() + { + return FormatType::UNBOUNDED; + } +} diff --git a/core/lib/Thelia/Core/FileFormat/Formatting/FormatterData.php b/core/lib/Thelia/Core/FileFormat/Formatting/FormatterData.php new file mode 100644 index 000000000..cef6547c9 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Formatting/FormatterData.php @@ -0,0 +1,240 @@ + + */ +class FormatterData +{ + protected $lang; + + /** @var array */ + protected $data = array(); + + /** @var null|array */ + protected $aliases; + + /** @var Translator */ + protected $translator; + + /** + * @param array $aliases + * + * $aliases is a associative array where the key represents propel TYPE_PHP_NAME of column if you use + * loadModelCriteria, or your own aliases for setData, and the value + * is the alias. It can be null or empty if you don't want aliases, + * but remember to always define all the fields the you want: + * non aliases fields will be ignored. + */ + public function __construct(array $aliases = null) + { + $this->translator = Translator::getInstance(); + + if (!is_array($aliases)) { + $aliases = []; + } + + /** + * Lower all the values + */ + foreach ($aliases as $key => $value) { + $lowerKey = strtolower($key); + $lowerValue = strtolower($value); + if ($lowerKey !== $key) { + $aliases[$lowerKey] = $lowerValue; + unset($aliases[$key]); + } else { + $aliases[$key] = $lowerValue; + } + } + + $this->aliases = $aliases; + } + + /** + * @param array $data + * @return $this + * + * Sets raw data with aliases + * may bug with some formatter + */ + public function setData(array $data) + { + $this->data = $this->applyAliases($data, $this->aliases); + + return $this; + } + + /** + * @param ModelCriteria $criteria + * @return $this|null + * + * Loads a model criteria. + * Warning: This doesn't goodly support multi table queries. + * If you need to use more than one table, use a PDO instance and + * use the fetchArray() method, or select every columns you need + */ + public function loadModelCriteria(ModelCriteria $criteria) + { + $propelData = $criteria->find(); + + if (empty($propelData)) { + return null; + } + + $asColumns = $propelData->getFormatter()->getAsColumns(); + + /** + * Format it correctly + * After this pass, we MUST have a 2D array. + * The first may be keyed with integers. + */ + $formattedResult = $propelData + ->toArray(null, false, TableMap::TYPE_COLNAME); + + if (count($asColumns) > 1) { + /** + * Request with multiple select + * Apply propel aliases + */ + $formattedResult = $this->applyAliases($formattedResult, $asColumns); + } elseif (count($asColumns) === 1) { + /** + * Request with one select + */ + $key = str_replace("\"", "", array_keys($asColumns)[0]); + $formattedResult = [[$key => $formattedResult[0]]]; + } + + $data = $this->applyAliases($formattedResult, $this->aliases); + + /** + * Then store it + */ + $this->data = $data; + + return $this; + } + + /** + * @param array $data + * @param array $aliases + */ + public function applyAliases(array $data, array $aliases) + { + $formattedData = []; + + foreach ($data as $key=>$entry) { + $key = strtolower($key); + + if (is_array($entry)) { + $formattedData[$key] = $this->applyAliases($entry, $aliases); + } else { + $alias = isset($aliases[$key]) ? $aliases[$key] : $key; + $formattedData[$alias] = $entry; + } + } + + return $formattedData; + } + + /** + * @param array $row + * @return $this + */ + public function addRow(array $row) + { + $this->data += [$this->applyAliases($row, $this->aliases)]; + + return $this; + } + + /** + * @param int $index + * @return array|bool + */ + public function popRow() + { + $row = array_pop($this->data); + + return $row; + } + + /** + * @param int $index + * @return array|bool + * @throws \OutOfBoundsException + */ + public function getRow($index = 0, $reverseAliases = false) + { + if (empty($this->data)) { + return false; + } elseif (!isset($this->data[$index])) { + throw new \OutOfBoundsException( + $this->translator->trans( + "Bad index value %idx", + [ + "%idx" => $index + ] + ) + ); + } + + $row = $this->data[$index]; + + if ($reverseAliases === true) { + $row = $this->reverseAliases($row, $this->aliases); + } + + return $row; + } + + /** + * @param array $data + * @param array $aliases + * @return array + */ + protected function reverseAliases(array $data, array $aliases) + { + return $this->applyAliases($data, array_flip($aliases)); + } + + public function getData() + { + return $this->data; + } + + public function getDataReverseAliases() + { + return $this->reverseAliases($this->data, $this->aliases); + } + + public function setLang(Lang $lang = null) + { + $this->lang = $lang; + + return $this; + } + + public function getLang() + { + return $this->lang; + } +} diff --git a/core/lib/Thelia/Core/FileFormat/Formatting/FormatterInterface.php b/core/lib/Thelia/Core/FileFormat/Formatting/FormatterInterface.php new file mode 100644 index 000000000..93f018873 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Formatting/FormatterInterface.php @@ -0,0 +1,52 @@ + + */ +interface FormatterInterface +{ + /** + * @param FormatterData $data + * @return mixed + * + * This method must use a FormatterData object and output + * a formatted value. + */ + public function encode(FormatterData $data); + + /** + * @param $rawData + * @return FormatterData + * + * This must takes raw data as argument and outputs + * a FormatterData object. + */ + public function decode($rawData); + + /** + * @return string + * + * return a string that defines the handled format type. + * + * Thelia types are defined in \Thelia\Core\FileFormat\FormatType + * + * examples: + * return FormatType::TABLE; + * return FormatType::UNBOUNDED; + */ + public function getHandledType(); +} diff --git a/core/lib/Thelia/Core/FileFormat/Formatting/FormatterManager.php b/core/lib/Thelia/Core/FileFormat/Formatting/FormatterManager.php new file mode 100644 index 000000000..c2984e746 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Formatting/FormatterManager.php @@ -0,0 +1,193 @@ + + */ +class FormatterManager +{ + + protected $formatters = array(); + + /** + * @param $archiveCreator + * @return $this + */ + public function add(AbstractFormatter $formatter) + { + if (null !== $formatter) { + $this->formatters[$formatter->getName()] = $formatter; + } + + return $this; + } + + /** + * @param $name + * @return $this + * @throws \OutOfBoundsException + */ + public function delete($name) + { + if (!array_key_exists($name, $this->formatters)) { + $this->throwOutOfBounds($name); + } + + unset($this->formatters[$name]); + + return $this; + } + + public function get($name) + { + if (!array_key_exists($name, $this->formatters)) { + $this->throwOutOfBounds($name); + } + + return $this->formatters[$name]; + } + + /** + * @return array[AbstractFormatter] + */ + public function getAll() + { + return $this->formatters; + } + + /** + * @return array + */ + public function getNames() + { + $names = []; + + /** @var AbstractFormatter $formatter */ + foreach ($this->formatters as $formatter) { + $names[] = $formatter->getName(); + } + + return $names; + } + + /** + * @param $name + * @throws \OutOfBoundsException + */ + protected function throwOutOfBounds($name) + { + throw new \OutOfBoundsException( + Translator::getInstance()->trans( + "The formatter \"%name\" doesn't exist", + [ + "%name" => $name + ] + ) + ); + } + + /** + * @return array + * + * Return the extensions handled by archive builders + */ + public function getExtensions($withDot = false) + { + $extensions = []; + + /** @var AbstractFormatter $formatter */ + foreach ($this->formatters as $formatter) { + $extensionName = $withDot ? ".": ""; + $extensionName .= $formatter->getExtension(); + $extensions[$formatter->getName()] = $extensionName; + } + + return $extensions; + } + + public function getExtensionsByTypes($types, $withDot = false) + { + $extensions = []; + + /** @var AbstractFormatter $formatter */ + foreach ($this->getFormattersByTypes($types) as $formatter) { + $extensionName = $withDot ? ".": ""; + $extensionName .= $formatter->getExtension(); + $extensions[$formatter->getName()] = $extensionName; + } + + return $extensions; + } + + /** + * @param $extension + * @return bool|AbstractFormatter + */ + public function getFormatterByExtension($extension) + { + if ($extension[0] === ".") { + $extension = substr($extension, 1); + } + + $extensions = $this->getExtensions(); + + if (!in_array($extension, $extensions)) { + return false; + } else { + $flip = array_flip($extensions); + $formatterName = $flip[$extension]; + + return $this->formatters[$formatterName]; + } + } + + public function getFormattersByTypes($types) + { + if (!is_array($types)) { + $types = [$types]; + } + + $selectedFormatters = []; + + /** @var AbstractFormatter $formatter */ + foreach ($this->formatters as $formatter) { + $handledType = $formatter->getHandledType(); + + if (in_array($handledType, $types)) { + $selectedFormatters[$formatter->getName()] = $formatter; + } + } + + return $selectedFormatters; + } + + public function getMimeTypesByTypes($types) + { + if (!is_array($types)) { + $types = [$types]; + } + + $mimeTypes = []; + + /** @var AbstractFormatter $formatter */ + foreach ($this->getFormattersByTypes($types) as $formatter) { + $mimeTypes[$formatter->getName()] = $formatter->getMimeType(); + } + + return $mimeTypes; + } +} diff --git a/core/lib/Thelia/Core/FileFormat/Formatting/FormatterManagerTrait.php b/core/lib/Thelia/Core/FileFormat/Formatting/FormatterManagerTrait.php new file mode 100644 index 000000000..a02e1b400 --- /dev/null +++ b/core/lib/Thelia/Core/FileFormat/Formatting/FormatterManagerTrait.php @@ -0,0 +1,31 @@ + + */ +trait FormatterManagerTrait +{ + /** + * @param ContainerInterface $container + * @return \Thelia\Core\FileFormat\Formatting\FormatterManager + */ + public function getFormatterManager(ContainerInterface $container) + { + return $container->get("thelia.manager.formatter_manager"); + } +} diff --git a/core/lib/Thelia/Core/Security/Resource/AdminResources.php b/core/lib/Thelia/Core/Security/Resource/AdminResources.php index 2ddea9877..532e8e5bc 100644 --- a/core/lib/Thelia/Core/Security/Resource/AdminResources.php +++ b/core/lib/Thelia/Core/Security/Resource/AdminResources.php @@ -105,7 +105,7 @@ final class AdminResources const EXPORT = "admin.export"; - const EXPORT_CUSTOMER_NEWSLETTER = "admin.export.customer.newsletter"; + const IMPORT = "admin.import"; const TOOLS = "admin.tools"; } diff --git a/core/lib/Thelia/Core/Template/Loop/ArchiveBuilder.php b/core/lib/Thelia/Core/Template/Loop/ArchiveBuilder.php new file mode 100644 index 000000000..b21eff052 --- /dev/null +++ b/core/lib/Thelia/Core/Template/Loop/ArchiveBuilder.php @@ -0,0 +1,132 @@ + + */ +class ArchiveBuilder extends BaseLoop implements ArraySearchLoopInterface +{ + /** + * this method returns an array + * + * @return array + */ + public function buildArray() + { + /** @var \Thelia\Core\FileFormat\Archive\archiveBuilderManager $service */ + $service = $this->container->get("thelia.manager.archive_builder_manager"); + + $rawArchiveBuilders = array_change_key_case($service->getAll()); + + $allowedArchiveBuilder = $this->getAllowed_archive_builder(); + $archiveBuilders = []; + + if ($allowedArchiveBuilder !== null) { + $allowedArchiveBuilder = explode(",", $allowedArchiveBuilder); + + foreach ($allowedArchiveBuilder as $archiveBuilder) { + $archiveBuilder = trim(strtolower($archiveBuilder)); + + if (isset($rawArchiveBuilders[$archiveBuilder])) { + $archiveBuilders[$archiveBuilder] = $rawArchiveBuilders[$archiveBuilder]; + } + } + } else { + $archiveBuilders = $rawArchiveBuilders; + } + + switch ($this->getOrder()) { + case "alpha": + ksort($archiveBuilders); + break; + case "alpha_reverse": + krsort($archiveBuilders); + break; + } + + return $archiveBuilders; + } + + /** + * @param LoopResult $loopResult + * + * @return LoopResult + */ + public function parseResults(LoopResult $loopResult) + { + /** @var \Thelia\Core\FileFormat\Archive\AbstractarchiveBuilder $archiveBuilder */ + foreach ($loopResult->getResultDataCollection() as $archiveBuilder) { + $loopResultRow = new LoopResultRow(); + + $loopResultRow + ->set("NAME", $archiveBuilder->getName()) + ->set("EXTENSION", $archiveBuilder->getExtension()) + ->set("MIME_TYPE", $archiveBuilder->getMimeType()) + ; + + $loopResult->addRow($loopResultRow); + + } + + return $loopResult; + } + + /** + * Definition of loop arguments + * + * example : + * + * public function getArgDefinitions() + * { + * return new ArgumentCollection( + * + * Argument::createIntListTypeArgument('id'), + * new Argument( + * 'ref', + * new TypeCollection( + * new Type\AlphaNumStringListType() + * ) + * ), + * Argument::createIntListTypeArgument('category'), + * Argument::createBooleanTypeArgument('new'), + * ... + * ); + * } + * + * @return \Thelia\Core\Template\Loop\Argument\ArgumentCollection + */ + protected function getArgDefinitions() + { + return new ArgumentCollection( + Argument::createAnyTypeArgument("allowed_archive_builder"), + new Argument( + "order", + new TypeCollection( + new EnumType(["alpha", "alpha_reverse"]) + ), + "alpha" + ) + ); + } +} diff --git a/core/lib/Thelia/Core/Template/Loop/Export.php b/core/lib/Thelia/Core/Template/Loop/Export.php new file mode 100644 index 000000000..30660c2da --- /dev/null +++ b/core/lib/Thelia/Core/Template/Loop/Export.php @@ -0,0 +1,37 @@ + + */ +class Export extends ImportExportType +{ + protected function getBaseUrl() + { + return $this->container->getParameter("export.base_url"); + } + + protected function getQueryModel() + { + return ExportQuery::create(); + } + + protected function getCategoryName() + { + return "ExportCategoryId"; + } +} diff --git a/core/lib/Thelia/Core/Template/Loop/ExportCategory.php b/core/lib/Thelia/Core/Template/Loop/ExportCategory.php new file mode 100644 index 000000000..997e8edb5 --- /dev/null +++ b/core/lib/Thelia/Core/Template/Loop/ExportCategory.php @@ -0,0 +1,28 @@ + + */ +class ExportCategory extends ImportExportCategory +{ + protected function getQueryModel() + { + return ExportCategoryQuery::create(); + } + +} diff --git a/core/lib/Thelia/Core/Template/Loop/Formatter.php b/core/lib/Thelia/Core/Template/Loop/Formatter.php new file mode 100644 index 000000000..db76749f0 --- /dev/null +++ b/core/lib/Thelia/Core/Template/Loop/Formatter.php @@ -0,0 +1,143 @@ + + */ +class Formatter extends BaseLoop implements ArraySearchLoopInterface +{ + /** + * this method returns an array + * + * @return array + */ + public function buildArray() + { + /** @var \Thelia\Core\FileFormat\Formatting\FormatterManager $service */ + $service = $this->container->get("thelia.manager.formatter_manager"); + + $rawFormatters = array_change_key_case($service->getAll()); + + $exportId = $this->getExport(); + $formatters = []; + + if ($exportId !== null) { + $export = ExportQuery::create()->findPk($exportId); + + if (null !== $export) { + $handlerInstance = $export->getHandleClassInstance($this->container); + + $types = $handlerInstance->getHandledTypes(); + + if (is_scalar($types)) { + $types = [$types]; + } + + /** @var \Thelia\Core\FileFormat\Formatting\AbstractFormatter $formatter */ + foreach ($rawFormatters as $key=>$formatter) { + if (in_array($formatter->getHandledType(), $types)) { + $formatters[$key] = $formatter; + } + } + } + + } else { + $formatters = $rawFormatters; + } + + switch ($this->getOrder()) { + case "alpha": + ksort($formatters); + break; + case "alpha_reverse": + krsort($formatters); + break; + } + + return $formatters; + } + + /** + * @param LoopResult $loopResult + * + * @return LoopResult + */ + public function parseResults(LoopResult $loopResult) + { + /** @var \Thelia\Core\FileFormat\Formatting\AbstractFormatter $formatter */ + foreach ($loopResult->getResultDataCollection() as $formatter) { + $loopResultRow = new LoopResultRow(); + + $loopResultRow + ->set("NAME", $formatter->getName()) + ->set("EXTENSION", $formatter->getExtension()) + ->set("MIME_TYPE", $formatter->getMimeType()) + ; + + $loopResult->addRow($loopResultRow); + } + + return $loopResult; + } + + /** + * Definition of loop arguments + * + * example : + * + * public function getArgDefinitions() + * { + * return new ArgumentCollection( + * + * Argument::createIntListTypeArgument('id'), + * new Argument( + * 'ref', + * new TypeCollection( + * new Type\AlphaNumStringListType() + * ) + * ), + * Argument::createIntListTypeArgument('category'), + * Argument::createBooleanTypeArgument('new'), + * ... + * ); + * } + * + * @return \Thelia\Core\Template\Loop\Argument\ArgumentCollection + */ + protected function getArgDefinitions() + { + return new ArgumentCollection( + Argument::createIntTypeArgument("export"), + new Argument( + "order", + new TypeCollection( + new EnumType(["alpha", "alpha_reverse"]) + ), + "alpha" + ) + ); + } + +} diff --git a/core/lib/Thelia/Core/Template/Loop/Import.php b/core/lib/Thelia/Core/Template/Loop/Import.php new file mode 100644 index 000000000..d8701c117 --- /dev/null +++ b/core/lib/Thelia/Core/Template/Loop/Import.php @@ -0,0 +1,37 @@ + + */ +class Import extends ImportExportType +{ + protected function getBaseUrl() + { + return $this->container->getParameter("import.base_url"); + } + + protected function getQueryModel() + { + return ImportQuery::create(); + } + + protected function getCategoryName() + { + return "ImportCategoryId"; + } +} diff --git a/core/lib/Thelia/Core/Template/Loop/ImportCategory.php b/core/lib/Thelia/Core/Template/Loop/ImportCategory.php new file mode 100644 index 000000000..bf54ee45d --- /dev/null +++ b/core/lib/Thelia/Core/Template/Loop/ImportCategory.php @@ -0,0 +1,27 @@ + + */ +class ImportCategory extends ImportExportCategory +{ + protected function getQueryModel() + { + return ImportCategoryQuery::create(); + } +} diff --git a/core/lib/Thelia/Core/Template/Loop/ImportExportCategory.php b/core/lib/Thelia/Core/Template/Loop/ImportExportCategory.php new file mode 100644 index 000000000..c03fda4d0 --- /dev/null +++ b/core/lib/Thelia/Core/Template/Loop/ImportExportCategory.php @@ -0,0 +1,139 @@ + + */ +abstract class ImportExportCategory extends BaseI18nLoop implements PropelSearchLoopInterface +{ + protected $timestampable = true; + + /** + * @param LoopResult $loopResult + * + * @return LoopResult + */ + public function parseResults(LoopResult $loopResult) + { + foreach ($loopResult->getResultDataCollection() as $category) { + $loopResultRow = new LoopResultRow($category); + + $loopResultRow + ->set("ID", $category->getId()) + ->set("TITLE", $category->getVirtualColumn("i18n_TITLE")) + ->set("POSITION", $category->getPosition()) + ; + + $loopResult->addRow($loopResultRow); + } + + return $loopResult; + } + + /** + * this method returns a Propel ModelCriteria + * + * @return \Propel\Runtime\ActiveQuery\ModelCriteria + */ + public function buildModelCriteria() + { + /** @var ModelCriteria $query */ + $query = $this->getQueryModel(); + + $this->configureI18nProcessing($query, array('TITLE')); + + if (null !== $ids = $this->getId()) { + $query->filterById($ids, Criteria::IN); + } + + if (null !== $orders = $this->getOrder()) { + foreach ($orders as $order) { + switch ($order) { + case "id": + $query->orderById(); + break; + case "id_reverse": + $query->orderById(Criteria::DESC); + break; + case "alpha": + $query->addAscendingOrderByColumn("i18n_TITLE"); + break; + case "alpha_reverse": + $query->addDescendingOrderByColumn("i18n_TITLE"); + break; + case "manual": + $query->orderByPosition(); + break; + case "manual_reverse": + $query->orderByPosition(Criteria::DESC); + break; + } + } + } + + return $query; + } + + /** + * Definition of loop arguments + * + * example : + * + * public function getArgDefinitions() + * { + * return new ArgumentCollection( + * + * Argument::createIntListTypeArgument('id'), + * new Argument( + * 'ref', + * new TypeCollection( + * new Type\AlphaNumStringListType() + * ) + * ), + * Argument::createIntListTypeArgument('category'), + * Argument::createBooleanTypeArgument('new'), + * ... + * ); + * } + * + * @return \Thelia\Core\Template\Loop\Argument\ArgumentCollection + */ + protected function getArgDefinitions() + { + return new ArgumentCollection( + Argument::createIntListTypeArgument('id'), + new Argument( + "order", + new TypeCollection( + new EnumListType(["id", "id_reverse", "alpha", "alpha_reverse", "manual", "manual_reverse"]) + ), + "manual" + ) + ); + } + + abstract protected function getQueryModel(); +} diff --git a/core/lib/Thelia/Core/Template/Loop/ImportExportType.php b/core/lib/Thelia/Core/Template/Loop/ImportExportType.php new file mode 100644 index 000000000..e9b472f64 --- /dev/null +++ b/core/lib/Thelia/Core/Template/Loop/ImportExportType.php @@ -0,0 +1,169 @@ + + */ +abstract class ImportExportType extends BaseI18nLoop implements PropelSearchLoopInterface +{ + const DEFAULT_ORDER = "manual"; + + protected $timestampable = true; + + /** + * @param LoopResult $loopResult + * + * @return LoopResult + */ + public function parseResults(LoopResult $loopResult) + { + foreach ($loopResult->getResultDataCollection() as $type) { + $loopResultRow = new LoopResultRow($type); + + $url = URL::getInstance()->absoluteUrl( + $this->getBaseUrl() . DS . $type->getId() + ); + + try { + $loopResultRow + ->set("HANDLE_CLASS", $type->getHandleClass()) + ->set("ID", $type->getId()) + ->set("TITLE", $type->getVirtualColumn("i18n_TITLE")) + ->set("DESCRIPTION", $type->getVirtualColumn("i18n_DESCRIPTION")) + ->set("URL", $url) + ->set("POSITION", $type->getPosition()) + ->set("CATEGORY_ID", $type->getByName($this->getCategoryName())) + ; + } catch (ClassNotFoundException $e) { + + } catch (\ErrorException $e) {} + + $loopResult->addRow($loopResultRow); + } + + return $loopResult; + } + + /** + * this method returns a Propel ModelCriteria + * + * @return \Propel\Runtime\ActiveQuery\ModelCriteria + */ + public function buildModelCriteria() + { + /** @var ModelCriteria $query */ + $query = $this->getQueryModel(); + + $this->configureI18nProcessing($query, array('TITLE', 'DESCRIPTION')); + + if (null !== $ids = $this->getId()) { + $query->filterById($ids); + } + + if (null !== $categories = $this->getCategory()) { + $query->filterBy($this->getCategoryName(), $categories, Criteria::IN); + } + + if (null !== $orders = $this->getOrder()) { + foreach ($orders as $order) { + switch ($order) { + case "id": + $query->orderById(); + break; + case "id_reverse": + $query->orderById(Criteria::DESC); + break; + case "alpha": + $query->addAscendingOrderByColumn("i18n_TITLE"); + break; + case "alpha_reverse": + $query->addDescendingOrderByColumn("i18n_TITLE"); + break; + case "manual": + $query->orderByPosition(); + break; + case "manual_reverse": + $query->orderByPosition(Criteria::DESC); + break; + } + } + } + + return $query; + } + + /** + * Definition of loop arguments + * + * example : + * + * public function getArgDefinitions() + * { + * return new ArgumentCollection( + * + * Argument::createIntListTypeArgument('id'), + * new Argument( + * 'ref', + * new TypeCollection( + * new Type\AlphaNumStringListType() + * ) + * ), + * Argument::createIntListTypeArgument('category'), + * Argument::createBooleanTypeArgument('new'), + * ... + * ); + * } + * + * @return \Thelia\Core\Template\Loop\Argument\ArgumentCollection + */ + protected function getArgDefinitions() + { + return new ArgumentCollection( + Argument::createIntListTypeArgument('id'), + Argument::createIntListTypeArgument('category'), + new Argument( + "order", + new TypeCollection( + new EnumListType(static::getAllowedOrders()) + ), + static::DEFAULT_ORDER + ) + ); + } + + public static function getAllowedOrders() + { + return ["id", "id_reverse", "alpha", "alpha_reverse", "manual", "manual_reverse"]; + } + + abstract protected function getBaseUrl(); + + abstract protected function getQueryModel(); + + abstract protected function getCategoryName(); +} diff --git a/core/lib/Thelia/Core/Template/Loop/ProductSaleElements.php b/core/lib/Thelia/Core/Template/Loop/ProductSaleElements.php index a55d746b6..30fdeeb23 100644 --- a/core/lib/Thelia/Core/Template/Loop/ProductSaleElements.php +++ b/core/lib/Thelia/Core/Template/Loop/ProductSaleElements.php @@ -84,7 +84,7 @@ class ProductSaleElements extends BaseLoop implements PropelSearchLoopInterface break; case "quantity_reverse": $search->orderByQuantity(Criteria::DESC); - break; + break; case "min_price": $search->addAscendingOrderByColumn('price_FINAL_PRICE', Criteria::ASC); break; diff --git a/core/lib/Thelia/Exception/FileNotFoundException.php b/core/lib/Thelia/Exception/FileNotFoundException.php new file mode 100644 index 000000000..7dc13dbd0 --- /dev/null +++ b/core/lib/Thelia/Exception/FileNotFoundException.php @@ -0,0 +1,23 @@ + + */ +class FileNotFoundException extends \ErrorException +{ + +} diff --git a/core/lib/Thelia/Exception/FileNotReadableException.php b/core/lib/Thelia/Exception/FileNotReadableException.php new file mode 100644 index 000000000..7afdab25f --- /dev/null +++ b/core/lib/Thelia/Exception/FileNotReadableException.php @@ -0,0 +1,23 @@ + + */ +class FileNotReadableException extends \Exception +{ + +} diff --git a/core/lib/Thelia/Exception/HttpUrlException.php b/core/lib/Thelia/Exception/HttpUrlException.php new file mode 100644 index 000000000..9e86e889b --- /dev/null +++ b/core/lib/Thelia/Exception/HttpUrlException.php @@ -0,0 +1,23 @@ + + */ +class HttpUrlException extends \Exception +{ + +} diff --git a/core/lib/Thelia/Form/ExportForm.php b/core/lib/Thelia/Form/ExportForm.php new file mode 100644 index 000000000..b149bcdc9 --- /dev/null +++ b/core/lib/Thelia/Form/ExportForm.php @@ -0,0 +1,98 @@ + + */ +class ExportForm extends BaseForm +{ + protected $translator; + + public function __construct(Request $request, $type= "form", $data = array(), $options = array()) + { + $this->translator = Translator::getInstance(); + + parent::__construct($request, $type, $data, $options); + } + + protected function buildForm() + { + $this->formBuilder + ->add("formatter", "text", array( + "label" => $this->translator->trans("File format"), + "label_attr" => ["for" => "formatter"], + "required" => true, + )) + ->add("do_compress", "checkbox", array( + "label" => $this->translator->trans("Do compress"), + "label_attr" => ["for" => "do_compress"], + "required" => false, + )) + ->add("archive_builder", "text", array( + "label" => $this->translator->trans("Archive Format"), + "label_attr" => ["for" => "archive_builder"], + "required" => false, + )) + ->add("images", "checkbox", array( + "label" => $this->translator->trans("Include images"), + "label_attr" => ["for" => "with_images"], + "required" => false, + )) + ->add("documents", "checkbox", array( + "label" => $this->translator->trans("Include documents"), + "label_attr" => ["for" => "with_documents"], + "required" => false, + )) + ->add("language", "integer", array( + "label" => $this->translator->trans("Language"), + "label_attr" => ["for" => "language"], + "required" => true, + "constraints" => [ + new Callback([ + "methods" => [ + [$this, "checkLanguage"], + ] + ]) + ] + )) + ; + } + + public function getName() + { + return "thelia_export"; + } + + public function checkLanguage($value, ExecutionContextInterface $context) + { + if (null === LangQuery::create()->findPk($value)) { + $context->addViolation( + $this->translator->trans( + "The language \"%id\" doesn't exist", + [ + "%id" => $value + ] + ) + ); + } + } + +} diff --git a/core/lib/Thelia/Form/ImportForm.php b/core/lib/Thelia/Form/ImportForm.php new file mode 100644 index 000000000..512ac2011 --- /dev/null +++ b/core/lib/Thelia/Form/ImportForm.php @@ -0,0 +1,102 @@ + + */ +class ImportForm extends BaseForm +{ + /** @var Translator */ + protected $translator; + + public function __construct(Request $request, $type = "form", $data = array(), $options = array()) + { + $this->translator = Translator::getInstance(); + + parent::__construct($request, $type, $data, $options); // TODO: Change the autogenerated stub + } + + /** + * + * in this function you add all the fields you need for your Form. + * Form this you have to call add method on $this->formBuilder attribute : + * + * $this->formBuilder->add("name", "text") + * ->add("email", "email", array( + * "attr" => array( + * "class" => "field" + * ), + * "label" => "email", + * "constraints" => array( + * new \Symfony\Component\Validator\Constraints\NotBlank() + * ) + * ) + * ) + * ->add('age', 'integer'); + * + * @return null + */ + protected function buildForm() + { + $this->formBuilder + ->add("file_upload", "file", array( + "label" => $this->translator->trans("File to upload"), + "label_attr" => ["for" => "file_to_upload"], + "required" => true, + )) + ->add("language", "integer", array( + "label" => $this->translator->trans("Language"), + "label_attr" => ["for" => "language"], + "required" => true, + "constraints" => [ + new Callback([ + "methods" => [ + [$this, "checkLanguage"], + ] + ]) + ] + )) + ; + } + + /** + * @return string the name of you form. This name must be unique + */ + public function getName() + { + return "thelia_import"; + } + + public function checkLanguage($value, ExecutionContextInterface $context) + { + if (null === LangQuery::create()->findPk($value)) { + $context->addViolation( + $this->translator->trans( + "The language \"%id\" doesn't exist", + [ + "%id" => $value + ] + ) + ); + } + } + +} diff --git a/core/lib/Thelia/ImportExport/AbstractHandler.php b/core/lib/Thelia/ImportExport/AbstractHandler.php new file mode 100644 index 000000000..a54b774f0 --- /dev/null +++ b/core/lib/Thelia/ImportExport/AbstractHandler.php @@ -0,0 +1,69 @@ + + */ +abstract class AbstractHandler +{ + /** @var \Symfony\Component\DependencyInjection\ContainerInterface */ + protected $container; + + protected $defaultLocale; + /** + * @param ContainerInterface $container + * + * Dependency injection: load the container to be able to get parameters and services + */ + public function __construct(ContainerInterface $container) + { + $this->defaultLocale = Lang::getDefaultLanguage()->getLocale(); + + $this->container = $container; + } + + public function getContainer() + { + return $this->container; + } + + /** + * @return \Thelia\Core\HttpFoundation\Request + */ + public function getRequest() + { + return $this->container->get("request"); + } + + /** + * @return string|array + * + * Define all the type of formatters that this can handle + * return a string if it handle a single type ( specific exports ), + * or an array if multiple. + * + * Thelia types are defined in \Thelia\Core\FileFormat\FormatType + * + * example: + * return array( + * FormatType::TABLE, + * FormatType::UNBOUNDED, + * ); + */ + abstract public function getHandledTypes(); +} diff --git a/core/lib/Thelia/ImportExport/Export/DocumentsExportInterface.php b/core/lib/Thelia/ImportExport/Export/DocumentsExportInterface.php new file mode 100644 index 000000000..ad952e2b8 --- /dev/null +++ b/core/lib/Thelia/ImportExport/Export/DocumentsExportInterface.php @@ -0,0 +1,29 @@ + + */ +interface DocumentsExportInterface +{ + const DOCUMENTS_DIRECTORY = "documents"; + + /** + * @return array + * + * return an array with the paths to the documents to include in the archive + */ + public function getDocumentsPaths(); +} diff --git a/core/lib/Thelia/ImportExport/Export/ExportHandler.php b/core/lib/Thelia/ImportExport/Export/ExportHandler.php new file mode 100644 index 000000000..31bd8fea2 --- /dev/null +++ b/core/lib/Thelia/ImportExport/Export/ExportHandler.php @@ -0,0 +1,204 @@ + + */ +abstract class ExportHandler extends AbstractHandler +{ + protected $locale; + + /** @var array */ + protected $order = array(); + + protected $isImageExport = false; + + protected $isDocumentExport = false; + + /** + * @return array + * + * You may override this method to return an array, containing + * the order that you want to have for your columns. + * The order appliance depends on the formatter + */ + protected function getDefaultOrder() + { + return array(); + } + + /** + * @return null|array + * + * You may override this method to return an array, containing + * the aliases to use. + */ + protected function getAliases() + { + return null; + } + + /** + * @return array + * + * Use this method to access the order. + * + */ + public function getOrder() + { + $order = $this->getDefaultOrder(); + + if (empty($order)) { + $order = $this->order; + } + + return $order; + } + + public function setOrder(array $order) + { + $this->order = $order; + + return $this; + } + + /** + * @param \Thelia\Model\Lang $lang + * @return \Thelia\Core\FileFormat\Formatting\FormatterData + * + * The method builds the FormatterData for the formatter + */ + public function buildData(Lang $lang) + { + $data = new FormatterData($this->getAliases()); + + $query = $this->buildDataSet($lang); + + if ($query instanceof ModelCriteria) { + return $data->loadModelCriteria($query); + } elseif (is_array($query)) { + return $data->setData($query); + } elseif ($query instanceof BaseLoop) { + $pagination = null; + $results = $query->exec($pagination); + + for ($results->rewind(); $results->valid(); $results->next() ) { + $current = $results->current(); + + $data->addRow($current->getVarVal()); + } + + return $data; + } + + throw new InvalidValueException( + Translator::getInstance()->trans( + "The method \"%class\"::buildDataSet must return an array or a ModelCriteria", + [ + "%class" => get_class($this), + ] + ) + ); + } + + public function renderLoop($type, array $args = array()) + { + $loopsDefinition = $this->container->getParameter("thelia.parser.loops"); + + if (!isset($loopsDefinition[$type])) { + throw new LoopException( + Translator::getInstance()->trans( + "The loop \"%loop\" doesn't exist", + [ + "%loop" => $type + ] + ) + ); + } + + $reflection = new \ReflectionClass($loopsDefinition[$type]); + + if (!$reflection->isSubclassOf("Thelia\\Core\\Template\\Element\\BaseLoop")) { + throw new LoopException( + Translator::getInstance()->trans( + "The class \"%class\" must be a subclass of %baseClass", + [ + "%class" => $loopsDefinition[$type], + "%baseClass" => "Thelia\\Core\\Template\\Element\\BaseLoop", + ] + ) + ); + } + + /** @var BaseLoop $loopInstance */ + $loopInstance = $reflection->newInstance($this->container); + + $loopInstance->initializeArgs($args); + + return $loopInstance; + } + + protected function addFileToArray(FileModelInterface $model, array &$paths) + { + $path = $model->getUploadDir() . DS . $model->getFile(); + + if (is_file($path) && is_readable($path)) { + $parent = $model->getParentFileModel(); + + $name = constant($parent::TABLE_MAP . "::TABLE_NAME"); + $paths[$name . DS . $model->getFile()] = $path; + } + } + + public function setDocumentExport($bool) + { + $this->isDocumentExport = (bool) $bool; + + return $this; + } + + public function setImageExport($bool) + { + $this->isImageExport = (bool) $bool; + + return $this; + } + + public function isDocumentExport() + { + return $this->isDocumentExport; + } + + public function isImageExport() + { + return $this->isImageExport; + } + + /** + * @param Lang $lang + * @return ModelCriteria|array|BaseLoop + */ + abstract public function buildDataSet(Lang $lang); +} diff --git a/core/lib/Thelia/ImportExport/Export/ImagesExportInterface.php b/core/lib/Thelia/ImportExport/Export/ImagesExportInterface.php new file mode 100644 index 000000000..dad485ec5 --- /dev/null +++ b/core/lib/Thelia/ImportExport/Export/ImagesExportInterface.php @@ -0,0 +1,29 @@ + + */ +interface ImagesExportInterface +{ + const IMAGES_DIRECTORY = "images"; + + /** + * @return array + * + * return an array with the paths to the images to include in the archive + */ + public function getImagesPaths(); +} diff --git a/core/lib/Thelia/ImportExport/Export/Type/ContentExport.php b/core/lib/Thelia/ImportExport/Export/Type/ContentExport.php new file mode 100644 index 000000000..499b6c23e --- /dev/null +++ b/core/lib/Thelia/ImportExport/Export/Type/ContentExport.php @@ -0,0 +1,310 @@ + + */ +class ContentExport extends ExportHandler implements + ImagesExportInterface, + DocumentsExportInterface +{ + const DIRECTORY_NAME = "content"; + + /** + * @return string|array + * + * Define all the type of formatters that this can handle + * return a string if it handle a single type ( specific exports ), + * or an array if multiple. + * + * Thelia types are defined in \Thelia\Core\FileFormat\FormatType + * + * example: + * return array( + * FormatType::TABLE, + * FormatType::UNBOUNDED, + * ); + */ + public function getHandledTypes() + { + return array( + FormatType::TABLE, + FormatType::UNBOUNDED, + ); + } + + /** + * @return ContentQuery + */ + public function getQuery(Lang $lang) + { + $locale = $lang->getLocale(); + + $contentI18nJoin = new Join(ContentTableMap::ID, ContentI18nTableMap::ID, Criteria::LEFT_JOIN); + $folderI18nJoin = new Join(FolderTableMap::ID, FolderI18nTableMap::ID, Criteria::LEFT_JOIN); + $urlJoin = new Join(ContentTableMap::ID, RewritingUrlTableMap::VIEW_ID, Criteria::LEFT_JOIN); + + + $query = ContentQuery::create() + ->select([ + ContentTableMap::ID, + ContentTableMap::VISIBLE, + "content_TITLE", + "content_CHAPO", + "content_DESCRIPTION", + "content_CONCLUSION", + "content_seo_TITLE", + "content_seo_DESCRIPTION", + "content_seo_KEYWORDS", + "url_URL", + "folder_TITLE", + "folder_ID", + "folder_IS_DEFAULT" + ]) + ->_if($this->isImageExport()) + ->useContentImageQuery("content_image_join", Criteria::LEFT_JOIN) + ->addAsColumn("content_IMAGES", "GROUP_CONCAT(DISTINCT `content_image_join`.FILE)") + ->addSelectColumn("content_IMAGES") + ->groupByContentId() + ->endUse() + ->_endif() + ->_if($this->isDocumentExport()) + ->useContentDocumentQuery("content_document_join", Criteria::LEFT_JOIN) + ->addAsColumn("content_DOCUMENTS", "GROUP_CONCAT(DISTINCT `content_document_join`.FILE)") + ->addSelectColumn("content_DOCUMENTS") + ->groupByContentId() + ->endUse() + ->_endif() + ->useContentFolderQuery(null, Criteria::LEFT_JOIN) + ->useFolderQuery(null, Criteria::LEFT_JOIN) + ->_if($this->isDocumentExport()) + ->useFolderDocumentQuery(null, Criteria::LEFT_JOIN) + ->addAsColumn("folder_DOCUMENTS", "GROUP_CONCAT(DISTINCT ".FolderDocumentTableMap::FILE.")") + ->addSelectColumn("folder_DOCUMENTS") + ->endUse() + ->_endif() + ->_if($this->isImageExport()) + ->useFolderImageQuery(null, Criteria::LEFT_JOIN) + ->addAsColumn("folder_IMAGES", "GROUP_CONCAT(DISTINCT ".FolderImageTableMap::FILE.")") + ->addSelectColumn("folder_IMAGES") + ->endUse() + ->_endif() + ->addJoinObject($folderI18nJoin, "folder_i18n_join") + ->addJoinCondition("folder_i18n_join", FolderI18nTableMap::LOCALE . " = ?", $locale, null, \PDO::PARAM_STR) + ->addAsColumn("folder_TITLE", FolderI18nTableMap::TITLE) + ->addAsColumn("folder_ID", FolderTableMap::ID) + ->endUse() + ->addAsColumn("folder_IS_DEFAULT", ContentFolderTableMap::DEFAULT_FOLDER) + ->endUse() + ->addJoinObject($contentI18nJoin, "content_i18n_join") + ->addJoinCondition("content_i18n_join", ContentI18nTableMap::LOCALE . " = ?", $locale, null, \PDO::PARAM_STR) + ->addAsColumn("content_TITLE", ContentI18nTableMap::TITLE) + ->addAsColumn("content_CHAPO", ContentI18nTableMap::CHAPO) + ->addAsColumn("content_DESCRIPTION", ContentI18nTableMap::DESCRIPTION) + ->addAsColumn("content_CONCLUSION", ContentI18nTableMap::POSTSCRIPTUM) + ->addAsColumn("content_seo_TITLE", ContentI18nTableMap::META_TITLE) + ->addAsColumn("content_seo_DESCRIPTION", ContentI18nTableMap::META_DESCRIPTION) + ->addAsColumn("content_seo_KEYWORDS", ContentI18nTableMap::META_KEYWORDS) + ->addJoinObject($urlJoin, "url_rewriting_join") + ->addJoinCondition( + "url_rewriting_join", + RewritingUrlTableMap::VIEW . " = ?", + (new Content())->getRewrittenUrlViewName(), + null, + \PDO::PARAM_STR + ) + ->addJoinCondition( + "url_rewriting_join", + RewritingUrlTableMap::VIEW_LOCALE . " = ?", + $locale, + null, + \PDO::PARAM_STR + ) + ->addAsColumn("url_URL", RewritingUrlTableMap::URL) + ->groupBy(ContentTableMap::ID) + ->groupBy("folder_ID") + ->orderById() + ; + + return $query; + } + + /** + * @param Lang $lang + * @return ModelCriteria|array|BaseLoop + */ + public function buildDataSet(Lang $lang) + { + $query = $this->getQuery($lang); + + $dataSet = $query + ->find() + ->toArray() + ; + + $previous = null; + foreach ($dataSet as &$line) { + if ($previous === null || $previous !== $line[ContentTableMap::ID]) { + $previous = $line[ContentTableMap::ID]; + } else { + /** + * Do not repeat content values + */ + $line["content_TITLE"] = ""; + $line[ContentTableMap::VISIBLE] = ""; + $line["content_CHAPO"] = ""; + $line["content_DESCRIPTION"] = ""; + $line["content_CONCLUSION"] = ""; + $line["content_seo_TITLE"] = ""; + $line["content_seo_DESCRIPTION"] = ""; + $line["content_seo_KEYWORDS"] = ""; + $line["url_URL"] = ""; + $line["content_IMAGES"] = ""; + $line["content_DOCUMENTS"] = ""; + + if (isset($line["content_IMAGES"])) { + $line["content_IMAGES"] = ""; + } + + if (isset($line["content_DOCUMENTS"])) { + $line["content_DOCUMENTS"] = ""; + } + } + } + + return $dataSet; + } + + protected function getDefaultOrder() + { + return [ + "id", + "title", + "chapo", + "description", + "conclusion", + "visible", + "seo_title", + "seo_description", + "seo_keywords", + "url", + "folder_id", + "is_default_folder", + "folder_title", + ]; + } + + protected function getAliases() + { + return [ + ContentTableMap::ID => "id", + ContentTableMap::VISIBLE => "visible", + "content_TITLE" => "title", + "content_CHAPO" => "chapo", + "content_DESCRIPTION" => "description", + "content_CONCLUSION" => "conclusion", + "content_seo_TITLE" => "seo_title", + "content_seo_DESCRIPTION" => "seo_description", + "content_seo_KEYWORDS" => "seo_keywords", + "url_URL" => "url", + "folder_TITLE" => "folder_title", + "folder_ID" => "folder_id", + "folder_IS_DEFAULT" => "is_default_folder" + ]; + } + + + /** + * @return array + * + * return an array with the paths to the documents to include in the archive + */ + public function getDocumentsPaths() + { + $documentPaths = []; + + $folderDocuments = FolderDocumentQuery::create() + ->find(); + /** @var \Thelia\Model\FolderDocument $folderDocument */ + foreach ($folderDocuments as $folderDocument) { + $this->addFileToArray($folderDocument, $documentPaths); + + } + + $contentDocuments = ContentDocumentQuery::create() + ->find(); + + /** @var \Thelia\Model\ContentDocument $contentDocument */ + foreach ($contentDocuments as $contentDocument) { + $this->addFileToArray($contentDocument, $documentPaths); + } + + return $documentPaths; + } + + /** + * @return array + * + * return an array with the paths to the images to include in the archive + */ + public function getImagesPaths() + { + $imagePaths = []; + + $folderImages = FolderImageQuery::create() + ->find(); + + /** @var \Thelia\Model\FolderDocument $folderImage */ + foreach ($folderImages as $folderImage) { + $this->addFileToArray($folderImage, $imagePaths); + } + + $contentImages = ContentImageQuery::create() + ->find(); + + /** @var \Thelia\Model\ContentImage $contentImage */ + foreach ($contentImages as $contentImage) { + $this->addFileToArray($contentImage, $imagePaths); + } + + return $imagePaths; + } +} \ No newline at end of file diff --git a/core/lib/Thelia/ImportExport/Export/Type/CustomerExport.php b/core/lib/Thelia/ImportExport/Export/Type/CustomerExport.php new file mode 100644 index 000000000..9768c5648 --- /dev/null +++ b/core/lib/Thelia/ImportExport/Export/Type/CustomerExport.php @@ -0,0 +1,357 @@ + + */ +class CustomerExport extends ExportHandler +{ + /** + * @return string|array + * + * Define all the type of formatters that this can handle + * return a string if it handle a single type ( specific exports ), + * or an array if multiple. + * + * Thelia types are defined in \Thelia\Core\FileFormat\FormatType + * + * example: + * return array( + * FormatType::TABLE, + * FormatType::UNBOUNDED, + * ); + */ + public function getHandledTypes() + { + return array( + FormatType::TABLE, + FormatType::UNBOUNDED, + ); + } + + /** + * @param Lang $lang + * @return array|\Propel\Runtime\ActiveQuery\ModelCriteria + * + * The tax engine of Thelia is in PHP, so we can't compute orders for each customers + * directly in SQL, we need two SQL queries, and some computing to get the last order amount and total amount. + */ + public function buildDataSet(Lang $lang) + { + $locale = $lang->getLocale(); + $defaultLocale = Lang::getDefaultLanguage()->getLocale(); + /** + * This first query get each customer info and addresses. + */ + $newsletterJoin = new Join(CustomerTableMap::EMAIL, NewsletterTableMap::EMAIL, Criteria::LEFT_JOIN); + + $query = CustomerQuery::create() + ->useCustomerTitleQuery("customer_title_") + ->useCustomerTitleI18nQuery("customer_title_i18n_") + ->addAsColumn("title_TITLE", "customer_title_i18n_.SHORT") + ->endUse() + ->endUse() + ->useAddressQuery() + ->useCountryQuery() + ->useCountryI18nQuery() + ->addAsColumn("address_COUNTRY", CountryI18nTableMap::TITLE) + ->endUse() + ->endUse() + ->useCustomerTitleQuery("address_title") + ->useCustomerTitleI18nQuery("address_title_i18n") + ->addAsColumn("address_TITLE", "address_title_i18n.SHORT") + ->endUse() + ->endUse() + ->addAsColumn("address_LABEL", AddressTableMap::LABEL) + ->addAsColumn("address_FIRST_NAME", AddressTableMap::FIRSTNAME) + ->addAsColumn("address_LAST_NAME", AddressTableMap::LASTNAME) + ->addAsColumn("address_COMPANY", AddressTableMap::COMPANY) + ->addAsColumn("address_ADDRESS1", AddressTableMap::ADDRESS1) + ->addAsColumn("address_ADDRESS2", AddressTableMap::ADDRESS2) + ->addAsColumn("address_ADDRESS3", AddressTableMap::ADDRESS3) + ->addAsColumn("address_ZIPCODE", AddressTableMap::ZIPCODE) + ->addAsColumn("address_CITY", AddressTableMap::CITY) + ->addAsColumn("address_PHONE", AddressTableMap::PHONE) + ->addAsColumn("address_CELLPHONE", AddressTableMap::CELLPHONE) + ->addAsColumn("address_IS_DEFAULT", AddressTableMap::IS_DEFAULT) + ->endUse() + ->addJoinObject($newsletterJoin) + ->addAsColumn("newsletter_IS_REGISTRED", "IF(NOT ISNULL(".NewsletterTableMap::EMAIL."),1,0)") + ->select([ + CustomerTableMap::ID, + CustomerTableMap::REF, + CustomerTableMap::LASTNAME, + CustomerTableMap::FIRSTNAME, + CustomerTableMap::EMAIL, + CustomerTableMap::DISCOUNT, + CustomerTableMap::CREATED_AT, + "title_TITLE", + "address_TITLE", + "address_LABEL", + "address_COMPANY", + "address_FIRST_NAME", + "address_LAST_NAME", + "address_ADDRESS1", + "address_ADDRESS2", + "address_ADDRESS3", + "address_ZIPCODE", + "address_CITY", + "address_COUNTRY", + "address_PHONE", + "address_CELLPHONE", + "address_IS_DEFAULT", + "newsletter_IS_REGISTRED", + ]) + ->orderById() + ; + + I18n::addI18nCondition( + $query, + CountryI18nTableMap::TABLE_NAME, + CountryTableMap::ID, + CountryI18nTableMap::ID, + CountryI18nTableMap::LOCALE, + $locale + ); + + I18n::addI18nCondition( + $query, + CustomerTitleI18nTableMap::TABLE_NAME, + "`customer_title_`.ID", + "`customer_title_i18n_`.ID", + "`customer_title_i18n_`.LOCALE", + $locale + ); + + I18n::addI18nCondition( + $query, + CustomerTitleI18nTableMap::TABLE_NAME, + "`address_title`.ID", + "`address_title_i18n`.ID", + "`address_title_i18n`.LOCALE", + $locale + ); + + /** @var CustomerQuery $query */ + $results = $query + ->find() + ->toArray() + ; + + /** + * Then get the orders + */ + $orders = OrderQuery::create() + ->useCustomerQuery() + ->orderById() + ->endUse() + ->find() + ; + + /** + * And add them info the array + */ + $orders->rewind(); + + $arrayLength = count($results); + + $previousCustomerId = null; + + for ($i = 0; $i < $arrayLength; ++$i) { + $currentCustomer = &$results[$i]; + + $currentCustomerId = $currentCustomer[CustomerTableMap::ID]; + unset ($currentCustomer[CustomerTableMap::ID]); + + if ($currentCustomerId === $previousCustomerId) { + $currentCustomer["title_TITLE"] = ""; + $currentCustomer[CustomerTableMap::LASTNAME] = ""; + $currentCustomer[CustomerTableMap::FIRSTNAME] = ""; + $currentCustomer[CustomerTableMap::EMAIL] = ""; + $currentCustomer["address_COMPANY"] = ""; + $currentCustomer["newsletter_IS_REGISTRED"] = ""; + $currentCustomer[CustomerTableMap::CREATED_AT] = ""; + $currentCustomer[CustomerTableMap::DISCOUNT] = ""; + + $currentCustomer += [ + "order_TOTAL" => "", + "last_order_AMOUNT" => "", + "last_order_DATE" => "", + ]; + } else { + + /** + * Reformat created_at date + */ + $date = $currentCustomer[CustomerTableMap::CREATED_AT]; + $dateTime = new \DateTime($date); + $currentCustomer[CustomerTableMap::CREATED_AT] = $dateTime->format($lang->getDatetimeFormat()); + + /** + * Then compute everything about the orders + */ + $total = 0; + $lastOrderAmount = 0; + $lastOrderDate = null; + $lastOrder = null; + $lastOrderCurrencyCode = null; + $lastOrderId = 0; + + $defaultCurrency = Currency::getDefaultCurrency(); + $defaultCurrencyCode = $defaultCurrency + ->getCode() + ; + + if (empty($defaultCurrencyCode)) { + $defaultCurrencyCode = $defaultCurrency + ->getCode() + ; + } + + $formattedDate = null; + + /** @var \Thelia\Model\Order $currentOrder */ + while (false !== $currentOrder = $orders->current()) { + if ($currentCustomerId != $currentOrder->getCustomerId()) { + break; + } + + $amount = $currentOrder->getTotalAmount($tax); + if (0 < $rate = $currentOrder->getCurrencyRate()) { + $amount = round($amount / $rate, 2); + } + + $total += $amount; + + /** @var \DateTime $date */ + $date = $currentOrder->getCreatedAt(); + + if (null === $lastOrderDate || ($date >= $lastOrderDate && $lastOrderId < $currentOrder->getId())) { + $lastOrder = $currentOrder; + $lastOrderDate = $date; + $lastOrderId = $currentOrder->getId(); + } + + $orders->next(); + } + + if ($lastOrderDate !== null) { + $formattedDate = $lastOrderDate->format($lang->getDatetimeFormat()); + + $orderCurrency = $lastOrder->getCurrency(); + $lastOrderCurrencyCode = $orderCurrency + ->getCode() + ; + + if (empty($lastOrderCurrencyCode)) { + $lastOrderCurrencyCode = $orderCurrency + ->getCode() + ; + } + + $lastOrderAmount = $lastOrder->getTotalAmount($tax_); + } + + $currentCustomer += [ + "order_TOTAL" => $total . " " . $defaultCurrencyCode, + "last_order_AMOUNT" => $lastOrderAmount === 0 ? "" : $lastOrderAmount . " " . $lastOrderCurrencyCode, + "last_order_DATE" => $formattedDate, + ]; + } + + $previousCustomerId = $currentCustomerId; + } + + return $results; + } + + protected function getAliases() + { + return [ + CustomerTableMap::REF => "ref", + CustomerTableMap::LASTNAME => "last_name", + CustomerTableMap::FIRSTNAME => "first_name", + CustomerTableMap::EMAIL => "email", + CustomerTableMap::DISCOUNT => "discount", + CustomerTableMap::CREATED_AT => "sign_up_date", + "title_TITLE" => "title", + "address_TITLE" => "address_title", + "address_LABEL" => "label", + "address_IS_DEFAULT" => "is_default_address", + "address_COMPANY" => "company", + "address_ADDRESS1" => "address1", + "address_ADDRESS2" => "address2", + "address_ADDRESS3" => "address3", + "address_ZIPCODE" => "zipcode", + "address_CITY" => "city", + "address_COUNTRY" => "country", + "address_PHONE" => "phone", + "address_CELLPHONE" => "cellphone", + "address_FIRST_NAME" => "address_first_name", + "address_LAST_NAME" => "address_last_name", + "newsletter_IS_REGISTRED" => "is_registered_to_newsletter", + "order_TOTAL" => "total_orders", + "last_order_AMOUNT" => "last_order_amount", + "last_order_DATE" => "last_order_date", + ]; + } + + public function getOrder() + { + return [ + "ref", + "title", + "last_name", + "first_name", + "email", + "discount", + "is_registered_to_newsletter", + "sign_up_date", + "total_orders", + "last_order_amount", + "last_order_date", + "label", + "address_title", + "address_first_name", + "address_last_name", + "company", + "address1", + "address2", + "address3", + "zipcode", + "city", + "country", + "phone", + "cellphone", + "is_default_address", + ]; + } +} diff --git a/core/lib/Thelia/ImportExport/Export/Type/MailingExport.php b/core/lib/Thelia/ImportExport/Export/Type/MailingExport.php new file mode 100644 index 000000000..40621adc8 --- /dev/null +++ b/core/lib/Thelia/ImportExport/Export/Type/MailingExport.php @@ -0,0 +1,98 @@ + + */ +class MailingExport extends ExportHandler +{ + /** + * @param Lang $lang + * @return array|\Propel\Runtime\ActiveQuery\ModelCriteria + */ + public function buildDataSet(Lang $lang) + { + $newsletter = NewsletterQuery::create() + ->select([ + NewsletterTableMap::EMAIL, + NewsletterTableMap::LASTNAME, + NewsletterTableMap::FIRSTNAME, + ]) + ->find() + ->toArray() + ; + + $customers = CustomerQuery::create() + ->select([ + CustomerTableMap::EMAIL, + CustomerTableMap::LASTNAME, + CustomerTableMap::FIRSTNAME, + ]) + ->find() + ->toArray() + ; + + return $customers + $newsletter; + } + + protected function getAliases() + { + $email = "email"; + $lastName = "last_name"; + $firstName = "first_name"; + + return [ + NewsletterTableMap::EMAIL => $email, + CustomerTableMap::EMAIL => $email, + + NewsletterTableMap::LASTNAME => $lastName, + CustomerTableMap::LASTNAME => $lastName, + + NewsletterTableMap::FIRSTNAME => $firstName, + CustomerTableMap::FIRSTNAME => $firstName, + ]; + } + + /** + * @return string|array + * + * Define all the type of export/formatters that this can handle + * return a string if it handle a single type ( specific exports ), + * or an array if multiple. + * + * Thelia types are defined in \Thelia\Core\FileFormat\FormatType + * + * example: + * return array( + * FormatType::TABLE, + * FormatType::UNBOUNDED, + * ); + */ + public function getHandledTypes() + { + return array( + FormatType::TABLE, + FormatType::UNBOUNDED, + ); + } +} diff --git a/core/lib/Thelia/ImportExport/Export/Type/OrderExport.php b/core/lib/Thelia/ImportExport/Export/Type/OrderExport.php new file mode 100644 index 000000000..68ea24fa5 --- /dev/null +++ b/core/lib/Thelia/ImportExport/Export/Type/OrderExport.php @@ -0,0 +1,446 @@ + + */ +class OrderExport extends ExportHandler +{ + /** + * @return string|array + * + * Define all the type of formatters that this can handle + * return a string if it handle a single type ( specific exports ), + * or an array if multiple. + * + * Thelia types are defined in \Thelia\Core\FileFormat\FormatType + * + * example: + * return array( + * FormatType::TABLE, + * FormatType::UNBOUNDED, + * ); + */ + public function getHandledTypes() + { + return array( + FormatType::TABLE, + FormatType::UNBOUNDED, + ); + } + + protected function getQuery(Lang $lang) + { + $locale = $lang->getLocale(); + + $query = OrderQuery::create() + ->useCurrencyQuery() + ->addAsColumn("currency_CODE", CurrencyTableMap::CODE) + ->endUse() + ->useCustomerQuery() + ->addAsColumn("customer_REF", CustomerTableMap::REF) + ->endUse() + ->useOrderProductQuery() + ->useOrderProductTaxQuery(null, Criteria::LEFT_JOIN) + ->addAsColumn( + "product_TAX", + "IF(".OrderProductTableMap::WAS_IN_PROMO.",". + "SUM(".OrderProductTaxTableMap::PROMO_AMOUNT."),". + "SUM(".OrderProductTaxTableMap::AMOUNT.")". + ")" + ) + ->addAsColumn("tax_TITLE", OrderProductTableMap::TAX_RULE_TITLE) + ->endUse() + ->addAsColumn("product_TITLE", OrderProductTableMap::TITLE) + ->addAsColumn( + "product_PRICE", + "IF(".OrderProductTableMap::WAS_IN_PROMO.",". + OrderProductTableMap::PROMO_PRICE .",". + OrderProductTableMap::PRICE . + ")" + ) + ->addAsColumn("product_QUANTITY", OrderProductTableMap::QUANTITY) + ->addAsColumn("product_WAS_IN_PROMO", OrderProductTableMap::WAS_IN_PROMO) + ->groupById() + ->endUse() + ->orderById() + ->groupById() + ->useOrderCouponQuery(null, Criteria::LEFT_JOIN) + ->addAsColumn("coupon_COUPONS", "GROUP_CONCAT(".OrderCouponTableMap::TITLE.")") + ->groupBy(OrderCouponTableMap::ORDER_ID) + ->endUse() + ->useModuleRelatedByPaymentModuleIdQuery("payment_module") + ->addAsColumn("payment_module_TITLE", "`payment_module`.CODE") + ->endUse() + ->useModuleRelatedByDeliveryModuleIdQuery("delivery_module") + ->addAsColumn("delivery_module_TITLE", "`delivery_module`.CODE") + ->endUse() + ->useOrderAddressRelatedByDeliveryOrderAddressIdQuery("delivery_address_join") + ->useCustomerTitleQuery("delivery_address_customer_title_join") + ->useCustomerTitleI18nQuery("delivery_address_customer_title_i18n_join") + ->addAsColumn("delivery_address_TITLE", "`delivery_address_customer_title_i18n_join`.SHORT") + ->endUse() + ->endUse() + ->useCountryQuery("delivery_address_country_join") + ->useCountryI18nQuery("delivery_address_country_i18n_join") + ->addAsColumn("delivery_address_country_TITLE", "`delivery_address_country_i18n_join`.TITLE") + ->endUse() + ->addAsColumn("delivery_address_COMPANY", "`delivery_address_join`.COMPANY") + ->addAsColumn("delivery_address_FIRSTNAME", "`delivery_address_join`.FIRSTNAME") + ->addAsColumn("delivery_address_LASTNAME", "`delivery_address_join`.LASTNAME") + ->addAsColumn("delivery_address_ADDRESS1", "`delivery_address_join`.ADDRESS1") + ->addAsColumn("delivery_address_ADDRESS2", "`delivery_address_join`.ADDRESS2") + ->addAsColumn("delivery_address_ADDRESS3", "`delivery_address_join`.ADDRESS3") + ->addAsColumn("delivery_address_ZIPCODE", "`delivery_address_join`.ZIPCODE") + ->addAsColumn("delivery_address_CITY", "`delivery_address_join`.CITY") + ->addAsColumn("delivery_address_PHONE", "`delivery_address_join`.PHONE") + ->endUse() + ->endUse() + ->useOrderAddressRelatedByInvoiceOrderAddressIdQuery("invoice_address_join") + ->useCustomerTitleQuery("invoice_address_customer_title_join") + ->useCustomerTitleI18nQuery("invoice_address_customer_title_i18n_join") + ->addAsColumn("invoice_address_TITLE", "`invoice_address_customer_title_i18n_join`.SHORT") + ->endUse() + ->endUse() + ->useCountryQuery("invoice_address_country_join") + ->useCountryI18nQuery("invoice_address_country_i18n_join") + ->addAsColumn("invoice_address_country_TITLE", "`invoice_address_country_i18n_join`.TITLE") + ->endUse() + ->endUse() + ->addAsColumn("invoice_address_COMPANY", "`invoice_address_join`.COMPANY") + ->addAsColumn("invoice_address_FIRSTNAME", "`invoice_address_join`.FIRSTNAME") + ->addAsColumn("invoice_address_LASTNAME", "`invoice_address_join`.LASTNAME") + ->addAsColumn("invoice_address_ADDRESS1", "`invoice_address_join`.ADDRESS1") + ->addAsColumn("invoice_address_ADDRESS2", "`invoice_address_join`.ADDRESS2") + ->addAsColumn("invoice_address_ADDRESS3", "`invoice_address_join`.ADDRESS3") + ->addAsColumn("invoice_address_ZIPCODE", "`invoice_address_join`.ZIPCODE") + ->addAsColumn("invoice_address_CITY", "`invoice_address_join`.CITY") + ->addAsColumn("invoice_address_PHONE", "`invoice_address_join`.PHONE") + ->endUse() + ->useOrderStatusQuery() + ->useOrderStatusI18nQuery() + ->addAsColumn("order_status_TITLE", OrderStatusI18nTableMap::TITLE) + ->endUse() + ->endUse() + ->select([ + OrderTableMap::REF, + "customer_REF", + "product_TITLE", + "product_PRICE", + "product_TAX", + "tax_TITLE", + // PRODUCT_TTC_PRICE + "product_QUANTITY", + "product_WAS_IN_PROMO", + // ORDER_TOTAL_TTC + OrderTableMap::DISCOUNT, + "coupon_COUPONS", + // TOTAL_WITH_DISCOUNT + OrderTableMap::POSTAGE, + // total ttc +postage + "payment_module_TITLE", + OrderTableMap::INVOICE_REF, + OrderTableMap::DELIVERY_REF, + "delivery_module_TITLE", + "delivery_address_TITLE", + "delivery_address_COMPANY", + "delivery_address_FIRSTNAME", + "delivery_address_LASTNAME", + "delivery_address_ADDRESS1", + "delivery_address_ADDRESS2", + "delivery_address_ADDRESS3", + "delivery_address_ZIPCODE", + "delivery_address_CITY", + "delivery_address_country_TITLE", + "delivery_address_PHONE", + "invoice_address_TITLE", + "invoice_address_COMPANY", + "invoice_address_FIRSTNAME", + "invoice_address_LASTNAME", + "invoice_address_ADDRESS1", + "invoice_address_ADDRESS2", + "invoice_address_ADDRESS3", + "invoice_address_ZIPCODE", + "invoice_address_CITY", + "invoice_address_country_TITLE", + "invoice_address_PHONE", + "order_status_TITLE", + "currency_CODE", + OrderTableMap::CREATED_AT, + ]) + ->orderByCreatedAt(Criteria::DESC) + ; + + I18n::addI18nCondition( + $query, + CustomerTitleI18nTableMap::TABLE_NAME, + "`delivery_address_customer_title_join`.ID", + CustomerTitleI18nTableMap::ID, + "`delivery_address_customer_title_i18n_join`.LOCALE", + $locale + ); + + I18n::addI18nCondition( + $query, + CustomerTitleI18nTableMap::TABLE_NAME, + "`invoice_address_customer_title_join`.ID", + CustomerTitleI18nTableMap::ID, + "`invoice_address_customer_title_i18n_join`.LOCALE", + $locale + ); + + I18n::addI18nCondition( + $query, + CountryI18nTableMap::TABLE_NAME, + "`delivery_address_country_join`.ID", + CountryI18nTableMap::ID, + "`delivery_address_country_i18n_join`.LOCALE", + $locale + ); + + I18n::addI18nCondition( + $query, + CountryI18nTableMap::TABLE_NAME, + "`invoice_address_country_join`.ID", + CountryI18nTableMap::ID, + "`invoice_address_country_i18n_join`.LOCALE", + $locale + ); + + I18n::addI18nCondition( + $query, + OrderStatusI18nTableMap::TABLE_NAME, + OrderStatusI18nTableMap::ID, + OrderStatusTableMap::ID, + OrderStatusI18nTableMap::LOCALE, + $locale + ); + + return $query; + } + + /** + * @param Lang $lang + * @return ModelCriteria|array|BaseLoop + */ + public function buildDataSet(Lang $lang) + { + + $query = $this->getQuery($lang); + + $dataSet = $query + ->find() + ->toArray() + ; + + $orders = OrderQuery::create() + ->orderById() + ->find() + ; + + $current = 0; + $previous = null; + + foreach ($dataSet as &$line) { + /** + * Add computed columns + */ + $line["order_TOTAL_TTC"] = ""; + $line["order_TOTAL_WITH_DISCOUNT"] = ""; + $line["order_TOTAL_WITH_DISCOUNT_AND_POSTAGE"] = ""; + + if (null === $previous || $previous !== $line[OrderTableMap::REF]) { + $previous = $line[OrderTableMap::REF]; + + /** @var \Thelia\Model\Order $order */ + $order = $orders->get($current); + + $line["order_TOTAL_TTC"] = $order->getTotalAmount($tax, false, false); + $line["order_TOTAL_WITH_DISCOUNT"] = $order->getTotalAmount($tax, false, true); + $line["order_TOTAL_WITH_DISCOUNT_AND_POSTAGE"] = $order->getTotalAmount($tax, true, true); + + /** + * Format the date + */ + + $date = new \DateTime($line[OrderTableMap::CREATED_AT]); + + + $line[OrderTableMap::CREATED_AT] = $date->format($lang->getDatetimeFormat()); + + $current++; + } else { + /** + * Remove all the information of the order + * for each line that only contains a product. + */ + $line["customer_REF"] = ""; + $line[OrderTableMap::DISCOUNT] = ""; + $line["coupon_COUPONS"] = ""; + $line[OrderTableMap::POSTAGE] = ""; + $line["payment_module_TITLE"] = ""; + $line[OrderTableMap::INVOICE_REF] = ""; + $line["delivery_module_TITLE"] = ""; + $line["delivery_address_TITLE"] = ""; + $line["delivery_address_COMPANY"] = ""; + $line["delivery_address_FIRSTNAME"] = ""; + $line["delivery_address_LASTNAME"] = ""; + $line["delivery_address_ADDRESS1"] = ""; + $line["delivery_address_ADDRESS2"] = ""; + $line["delivery_address_ADDRESS3"] = ""; + $line["delivery_address_ZIPCODE"] = ""; + $line["delivery_address_CITY"] = ""; + $line["delivery_address_country_TITLE"] = ""; + $line["delivery_address_PHONE"] = ""; + $line["invoice_address_TITLE"] = ""; + $line["invoice_address_COMPANY"] = ""; + $line["invoice_address_FIRSTNAME"] = ""; + $line["invoice_address_LASTNAME"] = ""; + $line["invoice_address_ADDRESS1"] = ""; + $line["invoice_address_ADDRESS2"] = ""; + $line["invoice_address_ADDRESS3"] = ""; + $line["invoice_address_ZIPCODE"] = ""; + $line["invoice_address_CITY"] = ""; + $line["invoice_address_country_TITLE"] = ""; + $line["invoice_address_PHONE"] = ""; + $line["order_status_TITLE"] = ""; + $line[OrderTableMap::CREATED_AT] = ""; + } + + $line["product_TAXED_PRICE"] = $line["product_PRICE"] + $line["product_TAX"]; + } + + return $dataSet; + } + + protected function getAliases() + { + return [ + OrderTableMap::REF => "ref", + "customer_REF" => "customer_ref", + "product_TITLE" => "product_title", + "product_PRICE" => "price", + "product_TAX" => "tax_amount", + "tax_TITLE" => "tax_title", + "order_TOTAL_TTC" => "total_including_taxes", + "product_QUANTITY" => "quantity", + "product_WAS_IN_PROMO" => "was_in_promo", + "order_TOTAL_WITH_DISCOUNT" => "total_with_discount", + OrderTableMap::DISCOUNT => "discount", + "coupon_COUPONS" => "coupons", + "order_TOTAL_WITH_DISCOUNT_AND_POSTAGE" => "total_discount_and_postage", + OrderTableMap::POSTAGE => "postage", + "product_TAXED_PRICE" => "taxed_price", + "payment_module_TITLE" => "payment_module", + OrderTableMap::INVOICE_REF => "invoice_ref", + OrderTableMap::DELIVERY_REF => "delivery_ref", + "delivery_module_TITLE" => "delivery_module", + "delivery_address_TITLE" => "delivery_title", + "delivery_address_COMPANY" => "delivery_company", + "delivery_address_FIRSTNAME" => "delivery_first_name", + "delivery_address_LASTNAME" => "delivery_last_name", + "delivery_address_ADDRESS1" => "delivery_address1", + "delivery_address_ADDRESS2" => "delivery_address2", + "delivery_address_ADDRESS3" => "delivery_address3", + "delivery_address_ZIPCODE" => "delivery_zip_code", + "delivery_address_CITY" => "delivery_city", + "delivery_address_country_TITLE" => "delivery_country", + "delivery_address_PHONE" => "delivery_phone", + "invoice_address_TITLE" => "invoice_title", + "invoice_address_COMPANY" => "invoice_company", + "invoice_address_FIRSTNAME" => "invoice_first_name", + "invoice_address_LASTNAME" => "invoice_last_name", + "invoice_address_ADDRESS1" => "invoice_address1", + "invoice_address_ADDRESS2" => "invoice_address2", + "invoice_address_ADDRESS3" => "invoice_address3", + "invoice_address_ZIPCODE" => "invoice_zip_code", + "invoice_address_CITY" => "invoice_city", + "invoice_address_country_TITLE" => "invoice_country", + "invoice_address_PHONE" => "invoice_phone", + "order_status_TITLE" => "status", + "currency_CODE" => "currency", + OrderTableMap::CREATED_AT => "date", + ]; + } + + public function getOrder() + { + return [ + "ref", + "date", + "customer_ref", + "discount", + "coupons", + "postage", + "total_including_taxes", + "total_with_discount", + "total_discount_and_postage", + "delivery_module", + "delivery_ref", + "payment_module", + "invoice_ref", + "status", + "delivery_title", + "delivery_company", + "delivery_first_name", + "delivery_last_name", + "delivery_address1", + "delivery_address2", + "delivery_address3", + "delivery_zip_code", + "delivery_city", + "delivery_country", + "delivery_phone", + "invoice_title", + "invoice_company", + "invoice_first_name", + "invoice_last_name", + "invoice_address1", + "invoice_address2", + "invoice_address3", + "invoice_zip_code", + "invoice_city", + "invoice_country", + "invoice_phone", + "product_title", + "price", + "taxed_price", + "currency", + "was_in_promo", + "quantity", + "tax_amount", + "tax_title", + ]; + } +} diff --git a/core/lib/Thelia/ImportExport/Export/Type/ProductPricesExport.php b/core/lib/Thelia/ImportExport/Export/Type/ProductPricesExport.php new file mode 100644 index 000000000..60ab87f35 --- /dev/null +++ b/core/lib/Thelia/ImportExport/Export/Type/ProductPricesExport.php @@ -0,0 +1,151 @@ + + */ +class ProductPricesExport extends ExportHandler +{ + /** + * @return string|array + * + * Define all the type of formatters that this can handle + * return a string if it handle a single type ( specific exports ), + * or an array if multiple. + * + * Thelia types are defined in \Thelia\Core\FileFormat\FormatType + * + * example: + * return array( + * FormatType::TABLE, + * FormatType::UNBOUNDED, + * ); + */ + public function getHandledTypes() + { + return array( + FormatType::TABLE, + FormatType::UNBOUNDED, + ); + } + + /** + * @param Lang $lang + * @return array|\Propel\Runtime\ActiveQuery\ModelCriteria|\Thelia\Core\Template\Element\BaseLoop + */ + public function buildDataSet(Lang $lang) + { + $locale = $lang->getLocale(); + + $productJoin = new Join(ProductTableMap::ID, ProductI18nTableMap::ID, Criteria::LEFT_JOIN); + $attributeAvJoin = new Join(AttributeAvTableMap::ID, AttributeAvI18nTableMap::ID, Criteria::LEFT_JOIN); + + $query = AttributeCombinationQuery::create() + ->useProductSaleElementsQuery() + ->useProductPriceQuery() + ->useCurrencyQuery() + ->addAsColumn("currency_CODE", CurrencyTableMap::CODE) + ->endUse() + ->addAsColumn("price_PRICE", ProductPriceTableMap::PRICE) + ->addAsColumn("price_PROMO_PRICE", ProductPriceTableMap::PROMO_PRICE) + ->endUse() + ->useProductQuery() + ->addJoinObject($productJoin, "product_join") + ->addJoinCondition( + "product_join", + ProductI18nTableMap::LOCALE . " = ?", + $locale, + null, + \PDO::PARAM_STR + ) + ->addAsColumn("product_TITLE", ProductI18nTableMap::TITLE) + ->addAsColumn("product_ID", ProductTableMap::ID) + ->endUse() + ->addAsColumn("product_sale_elements_REF", ProductSaleElementsTableMap::REF) + ->addAsColumn("product_sale_elements_EAN_CODE", ProductSaleElementsTableMap::EAN_CODE) + ->addAsColumn("product_sale_elements_PROMO", ProductSaleElementsTableMap::PROMO) + ->endUse() + ->useAttributeAvQuery() + ->addJoinObject($attributeAvJoin, "attribute_av_join") + ->addJoinCondition( + "attribute_av_join", + AttributeAvI18nTableMap::LOCALE . " = ?", $locale, null, \PDO::PARAM_STR + ) + ->addAsColumn( + "attribute_av_i18n_ATTRIBUTES", + "GROUP_CONCAT(DISTINCT ".AttributeAvI18nTableMap::TITLE.")" + ) + ->endUse() + ->select([ + "product_sale_elements_REF", + "product_sale_elements_EAN_CODE", + "product_sale_elements_PROMO", + "price_PRICE", + "price_PROMO_PRICE", + "currency_CODE", + "product_TITLE", + "attribute_av_i18n_ATTRIBUTES", + ]) + ->groupBy("product_sale_elements_REF") + ; + + return $query; + } + + public function getOrder() + { + return [ + "product_id", + "ref", + "title", + "attributes", + "ean", + "price", + "promo_price", + "currency", + "promo", + ]; + } + + protected function getAliases() + { + return [ + "product_sale_elements_REF" => "ref", + "product_sale_elements_EAN_CODE" => "ean", + "price_PRICE" => "price", + "price_PROMO_PRICE" => "promo_price", + "currency_CODE" => "currency", + "product_TITLE" => "title", + "attribute_av_i18n_ATTRIBUTES" => "attributes", + "product_sale_elements_PROMO" => "promo", + ]; + } + +} diff --git a/core/lib/Thelia/ImportExport/Export/Type/ProductSEOExport.php b/core/lib/Thelia/ImportExport/Export/Type/ProductSEOExport.php new file mode 100644 index 000000000..ee04b12a0 --- /dev/null +++ b/core/lib/Thelia/ImportExport/Export/Type/ProductSEOExport.php @@ -0,0 +1,130 @@ + + */ +class ProductSEOExport extends ExportHandler +{ + /** + * @return string|array + * + * Define all the type of formatters that this can handle + * return a string if it handle a single type ( specific exports ), + * or an array if multiple. + * + * Thelia types are defined in \Thelia\Core\FileFormat\FormatType + * + * example: + * return array( + * FormatType::TABLE, + * FormatType::UNBOUNDED, + * ); + */ + public function getHandledTypes() + { + return array( + FormatType::TABLE, + FormatType::UNBOUNDED, + ); + } + + /** + * @param Lang $lang + * @return array|\Propel\Runtime\ActiveQuery\ModelCriteria + */ + public function buildDataSet(Lang $lang) + { + $locale = $this->locale = $lang->getLocale(); + + /** + * Join objects + */ + $urlJoin = new Join(ProductTableMap::ID, RewritingUrlTableMap::VIEW_ID, Criteria::LEFT_JOIN); + $productJoin = new Join(ProductTableMap::ID, ProductI18nTableMap::ID, Criteria::LEFT_JOIN); + + $query = ProductAssociatedContentQuery::create() + ->useProductQuery() + ->addJoinObject($productJoin, "product_join") + ->addJoinCondition("product_join", ProductI18nTableMap::LOCALE . " = ?", $locale, null, \PDO::PARAM_STR) + ->addAsColumn("product_i18n_TITLE", ProductI18nTableMap::TITLE) + ->addAsColumn("product_REF", ProductTableMap::REF) + ->addAsColumn("product_VISIBLE", ProductTableMap::VISIBLE) + ->addAsColumn("product_seo_TITLE", ProductI18nTableMap::META_TITLE) + ->addAsColumn("product_seo_META_DESCRIPTION", ProductI18nTableMap::META_DESCRIPTION) + ->addAsColumn("product_seo_META_KEYWORDS", ProductI18nTableMap::META_KEYWORDS) + ->endUse() + ->addJoinObject($urlJoin, "rewriting_url_join") + ->addJoinCondition("rewriting_url_join", RewritingUrlTableMap::VIEW_LOCALE . " = ?", $locale, null, \PDO::PARAM_STR) + ->addJoinCondition( + "rewriting_url_join", + RewritingUrlTableMap::VIEW . " = ?",(new Product())->getRewrittenUrlViewName(), + null, + \PDO::PARAM_STR + ) + ->addJoinCondition("rewriting_url_join", "ISNULL(".RewritingUrlTableMap::REDIRECTED.")") + ->addAsColumn("product_URL", RewritingUrlTableMap::URL) + ->select([ + "product_REF", + "product_VISIBLE", + "product_i18n_TITLE", + "product_URL", + "product_seo_TITLE", + "product_seo_META_DESCRIPTION", + "product_seo_META_KEYWORDS", + ]) + ; + + return $query; + } + + protected function getDefaultOrder() + { + return [ + "ref", + "product_title", + "visible", + "url", + "page_title", + "meta_description", + "meta_keywords", + ]; + } + + protected function getAliases() + { + return [ + "product_REF" => "ref", + "product_VISIBLE" => "visible", + "product_i18n_TITLE" => "product_title", + "product_URL" => "url", + "product_seo_TITLE" => "page_title", + "product_seo_META_DESCRIPTION" => "meta_description", + "product_seo_META_KEYWORDS" => "meta_keywords", + ]; + } + +} diff --git a/core/lib/Thelia/ImportExport/Export/Type/ProductTaxedPricesExport.php b/core/lib/Thelia/ImportExport/Export/Type/ProductTaxedPricesExport.php new file mode 100644 index 000000000..329b1f29c --- /dev/null +++ b/core/lib/Thelia/ImportExport/Export/Type/ProductTaxedPricesExport.php @@ -0,0 +1,98 @@ + + */ +class ProductTaxedPricesExport extends ProductPricesExport +{ + public function buildDataSet(Lang $lang) + { + /** @var \Thelia\Model\AttributeCombinationQuery $query */ + $query = parent::buildDataSet($lang); + + + $pseJoin = new Join(AttributeCombinationTableMap::PRODUCT_SALE_ELEMENTS_ID, ProductSaleElementsTableMap::ID); + $pseJoin->setRightTableAlias("pse_tax_join"); + + $productJoin = new Join(ProductSaleElementsTableMap::ID, ProductTableMap::ID); + $productJoin->setRightTableAlias("product_tax_join"); + + $taxJoin = new Join("`product_tax_join`.TAX_RULE_ID", TaxRuleTableMap::ID, Criteria::LEFT_JOIN); + $taxI18nJoin = new Join(TaxRuleTableMap::ID, TaxRuleI18nTableMap::ID, Criteria::LEFT_JOIN); + + $query + ->addJoinObject($pseJoin, "pse_tax_join") + ->addJoinObject($productJoin, "product_tax_join") + ->addJoinObject($productJoin) + ->addJoinObject($taxJoin) + ->addJoinObject($taxI18nJoin) + ->addAsColumn("product_TAX_TITLE", TaxRuleI18nTableMap::TITLE) + ->addAsColumn("tax_ID", TaxRuleTableMap::ID) + ->select($query->getSelect() + [ + "product_TAX_TITLE", + "tax_ID", + ]) + ; + + I18n::addI18nCondition( + $query, + TaxRuleI18nTableMap::TABLE_NAME, + TaxRuleTableMap::ID, + TaxRuleI18nTableMap::ID, + TaxRuleI18nTableMap::LOCALE, + $lang->getLocale() + ); + + $dataSet = $query + ->keepQuery(true) + ->find() + ->toArray() + ; + + $productSaleElements = ProductSaleElementsQuery::create() + ->find() + ->toKeyIndex("Ref") + ; + + $currencies = CurrencyQuery::create() + ->find() + ->toKeyIndex("Code") + ; + + foreach ($dataSet as &$line) { + /** @var \Thelia\Model\ProductSaleElements $pse */ + $pse = $productSaleElements[$line["product_sale_elements_REF"]]; + + $pricesTools = $pse->getPricesByCurrency($currencies[$line["currency_CODE"]]); + $line["price_PRICE"] = $pricesTools->getPrice(); + $line["price_PROMO_PRICE"] = $pricesTools->getPromoPrice(); + } + + return $dataSet; + } +} \ No newline at end of file diff --git a/core/lib/Thelia/ImportExport/Import/ImportHandler.php b/core/lib/Thelia/ImportExport/Import/ImportHandler.php new file mode 100644 index 000000000..f08d84d14 --- /dev/null +++ b/core/lib/Thelia/ImportExport/Import/ImportHandler.php @@ -0,0 +1,80 @@ + + */ +abstract class ImportHandler extends AbstractHandler +{ + protected $importedRows = 0; + + /** @var Translator */ + protected $translator; + + public function __construct(ContainerInterface $container) + { + $this->translator = Translator::getInstance(); + + parent::__construct($container); + } + + public function getImportedRows() + { + return $this->importedRows; + } + + protected function checkMandatoryColumns(array $row) + { + $mandatoryColumns = $this->getMandatoryColumns(); + sort($mandatoryColumns); + + $diff = []; + + foreach ($mandatoryColumns as $name) { + if (!isset($row[$name]) || empty($row[$name])) { + $diff[] = $name; + } + } + + if (!empty($diff)) { + throw new \UnexpectedValueException( + $this->translator->trans( + "The following columns are missing: %columns", + [ + "%columns" => implode(", ", $diff), + ] + ) + ); + } + } + + /** + * @return array The mandatory columns to have for import + */ + abstract protected function getMandatoryColumns(); + + /** + * @param \Thelia\Core\FileFormat\Formatting\FormatterData + * @return string|array error messages + * + * The method does the import routine from a FormatterData + */ + abstract public function retrieveFromFormatterData(FormatterData $data); +} diff --git a/core/lib/Thelia/ImportExport/Import/Type/ProductPricesImport.php b/core/lib/Thelia/ImportExport/Import/Type/ProductPricesImport.php new file mode 100644 index 000000000..3bd9405f0 --- /dev/null +++ b/core/lib/Thelia/ImportExport/Import/Type/ProductPricesImport.php @@ -0,0 +1,136 @@ + + */ +class ProductPricesImport extends ImportHandler +{ + /** + * @return string|array + * + * Define all the type of formatters that this can handle + * return a string if it handle a single type ( specific exports ), + * or an array if multiple. + * + * Thelia types are defined in \Thelia\Core\FileFormat\FormatType + * + * example: + * return array( + * FormatType::TABLE, + * FormatType::UNBOUNDED, + * ); + */ + public function getHandledTypes() + { + return array( + FormatType::TABLE, + FormatType::UNBOUNDED, + ); + } + + /** + * @param \Thelia\Core\FileFormat\Formatting\FormatterData + * @return string|array error messages + * + * The method does the import routine from a FormatterData + */ + public function retrieveFromFormatterData(FormatterData $data) + { + $errors = []; + $translator = Translator::getInstance(); + + while (null !== $row = $data->popRow()) { + + $this->checkMandatoryColumns($row); + + $obj = ProductSaleElementsQuery::create()->findOneByRef($row["ref"]); + + if ($obj === null) { + $errorMessage = $translator->trans( + "The product sale element reference %ref doesn't exist", + [ + "%ref" => $row["ref"] + ] + ); + + $errors[] = $errorMessage ; + } else { + + $currency = null; + + if (isset($row["currency"])) { + $currency = CurrencyQuery::create()->findOneByCode($row["currency"]); + } + + if ($currency === null) { + $currency = Currency::getDefaultCurrency(); + } + + $price = ProductPriceQuery::create() + ->filterByProductSaleElementsId($obj->getId()) + ->findOneByCurrencyId($currency->getId()) + ; + + if ($price === null) { + $price = new ProductPrice(); + + $price + ->setProductSaleElements($obj) + ->setCurrency($currency) + ; + } + + $price->setPrice($row["price"]); + + if (isset($row["promo_price"])) { + $price->setPromoPrice($row["promo_price"]); + } + + if (isset($row["promo"])) { + $price + ->getProductSaleElements() + ->setPromo((int) $row["promo"]) + ->save() + ; + } + + $price->save(); + $this->importedRows++; + } + } + + return $errors; + } + + /** + * @return array The mandatory columns to have for import + */ + protected function getMandatoryColumns() + { + return ["ref", "price"]; + } + +} diff --git a/core/lib/Thelia/ImportExport/Import/Type/ProductStockImport.php b/core/lib/Thelia/ImportExport/Import/Type/ProductStockImport.php new file mode 100644 index 000000000..b660b327d --- /dev/null +++ b/core/lib/Thelia/ImportExport/Import/Type/ProductStockImport.php @@ -0,0 +1,94 @@ + + */ +class ProductStockImport extends ImportHandler +{ + /** + * @param \Thelia\Core\FileFormat\Formatting\FormatterData + * @return string|array error messages + * + * The method does the import routine from a FormatterData + */ + public function retrieveFromFormatterData(FormatterData $data) + { + $errors = []; + + while (null !== $row = $data->popRow()) { + /** + * Check for mandatory columns + */ + $this->checkMandatoryColumns($row); + + $obj = ProductSaleElementsQuery::create()->findOneByRef($row["ref"]); + + if ($obj === null) { + $errors[] = $this->translator->trans( + "The product sale element reference %ref doesn't exist", + [ + "%ref" => $row["ref"] + ] + ); + } else { + $obj->setQuantity($row["stock"]); + + if (isset($row["ean"]) && !empty($row["ean"])) { + $obj->setEanCode($row["ean"]); + } + + $obj->save(); + $this->importedRows++; + } + } + + return $errors; + } + + protected function getMandatoryColumns() + { + return ["ref", "stock"]; + } + + /** + * @return string|array + * + * Define all the type of import/formatters that this can handle + * return a string if it handle a single type ( specific exports ), + * or an array if multiple. + * + * Thelia types are defined in \Thelia\Core\FileFormat\FormatType + * + * example: + * return array( + * FormatType::TABLE, + * FormatType::UNBOUNDED, + * ); + */ + public function getHandledTypes() + { + return array( + FormatType::TABLE, + FormatType::UNBOUNDED, + ); + } + +} diff --git a/core/lib/Thelia/Model/Base/Export.php b/core/lib/Thelia/Model/Base/Export.php new file mode 100644 index 000000000..304bccdcd --- /dev/null +++ b/core/lib/Thelia/Model/Base/Export.php @@ -0,0 +1,2000 @@ +modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another Export instance. If + * obj is an instance of Export, delegates to + * equals(Export). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return Export The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return Export The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [ref] column value. + * + * @return string + */ + public function getRef() + { + + return $this->ref; + } + + /** + * Get the [export_category_id] column value. + * + * @return int + */ + public function getExportCategoryId() + { + + return $this->export_category_id; + } + + /** + * Get the [position] column value. + * + * @return int + */ + public function getPosition() + { + + return $this->position; + } + + /** + * Get the [handle_class] column value. + * + * @return string + */ + public function getHandleClass() + { + + return $this->handle_class; + } + + /** + * Get the [optionally formatted] temporal [created_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getCreatedAt($format = NULL) + { + if ($format === null) { + return $this->created_at; + } else { + return $this->created_at instanceof \DateTime ? $this->created_at->format($format) : null; + } + } + + /** + * Get the [optionally formatted] temporal [updated_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getUpdatedAt($format = NULL) + { + if ($format === null) { + return $this->updated_at; + } else { + return $this->updated_at instanceof \DateTime ? $this->updated_at->format($format) : null; + } + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\Export The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ExportTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [ref] column. + * + * @param string $v new value + * @return \Thelia\Model\Export The current object (for fluent API support) + */ + public function setRef($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->ref !== $v) { + $this->ref = $v; + $this->modifiedColumns[ExportTableMap::REF] = true; + } + + + return $this; + } // setRef() + + /** + * Set the value of [export_category_id] column. + * + * @param int $v new value + * @return \Thelia\Model\Export The current object (for fluent API support) + */ + public function setExportCategoryId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->export_category_id !== $v) { + $this->export_category_id = $v; + $this->modifiedColumns[ExportTableMap::EXPORT_CATEGORY_ID] = true; + } + + if ($this->aExportCategory !== null && $this->aExportCategory->getId() !== $v) { + $this->aExportCategory = null; + } + + + return $this; + } // setExportCategoryId() + + /** + * Set the value of [position] column. + * + * @param int $v new value + * @return \Thelia\Model\Export The current object (for fluent API support) + */ + public function setPosition($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->position !== $v) { + $this->position = $v; + $this->modifiedColumns[ExportTableMap::POSITION] = true; + } + + + return $this; + } // setPosition() + + /** + * Set the value of [handle_class] column. + * + * @param string $v new value + * @return \Thelia\Model\Export The current object (for fluent API support) + */ + public function setHandleClass($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->handle_class !== $v) { + $this->handle_class = $v; + $this->modifiedColumns[ExportTableMap::HANDLE_CLASS] = true; + } + + + return $this; + } // setHandleClass() + + /** + * Sets the value of [created_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\Export The current object (for fluent API support) + */ + public function setCreatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->created_at !== null || $dt !== null) { + if ($dt !== $this->created_at) { + $this->created_at = $dt; + $this->modifiedColumns[ExportTableMap::CREATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setCreatedAt() + + /** + * Sets the value of [updated_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\Export The current object (for fluent API support) + */ + public function setUpdatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->updated_at !== null || $dt !== null) { + if ($dt !== $this->updated_at) { + $this->updated_at = $dt; + $this->modifiedColumns[ExportTableMap::UPDATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setUpdatedAt() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-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 array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ExportTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ExportTableMap::translateFieldName('Ref', TableMap::TYPE_PHPNAME, $indexType)]; + $this->ref = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ExportTableMap::translateFieldName('ExportCategoryId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->export_category_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ExportTableMap::translateFieldName('Position', TableMap::TYPE_PHPNAME, $indexType)]; + $this->position = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ExportTableMap::translateFieldName('HandleClass', TableMap::TYPE_PHPNAME, $indexType)]; + $this->handle_class = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ExportTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : ExportTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->updated_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 7; // 7 = ExportTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\Export object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aExportCategory !== null && $this->export_category_id !== $this->aExportCategory->getId()) { + $this->aExportCategory = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ExportTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildExportQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aExportCategory = null; + $this->collExportI18ns = null; + + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see Export::setDeleted() + * @see Export::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildExportQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $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(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + // timestampable behavior + if (!$this->isColumnModified(ExportTableMap::CREATED_AT)) { + $this->setCreatedAt(time()); + } + if (!$this->isColumnModified(ExportTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } else { + $ret = $ret && $this->preUpdate($con); + // timestampable behavior + if ($this->isModified() && !$this->isColumnModified(ExportTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ExportTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row 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 ConnectionInterface $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(ConnectionInterface $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 corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aExportCategory !== null) { + if ($this->aExportCategory->isModified() || $this->aExportCategory->isNew()) { + $affectedRows += $this->aExportCategory->save($con); + } + $this->setExportCategory($this->aExportCategory); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + if ($this->exportI18nsScheduledForDeletion !== null) { + if (!$this->exportI18nsScheduledForDeletion->isEmpty()) { + \Thelia\Model\ExportI18nQuery::create() + ->filterByPrimaryKeys($this->exportI18nsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->exportI18nsScheduledForDeletion = null; + } + } + + if ($this->collExportI18ns !== null) { + foreach ($this->collExportI18ns as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + $this->modifiedColumns[ExportTableMap::ID] = true; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . ExportTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ExportTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(ExportTableMap::REF)) { + $modifiedColumns[':p' . $index++] = '`REF`'; + } + if ($this->isColumnModified(ExportTableMap::EXPORT_CATEGORY_ID)) { + $modifiedColumns[':p' . $index++] = '`EXPORT_CATEGORY_ID`'; + } + if ($this->isColumnModified(ExportTableMap::POSITION)) { + $modifiedColumns[':p' . $index++] = '`POSITION`'; + } + if ($this->isColumnModified(ExportTableMap::HANDLE_CLASS)) { + $modifiedColumns[':p' . $index++] = '`HANDLE_CLASS`'; + } + if ($this->isColumnModified(ExportTableMap::CREATED_AT)) { + $modifiedColumns[':p' . $index++] = '`CREATED_AT`'; + } + if ($this->isColumnModified(ExportTableMap::UPDATED_AT)) { + $modifiedColumns[':p' . $index++] = '`UPDATED_AT`'; + } + + $sql = sprintf( + 'INSERT INTO `export` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`ID`': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case '`REF`': + $stmt->bindValue($identifier, $this->ref, PDO::PARAM_STR); + break; + case '`EXPORT_CATEGORY_ID`': + $stmt->bindValue($identifier, $this->export_category_id, PDO::PARAM_INT); + break; + case '`POSITION`': + $stmt->bindValue($identifier, $this->position, PDO::PARAM_INT); + break; + case '`HANDLE_CLASS`': + $stmt->bindValue($identifier, $this->handle_class, PDO::PARAM_STR); + break; + case '`CREATED_AT`': + $stmt->bindValue($identifier, $this->created_at ? $this->created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + case '`UPDATED_AT`': + $stmt->bindValue($identifier, $this->updated_at ? $this->updated_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + try { + $pk = $con->lastInsertId(); + } catch (Exception $e) { + throw new PropelException('Unable to get autoincrement id.', 0, $e); + } + $this->setId($pk); + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * 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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ExportTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * 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->getId(); + break; + case 1: + return $this->getRef(); + break; + case 2: + return $this->getExportCategoryId(); + break; + case 3: + return $this->getPosition(); + break; + case 4: + return $this->getHandleClass(); + break; + case 5: + return $this->getCreatedAt(); + break; + case 6: + return $this->getUpdatedAt(); + 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 (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['Export'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['Export'][$this->getPrimaryKey()] = true; + $keys = ExportTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getRef(), + $keys[2] => $this->getExportCategoryId(), + $keys[3] => $this->getPosition(), + $keys[4] => $this->getHandleClass(), + $keys[5] => $this->getCreatedAt(), + $keys[6] => $this->getUpdatedAt(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aExportCategory) { + $result['ExportCategory'] = $this->aExportCategory->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->collExportI18ns) { + $result['ExportI18ns'] = $this->collExportI18ns->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ExportTableMap::translateFieldName($name, $type, TableMap::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->setId($value); + break; + case 1: + $this->setRef($value); + break; + case 2: + $this->setExportCategoryId($value); + break; + case 3: + $this->setPosition($value); + break; + case 4: + $this->setHandleClass($value); + break; + case 5: + $this->setCreatedAt($value); + break; + case 6: + $this->setUpdatedAt($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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @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 = TableMap::TYPE_PHPNAME) + { + $keys = ExportTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setRef($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setExportCategoryId($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setPosition($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setHandleClass($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setCreatedAt($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setUpdatedAt($arr[$keys[6]]); + } + + /** + * 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(ExportTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ExportTableMap::ID)) $criteria->add(ExportTableMap::ID, $this->id); + if ($this->isColumnModified(ExportTableMap::REF)) $criteria->add(ExportTableMap::REF, $this->ref); + if ($this->isColumnModified(ExportTableMap::EXPORT_CATEGORY_ID)) $criteria->add(ExportTableMap::EXPORT_CATEGORY_ID, $this->export_category_id); + if ($this->isColumnModified(ExportTableMap::POSITION)) $criteria->add(ExportTableMap::POSITION, $this->position); + if ($this->isColumnModified(ExportTableMap::HANDLE_CLASS)) $criteria->add(ExportTableMap::HANDLE_CLASS, $this->handle_class); + if ($this->isColumnModified(ExportTableMap::CREATED_AT)) $criteria->add(ExportTableMap::CREATED_AT, $this->created_at); + if ($this->isColumnModified(ExportTableMap::UPDATED_AT)) $criteria->add(ExportTableMap::UPDATED_AT, $this->updated_at); + + 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(ExportTableMap::DATABASE_NAME); + $criteria->add(ExportTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * 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 \Thelia\Model\Export (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setRef($this->getRef()); + $copyObj->setExportCategoryId($this->getExportCategoryId()); + $copyObj->setPosition($this->getPosition()); + $copyObj->setHandleClass($this->getHandleClass()); + $copyObj->setCreatedAt($this->getCreatedAt()); + $copyObj->setUpdatedAt($this->getUpdatedAt()); + + if ($deepCopy) { + // important: temporarily setNew(false) because this affects the behavior of + // the getter/setter methods for fkey referrer objects. + $copyObj->setNew(false); + + foreach ($this->getExportI18ns() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addExportI18n($relObj->copy($deepCopy)); + } + } + + } // if ($deepCopy) + + if ($makeNew) { + $copyObj->setNew(true); + $copyObj->setId(NULL); // this is a auto-increment 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 \Thelia\Model\Export 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; + } + + /** + * Declares an association between this object and a ChildExportCategory object. + * + * @param ChildExportCategory $v + * @return \Thelia\Model\Export The current object (for fluent API support) + * @throws PropelException + */ + public function setExportCategory(ChildExportCategory $v = null) + { + if ($v === null) { + $this->setExportCategoryId(NULL); + } else { + $this->setExportCategoryId($v->getId()); + } + + $this->aExportCategory = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildExportCategory object, it will not be re-added. + if ($v !== null) { + $v->addExport($this); + } + + + return $this; + } + + + /** + * Get the associated ChildExportCategory object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildExportCategory The associated ChildExportCategory object. + * @throws PropelException + */ + public function getExportCategory(ConnectionInterface $con = null) + { + if ($this->aExportCategory === null && ($this->export_category_id !== null)) { + $this->aExportCategory = ChildExportCategoryQuery::create()->findPk($this->export_category_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aExportCategory->addExports($this); + */ + } + + return $this->aExportCategory; + } + + + /** + * Initializes a collection based on the name of a relation. + * Avoids crafting an 'init[$relationName]s' method name + * that wouldn't work when StandardEnglishPluralizer is used. + * + * @param string $relationName The name of the relation to initialize + * @return void + */ + public function initRelation($relationName) + { + if ('ExportI18n' == $relationName) { + return $this->initExportI18ns(); + } + } + + /** + * Clears out the collExportI18ns collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addExportI18ns() + */ + public function clearExportI18ns() + { + $this->collExportI18ns = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collExportI18ns collection loaded partially. + */ + public function resetPartialExportI18ns($v = true) + { + $this->collExportI18nsPartial = $v; + } + + /** + * Initializes the collExportI18ns collection. + * + * By default this just sets the collExportI18ns collection to an empty array (like clearcollExportI18ns()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initExportI18ns($overrideExisting = true) + { + if (null !== $this->collExportI18ns && !$overrideExisting) { + return; + } + $this->collExportI18ns = new ObjectCollection(); + $this->collExportI18ns->setModel('\Thelia\Model\ExportI18n'); + } + + /** + * Gets an array of ChildExportI18n objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildExport is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildExportI18n[] List of ChildExportI18n objects + * @throws PropelException + */ + public function getExportI18ns($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collExportI18nsPartial && !$this->isNew(); + if (null === $this->collExportI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collExportI18ns) { + // return empty collection + $this->initExportI18ns(); + } else { + $collExportI18ns = ChildExportI18nQuery::create(null, $criteria) + ->filterByExport($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collExportI18nsPartial && count($collExportI18ns)) { + $this->initExportI18ns(false); + + foreach ($collExportI18ns as $obj) { + if (false == $this->collExportI18ns->contains($obj)) { + $this->collExportI18ns->append($obj); + } + } + + $this->collExportI18nsPartial = true; + } + + reset($collExportI18ns); + + return $collExportI18ns; + } + + if ($partial && $this->collExportI18ns) { + foreach ($this->collExportI18ns as $obj) { + if ($obj->isNew()) { + $collExportI18ns[] = $obj; + } + } + } + + $this->collExportI18ns = $collExportI18ns; + $this->collExportI18nsPartial = false; + } + } + + return $this->collExportI18ns; + } + + /** + * Sets a collection of ExportI18n objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $exportI18ns A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildExport The current object (for fluent API support) + */ + public function setExportI18ns(Collection $exportI18ns, ConnectionInterface $con = null) + { + $exportI18nsToDelete = $this->getExportI18ns(new Criteria(), $con)->diff($exportI18ns); + + + //since at least one column in the foreign key is at the same time a PK + //we can not just set a PK to NULL in the lines below. We have to store + //a backup of all values, so we are able to manipulate these items based on the onDelete value later. + $this->exportI18nsScheduledForDeletion = clone $exportI18nsToDelete; + + foreach ($exportI18nsToDelete as $exportI18nRemoved) { + $exportI18nRemoved->setExport(null); + } + + $this->collExportI18ns = null; + foreach ($exportI18ns as $exportI18n) { + $this->addExportI18n($exportI18n); + } + + $this->collExportI18ns = $exportI18ns; + $this->collExportI18nsPartial = false; + + return $this; + } + + /** + * Returns the number of related ExportI18n objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related ExportI18n objects. + * @throws PropelException + */ + public function countExportI18ns(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collExportI18nsPartial && !$this->isNew(); + if (null === $this->collExportI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collExportI18ns) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getExportI18ns()); + } + + $query = ChildExportI18nQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByExport($this) + ->count($con); + } + + return count($this->collExportI18ns); + } + + /** + * Method called to associate a ChildExportI18n object to this object + * through the ChildExportI18n foreign key attribute. + * + * @param ChildExportI18n $l ChildExportI18n + * @return \Thelia\Model\Export The current object (for fluent API support) + */ + public function addExportI18n(ChildExportI18n $l) + { + if ($l && $locale = $l->getLocale()) { + $this->setLocale($locale); + $this->currentTranslations[$locale] = $l; + } + if ($this->collExportI18ns === null) { + $this->initExportI18ns(); + $this->collExportI18nsPartial = true; + } + + if (!in_array($l, $this->collExportI18ns->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddExportI18n($l); + } + + return $this; + } + + /** + * @param ExportI18n $exportI18n The exportI18n object to add. + */ + protected function doAddExportI18n($exportI18n) + { + $this->collExportI18ns[]= $exportI18n; + $exportI18n->setExport($this); + } + + /** + * @param ExportI18n $exportI18n The exportI18n object to remove. + * @return ChildExport The current object (for fluent API support) + */ + public function removeExportI18n($exportI18n) + { + if ($this->getExportI18ns()->contains($exportI18n)) { + $this->collExportI18ns->remove($this->collExportI18ns->search($exportI18n)); + if (null === $this->exportI18nsScheduledForDeletion) { + $this->exportI18nsScheduledForDeletion = clone $this->collExportI18ns; + $this->exportI18nsScheduledForDeletion->clear(); + } + $this->exportI18nsScheduledForDeletion[]= clone $exportI18n; + $exportI18n->setExport(null); + } + + return $this; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->ref = null; + $this->export_category_id = null; + $this->position = null; + $this->handle_class = null; + $this->created_at = null; + $this->updated_at = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + if ($this->collExportI18ns) { + foreach ($this->collExportI18ns as $o) { + $o->clearAllReferences($deep); + } + } + } // if ($deep) + + // i18n behavior + $this->currentLocale = 'en_US'; + $this->currentTranslations = null; + + $this->collExportI18ns = null; + $this->aExportCategory = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ExportTableMap::DEFAULT_STRING_FORMAT); + } + + // i18n behavior + + /** + * Sets the locale for translations + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * + * @return ChildExport The current object (for fluent API support) + */ + public function setLocale($locale = 'en_US') + { + $this->currentLocale = $locale; + + return $this; + } + + /** + * Gets the locale for translations + * + * @return string $locale Locale to use for the translation, e.g. 'fr_FR' + */ + public function getLocale() + { + return $this->currentLocale; + } + + /** + * Returns the current translation for a given locale + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * @param ConnectionInterface $con an optional connection object + * + * @return ChildExportI18n */ + public function getTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!isset($this->currentTranslations[$locale])) { + if (null !== $this->collExportI18ns) { + foreach ($this->collExportI18ns as $translation) { + if ($translation->getLocale() == $locale) { + $this->currentTranslations[$locale] = $translation; + + return $translation; + } + } + } + if ($this->isNew()) { + $translation = new ChildExportI18n(); + $translation->setLocale($locale); + } else { + $translation = ChildExportI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->findOneOrCreate($con); + $this->currentTranslations[$locale] = $translation; + } + $this->addExportI18n($translation); + } + + return $this->currentTranslations[$locale]; + } + + /** + * Remove the translation for a given locale + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * @param ConnectionInterface $con an optional connection object + * + * @return ChildExport The current object (for fluent API support) + */ + public function removeTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!$this->isNew()) { + ChildExportI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->delete($con); + } + if (isset($this->currentTranslations[$locale])) { + unset($this->currentTranslations[$locale]); + } + foreach ($this->collExportI18ns as $key => $translation) { + if ($translation->getLocale() == $locale) { + unset($this->collExportI18ns[$key]); + break; + } + } + + return $this; + } + + /** + * Returns the current translation + * + * @param ConnectionInterface $con an optional connection object + * + * @return ChildExportI18n */ + public function getCurrentTranslation(ConnectionInterface $con = null) + { + return $this->getTranslation($this->getLocale(), $con); + } + + + /** + * Get the [title] column value. + * + * @return string + */ + public function getTitle() + { + return $this->getCurrentTranslation()->getTitle(); + } + + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\ExportI18n The current object (for fluent API support) + */ + public function setTitle($v) + { $this->getCurrentTranslation()->setTitle($v); + + return $this; + } + + + /** + * Get the [description] column value. + * + * @return string + */ + public function getDescription() + { + return $this->getCurrentTranslation()->getDescription(); + } + + + /** + * Set the value of [description] column. + * + * @param string $v new value + * @return \Thelia\Model\ExportI18n The current object (for fluent API support) + */ + public function setDescription($v) + { $this->getCurrentTranslation()->setDescription($v); + + return $this; + } + + // timestampable behavior + + /** + * Mark the current object so that the update date doesn't get updated during next save + * + * @return ChildExport The current object (for fluent API support) + */ + public function keepUpdateDateUnchanged() + { + $this->modifiedColumns[ExportTableMap::UPDATED_AT] = true; + + return $this; + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/ExportCategory.php b/core/lib/Thelia/Model/Base/ExportCategory.php new file mode 100644 index 000000000..6f7ce72ec --- /dev/null +++ b/core/lib/Thelia/Model/Base/ExportCategory.php @@ -0,0 +1,2047 @@ +modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ExportCategory instance. If + * obj is an instance of ExportCategory, delegates to + * equals(ExportCategory). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ExportCategory The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ExportCategory The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [ref] column value. + * + * @return string + */ + public function getRef() + { + + return $this->ref; + } + + /** + * Get the [position] column value. + * + * @return int + */ + public function getPosition() + { + + return $this->position; + } + + /** + * Get the [optionally formatted] temporal [created_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getCreatedAt($format = NULL) + { + if ($format === null) { + return $this->created_at; + } else { + return $this->created_at instanceof \DateTime ? $this->created_at->format($format) : null; + } + } + + /** + * Get the [optionally formatted] temporal [updated_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getUpdatedAt($format = NULL) + { + if ($format === null) { + return $this->updated_at; + } else { + return $this->updated_at instanceof \DateTime ? $this->updated_at->format($format) : null; + } + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\ExportCategory The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ExportCategoryTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [ref] column. + * + * @param string $v new value + * @return \Thelia\Model\ExportCategory The current object (for fluent API support) + */ + public function setRef($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->ref !== $v) { + $this->ref = $v; + $this->modifiedColumns[ExportCategoryTableMap::REF] = true; + } + + + return $this; + } // setRef() + + /** + * Set the value of [position] column. + * + * @param int $v new value + * @return \Thelia\Model\ExportCategory The current object (for fluent API support) + */ + public function setPosition($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->position !== $v) { + $this->position = $v; + $this->modifiedColumns[ExportCategoryTableMap::POSITION] = true; + } + + + return $this; + } // setPosition() + + /** + * Sets the value of [created_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\ExportCategory The current object (for fluent API support) + */ + public function setCreatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->created_at !== null || $dt !== null) { + if ($dt !== $this->created_at) { + $this->created_at = $dt; + $this->modifiedColumns[ExportCategoryTableMap::CREATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setCreatedAt() + + /** + * Sets the value of [updated_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\ExportCategory The current object (for fluent API support) + */ + public function setUpdatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->updated_at !== null || $dt !== null) { + if ($dt !== $this->updated_at) { + $this->updated_at = $dt; + $this->modifiedColumns[ExportCategoryTableMap::UPDATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setUpdatedAt() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-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 array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ExportCategoryTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ExportCategoryTableMap::translateFieldName('Ref', TableMap::TYPE_PHPNAME, $indexType)]; + $this->ref = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ExportCategoryTableMap::translateFieldName('Position', TableMap::TYPE_PHPNAME, $indexType)]; + $this->position = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ExportCategoryTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ExportCategoryTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->updated_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 5; // 5 = ExportCategoryTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\ExportCategory object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ExportCategoryTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildExportCategoryQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->collExports = null; + + $this->collExportCategoryI18ns = null; + + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ExportCategory::setDeleted() + * @see ExportCategory::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportCategoryTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildExportCategoryQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $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(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportCategoryTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + // timestampable behavior + if (!$this->isColumnModified(ExportCategoryTableMap::CREATED_AT)) { + $this->setCreatedAt(time()); + } + if (!$this->isColumnModified(ExportCategoryTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } else { + $ret = $ret && $this->preUpdate($con); + // timestampable behavior + if ($this->isModified() && !$this->isColumnModified(ExportCategoryTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ExportCategoryTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row 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 ConnectionInterface $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(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + if ($this->exportsScheduledForDeletion !== null) { + if (!$this->exportsScheduledForDeletion->isEmpty()) { + \Thelia\Model\ExportQuery::create() + ->filterByPrimaryKeys($this->exportsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->exportsScheduledForDeletion = null; + } + } + + if ($this->collExports !== null) { + foreach ($this->collExports as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->exportCategoryI18nsScheduledForDeletion !== null) { + if (!$this->exportCategoryI18nsScheduledForDeletion->isEmpty()) { + \Thelia\Model\ExportCategoryI18nQuery::create() + ->filterByPrimaryKeys($this->exportCategoryI18nsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->exportCategoryI18nsScheduledForDeletion = null; + } + } + + if ($this->collExportCategoryI18ns !== null) { + foreach ($this->collExportCategoryI18ns as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + $this->modifiedColumns[ExportCategoryTableMap::ID] = true; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . ExportCategoryTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ExportCategoryTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(ExportCategoryTableMap::REF)) { + $modifiedColumns[':p' . $index++] = '`REF`'; + } + if ($this->isColumnModified(ExportCategoryTableMap::POSITION)) { + $modifiedColumns[':p' . $index++] = '`POSITION`'; + } + if ($this->isColumnModified(ExportCategoryTableMap::CREATED_AT)) { + $modifiedColumns[':p' . $index++] = '`CREATED_AT`'; + } + if ($this->isColumnModified(ExportCategoryTableMap::UPDATED_AT)) { + $modifiedColumns[':p' . $index++] = '`UPDATED_AT`'; + } + + $sql = sprintf( + 'INSERT INTO `export_category` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`ID`': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case '`REF`': + $stmt->bindValue($identifier, $this->ref, PDO::PARAM_STR); + break; + case '`POSITION`': + $stmt->bindValue($identifier, $this->position, PDO::PARAM_INT); + break; + case '`CREATED_AT`': + $stmt->bindValue($identifier, $this->created_at ? $this->created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + case '`UPDATED_AT`': + $stmt->bindValue($identifier, $this->updated_at ? $this->updated_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + try { + $pk = $con->lastInsertId(); + } catch (Exception $e) { + throw new PropelException('Unable to get autoincrement id.', 0, $e); + } + $this->setId($pk); + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * 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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ExportCategoryTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * 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->getId(); + break; + case 1: + return $this->getRef(); + break; + case 2: + return $this->getPosition(); + break; + case 3: + return $this->getCreatedAt(); + break; + case 4: + return $this->getUpdatedAt(); + 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 (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['ExportCategory'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ExportCategory'][$this->getPrimaryKey()] = true; + $keys = ExportCategoryTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getRef(), + $keys[2] => $this->getPosition(), + $keys[3] => $this->getCreatedAt(), + $keys[4] => $this->getUpdatedAt(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->collExports) { + $result['Exports'] = $this->collExports->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collExportCategoryI18ns) { + $result['ExportCategoryI18ns'] = $this->collExportCategoryI18ns->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ExportCategoryTableMap::translateFieldName($name, $type, TableMap::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->setId($value); + break; + case 1: + $this->setRef($value); + break; + case 2: + $this->setPosition($value); + break; + case 3: + $this->setCreatedAt($value); + break; + case 4: + $this->setUpdatedAt($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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @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 = TableMap::TYPE_PHPNAME) + { + $keys = ExportCategoryTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setRef($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setPosition($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setCreatedAt($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setUpdatedAt($arr[$keys[4]]); + } + + /** + * 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(ExportCategoryTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ExportCategoryTableMap::ID)) $criteria->add(ExportCategoryTableMap::ID, $this->id); + if ($this->isColumnModified(ExportCategoryTableMap::REF)) $criteria->add(ExportCategoryTableMap::REF, $this->ref); + if ($this->isColumnModified(ExportCategoryTableMap::POSITION)) $criteria->add(ExportCategoryTableMap::POSITION, $this->position); + if ($this->isColumnModified(ExportCategoryTableMap::CREATED_AT)) $criteria->add(ExportCategoryTableMap::CREATED_AT, $this->created_at); + if ($this->isColumnModified(ExportCategoryTableMap::UPDATED_AT)) $criteria->add(ExportCategoryTableMap::UPDATED_AT, $this->updated_at); + + 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(ExportCategoryTableMap::DATABASE_NAME); + $criteria->add(ExportCategoryTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * 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 \Thelia\Model\ExportCategory (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setRef($this->getRef()); + $copyObj->setPosition($this->getPosition()); + $copyObj->setCreatedAt($this->getCreatedAt()); + $copyObj->setUpdatedAt($this->getUpdatedAt()); + + if ($deepCopy) { + // important: temporarily setNew(false) because this affects the behavior of + // the getter/setter methods for fkey referrer objects. + $copyObj->setNew(false); + + foreach ($this->getExports() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addExport($relObj->copy($deepCopy)); + } + } + + foreach ($this->getExportCategoryI18ns() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addExportCategoryI18n($relObj->copy($deepCopy)); + } + } + + } // if ($deepCopy) + + if ($makeNew) { + $copyObj->setNew(true); + $copyObj->setId(NULL); // this is a auto-increment 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 \Thelia\Model\ExportCategory 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; + } + + + /** + * Initializes a collection based on the name of a relation. + * Avoids crafting an 'init[$relationName]s' method name + * that wouldn't work when StandardEnglishPluralizer is used. + * + * @param string $relationName The name of the relation to initialize + * @return void + */ + public function initRelation($relationName) + { + if ('Export' == $relationName) { + return $this->initExports(); + } + if ('ExportCategoryI18n' == $relationName) { + return $this->initExportCategoryI18ns(); + } + } + + /** + * Clears out the collExports collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addExports() + */ + public function clearExports() + { + $this->collExports = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collExports collection loaded partially. + */ + public function resetPartialExports($v = true) + { + $this->collExportsPartial = $v; + } + + /** + * Initializes the collExports collection. + * + * By default this just sets the collExports collection to an empty array (like clearcollExports()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initExports($overrideExisting = true) + { + if (null !== $this->collExports && !$overrideExisting) { + return; + } + $this->collExports = new ObjectCollection(); + $this->collExports->setModel('\Thelia\Model\Export'); + } + + /** + * Gets an array of ChildExport objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildExportCategory is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildExport[] List of ChildExport objects + * @throws PropelException + */ + public function getExports($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collExportsPartial && !$this->isNew(); + if (null === $this->collExports || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collExports) { + // return empty collection + $this->initExports(); + } else { + $collExports = ChildExportQuery::create(null, $criteria) + ->filterByExportCategory($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collExportsPartial && count($collExports)) { + $this->initExports(false); + + foreach ($collExports as $obj) { + if (false == $this->collExports->contains($obj)) { + $this->collExports->append($obj); + } + } + + $this->collExportsPartial = true; + } + + reset($collExports); + + return $collExports; + } + + if ($partial && $this->collExports) { + foreach ($this->collExports as $obj) { + if ($obj->isNew()) { + $collExports[] = $obj; + } + } + } + + $this->collExports = $collExports; + $this->collExportsPartial = false; + } + } + + return $this->collExports; + } + + /** + * Sets a collection of Export objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $exports A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildExportCategory The current object (for fluent API support) + */ + public function setExports(Collection $exports, ConnectionInterface $con = null) + { + $exportsToDelete = $this->getExports(new Criteria(), $con)->diff($exports); + + + $this->exportsScheduledForDeletion = $exportsToDelete; + + foreach ($exportsToDelete as $exportRemoved) { + $exportRemoved->setExportCategory(null); + } + + $this->collExports = null; + foreach ($exports as $export) { + $this->addExport($export); + } + + $this->collExports = $exports; + $this->collExportsPartial = false; + + return $this; + } + + /** + * Returns the number of related Export objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related Export objects. + * @throws PropelException + */ + public function countExports(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collExportsPartial && !$this->isNew(); + if (null === $this->collExports || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collExports) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getExports()); + } + + $query = ChildExportQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByExportCategory($this) + ->count($con); + } + + return count($this->collExports); + } + + /** + * Method called to associate a ChildExport object to this object + * through the ChildExport foreign key attribute. + * + * @param ChildExport $l ChildExport + * @return \Thelia\Model\ExportCategory The current object (for fluent API support) + */ + public function addExport(ChildExport $l) + { + if ($this->collExports === null) { + $this->initExports(); + $this->collExportsPartial = true; + } + + if (!in_array($l, $this->collExports->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddExport($l); + } + + return $this; + } + + /** + * @param Export $export The export object to add. + */ + protected function doAddExport($export) + { + $this->collExports[]= $export; + $export->setExportCategory($this); + } + + /** + * @param Export $export The export object to remove. + * @return ChildExportCategory The current object (for fluent API support) + */ + public function removeExport($export) + { + if ($this->getExports()->contains($export)) { + $this->collExports->remove($this->collExports->search($export)); + if (null === $this->exportsScheduledForDeletion) { + $this->exportsScheduledForDeletion = clone $this->collExports; + $this->exportsScheduledForDeletion->clear(); + } + $this->exportsScheduledForDeletion[]= clone $export; + $export->setExportCategory(null); + } + + return $this; + } + + /** + * Clears out the collExportCategoryI18ns collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addExportCategoryI18ns() + */ + public function clearExportCategoryI18ns() + { + $this->collExportCategoryI18ns = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collExportCategoryI18ns collection loaded partially. + */ + public function resetPartialExportCategoryI18ns($v = true) + { + $this->collExportCategoryI18nsPartial = $v; + } + + /** + * Initializes the collExportCategoryI18ns collection. + * + * By default this just sets the collExportCategoryI18ns collection to an empty array (like clearcollExportCategoryI18ns()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initExportCategoryI18ns($overrideExisting = true) + { + if (null !== $this->collExportCategoryI18ns && !$overrideExisting) { + return; + } + $this->collExportCategoryI18ns = new ObjectCollection(); + $this->collExportCategoryI18ns->setModel('\Thelia\Model\ExportCategoryI18n'); + } + + /** + * Gets an array of ChildExportCategoryI18n objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildExportCategory is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildExportCategoryI18n[] List of ChildExportCategoryI18n objects + * @throws PropelException + */ + public function getExportCategoryI18ns($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collExportCategoryI18nsPartial && !$this->isNew(); + if (null === $this->collExportCategoryI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collExportCategoryI18ns) { + // return empty collection + $this->initExportCategoryI18ns(); + } else { + $collExportCategoryI18ns = ChildExportCategoryI18nQuery::create(null, $criteria) + ->filterByExportCategory($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collExportCategoryI18nsPartial && count($collExportCategoryI18ns)) { + $this->initExportCategoryI18ns(false); + + foreach ($collExportCategoryI18ns as $obj) { + if (false == $this->collExportCategoryI18ns->contains($obj)) { + $this->collExportCategoryI18ns->append($obj); + } + } + + $this->collExportCategoryI18nsPartial = true; + } + + reset($collExportCategoryI18ns); + + return $collExportCategoryI18ns; + } + + if ($partial && $this->collExportCategoryI18ns) { + foreach ($this->collExportCategoryI18ns as $obj) { + if ($obj->isNew()) { + $collExportCategoryI18ns[] = $obj; + } + } + } + + $this->collExportCategoryI18ns = $collExportCategoryI18ns; + $this->collExportCategoryI18nsPartial = false; + } + } + + return $this->collExportCategoryI18ns; + } + + /** + * Sets a collection of ExportCategoryI18n objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $exportCategoryI18ns A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildExportCategory The current object (for fluent API support) + */ + public function setExportCategoryI18ns(Collection $exportCategoryI18ns, ConnectionInterface $con = null) + { + $exportCategoryI18nsToDelete = $this->getExportCategoryI18ns(new Criteria(), $con)->diff($exportCategoryI18ns); + + + //since at least one column in the foreign key is at the same time a PK + //we can not just set a PK to NULL in the lines below. We have to store + //a backup of all values, so we are able to manipulate these items based on the onDelete value later. + $this->exportCategoryI18nsScheduledForDeletion = clone $exportCategoryI18nsToDelete; + + foreach ($exportCategoryI18nsToDelete as $exportCategoryI18nRemoved) { + $exportCategoryI18nRemoved->setExportCategory(null); + } + + $this->collExportCategoryI18ns = null; + foreach ($exportCategoryI18ns as $exportCategoryI18n) { + $this->addExportCategoryI18n($exportCategoryI18n); + } + + $this->collExportCategoryI18ns = $exportCategoryI18ns; + $this->collExportCategoryI18nsPartial = false; + + return $this; + } + + /** + * Returns the number of related ExportCategoryI18n objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related ExportCategoryI18n objects. + * @throws PropelException + */ + public function countExportCategoryI18ns(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collExportCategoryI18nsPartial && !$this->isNew(); + if (null === $this->collExportCategoryI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collExportCategoryI18ns) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getExportCategoryI18ns()); + } + + $query = ChildExportCategoryI18nQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByExportCategory($this) + ->count($con); + } + + return count($this->collExportCategoryI18ns); + } + + /** + * Method called to associate a ChildExportCategoryI18n object to this object + * through the ChildExportCategoryI18n foreign key attribute. + * + * @param ChildExportCategoryI18n $l ChildExportCategoryI18n + * @return \Thelia\Model\ExportCategory The current object (for fluent API support) + */ + public function addExportCategoryI18n(ChildExportCategoryI18n $l) + { + if ($l && $locale = $l->getLocale()) { + $this->setLocale($locale); + $this->currentTranslations[$locale] = $l; + } + if ($this->collExportCategoryI18ns === null) { + $this->initExportCategoryI18ns(); + $this->collExportCategoryI18nsPartial = true; + } + + if (!in_array($l, $this->collExportCategoryI18ns->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddExportCategoryI18n($l); + } + + return $this; + } + + /** + * @param ExportCategoryI18n $exportCategoryI18n The exportCategoryI18n object to add. + */ + protected function doAddExportCategoryI18n($exportCategoryI18n) + { + $this->collExportCategoryI18ns[]= $exportCategoryI18n; + $exportCategoryI18n->setExportCategory($this); + } + + /** + * @param ExportCategoryI18n $exportCategoryI18n The exportCategoryI18n object to remove. + * @return ChildExportCategory The current object (for fluent API support) + */ + public function removeExportCategoryI18n($exportCategoryI18n) + { + if ($this->getExportCategoryI18ns()->contains($exportCategoryI18n)) { + $this->collExportCategoryI18ns->remove($this->collExportCategoryI18ns->search($exportCategoryI18n)); + if (null === $this->exportCategoryI18nsScheduledForDeletion) { + $this->exportCategoryI18nsScheduledForDeletion = clone $this->collExportCategoryI18ns; + $this->exportCategoryI18nsScheduledForDeletion->clear(); + } + $this->exportCategoryI18nsScheduledForDeletion[]= clone $exportCategoryI18n; + $exportCategoryI18n->setExportCategory(null); + } + + return $this; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->ref = null; + $this->position = null; + $this->created_at = null; + $this->updated_at = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + if ($this->collExports) { + foreach ($this->collExports as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collExportCategoryI18ns) { + foreach ($this->collExportCategoryI18ns as $o) { + $o->clearAllReferences($deep); + } + } + } // if ($deep) + + // i18n behavior + $this->currentLocale = 'en_US'; + $this->currentTranslations = null; + + $this->collExports = null; + $this->collExportCategoryI18ns = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ExportCategoryTableMap::DEFAULT_STRING_FORMAT); + } + + // i18n behavior + + /** + * Sets the locale for translations + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * + * @return ChildExportCategory The current object (for fluent API support) + */ + public function setLocale($locale = 'en_US') + { + $this->currentLocale = $locale; + + return $this; + } + + /** + * Gets the locale for translations + * + * @return string $locale Locale to use for the translation, e.g. 'fr_FR' + */ + public function getLocale() + { + return $this->currentLocale; + } + + /** + * Returns the current translation for a given locale + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * @param ConnectionInterface $con an optional connection object + * + * @return ChildExportCategoryI18n */ + public function getTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!isset($this->currentTranslations[$locale])) { + if (null !== $this->collExportCategoryI18ns) { + foreach ($this->collExportCategoryI18ns as $translation) { + if ($translation->getLocale() == $locale) { + $this->currentTranslations[$locale] = $translation; + + return $translation; + } + } + } + if ($this->isNew()) { + $translation = new ChildExportCategoryI18n(); + $translation->setLocale($locale); + } else { + $translation = ChildExportCategoryI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->findOneOrCreate($con); + $this->currentTranslations[$locale] = $translation; + } + $this->addExportCategoryI18n($translation); + } + + return $this->currentTranslations[$locale]; + } + + /** + * Remove the translation for a given locale + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * @param ConnectionInterface $con an optional connection object + * + * @return ChildExportCategory The current object (for fluent API support) + */ + public function removeTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!$this->isNew()) { + ChildExportCategoryI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->delete($con); + } + if (isset($this->currentTranslations[$locale])) { + unset($this->currentTranslations[$locale]); + } + foreach ($this->collExportCategoryI18ns as $key => $translation) { + if ($translation->getLocale() == $locale) { + unset($this->collExportCategoryI18ns[$key]); + break; + } + } + + return $this; + } + + /** + * Returns the current translation + * + * @param ConnectionInterface $con an optional connection object + * + * @return ChildExportCategoryI18n */ + public function getCurrentTranslation(ConnectionInterface $con = null) + { + return $this->getTranslation($this->getLocale(), $con); + } + + + /** + * Get the [title] column value. + * + * @return string + */ + public function getTitle() + { + return $this->getCurrentTranslation()->getTitle(); + } + + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\ExportCategoryI18n The current object (for fluent API support) + */ + public function setTitle($v) + { $this->getCurrentTranslation()->setTitle($v); + + return $this; + } + + // timestampable behavior + + /** + * Mark the current object so that the update date doesn't get updated during next save + * + * @return ChildExportCategory The current object (for fluent API support) + */ + public function keepUpdateDateUnchanged() + { + $this->modifiedColumns[ExportCategoryTableMap::UPDATED_AT] = true; + + return $this; + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/ExportCategoryI18n.php b/core/lib/Thelia/Model/Base/ExportCategoryI18n.php new file mode 100644 index 000000000..761f8239c --- /dev/null +++ b/core/lib/Thelia/Model/Base/ExportCategoryI18n.php @@ -0,0 +1,1268 @@ +locale = 'en_US'; + } + + /** + * Initializes internal state of Thelia\Model\Base\ExportCategoryI18n object. + * @see applyDefaults() + */ + public function __construct() + { + $this->applyDefaultValues(); + } + + /** + * Returns whether the object has been modified. + * + * @return boolean True if the object has been modified. + */ + public function isModified() + { + return !!$this->modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ExportCategoryI18n instance. If + * obj is an instance of ExportCategoryI18n, delegates to + * equals(ExportCategoryI18n). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ExportCategoryI18n The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ExportCategoryI18n The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [locale] column value. + * + * @return string + */ + public function getLocale() + { + + return $this->locale; + } + + /** + * Get the [title] column value. + * + * @return string + */ + public function getTitle() + { + + return $this->title; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\ExportCategoryI18n The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ExportCategoryI18nTableMap::ID] = true; + } + + if ($this->aExportCategory !== null && $this->aExportCategory->getId() !== $v) { + $this->aExportCategory = null; + } + + + return $this; + } // setId() + + /** + * Set the value of [locale] column. + * + * @param string $v new value + * @return \Thelia\Model\ExportCategoryI18n The current object (for fluent API support) + */ + public function setLocale($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->locale !== $v) { + $this->locale = $v; + $this->modifiedColumns[ExportCategoryI18nTableMap::LOCALE] = true; + } + + + return $this; + } // setLocale() + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\ExportCategoryI18n The current object (for fluent API support) + */ + public function setTitle($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->title !== $v) { + $this->title = $v; + $this->modifiedColumns[ExportCategoryI18nTableMap::TITLE] = true; + } + + + return $this; + } // setTitle() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->locale !== 'en_US') { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-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 array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ExportCategoryI18nTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ExportCategoryI18nTableMap::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)]; + $this->locale = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ExportCategoryI18nTableMap::translateFieldName('Title', TableMap::TYPE_PHPNAME, $indexType)]; + $this->title = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 3; // 3 = ExportCategoryI18nTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\ExportCategoryI18n object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aExportCategory !== null && $this->id !== $this->aExportCategory->getId()) { + $this->aExportCategory = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ExportCategoryI18nTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildExportCategoryI18nQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aExportCategory = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ExportCategoryI18n::setDeleted() + * @see ExportCategoryI18n::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportCategoryI18nTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildExportCategoryI18nQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $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(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportCategoryI18nTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ExportCategoryI18nTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row 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 ConnectionInterface $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(ConnectionInterface $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 corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aExportCategory !== null) { + if ($this->aExportCategory->isModified() || $this->aExportCategory->isNew()) { + $affectedRows += $this->aExportCategory->save($con); + } + $this->setExportCategory($this->aExportCategory); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ExportCategoryI18nTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(ExportCategoryI18nTableMap::LOCALE)) { + $modifiedColumns[':p' . $index++] = '`LOCALE`'; + } + if ($this->isColumnModified(ExportCategoryI18nTableMap::TITLE)) { + $modifiedColumns[':p' . $index++] = '`TITLE`'; + } + + $sql = sprintf( + 'INSERT INTO `export_category_i18n` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`ID`': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case '`LOCALE`': + $stmt->bindValue($identifier, $this->locale, PDO::PARAM_STR); + break; + case '`TITLE`': + $stmt->bindValue($identifier, $this->title, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * 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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ExportCategoryI18nTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * 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->getId(); + break; + case 1: + return $this->getLocale(); + break; + case 2: + return $this->getTitle(); + 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 (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['ExportCategoryI18n'][serialize($this->getPrimaryKey())])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ExportCategoryI18n'][serialize($this->getPrimaryKey())] = true; + $keys = ExportCategoryI18nTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getLocale(), + $keys[2] => $this->getTitle(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aExportCategory) { + $result['ExportCategory'] = $this->aExportCategory->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ExportCategoryI18nTableMap::translateFieldName($name, $type, TableMap::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->setId($value); + break; + case 1: + $this->setLocale($value); + break; + case 2: + $this->setTitle($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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @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 = TableMap::TYPE_PHPNAME) + { + $keys = ExportCategoryI18nTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setLocale($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setTitle($arr[$keys[2]]); + } + + /** + * 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(ExportCategoryI18nTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ExportCategoryI18nTableMap::ID)) $criteria->add(ExportCategoryI18nTableMap::ID, $this->id); + if ($this->isColumnModified(ExportCategoryI18nTableMap::LOCALE)) $criteria->add(ExportCategoryI18nTableMap::LOCALE, $this->locale); + if ($this->isColumnModified(ExportCategoryI18nTableMap::TITLE)) $criteria->add(ExportCategoryI18nTableMap::TITLE, $this->title); + + 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(ExportCategoryI18nTableMap::DATABASE_NAME); + $criteria->add(ExportCategoryI18nTableMap::ID, $this->id); + $criteria->add(ExportCategoryI18nTableMap::LOCALE, $this->locale); + + 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() + { + $pks = array(); + $pks[0] = $this->getId(); + $pks[1] = $this->getLocale(); + + return $pks; + } + + /** + * 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->setId($keys[0]); + $this->setLocale($keys[1]); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return (null === $this->getId()) && (null === $this->getLocale()); + } + + /** + * 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 \Thelia\Model\ExportCategoryI18n (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setId($this->getId()); + $copyObj->setLocale($this->getLocale()); + $copyObj->setTitle($this->getTitle()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * 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 \Thelia\Model\ExportCategoryI18n 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; + } + + /** + * Declares an association between this object and a ChildExportCategory object. + * + * @param ChildExportCategory $v + * @return \Thelia\Model\ExportCategoryI18n The current object (for fluent API support) + * @throws PropelException + */ + public function setExportCategory(ChildExportCategory $v = null) + { + if ($v === null) { + $this->setId(NULL); + } else { + $this->setId($v->getId()); + } + + $this->aExportCategory = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildExportCategory object, it will not be re-added. + if ($v !== null) { + $v->addExportCategoryI18n($this); + } + + + return $this; + } + + + /** + * Get the associated ChildExportCategory object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildExportCategory The associated ChildExportCategory object. + * @throws PropelException + */ + public function getExportCategory(ConnectionInterface $con = null) + { + if ($this->aExportCategory === null && ($this->id !== null)) { + $this->aExportCategory = ChildExportCategoryQuery::create()->findPk($this->id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aExportCategory->addExportCategoryI18ns($this); + */ + } + + return $this->aExportCategory; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->locale = null; + $this->title = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aExportCategory = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ExportCategoryI18nTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/ExportCategoryI18nQuery.php b/core/lib/Thelia/Model/Base/ExportCategoryI18nQuery.php new file mode 100644 index 000000000..5dfc31870 --- /dev/null +++ b/core/lib/Thelia/Model/Base/ExportCategoryI18nQuery.php @@ -0,0 +1,508 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(array(12, 34), $con); + * + * + * @param array[$id, $locale] $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildExportCategoryI18n|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ExportCategoryI18nTableMap::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1]))))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ExportCategoryI18nTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildExportCategoryI18n A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `LOCALE`, `TITLE` FROM `export_category_i18n` WHERE `ID` = :p0 AND `LOCALE` = :p1'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); + $stmt->bindValue(':p1', $key[1], PDO::PARAM_STR); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildExportCategoryI18n(); + $obj->hydrate($row); + ExportCategoryI18nTableMap::addInstanceToPool($obj, serialize(array((string) $key[0], (string) $key[1]))); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildExportCategoryI18n|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildExportCategoryI18nQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + $this->addUsingAlias(ExportCategoryI18nTableMap::ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(ExportCategoryI18nTableMap::LOCALE, $key[1], Criteria::EQUAL); + + return $this; + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildExportCategoryI18nQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + if (empty($keys)) { + return $this->add(null, '1<>1', Criteria::CUSTOM); + } + foreach ($keys as $key) { + $cton0 = $this->getNewCriterion(ExportCategoryI18nTableMap::ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(ExportCategoryI18nTableMap::LOCALE, $key[1], Criteria::EQUAL); + $cton0->addAnd($cton1); + $this->addOr($cton0); + } + + return $this; + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @see filterByExportCategory() + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportCategoryI18nQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ExportCategoryI18nTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ExportCategoryI18nTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ExportCategoryI18nTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the locale column + * + * Example usage: + * + * $query->filterByLocale('fooValue'); // WHERE locale = 'fooValue' + * $query->filterByLocale('%fooValue%'); // WHERE locale LIKE '%fooValue%' + * + * + * @param string $locale The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportCategoryI18nQuery The current query, for fluid interface + */ + public function filterByLocale($locale = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($locale)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $locale)) { + $locale = str_replace('*', '%', $locale); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ExportCategoryI18nTableMap::LOCALE, $locale, $comparison); + } + + /** + * Filter the query on the title column + * + * Example usage: + * + * $query->filterByTitle('fooValue'); // WHERE title = 'fooValue' + * $query->filterByTitle('%fooValue%'); // WHERE title LIKE '%fooValue%' + * + * + * @param string $title The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportCategoryI18nQuery The current query, for fluid interface + */ + public function filterByTitle($title = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($title)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $title)) { + $title = str_replace('*', '%', $title); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ExportCategoryI18nTableMap::TITLE, $title, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\ExportCategory object + * + * @param \Thelia\Model\ExportCategory|ObjectCollection $exportCategory The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportCategoryI18nQuery The current query, for fluid interface + */ + public function filterByExportCategory($exportCategory, $comparison = null) + { + if ($exportCategory instanceof \Thelia\Model\ExportCategory) { + return $this + ->addUsingAlias(ExportCategoryI18nTableMap::ID, $exportCategory->getId(), $comparison); + } elseif ($exportCategory instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ExportCategoryI18nTableMap::ID, $exportCategory->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByExportCategory() only accepts arguments of type \Thelia\Model\ExportCategory or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the ExportCategory relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildExportCategoryI18nQuery The current query, for fluid interface + */ + public function joinExportCategory($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('ExportCategory'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'ExportCategory'); + } + + return $this; + } + + /** + * Use the ExportCategory relation ExportCategory object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ExportCategoryQuery A secondary query class using the current class as primary query + */ + public function useExportCategoryQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinExportCategory($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'ExportCategory', '\Thelia\Model\ExportCategoryQuery'); + } + + /** + * Exclude object from result + * + * @param ChildExportCategoryI18n $exportCategoryI18n Object to remove from the list of results + * + * @return ChildExportCategoryI18nQuery The current query, for fluid interface + */ + public function prune($exportCategoryI18n = null) + { + if ($exportCategoryI18n) { + $this->addCond('pruneCond0', $this->getAliasedColName(ExportCategoryI18nTableMap::ID), $exportCategoryI18n->getId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(ExportCategoryI18nTableMap::LOCALE), $exportCategoryI18n->getLocale(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); + } + + return $this; + } + + /** + * Deletes all rows from the export_category_i18n table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportCategoryI18nTableMap::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->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ExportCategoryI18nTableMap::clearInstancePool(); + ExportCategoryI18nTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildExportCategoryI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildExportCategoryI18n object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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 function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportCategoryI18nTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ExportCategoryI18nTableMap::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->beginTransaction(); + + + ExportCategoryI18nTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ExportCategoryI18nTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // ExportCategoryI18nQuery diff --git a/core/lib/Thelia/Model/Base/ExportCategoryQuery.php b/core/lib/Thelia/Model/Base/ExportCategoryQuery.php new file mode 100644 index 000000000..a24b1f8e3 --- /dev/null +++ b/core/lib/Thelia/Model/Base/ExportCategoryQuery.php @@ -0,0 +1,797 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildExportCategory|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ExportCategoryTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ExportCategoryTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildExportCategory A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `REF`, `POSITION`, `CREATED_AT`, `UPDATED_AT` FROM `export_category` WHERE `ID` = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildExportCategory(); + $obj->hydrate($row); + ExportCategoryTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildExportCategory|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(ExportCategoryTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(ExportCategoryTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ExportCategoryTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ExportCategoryTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ExportCategoryTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the ref column + * + * Example usage: + * + * $query->filterByRef('fooValue'); // WHERE ref = 'fooValue' + * $query->filterByRef('%fooValue%'); // WHERE ref LIKE '%fooValue%' + * + * + * @param string $ref The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function filterByRef($ref = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($ref)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $ref)) { + $ref = str_replace('*', '%', $ref); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ExportCategoryTableMap::REF, $ref, $comparison); + } + + /** + * Filter the query on the position column + * + * Example usage: + * + * $query->filterByPosition(1234); // WHERE position = 1234 + * $query->filterByPosition(array(12, 34)); // WHERE position IN (12, 34) + * $query->filterByPosition(array('min' => 12)); // WHERE position > 12 + * + * + * @param mixed $position The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function filterByPosition($position = null, $comparison = null) + { + if (is_array($position)) { + $useMinMax = false; + if (isset($position['min'])) { + $this->addUsingAlias(ExportCategoryTableMap::POSITION, $position['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($position['max'])) { + $this->addUsingAlias(ExportCategoryTableMap::POSITION, $position['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ExportCategoryTableMap::POSITION, $position, $comparison); + } + + /** + * Filter the query on the created_at column + * + * Example usage: + * + * $query->filterByCreatedAt('2011-03-14'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt('now'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt(array('max' => 'yesterday')); // WHERE created_at > '2011-03-13' + * + * + * @param mixed $createdAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function filterByCreatedAt($createdAt = null, $comparison = null) + { + if (is_array($createdAt)) { + $useMinMax = false; + if (isset($createdAt['min'])) { + $this->addUsingAlias(ExportCategoryTableMap::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($createdAt['max'])) { + $this->addUsingAlias(ExportCategoryTableMap::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ExportCategoryTableMap::CREATED_AT, $createdAt, $comparison); + } + + /** + * Filter the query on the updated_at column + * + * Example usage: + * + * $query->filterByUpdatedAt('2011-03-14'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt('now'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt(array('max' => 'yesterday')); // WHERE updated_at > '2011-03-13' + * + * + * @param mixed $updatedAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function filterByUpdatedAt($updatedAt = null, $comparison = null) + { + if (is_array($updatedAt)) { + $useMinMax = false; + if (isset($updatedAt['min'])) { + $this->addUsingAlias(ExportCategoryTableMap::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($updatedAt['max'])) { + $this->addUsingAlias(ExportCategoryTableMap::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ExportCategoryTableMap::UPDATED_AT, $updatedAt, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Export object + * + * @param \Thelia\Model\Export|ObjectCollection $export the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function filterByExport($export, $comparison = null) + { + if ($export instanceof \Thelia\Model\Export) { + return $this + ->addUsingAlias(ExportCategoryTableMap::ID, $export->getExportCategoryId(), $comparison); + } elseif ($export instanceof ObjectCollection) { + return $this + ->useExportQuery() + ->filterByPrimaryKeys($export->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByExport() only accepts arguments of type \Thelia\Model\Export or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Export relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function joinExport($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Export'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Export'); + } + + return $this; + } + + /** + * Use the Export relation Export object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ExportQuery A secondary query class using the current class as primary query + */ + public function useExportQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinExport($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Export', '\Thelia\Model\ExportQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\ExportCategoryI18n object + * + * @param \Thelia\Model\ExportCategoryI18n|ObjectCollection $exportCategoryI18n the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function filterByExportCategoryI18n($exportCategoryI18n, $comparison = null) + { + if ($exportCategoryI18n instanceof \Thelia\Model\ExportCategoryI18n) { + return $this + ->addUsingAlias(ExportCategoryTableMap::ID, $exportCategoryI18n->getId(), $comparison); + } elseif ($exportCategoryI18n instanceof ObjectCollection) { + return $this + ->useExportCategoryI18nQuery() + ->filterByPrimaryKeys($exportCategoryI18n->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByExportCategoryI18n() only accepts arguments of type \Thelia\Model\ExportCategoryI18n or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the ExportCategoryI18n relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function joinExportCategoryI18n($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('ExportCategoryI18n'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'ExportCategoryI18n'); + } + + return $this; + } + + /** + * Use the ExportCategoryI18n relation ExportCategoryI18n object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ExportCategoryI18nQuery A secondary query class using the current class as primary query + */ + public function useExportCategoryI18nQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinExportCategoryI18n($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'ExportCategoryI18n', '\Thelia\Model\ExportCategoryI18nQuery'); + } + + /** + * Exclude object from result + * + * @param ChildExportCategory $exportCategory Object to remove from the list of results + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function prune($exportCategory = null) + { + if ($exportCategory) { + $this->addUsingAlias(ExportCategoryTableMap::ID, $exportCategory->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the export_category table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportCategoryTableMap::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->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ExportCategoryTableMap::clearInstancePool(); + ExportCategoryTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildExportCategory or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildExportCategory object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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 function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportCategoryTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ExportCategoryTableMap::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->beginTransaction(); + + + ExportCategoryTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ExportCategoryTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + // i18n behavior + + /** + * Adds a JOIN clause to the query using the i18n relation + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function joinI18n($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $relationName = $relationAlias ? $relationAlias : 'ExportCategoryI18n'; + + return $this + ->joinExportCategoryI18n($relationAlias, $joinType) + ->addJoinCondition($relationName, $relationName . '.Locale = ?', $locale); + } + + /** + * Adds a JOIN clause to the query and hydrates the related I18n object. + * Shortcut for $c->joinI18n($locale)->with() + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function joinWithI18n($locale = 'en_US', $joinType = Criteria::LEFT_JOIN) + { + $this + ->joinI18n($locale, null, $joinType) + ->with('ExportCategoryI18n'); + $this->with['ExportCategoryI18n']->setIsWithOneToMany(false); + + return $this; + } + + /** + * Use the I18n relation query object + * + * @see useQuery() + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildExportCategoryI18nQuery A secondary query class using the current class as primary query + */ + public function useI18nQuery($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinI18n($locale, $relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'ExportCategoryI18n', '\Thelia\Model\ExportCategoryI18nQuery'); + } + + // timestampable behavior + + /** + * Filter by the latest updated + * + * @param int $nbDays Maximum age of the latest update in days + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function recentlyUpdated($nbDays = 7) + { + return $this->addUsingAlias(ExportCategoryTableMap::UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Filter by the latest created + * + * @param int $nbDays Maximum age of in days + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function recentlyCreated($nbDays = 7) + { + return $this->addUsingAlias(ExportCategoryTableMap::CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Order by update date desc + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function lastUpdatedFirst() + { + return $this->addDescendingOrderByColumn(ExportCategoryTableMap::UPDATED_AT); + } + + /** + * Order by update date asc + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function firstUpdatedFirst() + { + return $this->addAscendingOrderByColumn(ExportCategoryTableMap::UPDATED_AT); + } + + /** + * Order by create date desc + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function lastCreatedFirst() + { + return $this->addDescendingOrderByColumn(ExportCategoryTableMap::CREATED_AT); + } + + /** + * Order by create date asc + * + * @return ChildExportCategoryQuery The current query, for fluid interface + */ + public function firstCreatedFirst() + { + return $this->addAscendingOrderByColumn(ExportCategoryTableMap::CREATED_AT); + } + +} // ExportCategoryQuery diff --git a/core/lib/Thelia/Model/Base/ExportI18n.php b/core/lib/Thelia/Model/Base/ExportI18n.php new file mode 100644 index 000000000..e8271f18a --- /dev/null +++ b/core/lib/Thelia/Model/Base/ExportI18n.php @@ -0,0 +1,1326 @@ +locale = 'en_US'; + } + + /** + * Initializes internal state of Thelia\Model\Base\ExportI18n object. + * @see applyDefaults() + */ + public function __construct() + { + $this->applyDefaultValues(); + } + + /** + * Returns whether the object has been modified. + * + * @return boolean True if the object has been modified. + */ + public function isModified() + { + return !!$this->modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ExportI18n instance. If + * obj is an instance of ExportI18n, delegates to + * equals(ExportI18n). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ExportI18n The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ExportI18n The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [locale] column value. + * + * @return string + */ + public function getLocale() + { + + return $this->locale; + } + + /** + * Get the [title] column value. + * + * @return string + */ + public function getTitle() + { + + return $this->title; + } + + /** + * Get the [description] column value. + * + * @return string + */ + public function getDescription() + { + + return $this->description; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\ExportI18n The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ExportI18nTableMap::ID] = true; + } + + if ($this->aExport !== null && $this->aExport->getId() !== $v) { + $this->aExport = null; + } + + + return $this; + } // setId() + + /** + * Set the value of [locale] column. + * + * @param string $v new value + * @return \Thelia\Model\ExportI18n The current object (for fluent API support) + */ + public function setLocale($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->locale !== $v) { + $this->locale = $v; + $this->modifiedColumns[ExportI18nTableMap::LOCALE] = true; + } + + + return $this; + } // setLocale() + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\ExportI18n The current object (for fluent API support) + */ + public function setTitle($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->title !== $v) { + $this->title = $v; + $this->modifiedColumns[ExportI18nTableMap::TITLE] = true; + } + + + return $this; + } // setTitle() + + /** + * Set the value of [description] column. + * + * @param string $v new value + * @return \Thelia\Model\ExportI18n The current object (for fluent API support) + */ + public function setDescription($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->description !== $v) { + $this->description = $v; + $this->modifiedColumns[ExportI18nTableMap::DESCRIPTION] = true; + } + + + return $this; + } // setDescription() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->locale !== 'en_US') { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-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 array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ExportI18nTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ExportI18nTableMap::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)]; + $this->locale = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ExportI18nTableMap::translateFieldName('Title', TableMap::TYPE_PHPNAME, $indexType)]; + $this->title = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ExportI18nTableMap::translateFieldName('Description', TableMap::TYPE_PHPNAME, $indexType)]; + $this->description = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 4; // 4 = ExportI18nTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\ExportI18n object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aExport !== null && $this->id !== $this->aExport->getId()) { + $this->aExport = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ExportI18nTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildExportI18nQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aExport = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ExportI18n::setDeleted() + * @see ExportI18n::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportI18nTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildExportI18nQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $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(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportI18nTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ExportI18nTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row 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 ConnectionInterface $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(ConnectionInterface $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 corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aExport !== null) { + if ($this->aExport->isModified() || $this->aExport->isNew()) { + $affectedRows += $this->aExport->save($con); + } + $this->setExport($this->aExport); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ExportI18nTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(ExportI18nTableMap::LOCALE)) { + $modifiedColumns[':p' . $index++] = '`LOCALE`'; + } + if ($this->isColumnModified(ExportI18nTableMap::TITLE)) { + $modifiedColumns[':p' . $index++] = '`TITLE`'; + } + if ($this->isColumnModified(ExportI18nTableMap::DESCRIPTION)) { + $modifiedColumns[':p' . $index++] = '`DESCRIPTION`'; + } + + $sql = sprintf( + 'INSERT INTO `export_i18n` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`ID`': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case '`LOCALE`': + $stmt->bindValue($identifier, $this->locale, PDO::PARAM_STR); + break; + case '`TITLE`': + $stmt->bindValue($identifier, $this->title, PDO::PARAM_STR); + break; + case '`DESCRIPTION`': + $stmt->bindValue($identifier, $this->description, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * 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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ExportI18nTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * 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->getId(); + break; + case 1: + return $this->getLocale(); + break; + case 2: + return $this->getTitle(); + break; + case 3: + return $this->getDescription(); + 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 (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['ExportI18n'][serialize($this->getPrimaryKey())])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ExportI18n'][serialize($this->getPrimaryKey())] = true; + $keys = ExportI18nTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getLocale(), + $keys[2] => $this->getTitle(), + $keys[3] => $this->getDescription(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aExport) { + $result['Export'] = $this->aExport->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ExportI18nTableMap::translateFieldName($name, $type, TableMap::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->setId($value); + break; + case 1: + $this->setLocale($value); + break; + case 2: + $this->setTitle($value); + break; + case 3: + $this->setDescription($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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @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 = TableMap::TYPE_PHPNAME) + { + $keys = ExportI18nTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setLocale($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setTitle($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setDescription($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(ExportI18nTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ExportI18nTableMap::ID)) $criteria->add(ExportI18nTableMap::ID, $this->id); + if ($this->isColumnModified(ExportI18nTableMap::LOCALE)) $criteria->add(ExportI18nTableMap::LOCALE, $this->locale); + if ($this->isColumnModified(ExportI18nTableMap::TITLE)) $criteria->add(ExportI18nTableMap::TITLE, $this->title); + if ($this->isColumnModified(ExportI18nTableMap::DESCRIPTION)) $criteria->add(ExportI18nTableMap::DESCRIPTION, $this->description); + + 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(ExportI18nTableMap::DATABASE_NAME); + $criteria->add(ExportI18nTableMap::ID, $this->id); + $criteria->add(ExportI18nTableMap::LOCALE, $this->locale); + + 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() + { + $pks = array(); + $pks[0] = $this->getId(); + $pks[1] = $this->getLocale(); + + return $pks; + } + + /** + * 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->setId($keys[0]); + $this->setLocale($keys[1]); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return (null === $this->getId()) && (null === $this->getLocale()); + } + + /** + * 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 \Thelia\Model\ExportI18n (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setId($this->getId()); + $copyObj->setLocale($this->getLocale()); + $copyObj->setTitle($this->getTitle()); + $copyObj->setDescription($this->getDescription()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * 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 \Thelia\Model\ExportI18n 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; + } + + /** + * Declares an association between this object and a ChildExport object. + * + * @param ChildExport $v + * @return \Thelia\Model\ExportI18n The current object (for fluent API support) + * @throws PropelException + */ + public function setExport(ChildExport $v = null) + { + if ($v === null) { + $this->setId(NULL); + } else { + $this->setId($v->getId()); + } + + $this->aExport = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildExport object, it will not be re-added. + if ($v !== null) { + $v->addExportI18n($this); + } + + + return $this; + } + + + /** + * Get the associated ChildExport object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildExport The associated ChildExport object. + * @throws PropelException + */ + public function getExport(ConnectionInterface $con = null) + { + if ($this->aExport === null && ($this->id !== null)) { + $this->aExport = ChildExportQuery::create()->findPk($this->id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aExport->addExportI18ns($this); + */ + } + + return $this->aExport; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->locale = null; + $this->title = null; + $this->description = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aExport = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ExportI18nTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/ExportI18nQuery.php b/core/lib/Thelia/Model/Base/ExportI18nQuery.php new file mode 100644 index 000000000..4c0956f12 --- /dev/null +++ b/core/lib/Thelia/Model/Base/ExportI18nQuery.php @@ -0,0 +1,541 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(array(12, 34), $con); + * + * + * @param array[$id, $locale] $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildExportI18n|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ExportI18nTableMap::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1]))))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ExportI18nTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildExportI18n A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `LOCALE`, `TITLE`, `DESCRIPTION` FROM `export_i18n` WHERE `ID` = :p0 AND `LOCALE` = :p1'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); + $stmt->bindValue(':p1', $key[1], PDO::PARAM_STR); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildExportI18n(); + $obj->hydrate($row); + ExportI18nTableMap::addInstanceToPool($obj, serialize(array((string) $key[0], (string) $key[1]))); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildExportI18n|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildExportI18nQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + $this->addUsingAlias(ExportI18nTableMap::ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(ExportI18nTableMap::LOCALE, $key[1], Criteria::EQUAL); + + return $this; + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildExportI18nQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + if (empty($keys)) { + return $this->add(null, '1<>1', Criteria::CUSTOM); + } + foreach ($keys as $key) { + $cton0 = $this->getNewCriterion(ExportI18nTableMap::ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(ExportI18nTableMap::LOCALE, $key[1], Criteria::EQUAL); + $cton0->addAnd($cton1); + $this->addOr($cton0); + } + + return $this; + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @see filterByExport() + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportI18nQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ExportI18nTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ExportI18nTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ExportI18nTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the locale column + * + * Example usage: + * + * $query->filterByLocale('fooValue'); // WHERE locale = 'fooValue' + * $query->filterByLocale('%fooValue%'); // WHERE locale LIKE '%fooValue%' + * + * + * @param string $locale The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportI18nQuery The current query, for fluid interface + */ + public function filterByLocale($locale = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($locale)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $locale)) { + $locale = str_replace('*', '%', $locale); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ExportI18nTableMap::LOCALE, $locale, $comparison); + } + + /** + * Filter the query on the title column + * + * Example usage: + * + * $query->filterByTitle('fooValue'); // WHERE title = 'fooValue' + * $query->filterByTitle('%fooValue%'); // WHERE title LIKE '%fooValue%' + * + * + * @param string $title The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportI18nQuery The current query, for fluid interface + */ + public function filterByTitle($title = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($title)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $title)) { + $title = str_replace('*', '%', $title); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ExportI18nTableMap::TITLE, $title, $comparison); + } + + /** + * Filter the query on the description column + * + * Example usage: + * + * $query->filterByDescription('fooValue'); // WHERE description = 'fooValue' + * $query->filterByDescription('%fooValue%'); // WHERE description LIKE '%fooValue%' + * + * + * @param string $description The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportI18nQuery The current query, for fluid interface + */ + public function filterByDescription($description = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($description)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $description)) { + $description = str_replace('*', '%', $description); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ExportI18nTableMap::DESCRIPTION, $description, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Export object + * + * @param \Thelia\Model\Export|ObjectCollection $export The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportI18nQuery The current query, for fluid interface + */ + public function filterByExport($export, $comparison = null) + { + if ($export instanceof \Thelia\Model\Export) { + return $this + ->addUsingAlias(ExportI18nTableMap::ID, $export->getId(), $comparison); + } elseif ($export instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ExportI18nTableMap::ID, $export->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByExport() only accepts arguments of type \Thelia\Model\Export or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Export relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildExportI18nQuery The current query, for fluid interface + */ + public function joinExport($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Export'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Export'); + } + + return $this; + } + + /** + * Use the Export relation Export object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ExportQuery A secondary query class using the current class as primary query + */ + public function useExportQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinExport($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Export', '\Thelia\Model\ExportQuery'); + } + + /** + * Exclude object from result + * + * @param ChildExportI18n $exportI18n Object to remove from the list of results + * + * @return ChildExportI18nQuery The current query, for fluid interface + */ + public function prune($exportI18n = null) + { + if ($exportI18n) { + $this->addCond('pruneCond0', $this->getAliasedColName(ExportI18nTableMap::ID), $exportI18n->getId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(ExportI18nTableMap::LOCALE), $exportI18n->getLocale(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); + } + + return $this; + } + + /** + * Deletes all rows from the export_i18n table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportI18nTableMap::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->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ExportI18nTableMap::clearInstancePool(); + ExportI18nTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildExportI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildExportI18n object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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 function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportI18nTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ExportI18nTableMap::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->beginTransaction(); + + + ExportI18nTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ExportI18nTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // ExportI18nQuery diff --git a/core/lib/Thelia/Model/Base/ExportQuery.php b/core/lib/Thelia/Model/Base/ExportQuery.php new file mode 100644 index 000000000..73397efb2 --- /dev/null +++ b/core/lib/Thelia/Model/Base/ExportQuery.php @@ -0,0 +1,879 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildExport|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ExportTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ExportTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildExport A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `REF`, `EXPORT_CATEGORY_ID`, `POSITION`, `HANDLE_CLASS`, `CREATED_AT`, `UPDATED_AT` FROM `export` WHERE `ID` = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildExport(); + $obj->hydrate($row); + ExportTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildExport|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(ExportTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(ExportTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ExportTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ExportTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ExportTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the ref column + * + * Example usage: + * + * $query->filterByRef('fooValue'); // WHERE ref = 'fooValue' + * $query->filterByRef('%fooValue%'); // WHERE ref LIKE '%fooValue%' + * + * + * @param string $ref The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function filterByRef($ref = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($ref)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $ref)) { + $ref = str_replace('*', '%', $ref); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ExportTableMap::REF, $ref, $comparison); + } + + /** + * Filter the query on the export_category_id column + * + * Example usage: + * + * $query->filterByExportCategoryId(1234); // WHERE export_category_id = 1234 + * $query->filterByExportCategoryId(array(12, 34)); // WHERE export_category_id IN (12, 34) + * $query->filterByExportCategoryId(array('min' => 12)); // WHERE export_category_id > 12 + * + * + * @see filterByExportCategory() + * + * @param mixed $exportCategoryId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function filterByExportCategoryId($exportCategoryId = null, $comparison = null) + { + if (is_array($exportCategoryId)) { + $useMinMax = false; + if (isset($exportCategoryId['min'])) { + $this->addUsingAlias(ExportTableMap::EXPORT_CATEGORY_ID, $exportCategoryId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($exportCategoryId['max'])) { + $this->addUsingAlias(ExportTableMap::EXPORT_CATEGORY_ID, $exportCategoryId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ExportTableMap::EXPORT_CATEGORY_ID, $exportCategoryId, $comparison); + } + + /** + * Filter the query on the position column + * + * Example usage: + * + * $query->filterByPosition(1234); // WHERE position = 1234 + * $query->filterByPosition(array(12, 34)); // WHERE position IN (12, 34) + * $query->filterByPosition(array('min' => 12)); // WHERE position > 12 + * + * + * @param mixed $position The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function filterByPosition($position = null, $comparison = null) + { + if (is_array($position)) { + $useMinMax = false; + if (isset($position['min'])) { + $this->addUsingAlias(ExportTableMap::POSITION, $position['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($position['max'])) { + $this->addUsingAlias(ExportTableMap::POSITION, $position['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ExportTableMap::POSITION, $position, $comparison); + } + + /** + * Filter the query on the handle_class column + * + * Example usage: + * + * $query->filterByHandleClass('fooValue'); // WHERE handle_class = 'fooValue' + * $query->filterByHandleClass('%fooValue%'); // WHERE handle_class LIKE '%fooValue%' + * + * + * @param string $handleClass The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function filterByHandleClass($handleClass = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($handleClass)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $handleClass)) { + $handleClass = str_replace('*', '%', $handleClass); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ExportTableMap::HANDLE_CLASS, $handleClass, $comparison); + } + + /** + * Filter the query on the created_at column + * + * Example usage: + * + * $query->filterByCreatedAt('2011-03-14'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt('now'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt(array('max' => 'yesterday')); // WHERE created_at > '2011-03-13' + * + * + * @param mixed $createdAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function filterByCreatedAt($createdAt = null, $comparison = null) + { + if (is_array($createdAt)) { + $useMinMax = false; + if (isset($createdAt['min'])) { + $this->addUsingAlias(ExportTableMap::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($createdAt['max'])) { + $this->addUsingAlias(ExportTableMap::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ExportTableMap::CREATED_AT, $createdAt, $comparison); + } + + /** + * Filter the query on the updated_at column + * + * Example usage: + * + * $query->filterByUpdatedAt('2011-03-14'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt('now'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt(array('max' => 'yesterday')); // WHERE updated_at > '2011-03-13' + * + * + * @param mixed $updatedAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function filterByUpdatedAt($updatedAt = null, $comparison = null) + { + if (is_array($updatedAt)) { + $useMinMax = false; + if (isset($updatedAt['min'])) { + $this->addUsingAlias(ExportTableMap::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($updatedAt['max'])) { + $this->addUsingAlias(ExportTableMap::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ExportTableMap::UPDATED_AT, $updatedAt, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\ExportCategory object + * + * @param \Thelia\Model\ExportCategory|ObjectCollection $exportCategory The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function filterByExportCategory($exportCategory, $comparison = null) + { + if ($exportCategory instanceof \Thelia\Model\ExportCategory) { + return $this + ->addUsingAlias(ExportTableMap::EXPORT_CATEGORY_ID, $exportCategory->getId(), $comparison); + } elseif ($exportCategory instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ExportTableMap::EXPORT_CATEGORY_ID, $exportCategory->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByExportCategory() only accepts arguments of type \Thelia\Model\ExportCategory or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the ExportCategory relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function joinExportCategory($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('ExportCategory'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'ExportCategory'); + } + + return $this; + } + + /** + * Use the ExportCategory relation ExportCategory object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ExportCategoryQuery A secondary query class using the current class as primary query + */ + public function useExportCategoryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinExportCategory($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'ExportCategory', '\Thelia\Model\ExportCategoryQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\ExportI18n object + * + * @param \Thelia\Model\ExportI18n|ObjectCollection $exportI18n the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function filterByExportI18n($exportI18n, $comparison = null) + { + if ($exportI18n instanceof \Thelia\Model\ExportI18n) { + return $this + ->addUsingAlias(ExportTableMap::ID, $exportI18n->getId(), $comparison); + } elseif ($exportI18n instanceof ObjectCollection) { + return $this + ->useExportI18nQuery() + ->filterByPrimaryKeys($exportI18n->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByExportI18n() only accepts arguments of type \Thelia\Model\ExportI18n or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the ExportI18n relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function joinExportI18n($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('ExportI18n'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'ExportI18n'); + } + + return $this; + } + + /** + * Use the ExportI18n relation ExportI18n object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ExportI18nQuery A secondary query class using the current class as primary query + */ + public function useExportI18nQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinExportI18n($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'ExportI18n', '\Thelia\Model\ExportI18nQuery'); + } + + /** + * Exclude object from result + * + * @param ChildExport $export Object to remove from the list of results + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function prune($export = null) + { + if ($export) { + $this->addUsingAlias(ExportTableMap::ID, $export->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the export table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportTableMap::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->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ExportTableMap::clearInstancePool(); + ExportTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildExport or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildExport object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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 function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ExportTableMap::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->beginTransaction(); + + + ExportTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ExportTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + // i18n behavior + + /** + * Adds a JOIN clause to the query using the i18n relation + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function joinI18n($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $relationName = $relationAlias ? $relationAlias : 'ExportI18n'; + + return $this + ->joinExportI18n($relationAlias, $joinType) + ->addJoinCondition($relationName, $relationName . '.Locale = ?', $locale); + } + + /** + * Adds a JOIN clause to the query and hydrates the related I18n object. + * Shortcut for $c->joinI18n($locale)->with() + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function joinWithI18n($locale = 'en_US', $joinType = Criteria::LEFT_JOIN) + { + $this + ->joinI18n($locale, null, $joinType) + ->with('ExportI18n'); + $this->with['ExportI18n']->setIsWithOneToMany(false); + + return $this; + } + + /** + * Use the I18n relation query object + * + * @see useQuery() + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildExportI18nQuery A secondary query class using the current class as primary query + */ + public function useI18nQuery($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinI18n($locale, $relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'ExportI18n', '\Thelia\Model\ExportI18nQuery'); + } + + // timestampable behavior + + /** + * Filter by the latest updated + * + * @param int $nbDays Maximum age of the latest update in days + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function recentlyUpdated($nbDays = 7) + { + return $this->addUsingAlias(ExportTableMap::UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Filter by the latest created + * + * @param int $nbDays Maximum age of in days + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function recentlyCreated($nbDays = 7) + { + return $this->addUsingAlias(ExportTableMap::CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Order by update date desc + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function lastUpdatedFirst() + { + return $this->addDescendingOrderByColumn(ExportTableMap::UPDATED_AT); + } + + /** + * Order by update date asc + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function firstUpdatedFirst() + { + return $this->addAscendingOrderByColumn(ExportTableMap::UPDATED_AT); + } + + /** + * Order by create date desc + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function lastCreatedFirst() + { + return $this->addDescendingOrderByColumn(ExportTableMap::CREATED_AT); + } + + /** + * Order by create date asc + * + * @return ChildExportQuery The current query, for fluid interface + */ + public function firstCreatedFirst() + { + return $this->addAscendingOrderByColumn(ExportTableMap::CREATED_AT); + } + +} // ExportQuery diff --git a/core/lib/Thelia/Model/Base/Import.php b/core/lib/Thelia/Model/Base/Import.php new file mode 100644 index 000000000..0b65b3867 --- /dev/null +++ b/core/lib/Thelia/Model/Base/Import.php @@ -0,0 +1,2000 @@ +modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another Import instance. If + * obj is an instance of Import, delegates to + * equals(Import). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return Import The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return Import The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [ref] column value. + * + * @return string + */ + public function getRef() + { + + return $this->ref; + } + + /** + * Get the [import_category_id] column value. + * + * @return int + */ + public function getImportCategoryId() + { + + return $this->import_category_id; + } + + /** + * Get the [position] column value. + * + * @return int + */ + public function getPosition() + { + + return $this->position; + } + + /** + * Get the [handle_class] column value. + * + * @return string + */ + public function getHandleClass() + { + + return $this->handle_class; + } + + /** + * Get the [optionally formatted] temporal [created_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getCreatedAt($format = NULL) + { + if ($format === null) { + return $this->created_at; + } else { + return $this->created_at instanceof \DateTime ? $this->created_at->format($format) : null; + } + } + + /** + * Get the [optionally formatted] temporal [updated_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getUpdatedAt($format = NULL) + { + if ($format === null) { + return $this->updated_at; + } else { + return $this->updated_at instanceof \DateTime ? $this->updated_at->format($format) : null; + } + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\Import The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ImportTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [ref] column. + * + * @param string $v new value + * @return \Thelia\Model\Import The current object (for fluent API support) + */ + public function setRef($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->ref !== $v) { + $this->ref = $v; + $this->modifiedColumns[ImportTableMap::REF] = true; + } + + + return $this; + } // setRef() + + /** + * Set the value of [import_category_id] column. + * + * @param int $v new value + * @return \Thelia\Model\Import The current object (for fluent API support) + */ + public function setImportCategoryId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->import_category_id !== $v) { + $this->import_category_id = $v; + $this->modifiedColumns[ImportTableMap::IMPORT_CATEGORY_ID] = true; + } + + if ($this->aImportCategory !== null && $this->aImportCategory->getId() !== $v) { + $this->aImportCategory = null; + } + + + return $this; + } // setImportCategoryId() + + /** + * Set the value of [position] column. + * + * @param int $v new value + * @return \Thelia\Model\Import The current object (for fluent API support) + */ + public function setPosition($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->position !== $v) { + $this->position = $v; + $this->modifiedColumns[ImportTableMap::POSITION] = true; + } + + + return $this; + } // setPosition() + + /** + * Set the value of [handle_class] column. + * + * @param string $v new value + * @return \Thelia\Model\Import The current object (for fluent API support) + */ + public function setHandleClass($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->handle_class !== $v) { + $this->handle_class = $v; + $this->modifiedColumns[ImportTableMap::HANDLE_CLASS] = true; + } + + + return $this; + } // setHandleClass() + + /** + * Sets the value of [created_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\Import The current object (for fluent API support) + */ + public function setCreatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->created_at !== null || $dt !== null) { + if ($dt !== $this->created_at) { + $this->created_at = $dt; + $this->modifiedColumns[ImportTableMap::CREATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setCreatedAt() + + /** + * Sets the value of [updated_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\Import The current object (for fluent API support) + */ + public function setUpdatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->updated_at !== null || $dt !== null) { + if ($dt !== $this->updated_at) { + $this->updated_at = $dt; + $this->modifiedColumns[ImportTableMap::UPDATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setUpdatedAt() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-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 array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ImportTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ImportTableMap::translateFieldName('Ref', TableMap::TYPE_PHPNAME, $indexType)]; + $this->ref = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ImportTableMap::translateFieldName('ImportCategoryId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->import_category_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ImportTableMap::translateFieldName('Position', TableMap::TYPE_PHPNAME, $indexType)]; + $this->position = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ImportTableMap::translateFieldName('HandleClass', TableMap::TYPE_PHPNAME, $indexType)]; + $this->handle_class = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ImportTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : ImportTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->updated_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 7; // 7 = ImportTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\Import object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aImportCategory !== null && $this->import_category_id !== $this->aImportCategory->getId()) { + $this->aImportCategory = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ImportTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildImportQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aImportCategory = null; + $this->collImportI18ns = null; + + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see Import::setDeleted() + * @see Import::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildImportQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $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(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + // timestampable behavior + if (!$this->isColumnModified(ImportTableMap::CREATED_AT)) { + $this->setCreatedAt(time()); + } + if (!$this->isColumnModified(ImportTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } else { + $ret = $ret && $this->preUpdate($con); + // timestampable behavior + if ($this->isModified() && !$this->isColumnModified(ImportTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ImportTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row 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 ConnectionInterface $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(ConnectionInterface $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 corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aImportCategory !== null) { + if ($this->aImportCategory->isModified() || $this->aImportCategory->isNew()) { + $affectedRows += $this->aImportCategory->save($con); + } + $this->setImportCategory($this->aImportCategory); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + if ($this->importI18nsScheduledForDeletion !== null) { + if (!$this->importI18nsScheduledForDeletion->isEmpty()) { + \Thelia\Model\ImportI18nQuery::create() + ->filterByPrimaryKeys($this->importI18nsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->importI18nsScheduledForDeletion = null; + } + } + + if ($this->collImportI18ns !== null) { + foreach ($this->collImportI18ns as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + $this->modifiedColumns[ImportTableMap::ID] = true; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . ImportTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ImportTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(ImportTableMap::REF)) { + $modifiedColumns[':p' . $index++] = '`REF`'; + } + if ($this->isColumnModified(ImportTableMap::IMPORT_CATEGORY_ID)) { + $modifiedColumns[':p' . $index++] = '`IMPORT_CATEGORY_ID`'; + } + if ($this->isColumnModified(ImportTableMap::POSITION)) { + $modifiedColumns[':p' . $index++] = '`POSITION`'; + } + if ($this->isColumnModified(ImportTableMap::HANDLE_CLASS)) { + $modifiedColumns[':p' . $index++] = '`HANDLE_CLASS`'; + } + if ($this->isColumnModified(ImportTableMap::CREATED_AT)) { + $modifiedColumns[':p' . $index++] = '`CREATED_AT`'; + } + if ($this->isColumnModified(ImportTableMap::UPDATED_AT)) { + $modifiedColumns[':p' . $index++] = '`UPDATED_AT`'; + } + + $sql = sprintf( + 'INSERT INTO `import` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`ID`': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case '`REF`': + $stmt->bindValue($identifier, $this->ref, PDO::PARAM_STR); + break; + case '`IMPORT_CATEGORY_ID`': + $stmt->bindValue($identifier, $this->import_category_id, PDO::PARAM_INT); + break; + case '`POSITION`': + $stmt->bindValue($identifier, $this->position, PDO::PARAM_INT); + break; + case '`HANDLE_CLASS`': + $stmt->bindValue($identifier, $this->handle_class, PDO::PARAM_STR); + break; + case '`CREATED_AT`': + $stmt->bindValue($identifier, $this->created_at ? $this->created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + case '`UPDATED_AT`': + $stmt->bindValue($identifier, $this->updated_at ? $this->updated_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + try { + $pk = $con->lastInsertId(); + } catch (Exception $e) { + throw new PropelException('Unable to get autoincrement id.', 0, $e); + } + $this->setId($pk); + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * 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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ImportTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * 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->getId(); + break; + case 1: + return $this->getRef(); + break; + case 2: + return $this->getImportCategoryId(); + break; + case 3: + return $this->getPosition(); + break; + case 4: + return $this->getHandleClass(); + break; + case 5: + return $this->getCreatedAt(); + break; + case 6: + return $this->getUpdatedAt(); + 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 (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['Import'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['Import'][$this->getPrimaryKey()] = true; + $keys = ImportTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getRef(), + $keys[2] => $this->getImportCategoryId(), + $keys[3] => $this->getPosition(), + $keys[4] => $this->getHandleClass(), + $keys[5] => $this->getCreatedAt(), + $keys[6] => $this->getUpdatedAt(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aImportCategory) { + $result['ImportCategory'] = $this->aImportCategory->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->collImportI18ns) { + $result['ImportI18ns'] = $this->collImportI18ns->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ImportTableMap::translateFieldName($name, $type, TableMap::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->setId($value); + break; + case 1: + $this->setRef($value); + break; + case 2: + $this->setImportCategoryId($value); + break; + case 3: + $this->setPosition($value); + break; + case 4: + $this->setHandleClass($value); + break; + case 5: + $this->setCreatedAt($value); + break; + case 6: + $this->setUpdatedAt($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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @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 = TableMap::TYPE_PHPNAME) + { + $keys = ImportTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setRef($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setImportCategoryId($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setPosition($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setHandleClass($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setCreatedAt($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setUpdatedAt($arr[$keys[6]]); + } + + /** + * 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(ImportTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ImportTableMap::ID)) $criteria->add(ImportTableMap::ID, $this->id); + if ($this->isColumnModified(ImportTableMap::REF)) $criteria->add(ImportTableMap::REF, $this->ref); + if ($this->isColumnModified(ImportTableMap::IMPORT_CATEGORY_ID)) $criteria->add(ImportTableMap::IMPORT_CATEGORY_ID, $this->import_category_id); + if ($this->isColumnModified(ImportTableMap::POSITION)) $criteria->add(ImportTableMap::POSITION, $this->position); + if ($this->isColumnModified(ImportTableMap::HANDLE_CLASS)) $criteria->add(ImportTableMap::HANDLE_CLASS, $this->handle_class); + if ($this->isColumnModified(ImportTableMap::CREATED_AT)) $criteria->add(ImportTableMap::CREATED_AT, $this->created_at); + if ($this->isColumnModified(ImportTableMap::UPDATED_AT)) $criteria->add(ImportTableMap::UPDATED_AT, $this->updated_at); + + 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(ImportTableMap::DATABASE_NAME); + $criteria->add(ImportTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * 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 \Thelia\Model\Import (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setRef($this->getRef()); + $copyObj->setImportCategoryId($this->getImportCategoryId()); + $copyObj->setPosition($this->getPosition()); + $copyObj->setHandleClass($this->getHandleClass()); + $copyObj->setCreatedAt($this->getCreatedAt()); + $copyObj->setUpdatedAt($this->getUpdatedAt()); + + if ($deepCopy) { + // important: temporarily setNew(false) because this affects the behavior of + // the getter/setter methods for fkey referrer objects. + $copyObj->setNew(false); + + foreach ($this->getImportI18ns() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addImportI18n($relObj->copy($deepCopy)); + } + } + + } // if ($deepCopy) + + if ($makeNew) { + $copyObj->setNew(true); + $copyObj->setId(NULL); // this is a auto-increment 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 \Thelia\Model\Import 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; + } + + /** + * Declares an association between this object and a ChildImportCategory object. + * + * @param ChildImportCategory $v + * @return \Thelia\Model\Import The current object (for fluent API support) + * @throws PropelException + */ + public function setImportCategory(ChildImportCategory $v = null) + { + if ($v === null) { + $this->setImportCategoryId(NULL); + } else { + $this->setImportCategoryId($v->getId()); + } + + $this->aImportCategory = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildImportCategory object, it will not be re-added. + if ($v !== null) { + $v->addImport($this); + } + + + return $this; + } + + + /** + * Get the associated ChildImportCategory object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildImportCategory The associated ChildImportCategory object. + * @throws PropelException + */ + public function getImportCategory(ConnectionInterface $con = null) + { + if ($this->aImportCategory === null && ($this->import_category_id !== null)) { + $this->aImportCategory = ChildImportCategoryQuery::create()->findPk($this->import_category_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aImportCategory->addImports($this); + */ + } + + return $this->aImportCategory; + } + + + /** + * Initializes a collection based on the name of a relation. + * Avoids crafting an 'init[$relationName]s' method name + * that wouldn't work when StandardEnglishPluralizer is used. + * + * @param string $relationName The name of the relation to initialize + * @return void + */ + public function initRelation($relationName) + { + if ('ImportI18n' == $relationName) { + return $this->initImportI18ns(); + } + } + + /** + * Clears out the collImportI18ns collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addImportI18ns() + */ + public function clearImportI18ns() + { + $this->collImportI18ns = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collImportI18ns collection loaded partially. + */ + public function resetPartialImportI18ns($v = true) + { + $this->collImportI18nsPartial = $v; + } + + /** + * Initializes the collImportI18ns collection. + * + * By default this just sets the collImportI18ns collection to an empty array (like clearcollImportI18ns()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initImportI18ns($overrideExisting = true) + { + if (null !== $this->collImportI18ns && !$overrideExisting) { + return; + } + $this->collImportI18ns = new ObjectCollection(); + $this->collImportI18ns->setModel('\Thelia\Model\ImportI18n'); + } + + /** + * Gets an array of ChildImportI18n objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildImport is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildImportI18n[] List of ChildImportI18n objects + * @throws PropelException + */ + public function getImportI18ns($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collImportI18nsPartial && !$this->isNew(); + if (null === $this->collImportI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collImportI18ns) { + // return empty collection + $this->initImportI18ns(); + } else { + $collImportI18ns = ChildImportI18nQuery::create(null, $criteria) + ->filterByImport($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collImportI18nsPartial && count($collImportI18ns)) { + $this->initImportI18ns(false); + + foreach ($collImportI18ns as $obj) { + if (false == $this->collImportI18ns->contains($obj)) { + $this->collImportI18ns->append($obj); + } + } + + $this->collImportI18nsPartial = true; + } + + reset($collImportI18ns); + + return $collImportI18ns; + } + + if ($partial && $this->collImportI18ns) { + foreach ($this->collImportI18ns as $obj) { + if ($obj->isNew()) { + $collImportI18ns[] = $obj; + } + } + } + + $this->collImportI18ns = $collImportI18ns; + $this->collImportI18nsPartial = false; + } + } + + return $this->collImportI18ns; + } + + /** + * Sets a collection of ImportI18n objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $importI18ns A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildImport The current object (for fluent API support) + */ + public function setImportI18ns(Collection $importI18ns, ConnectionInterface $con = null) + { + $importI18nsToDelete = $this->getImportI18ns(new Criteria(), $con)->diff($importI18ns); + + + //since at least one column in the foreign key is at the same time a PK + //we can not just set a PK to NULL in the lines below. We have to store + //a backup of all values, so we are able to manipulate these items based on the onDelete value later. + $this->importI18nsScheduledForDeletion = clone $importI18nsToDelete; + + foreach ($importI18nsToDelete as $importI18nRemoved) { + $importI18nRemoved->setImport(null); + } + + $this->collImportI18ns = null; + foreach ($importI18ns as $importI18n) { + $this->addImportI18n($importI18n); + } + + $this->collImportI18ns = $importI18ns; + $this->collImportI18nsPartial = false; + + return $this; + } + + /** + * Returns the number of related ImportI18n objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related ImportI18n objects. + * @throws PropelException + */ + public function countImportI18ns(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collImportI18nsPartial && !$this->isNew(); + if (null === $this->collImportI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collImportI18ns) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getImportI18ns()); + } + + $query = ChildImportI18nQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByImport($this) + ->count($con); + } + + return count($this->collImportI18ns); + } + + /** + * Method called to associate a ChildImportI18n object to this object + * through the ChildImportI18n foreign key attribute. + * + * @param ChildImportI18n $l ChildImportI18n + * @return \Thelia\Model\Import The current object (for fluent API support) + */ + public function addImportI18n(ChildImportI18n $l) + { + if ($l && $locale = $l->getLocale()) { + $this->setLocale($locale); + $this->currentTranslations[$locale] = $l; + } + if ($this->collImportI18ns === null) { + $this->initImportI18ns(); + $this->collImportI18nsPartial = true; + } + + if (!in_array($l, $this->collImportI18ns->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddImportI18n($l); + } + + return $this; + } + + /** + * @param ImportI18n $importI18n The importI18n object to add. + */ + protected function doAddImportI18n($importI18n) + { + $this->collImportI18ns[]= $importI18n; + $importI18n->setImport($this); + } + + /** + * @param ImportI18n $importI18n The importI18n object to remove. + * @return ChildImport The current object (for fluent API support) + */ + public function removeImportI18n($importI18n) + { + if ($this->getImportI18ns()->contains($importI18n)) { + $this->collImportI18ns->remove($this->collImportI18ns->search($importI18n)); + if (null === $this->importI18nsScheduledForDeletion) { + $this->importI18nsScheduledForDeletion = clone $this->collImportI18ns; + $this->importI18nsScheduledForDeletion->clear(); + } + $this->importI18nsScheduledForDeletion[]= clone $importI18n; + $importI18n->setImport(null); + } + + return $this; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->ref = null; + $this->import_category_id = null; + $this->position = null; + $this->handle_class = null; + $this->created_at = null; + $this->updated_at = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + if ($this->collImportI18ns) { + foreach ($this->collImportI18ns as $o) { + $o->clearAllReferences($deep); + } + } + } // if ($deep) + + // i18n behavior + $this->currentLocale = 'en_US'; + $this->currentTranslations = null; + + $this->collImportI18ns = null; + $this->aImportCategory = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ImportTableMap::DEFAULT_STRING_FORMAT); + } + + // i18n behavior + + /** + * Sets the locale for translations + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * + * @return ChildImport The current object (for fluent API support) + */ + public function setLocale($locale = 'en_US') + { + $this->currentLocale = $locale; + + return $this; + } + + /** + * Gets the locale for translations + * + * @return string $locale Locale to use for the translation, e.g. 'fr_FR' + */ + public function getLocale() + { + return $this->currentLocale; + } + + /** + * Returns the current translation for a given locale + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * @param ConnectionInterface $con an optional connection object + * + * @return ChildImportI18n */ + public function getTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!isset($this->currentTranslations[$locale])) { + if (null !== $this->collImportI18ns) { + foreach ($this->collImportI18ns as $translation) { + if ($translation->getLocale() == $locale) { + $this->currentTranslations[$locale] = $translation; + + return $translation; + } + } + } + if ($this->isNew()) { + $translation = new ChildImportI18n(); + $translation->setLocale($locale); + } else { + $translation = ChildImportI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->findOneOrCreate($con); + $this->currentTranslations[$locale] = $translation; + } + $this->addImportI18n($translation); + } + + return $this->currentTranslations[$locale]; + } + + /** + * Remove the translation for a given locale + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * @param ConnectionInterface $con an optional connection object + * + * @return ChildImport The current object (for fluent API support) + */ + public function removeTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!$this->isNew()) { + ChildImportI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->delete($con); + } + if (isset($this->currentTranslations[$locale])) { + unset($this->currentTranslations[$locale]); + } + foreach ($this->collImportI18ns as $key => $translation) { + if ($translation->getLocale() == $locale) { + unset($this->collImportI18ns[$key]); + break; + } + } + + return $this; + } + + /** + * Returns the current translation + * + * @param ConnectionInterface $con an optional connection object + * + * @return ChildImportI18n */ + public function getCurrentTranslation(ConnectionInterface $con = null) + { + return $this->getTranslation($this->getLocale(), $con); + } + + + /** + * Get the [title] column value. + * + * @return string + */ + public function getTitle() + { + return $this->getCurrentTranslation()->getTitle(); + } + + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\ImportI18n The current object (for fluent API support) + */ + public function setTitle($v) + { $this->getCurrentTranslation()->setTitle($v); + + return $this; + } + + + /** + * Get the [description] column value. + * + * @return string + */ + public function getDescription() + { + return $this->getCurrentTranslation()->getDescription(); + } + + + /** + * Set the value of [description] column. + * + * @param string $v new value + * @return \Thelia\Model\ImportI18n The current object (for fluent API support) + */ + public function setDescription($v) + { $this->getCurrentTranslation()->setDescription($v); + + return $this; + } + + // timestampable behavior + + /** + * Mark the current object so that the update date doesn't get updated during next save + * + * @return ChildImport The current object (for fluent API support) + */ + public function keepUpdateDateUnchanged() + { + $this->modifiedColumns[ImportTableMap::UPDATED_AT] = true; + + return $this; + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/ImportCategory.php b/core/lib/Thelia/Model/Base/ImportCategory.php new file mode 100644 index 000000000..2822e810b --- /dev/null +++ b/core/lib/Thelia/Model/Base/ImportCategory.php @@ -0,0 +1,2047 @@ +modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ImportCategory instance. If + * obj is an instance of ImportCategory, delegates to + * equals(ImportCategory). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ImportCategory The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ImportCategory The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [ref] column value. + * + * @return string + */ + public function getRef() + { + + return $this->ref; + } + + /** + * Get the [position] column value. + * + * @return int + */ + public function getPosition() + { + + return $this->position; + } + + /** + * Get the [optionally formatted] temporal [created_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getCreatedAt($format = NULL) + { + if ($format === null) { + return $this->created_at; + } else { + return $this->created_at instanceof \DateTime ? $this->created_at->format($format) : null; + } + } + + /** + * Get the [optionally formatted] temporal [updated_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getUpdatedAt($format = NULL) + { + if ($format === null) { + return $this->updated_at; + } else { + return $this->updated_at instanceof \DateTime ? $this->updated_at->format($format) : null; + } + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\ImportCategory The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ImportCategoryTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [ref] column. + * + * @param string $v new value + * @return \Thelia\Model\ImportCategory The current object (for fluent API support) + */ + public function setRef($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->ref !== $v) { + $this->ref = $v; + $this->modifiedColumns[ImportCategoryTableMap::REF] = true; + } + + + return $this; + } // setRef() + + /** + * Set the value of [position] column. + * + * @param int $v new value + * @return \Thelia\Model\ImportCategory The current object (for fluent API support) + */ + public function setPosition($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->position !== $v) { + $this->position = $v; + $this->modifiedColumns[ImportCategoryTableMap::POSITION] = true; + } + + + return $this; + } // setPosition() + + /** + * Sets the value of [created_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\ImportCategory The current object (for fluent API support) + */ + public function setCreatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->created_at !== null || $dt !== null) { + if ($dt !== $this->created_at) { + $this->created_at = $dt; + $this->modifiedColumns[ImportCategoryTableMap::CREATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setCreatedAt() + + /** + * Sets the value of [updated_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Thelia\Model\ImportCategory The current object (for fluent API support) + */ + public function setUpdatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->updated_at !== null || $dt !== null) { + if ($dt !== $this->updated_at) { + $this->updated_at = $dt; + $this->modifiedColumns[ImportCategoryTableMap::UPDATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setUpdatedAt() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-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 array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ImportCategoryTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ImportCategoryTableMap::translateFieldName('Ref', TableMap::TYPE_PHPNAME, $indexType)]; + $this->ref = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ImportCategoryTableMap::translateFieldName('Position', TableMap::TYPE_PHPNAME, $indexType)]; + $this->position = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ImportCategoryTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ImportCategoryTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->updated_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 5; // 5 = ImportCategoryTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\ImportCategory object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ImportCategoryTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildImportCategoryQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->collImports = null; + + $this->collImportCategoryI18ns = null; + + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ImportCategory::setDeleted() + * @see ImportCategory::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportCategoryTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildImportCategoryQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $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(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportCategoryTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + // timestampable behavior + if (!$this->isColumnModified(ImportCategoryTableMap::CREATED_AT)) { + $this->setCreatedAt(time()); + } + if (!$this->isColumnModified(ImportCategoryTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } else { + $ret = $ret && $this->preUpdate($con); + // timestampable behavior + if ($this->isModified() && !$this->isColumnModified(ImportCategoryTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ImportCategoryTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row 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 ConnectionInterface $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(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + if ($this->importsScheduledForDeletion !== null) { + if (!$this->importsScheduledForDeletion->isEmpty()) { + \Thelia\Model\ImportQuery::create() + ->filterByPrimaryKeys($this->importsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->importsScheduledForDeletion = null; + } + } + + if ($this->collImports !== null) { + foreach ($this->collImports as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->importCategoryI18nsScheduledForDeletion !== null) { + if (!$this->importCategoryI18nsScheduledForDeletion->isEmpty()) { + \Thelia\Model\ImportCategoryI18nQuery::create() + ->filterByPrimaryKeys($this->importCategoryI18nsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->importCategoryI18nsScheduledForDeletion = null; + } + } + + if ($this->collImportCategoryI18ns !== null) { + foreach ($this->collImportCategoryI18ns as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + $this->modifiedColumns[ImportCategoryTableMap::ID] = true; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . ImportCategoryTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ImportCategoryTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(ImportCategoryTableMap::REF)) { + $modifiedColumns[':p' . $index++] = '`REF`'; + } + if ($this->isColumnModified(ImportCategoryTableMap::POSITION)) { + $modifiedColumns[':p' . $index++] = '`POSITION`'; + } + if ($this->isColumnModified(ImportCategoryTableMap::CREATED_AT)) { + $modifiedColumns[':p' . $index++] = '`CREATED_AT`'; + } + if ($this->isColumnModified(ImportCategoryTableMap::UPDATED_AT)) { + $modifiedColumns[':p' . $index++] = '`UPDATED_AT`'; + } + + $sql = sprintf( + 'INSERT INTO `import_category` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`ID`': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case '`REF`': + $stmt->bindValue($identifier, $this->ref, PDO::PARAM_STR); + break; + case '`POSITION`': + $stmt->bindValue($identifier, $this->position, PDO::PARAM_INT); + break; + case '`CREATED_AT`': + $stmt->bindValue($identifier, $this->created_at ? $this->created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + case '`UPDATED_AT`': + $stmt->bindValue($identifier, $this->updated_at ? $this->updated_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + try { + $pk = $con->lastInsertId(); + } catch (Exception $e) { + throw new PropelException('Unable to get autoincrement id.', 0, $e); + } + $this->setId($pk); + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * 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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ImportCategoryTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * 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->getId(); + break; + case 1: + return $this->getRef(); + break; + case 2: + return $this->getPosition(); + break; + case 3: + return $this->getCreatedAt(); + break; + case 4: + return $this->getUpdatedAt(); + 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 (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['ImportCategory'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ImportCategory'][$this->getPrimaryKey()] = true; + $keys = ImportCategoryTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getRef(), + $keys[2] => $this->getPosition(), + $keys[3] => $this->getCreatedAt(), + $keys[4] => $this->getUpdatedAt(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->collImports) { + $result['Imports'] = $this->collImports->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collImportCategoryI18ns) { + $result['ImportCategoryI18ns'] = $this->collImportCategoryI18ns->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ImportCategoryTableMap::translateFieldName($name, $type, TableMap::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->setId($value); + break; + case 1: + $this->setRef($value); + break; + case 2: + $this->setPosition($value); + break; + case 3: + $this->setCreatedAt($value); + break; + case 4: + $this->setUpdatedAt($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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @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 = TableMap::TYPE_PHPNAME) + { + $keys = ImportCategoryTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setRef($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setPosition($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setCreatedAt($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setUpdatedAt($arr[$keys[4]]); + } + + /** + * 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(ImportCategoryTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ImportCategoryTableMap::ID)) $criteria->add(ImportCategoryTableMap::ID, $this->id); + if ($this->isColumnModified(ImportCategoryTableMap::REF)) $criteria->add(ImportCategoryTableMap::REF, $this->ref); + if ($this->isColumnModified(ImportCategoryTableMap::POSITION)) $criteria->add(ImportCategoryTableMap::POSITION, $this->position); + if ($this->isColumnModified(ImportCategoryTableMap::CREATED_AT)) $criteria->add(ImportCategoryTableMap::CREATED_AT, $this->created_at); + if ($this->isColumnModified(ImportCategoryTableMap::UPDATED_AT)) $criteria->add(ImportCategoryTableMap::UPDATED_AT, $this->updated_at); + + 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(ImportCategoryTableMap::DATABASE_NAME); + $criteria->add(ImportCategoryTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * 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 \Thelia\Model\ImportCategory (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setRef($this->getRef()); + $copyObj->setPosition($this->getPosition()); + $copyObj->setCreatedAt($this->getCreatedAt()); + $copyObj->setUpdatedAt($this->getUpdatedAt()); + + if ($deepCopy) { + // important: temporarily setNew(false) because this affects the behavior of + // the getter/setter methods for fkey referrer objects. + $copyObj->setNew(false); + + foreach ($this->getImports() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addImport($relObj->copy($deepCopy)); + } + } + + foreach ($this->getImportCategoryI18ns() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addImportCategoryI18n($relObj->copy($deepCopy)); + } + } + + } // if ($deepCopy) + + if ($makeNew) { + $copyObj->setNew(true); + $copyObj->setId(NULL); // this is a auto-increment 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 \Thelia\Model\ImportCategory 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; + } + + + /** + * Initializes a collection based on the name of a relation. + * Avoids crafting an 'init[$relationName]s' method name + * that wouldn't work when StandardEnglishPluralizer is used. + * + * @param string $relationName The name of the relation to initialize + * @return void + */ + public function initRelation($relationName) + { + if ('Import' == $relationName) { + return $this->initImports(); + } + if ('ImportCategoryI18n' == $relationName) { + return $this->initImportCategoryI18ns(); + } + } + + /** + * Clears out the collImports collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addImports() + */ + public function clearImports() + { + $this->collImports = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collImports collection loaded partially. + */ + public function resetPartialImports($v = true) + { + $this->collImportsPartial = $v; + } + + /** + * Initializes the collImports collection. + * + * By default this just sets the collImports collection to an empty array (like clearcollImports()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initImports($overrideExisting = true) + { + if (null !== $this->collImports && !$overrideExisting) { + return; + } + $this->collImports = new ObjectCollection(); + $this->collImports->setModel('\Thelia\Model\Import'); + } + + /** + * Gets an array of ChildImport objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildImportCategory is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildImport[] List of ChildImport objects + * @throws PropelException + */ + public function getImports($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collImportsPartial && !$this->isNew(); + if (null === $this->collImports || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collImports) { + // return empty collection + $this->initImports(); + } else { + $collImports = ChildImportQuery::create(null, $criteria) + ->filterByImportCategory($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collImportsPartial && count($collImports)) { + $this->initImports(false); + + foreach ($collImports as $obj) { + if (false == $this->collImports->contains($obj)) { + $this->collImports->append($obj); + } + } + + $this->collImportsPartial = true; + } + + reset($collImports); + + return $collImports; + } + + if ($partial && $this->collImports) { + foreach ($this->collImports as $obj) { + if ($obj->isNew()) { + $collImports[] = $obj; + } + } + } + + $this->collImports = $collImports; + $this->collImportsPartial = false; + } + } + + return $this->collImports; + } + + /** + * Sets a collection of Import objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $imports A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildImportCategory The current object (for fluent API support) + */ + public function setImports(Collection $imports, ConnectionInterface $con = null) + { + $importsToDelete = $this->getImports(new Criteria(), $con)->diff($imports); + + + $this->importsScheduledForDeletion = $importsToDelete; + + foreach ($importsToDelete as $importRemoved) { + $importRemoved->setImportCategory(null); + } + + $this->collImports = null; + foreach ($imports as $import) { + $this->addImport($import); + } + + $this->collImports = $imports; + $this->collImportsPartial = false; + + return $this; + } + + /** + * Returns the number of related Import objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related Import objects. + * @throws PropelException + */ + public function countImports(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collImportsPartial && !$this->isNew(); + if (null === $this->collImports || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collImports) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getImports()); + } + + $query = ChildImportQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByImportCategory($this) + ->count($con); + } + + return count($this->collImports); + } + + /** + * Method called to associate a ChildImport object to this object + * through the ChildImport foreign key attribute. + * + * @param ChildImport $l ChildImport + * @return \Thelia\Model\ImportCategory The current object (for fluent API support) + */ + public function addImport(ChildImport $l) + { + if ($this->collImports === null) { + $this->initImports(); + $this->collImportsPartial = true; + } + + if (!in_array($l, $this->collImports->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddImport($l); + } + + return $this; + } + + /** + * @param Import $import The import object to add. + */ + protected function doAddImport($import) + { + $this->collImports[]= $import; + $import->setImportCategory($this); + } + + /** + * @param Import $import The import object to remove. + * @return ChildImportCategory The current object (for fluent API support) + */ + public function removeImport($import) + { + if ($this->getImports()->contains($import)) { + $this->collImports->remove($this->collImports->search($import)); + if (null === $this->importsScheduledForDeletion) { + $this->importsScheduledForDeletion = clone $this->collImports; + $this->importsScheduledForDeletion->clear(); + } + $this->importsScheduledForDeletion[]= clone $import; + $import->setImportCategory(null); + } + + return $this; + } + + /** + * Clears out the collImportCategoryI18ns collection + * + * This does not modify the database; however, it will remove any associated objects, causing + * them to be refetched by subsequent calls to accessor method. + * + * @return void + * @see addImportCategoryI18ns() + */ + public function clearImportCategoryI18ns() + { + $this->collImportCategoryI18ns = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collImportCategoryI18ns collection loaded partially. + */ + public function resetPartialImportCategoryI18ns($v = true) + { + $this->collImportCategoryI18nsPartial = $v; + } + + /** + * Initializes the collImportCategoryI18ns collection. + * + * By default this just sets the collImportCategoryI18ns collection to an empty array (like clearcollImportCategoryI18ns()); + * however, you may wish to override this method in your stub class to provide setting appropriate + * to your application -- for example, setting the initial array to the values stored in database. + * + * @param boolean $overrideExisting If set to true, the method call initializes + * the collection even if it is not empty + * + * @return void + */ + public function initImportCategoryI18ns($overrideExisting = true) + { + if (null !== $this->collImportCategoryI18ns && !$overrideExisting) { + return; + } + $this->collImportCategoryI18ns = new ObjectCollection(); + $this->collImportCategoryI18ns->setModel('\Thelia\Model\ImportCategoryI18n'); + } + + /** + * Gets an array of ChildImportCategoryI18n objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this ChildImportCategory is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @return Collection|ChildImportCategoryI18n[] List of ChildImportCategoryI18n objects + * @throws PropelException + */ + public function getImportCategoryI18ns($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collImportCategoryI18nsPartial && !$this->isNew(); + if (null === $this->collImportCategoryI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collImportCategoryI18ns) { + // return empty collection + $this->initImportCategoryI18ns(); + } else { + $collImportCategoryI18ns = ChildImportCategoryI18nQuery::create(null, $criteria) + ->filterByImportCategory($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collImportCategoryI18nsPartial && count($collImportCategoryI18ns)) { + $this->initImportCategoryI18ns(false); + + foreach ($collImportCategoryI18ns as $obj) { + if (false == $this->collImportCategoryI18ns->contains($obj)) { + $this->collImportCategoryI18ns->append($obj); + } + } + + $this->collImportCategoryI18nsPartial = true; + } + + reset($collImportCategoryI18ns); + + return $collImportCategoryI18ns; + } + + if ($partial && $this->collImportCategoryI18ns) { + foreach ($this->collImportCategoryI18ns as $obj) { + if ($obj->isNew()) { + $collImportCategoryI18ns[] = $obj; + } + } + } + + $this->collImportCategoryI18ns = $collImportCategoryI18ns; + $this->collImportCategoryI18nsPartial = false; + } + } + + return $this->collImportCategoryI18ns; + } + + /** + * Sets a collection of ImportCategoryI18n objects related by a one-to-many relationship + * to the current object. + * It will also schedule objects for deletion based on a diff between old objects (aka persisted) + * and new objects from the given Propel collection. + * + * @param Collection $importCategoryI18ns A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildImportCategory The current object (for fluent API support) + */ + public function setImportCategoryI18ns(Collection $importCategoryI18ns, ConnectionInterface $con = null) + { + $importCategoryI18nsToDelete = $this->getImportCategoryI18ns(new Criteria(), $con)->diff($importCategoryI18ns); + + + //since at least one column in the foreign key is at the same time a PK + //we can not just set a PK to NULL in the lines below. We have to store + //a backup of all values, so we are able to manipulate these items based on the onDelete value later. + $this->importCategoryI18nsScheduledForDeletion = clone $importCategoryI18nsToDelete; + + foreach ($importCategoryI18nsToDelete as $importCategoryI18nRemoved) { + $importCategoryI18nRemoved->setImportCategory(null); + } + + $this->collImportCategoryI18ns = null; + foreach ($importCategoryI18ns as $importCategoryI18n) { + $this->addImportCategoryI18n($importCategoryI18n); + } + + $this->collImportCategoryI18ns = $importCategoryI18ns; + $this->collImportCategoryI18nsPartial = false; + + return $this; + } + + /** + * Returns the number of related ImportCategoryI18n objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related ImportCategoryI18n objects. + * @throws PropelException + */ + public function countImportCategoryI18ns(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collImportCategoryI18nsPartial && !$this->isNew(); + if (null === $this->collImportCategoryI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collImportCategoryI18ns) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getImportCategoryI18ns()); + } + + $query = ChildImportCategoryI18nQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByImportCategory($this) + ->count($con); + } + + return count($this->collImportCategoryI18ns); + } + + /** + * Method called to associate a ChildImportCategoryI18n object to this object + * through the ChildImportCategoryI18n foreign key attribute. + * + * @param ChildImportCategoryI18n $l ChildImportCategoryI18n + * @return \Thelia\Model\ImportCategory The current object (for fluent API support) + */ + public function addImportCategoryI18n(ChildImportCategoryI18n $l) + { + if ($l && $locale = $l->getLocale()) { + $this->setLocale($locale); + $this->currentTranslations[$locale] = $l; + } + if ($this->collImportCategoryI18ns === null) { + $this->initImportCategoryI18ns(); + $this->collImportCategoryI18nsPartial = true; + } + + if (!in_array($l, $this->collImportCategoryI18ns->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddImportCategoryI18n($l); + } + + return $this; + } + + /** + * @param ImportCategoryI18n $importCategoryI18n The importCategoryI18n object to add. + */ + protected function doAddImportCategoryI18n($importCategoryI18n) + { + $this->collImportCategoryI18ns[]= $importCategoryI18n; + $importCategoryI18n->setImportCategory($this); + } + + /** + * @param ImportCategoryI18n $importCategoryI18n The importCategoryI18n object to remove. + * @return ChildImportCategory The current object (for fluent API support) + */ + public function removeImportCategoryI18n($importCategoryI18n) + { + if ($this->getImportCategoryI18ns()->contains($importCategoryI18n)) { + $this->collImportCategoryI18ns->remove($this->collImportCategoryI18ns->search($importCategoryI18n)); + if (null === $this->importCategoryI18nsScheduledForDeletion) { + $this->importCategoryI18nsScheduledForDeletion = clone $this->collImportCategoryI18ns; + $this->importCategoryI18nsScheduledForDeletion->clear(); + } + $this->importCategoryI18nsScheduledForDeletion[]= clone $importCategoryI18n; + $importCategoryI18n->setImportCategory(null); + } + + return $this; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->ref = null; + $this->position = null; + $this->created_at = null; + $this->updated_at = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + if ($this->collImports) { + foreach ($this->collImports as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collImportCategoryI18ns) { + foreach ($this->collImportCategoryI18ns as $o) { + $o->clearAllReferences($deep); + } + } + } // if ($deep) + + // i18n behavior + $this->currentLocale = 'en_US'; + $this->currentTranslations = null; + + $this->collImports = null; + $this->collImportCategoryI18ns = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ImportCategoryTableMap::DEFAULT_STRING_FORMAT); + } + + // i18n behavior + + /** + * Sets the locale for translations + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * + * @return ChildImportCategory The current object (for fluent API support) + */ + public function setLocale($locale = 'en_US') + { + $this->currentLocale = $locale; + + return $this; + } + + /** + * Gets the locale for translations + * + * @return string $locale Locale to use for the translation, e.g. 'fr_FR' + */ + public function getLocale() + { + return $this->currentLocale; + } + + /** + * Returns the current translation for a given locale + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * @param ConnectionInterface $con an optional connection object + * + * @return ChildImportCategoryI18n */ + public function getTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!isset($this->currentTranslations[$locale])) { + if (null !== $this->collImportCategoryI18ns) { + foreach ($this->collImportCategoryI18ns as $translation) { + if ($translation->getLocale() == $locale) { + $this->currentTranslations[$locale] = $translation; + + return $translation; + } + } + } + if ($this->isNew()) { + $translation = new ChildImportCategoryI18n(); + $translation->setLocale($locale); + } else { + $translation = ChildImportCategoryI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->findOneOrCreate($con); + $this->currentTranslations[$locale] = $translation; + } + $this->addImportCategoryI18n($translation); + } + + return $this->currentTranslations[$locale]; + } + + /** + * Remove the translation for a given locale + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * @param ConnectionInterface $con an optional connection object + * + * @return ChildImportCategory The current object (for fluent API support) + */ + public function removeTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!$this->isNew()) { + ChildImportCategoryI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->delete($con); + } + if (isset($this->currentTranslations[$locale])) { + unset($this->currentTranslations[$locale]); + } + foreach ($this->collImportCategoryI18ns as $key => $translation) { + if ($translation->getLocale() == $locale) { + unset($this->collImportCategoryI18ns[$key]); + break; + } + } + + return $this; + } + + /** + * Returns the current translation + * + * @param ConnectionInterface $con an optional connection object + * + * @return ChildImportCategoryI18n */ + public function getCurrentTranslation(ConnectionInterface $con = null) + { + return $this->getTranslation($this->getLocale(), $con); + } + + + /** + * Get the [title] column value. + * + * @return string + */ + public function getTitle() + { + return $this->getCurrentTranslation()->getTitle(); + } + + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\ImportCategoryI18n The current object (for fluent API support) + */ + public function setTitle($v) + { $this->getCurrentTranslation()->setTitle($v); + + return $this; + } + + // timestampable behavior + + /** + * Mark the current object so that the update date doesn't get updated during next save + * + * @return ChildImportCategory The current object (for fluent API support) + */ + public function keepUpdateDateUnchanged() + { + $this->modifiedColumns[ImportCategoryTableMap::UPDATED_AT] = true; + + return $this; + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/ImportCategoryI18n.php b/core/lib/Thelia/Model/Base/ImportCategoryI18n.php new file mode 100644 index 000000000..6f6b5d6c4 --- /dev/null +++ b/core/lib/Thelia/Model/Base/ImportCategoryI18n.php @@ -0,0 +1,1268 @@ +locale = 'en_US'; + } + + /** + * Initializes internal state of Thelia\Model\Base\ImportCategoryI18n object. + * @see applyDefaults() + */ + public function __construct() + { + $this->applyDefaultValues(); + } + + /** + * Returns whether the object has been modified. + * + * @return boolean True if the object has been modified. + */ + public function isModified() + { + return !!$this->modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ImportCategoryI18n instance. If + * obj is an instance of ImportCategoryI18n, delegates to + * equals(ImportCategoryI18n). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ImportCategoryI18n The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ImportCategoryI18n The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [locale] column value. + * + * @return string + */ + public function getLocale() + { + + return $this->locale; + } + + /** + * Get the [title] column value. + * + * @return string + */ + public function getTitle() + { + + return $this->title; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\ImportCategoryI18n The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ImportCategoryI18nTableMap::ID] = true; + } + + if ($this->aImportCategory !== null && $this->aImportCategory->getId() !== $v) { + $this->aImportCategory = null; + } + + + return $this; + } // setId() + + /** + * Set the value of [locale] column. + * + * @param string $v new value + * @return \Thelia\Model\ImportCategoryI18n The current object (for fluent API support) + */ + public function setLocale($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->locale !== $v) { + $this->locale = $v; + $this->modifiedColumns[ImportCategoryI18nTableMap::LOCALE] = true; + } + + + return $this; + } // setLocale() + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\ImportCategoryI18n The current object (for fluent API support) + */ + public function setTitle($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->title !== $v) { + $this->title = $v; + $this->modifiedColumns[ImportCategoryI18nTableMap::TITLE] = true; + } + + + return $this; + } // setTitle() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->locale !== 'en_US') { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-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 array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ImportCategoryI18nTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ImportCategoryI18nTableMap::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)]; + $this->locale = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ImportCategoryI18nTableMap::translateFieldName('Title', TableMap::TYPE_PHPNAME, $indexType)]; + $this->title = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 3; // 3 = ImportCategoryI18nTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\ImportCategoryI18n object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aImportCategory !== null && $this->id !== $this->aImportCategory->getId()) { + $this->aImportCategory = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ImportCategoryI18nTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildImportCategoryI18nQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aImportCategory = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ImportCategoryI18n::setDeleted() + * @see ImportCategoryI18n::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportCategoryI18nTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildImportCategoryI18nQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $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(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportCategoryI18nTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ImportCategoryI18nTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row 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 ConnectionInterface $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(ConnectionInterface $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 corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aImportCategory !== null) { + if ($this->aImportCategory->isModified() || $this->aImportCategory->isNew()) { + $affectedRows += $this->aImportCategory->save($con); + } + $this->setImportCategory($this->aImportCategory); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ImportCategoryI18nTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(ImportCategoryI18nTableMap::LOCALE)) { + $modifiedColumns[':p' . $index++] = '`LOCALE`'; + } + if ($this->isColumnModified(ImportCategoryI18nTableMap::TITLE)) { + $modifiedColumns[':p' . $index++] = '`TITLE`'; + } + + $sql = sprintf( + 'INSERT INTO `import_category_i18n` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`ID`': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case '`LOCALE`': + $stmt->bindValue($identifier, $this->locale, PDO::PARAM_STR); + break; + case '`TITLE`': + $stmt->bindValue($identifier, $this->title, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * 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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ImportCategoryI18nTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * 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->getId(); + break; + case 1: + return $this->getLocale(); + break; + case 2: + return $this->getTitle(); + 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 (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['ImportCategoryI18n'][serialize($this->getPrimaryKey())])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ImportCategoryI18n'][serialize($this->getPrimaryKey())] = true; + $keys = ImportCategoryI18nTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getLocale(), + $keys[2] => $this->getTitle(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aImportCategory) { + $result['ImportCategory'] = $this->aImportCategory->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ImportCategoryI18nTableMap::translateFieldName($name, $type, TableMap::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->setId($value); + break; + case 1: + $this->setLocale($value); + break; + case 2: + $this->setTitle($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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @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 = TableMap::TYPE_PHPNAME) + { + $keys = ImportCategoryI18nTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setLocale($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setTitle($arr[$keys[2]]); + } + + /** + * 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(ImportCategoryI18nTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ImportCategoryI18nTableMap::ID)) $criteria->add(ImportCategoryI18nTableMap::ID, $this->id); + if ($this->isColumnModified(ImportCategoryI18nTableMap::LOCALE)) $criteria->add(ImportCategoryI18nTableMap::LOCALE, $this->locale); + if ($this->isColumnModified(ImportCategoryI18nTableMap::TITLE)) $criteria->add(ImportCategoryI18nTableMap::TITLE, $this->title); + + 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(ImportCategoryI18nTableMap::DATABASE_NAME); + $criteria->add(ImportCategoryI18nTableMap::ID, $this->id); + $criteria->add(ImportCategoryI18nTableMap::LOCALE, $this->locale); + + 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() + { + $pks = array(); + $pks[0] = $this->getId(); + $pks[1] = $this->getLocale(); + + return $pks; + } + + /** + * 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->setId($keys[0]); + $this->setLocale($keys[1]); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return (null === $this->getId()) && (null === $this->getLocale()); + } + + /** + * 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 \Thelia\Model\ImportCategoryI18n (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setId($this->getId()); + $copyObj->setLocale($this->getLocale()); + $copyObj->setTitle($this->getTitle()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * 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 \Thelia\Model\ImportCategoryI18n 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; + } + + /** + * Declares an association between this object and a ChildImportCategory object. + * + * @param ChildImportCategory $v + * @return \Thelia\Model\ImportCategoryI18n The current object (for fluent API support) + * @throws PropelException + */ + public function setImportCategory(ChildImportCategory $v = null) + { + if ($v === null) { + $this->setId(NULL); + } else { + $this->setId($v->getId()); + } + + $this->aImportCategory = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildImportCategory object, it will not be re-added. + if ($v !== null) { + $v->addImportCategoryI18n($this); + } + + + return $this; + } + + + /** + * Get the associated ChildImportCategory object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildImportCategory The associated ChildImportCategory object. + * @throws PropelException + */ + public function getImportCategory(ConnectionInterface $con = null) + { + if ($this->aImportCategory === null && ($this->id !== null)) { + $this->aImportCategory = ChildImportCategoryQuery::create()->findPk($this->id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aImportCategory->addImportCategoryI18ns($this); + */ + } + + return $this->aImportCategory; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->locale = null; + $this->title = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aImportCategory = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ImportCategoryI18nTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/ImportCategoryI18nQuery.php b/core/lib/Thelia/Model/Base/ImportCategoryI18nQuery.php new file mode 100644 index 000000000..648858914 --- /dev/null +++ b/core/lib/Thelia/Model/Base/ImportCategoryI18nQuery.php @@ -0,0 +1,508 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(array(12, 34), $con); + * + * + * @param array[$id, $locale] $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildImportCategoryI18n|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ImportCategoryI18nTableMap::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1]))))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ImportCategoryI18nTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildImportCategoryI18n A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `LOCALE`, `TITLE` FROM `import_category_i18n` WHERE `ID` = :p0 AND `LOCALE` = :p1'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); + $stmt->bindValue(':p1', $key[1], PDO::PARAM_STR); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildImportCategoryI18n(); + $obj->hydrate($row); + ImportCategoryI18nTableMap::addInstanceToPool($obj, serialize(array((string) $key[0], (string) $key[1]))); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildImportCategoryI18n|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildImportCategoryI18nQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + $this->addUsingAlias(ImportCategoryI18nTableMap::ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(ImportCategoryI18nTableMap::LOCALE, $key[1], Criteria::EQUAL); + + return $this; + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildImportCategoryI18nQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + if (empty($keys)) { + return $this->add(null, '1<>1', Criteria::CUSTOM); + } + foreach ($keys as $key) { + $cton0 = $this->getNewCriterion(ImportCategoryI18nTableMap::ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(ImportCategoryI18nTableMap::LOCALE, $key[1], Criteria::EQUAL); + $cton0->addAnd($cton1); + $this->addOr($cton0); + } + + return $this; + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @see filterByImportCategory() + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportCategoryI18nQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ImportCategoryI18nTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ImportCategoryI18nTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ImportCategoryI18nTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the locale column + * + * Example usage: + * + * $query->filterByLocale('fooValue'); // WHERE locale = 'fooValue' + * $query->filterByLocale('%fooValue%'); // WHERE locale LIKE '%fooValue%' + * + * + * @param string $locale The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportCategoryI18nQuery The current query, for fluid interface + */ + public function filterByLocale($locale = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($locale)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $locale)) { + $locale = str_replace('*', '%', $locale); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ImportCategoryI18nTableMap::LOCALE, $locale, $comparison); + } + + /** + * Filter the query on the title column + * + * Example usage: + * + * $query->filterByTitle('fooValue'); // WHERE title = 'fooValue' + * $query->filterByTitle('%fooValue%'); // WHERE title LIKE '%fooValue%' + * + * + * @param string $title The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportCategoryI18nQuery The current query, for fluid interface + */ + public function filterByTitle($title = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($title)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $title)) { + $title = str_replace('*', '%', $title); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ImportCategoryI18nTableMap::TITLE, $title, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\ImportCategory object + * + * @param \Thelia\Model\ImportCategory|ObjectCollection $importCategory The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportCategoryI18nQuery The current query, for fluid interface + */ + public function filterByImportCategory($importCategory, $comparison = null) + { + if ($importCategory instanceof \Thelia\Model\ImportCategory) { + return $this + ->addUsingAlias(ImportCategoryI18nTableMap::ID, $importCategory->getId(), $comparison); + } elseif ($importCategory instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ImportCategoryI18nTableMap::ID, $importCategory->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByImportCategory() only accepts arguments of type \Thelia\Model\ImportCategory or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the ImportCategory relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildImportCategoryI18nQuery The current query, for fluid interface + */ + public function joinImportCategory($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('ImportCategory'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'ImportCategory'); + } + + return $this; + } + + /** + * Use the ImportCategory relation ImportCategory object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ImportCategoryQuery A secondary query class using the current class as primary query + */ + public function useImportCategoryQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinImportCategory($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'ImportCategory', '\Thelia\Model\ImportCategoryQuery'); + } + + /** + * Exclude object from result + * + * @param ChildImportCategoryI18n $importCategoryI18n Object to remove from the list of results + * + * @return ChildImportCategoryI18nQuery The current query, for fluid interface + */ + public function prune($importCategoryI18n = null) + { + if ($importCategoryI18n) { + $this->addCond('pruneCond0', $this->getAliasedColName(ImportCategoryI18nTableMap::ID), $importCategoryI18n->getId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(ImportCategoryI18nTableMap::LOCALE), $importCategoryI18n->getLocale(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); + } + + return $this; + } + + /** + * Deletes all rows from the import_category_i18n table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportCategoryI18nTableMap::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->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ImportCategoryI18nTableMap::clearInstancePool(); + ImportCategoryI18nTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildImportCategoryI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildImportCategoryI18n object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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 function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportCategoryI18nTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ImportCategoryI18nTableMap::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->beginTransaction(); + + + ImportCategoryI18nTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ImportCategoryI18nTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // ImportCategoryI18nQuery diff --git a/core/lib/Thelia/Model/Base/ImportCategoryQuery.php b/core/lib/Thelia/Model/Base/ImportCategoryQuery.php new file mode 100644 index 000000000..a9dd3115c --- /dev/null +++ b/core/lib/Thelia/Model/Base/ImportCategoryQuery.php @@ -0,0 +1,797 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildImportCategory|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ImportCategoryTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ImportCategoryTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildImportCategory A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `REF`, `POSITION`, `CREATED_AT`, `UPDATED_AT` FROM `import_category` WHERE `ID` = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildImportCategory(); + $obj->hydrate($row); + ImportCategoryTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildImportCategory|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(ImportCategoryTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(ImportCategoryTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ImportCategoryTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ImportCategoryTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ImportCategoryTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the ref column + * + * Example usage: + * + * $query->filterByRef('fooValue'); // WHERE ref = 'fooValue' + * $query->filterByRef('%fooValue%'); // WHERE ref LIKE '%fooValue%' + * + * + * @param string $ref The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function filterByRef($ref = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($ref)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $ref)) { + $ref = str_replace('*', '%', $ref); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ImportCategoryTableMap::REF, $ref, $comparison); + } + + /** + * Filter the query on the position column + * + * Example usage: + * + * $query->filterByPosition(1234); // WHERE position = 1234 + * $query->filterByPosition(array(12, 34)); // WHERE position IN (12, 34) + * $query->filterByPosition(array('min' => 12)); // WHERE position > 12 + * + * + * @param mixed $position The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function filterByPosition($position = null, $comparison = null) + { + if (is_array($position)) { + $useMinMax = false; + if (isset($position['min'])) { + $this->addUsingAlias(ImportCategoryTableMap::POSITION, $position['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($position['max'])) { + $this->addUsingAlias(ImportCategoryTableMap::POSITION, $position['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ImportCategoryTableMap::POSITION, $position, $comparison); + } + + /** + * Filter the query on the created_at column + * + * Example usage: + * + * $query->filterByCreatedAt('2011-03-14'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt('now'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt(array('max' => 'yesterday')); // WHERE created_at > '2011-03-13' + * + * + * @param mixed $createdAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function filterByCreatedAt($createdAt = null, $comparison = null) + { + if (is_array($createdAt)) { + $useMinMax = false; + if (isset($createdAt['min'])) { + $this->addUsingAlias(ImportCategoryTableMap::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($createdAt['max'])) { + $this->addUsingAlias(ImportCategoryTableMap::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ImportCategoryTableMap::CREATED_AT, $createdAt, $comparison); + } + + /** + * Filter the query on the updated_at column + * + * Example usage: + * + * $query->filterByUpdatedAt('2011-03-14'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt('now'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt(array('max' => 'yesterday')); // WHERE updated_at > '2011-03-13' + * + * + * @param mixed $updatedAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function filterByUpdatedAt($updatedAt = null, $comparison = null) + { + if (is_array($updatedAt)) { + $useMinMax = false; + if (isset($updatedAt['min'])) { + $this->addUsingAlias(ImportCategoryTableMap::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($updatedAt['max'])) { + $this->addUsingAlias(ImportCategoryTableMap::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ImportCategoryTableMap::UPDATED_AT, $updatedAt, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Import object + * + * @param \Thelia\Model\Import|ObjectCollection $import the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function filterByImport($import, $comparison = null) + { + if ($import instanceof \Thelia\Model\Import) { + return $this + ->addUsingAlias(ImportCategoryTableMap::ID, $import->getImportCategoryId(), $comparison); + } elseif ($import instanceof ObjectCollection) { + return $this + ->useImportQuery() + ->filterByPrimaryKeys($import->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByImport() only accepts arguments of type \Thelia\Model\Import or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Import relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function joinImport($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Import'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Import'); + } + + return $this; + } + + /** + * Use the Import relation Import object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ImportQuery A secondary query class using the current class as primary query + */ + public function useImportQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinImport($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Import', '\Thelia\Model\ImportQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\ImportCategoryI18n object + * + * @param \Thelia\Model\ImportCategoryI18n|ObjectCollection $importCategoryI18n the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function filterByImportCategoryI18n($importCategoryI18n, $comparison = null) + { + if ($importCategoryI18n instanceof \Thelia\Model\ImportCategoryI18n) { + return $this + ->addUsingAlias(ImportCategoryTableMap::ID, $importCategoryI18n->getId(), $comparison); + } elseif ($importCategoryI18n instanceof ObjectCollection) { + return $this + ->useImportCategoryI18nQuery() + ->filterByPrimaryKeys($importCategoryI18n->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByImportCategoryI18n() only accepts arguments of type \Thelia\Model\ImportCategoryI18n or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the ImportCategoryI18n relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function joinImportCategoryI18n($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('ImportCategoryI18n'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'ImportCategoryI18n'); + } + + return $this; + } + + /** + * Use the ImportCategoryI18n relation ImportCategoryI18n object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ImportCategoryI18nQuery A secondary query class using the current class as primary query + */ + public function useImportCategoryI18nQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinImportCategoryI18n($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'ImportCategoryI18n', '\Thelia\Model\ImportCategoryI18nQuery'); + } + + /** + * Exclude object from result + * + * @param ChildImportCategory $importCategory Object to remove from the list of results + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function prune($importCategory = null) + { + if ($importCategory) { + $this->addUsingAlias(ImportCategoryTableMap::ID, $importCategory->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the import_category table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportCategoryTableMap::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->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ImportCategoryTableMap::clearInstancePool(); + ImportCategoryTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildImportCategory or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildImportCategory object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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 function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportCategoryTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ImportCategoryTableMap::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->beginTransaction(); + + + ImportCategoryTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ImportCategoryTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + // i18n behavior + + /** + * Adds a JOIN clause to the query using the i18n relation + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function joinI18n($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $relationName = $relationAlias ? $relationAlias : 'ImportCategoryI18n'; + + return $this + ->joinImportCategoryI18n($relationAlias, $joinType) + ->addJoinCondition($relationName, $relationName . '.Locale = ?', $locale); + } + + /** + * Adds a JOIN clause to the query and hydrates the related I18n object. + * Shortcut for $c->joinI18n($locale)->with() + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function joinWithI18n($locale = 'en_US', $joinType = Criteria::LEFT_JOIN) + { + $this + ->joinI18n($locale, null, $joinType) + ->with('ImportCategoryI18n'); + $this->with['ImportCategoryI18n']->setIsWithOneToMany(false); + + return $this; + } + + /** + * Use the I18n relation query object + * + * @see useQuery() + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildImportCategoryI18nQuery A secondary query class using the current class as primary query + */ + public function useI18nQuery($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinI18n($locale, $relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'ImportCategoryI18n', '\Thelia\Model\ImportCategoryI18nQuery'); + } + + // timestampable behavior + + /** + * Filter by the latest updated + * + * @param int $nbDays Maximum age of the latest update in days + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function recentlyUpdated($nbDays = 7) + { + return $this->addUsingAlias(ImportCategoryTableMap::UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Filter by the latest created + * + * @param int $nbDays Maximum age of in days + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function recentlyCreated($nbDays = 7) + { + return $this->addUsingAlias(ImportCategoryTableMap::CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Order by update date desc + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function lastUpdatedFirst() + { + return $this->addDescendingOrderByColumn(ImportCategoryTableMap::UPDATED_AT); + } + + /** + * Order by update date asc + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function firstUpdatedFirst() + { + return $this->addAscendingOrderByColumn(ImportCategoryTableMap::UPDATED_AT); + } + + /** + * Order by create date desc + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function lastCreatedFirst() + { + return $this->addDescendingOrderByColumn(ImportCategoryTableMap::CREATED_AT); + } + + /** + * Order by create date asc + * + * @return ChildImportCategoryQuery The current query, for fluid interface + */ + public function firstCreatedFirst() + { + return $this->addAscendingOrderByColumn(ImportCategoryTableMap::CREATED_AT); + } + +} // ImportCategoryQuery diff --git a/core/lib/Thelia/Model/Base/ImportI18n.php b/core/lib/Thelia/Model/Base/ImportI18n.php new file mode 100644 index 000000000..9387e2419 --- /dev/null +++ b/core/lib/Thelia/Model/Base/ImportI18n.php @@ -0,0 +1,1326 @@ +locale = 'en_US'; + } + + /** + * Initializes internal state of Thelia\Model\Base\ImportI18n object. + * @see applyDefaults() + */ + public function __construct() + { + $this->applyDefaultValues(); + } + + /** + * Returns whether the object has been modified. + * + * @return boolean True if the object has been modified. + */ + public function isModified() + { + return !!$this->modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ImportI18n instance. If + * obj is an instance of ImportI18n, delegates to + * equals(ImportI18n). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ImportI18n The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ImportI18n The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [locale] column value. + * + * @return string + */ + public function getLocale() + { + + return $this->locale; + } + + /** + * Get the [title] column value. + * + * @return string + */ + public function getTitle() + { + + return $this->title; + } + + /** + * Get the [description] column value. + * + * @return string + */ + public function getDescription() + { + + return $this->description; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\ImportI18n The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ImportI18nTableMap::ID] = true; + } + + if ($this->aImport !== null && $this->aImport->getId() !== $v) { + $this->aImport = null; + } + + + return $this; + } // setId() + + /** + * Set the value of [locale] column. + * + * @param string $v new value + * @return \Thelia\Model\ImportI18n The current object (for fluent API support) + */ + public function setLocale($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->locale !== $v) { + $this->locale = $v; + $this->modifiedColumns[ImportI18nTableMap::LOCALE] = true; + } + + + return $this; + } // setLocale() + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\ImportI18n The current object (for fluent API support) + */ + public function setTitle($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->title !== $v) { + $this->title = $v; + $this->modifiedColumns[ImportI18nTableMap::TITLE] = true; + } + + + return $this; + } // setTitle() + + /** + * Set the value of [description] column. + * + * @param string $v new value + * @return \Thelia\Model\ImportI18n The current object (for fluent API support) + */ + public function setDescription($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->description !== $v) { + $this->description = $v; + $this->modifiedColumns[ImportI18nTableMap::DESCRIPTION] = true; + } + + + return $this; + } // setDescription() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->locale !== 'en_US') { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-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 array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ImportI18nTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ImportI18nTableMap::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)]; + $this->locale = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ImportI18nTableMap::translateFieldName('Title', TableMap::TYPE_PHPNAME, $indexType)]; + $this->title = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ImportI18nTableMap::translateFieldName('Description', TableMap::TYPE_PHPNAME, $indexType)]; + $this->description = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 4; // 4 = ImportI18nTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\ImportI18n object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aImport !== null && $this->id !== $this->aImport->getId()) { + $this->aImport = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ImportI18nTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildImportI18nQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aImport = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ImportI18n::setDeleted() + * @see ImportI18n::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportI18nTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildImportI18nQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $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(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportI18nTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ImportI18nTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row 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 ConnectionInterface $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(ConnectionInterface $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 corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aImport !== null) { + if ($this->aImport->isModified() || $this->aImport->isNew()) { + $affectedRows += $this->aImport->save($con); + } + $this->setImport($this->aImport); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ImportI18nTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(ImportI18nTableMap::LOCALE)) { + $modifiedColumns[':p' . $index++] = '`LOCALE`'; + } + if ($this->isColumnModified(ImportI18nTableMap::TITLE)) { + $modifiedColumns[':p' . $index++] = '`TITLE`'; + } + if ($this->isColumnModified(ImportI18nTableMap::DESCRIPTION)) { + $modifiedColumns[':p' . $index++] = '`DESCRIPTION`'; + } + + $sql = sprintf( + 'INSERT INTO `import_i18n` (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case '`ID`': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case '`LOCALE`': + $stmt->bindValue($identifier, $this->locale, PDO::PARAM_STR); + break; + case '`TITLE`': + $stmt->bindValue($identifier, $this->title, PDO::PARAM_STR); + break; + case '`DESCRIPTION`': + $stmt->bindValue($identifier, $this->description, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * 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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ImportI18nTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * 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->getId(); + break; + case 1: + return $this->getLocale(); + break; + case 2: + return $this->getTitle(); + break; + case 3: + return $this->getDescription(); + 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 (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['ImportI18n'][serialize($this->getPrimaryKey())])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ImportI18n'][serialize($this->getPrimaryKey())] = true; + $keys = ImportI18nTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getLocale(), + $keys[2] => $this->getTitle(), + $keys[3] => $this->getDescription(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aImport) { + $result['Import'] = $this->aImport->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ImportI18nTableMap::translateFieldName($name, $type, TableMap::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->setId($value); + break; + case 1: + $this->setLocale($value); + break; + case 2: + $this->setTitle($value); + break; + case 3: + $this->setDescription($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 TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @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 = TableMap::TYPE_PHPNAME) + { + $keys = ImportI18nTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setLocale($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setTitle($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setDescription($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(ImportI18nTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ImportI18nTableMap::ID)) $criteria->add(ImportI18nTableMap::ID, $this->id); + if ($this->isColumnModified(ImportI18nTableMap::LOCALE)) $criteria->add(ImportI18nTableMap::LOCALE, $this->locale); + if ($this->isColumnModified(ImportI18nTableMap::TITLE)) $criteria->add(ImportI18nTableMap::TITLE, $this->title); + if ($this->isColumnModified(ImportI18nTableMap::DESCRIPTION)) $criteria->add(ImportI18nTableMap::DESCRIPTION, $this->description); + + 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(ImportI18nTableMap::DATABASE_NAME); + $criteria->add(ImportI18nTableMap::ID, $this->id); + $criteria->add(ImportI18nTableMap::LOCALE, $this->locale); + + 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() + { + $pks = array(); + $pks[0] = $this->getId(); + $pks[1] = $this->getLocale(); + + return $pks; + } + + /** + * 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->setId($keys[0]); + $this->setLocale($keys[1]); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return (null === $this->getId()) && (null === $this->getLocale()); + } + + /** + * 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 \Thelia\Model\ImportI18n (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setId($this->getId()); + $copyObj->setLocale($this->getLocale()); + $copyObj->setTitle($this->getTitle()); + $copyObj->setDescription($this->getDescription()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * 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 \Thelia\Model\ImportI18n 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; + } + + /** + * Declares an association between this object and a ChildImport object. + * + * @param ChildImport $v + * @return \Thelia\Model\ImportI18n The current object (for fluent API support) + * @throws PropelException + */ + public function setImport(ChildImport $v = null) + { + if ($v === null) { + $this->setId(NULL); + } else { + $this->setId($v->getId()); + } + + $this->aImport = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildImport object, it will not be re-added. + if ($v !== null) { + $v->addImportI18n($this); + } + + + return $this; + } + + + /** + * Get the associated ChildImport object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildImport The associated ChildImport object. + * @throws PropelException + */ + public function getImport(ConnectionInterface $con = null) + { + if ($this->aImport === null && ($this->id !== null)) { + $this->aImport = ChildImportQuery::create()->findPk($this->id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aImport->addImportI18ns($this); + */ + } + + return $this->aImport; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->locale = null; + $this->title = null; + $this->description = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aImport = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ImportI18nTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/core/lib/Thelia/Model/Base/ImportI18nQuery.php b/core/lib/Thelia/Model/Base/ImportI18nQuery.php new file mode 100644 index 000000000..630823b9e --- /dev/null +++ b/core/lib/Thelia/Model/Base/ImportI18nQuery.php @@ -0,0 +1,541 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(array(12, 34), $con); + * + * + * @param array[$id, $locale] $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildImportI18n|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ImportI18nTableMap::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1]))))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ImportI18nTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildImportI18n A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `LOCALE`, `TITLE`, `DESCRIPTION` FROM `import_i18n` WHERE `ID` = :p0 AND `LOCALE` = :p1'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); + $stmt->bindValue(':p1', $key[1], PDO::PARAM_STR); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildImportI18n(); + $obj->hydrate($row); + ImportI18nTableMap::addInstanceToPool($obj, serialize(array((string) $key[0], (string) $key[1]))); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildImportI18n|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildImportI18nQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + $this->addUsingAlias(ImportI18nTableMap::ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(ImportI18nTableMap::LOCALE, $key[1], Criteria::EQUAL); + + return $this; + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildImportI18nQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + if (empty($keys)) { + return $this->add(null, '1<>1', Criteria::CUSTOM); + } + foreach ($keys as $key) { + $cton0 = $this->getNewCriterion(ImportI18nTableMap::ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(ImportI18nTableMap::LOCALE, $key[1], Criteria::EQUAL); + $cton0->addAnd($cton1); + $this->addOr($cton0); + } + + return $this; + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @see filterByImport() + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportI18nQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ImportI18nTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ImportI18nTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ImportI18nTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the locale column + * + * Example usage: + * + * $query->filterByLocale('fooValue'); // WHERE locale = 'fooValue' + * $query->filterByLocale('%fooValue%'); // WHERE locale LIKE '%fooValue%' + * + * + * @param string $locale The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportI18nQuery The current query, for fluid interface + */ + public function filterByLocale($locale = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($locale)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $locale)) { + $locale = str_replace('*', '%', $locale); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ImportI18nTableMap::LOCALE, $locale, $comparison); + } + + /** + * Filter the query on the title column + * + * Example usage: + * + * $query->filterByTitle('fooValue'); // WHERE title = 'fooValue' + * $query->filterByTitle('%fooValue%'); // WHERE title LIKE '%fooValue%' + * + * + * @param string $title The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportI18nQuery The current query, for fluid interface + */ + public function filterByTitle($title = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($title)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $title)) { + $title = str_replace('*', '%', $title); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ImportI18nTableMap::TITLE, $title, $comparison); + } + + /** + * Filter the query on the description column + * + * Example usage: + * + * $query->filterByDescription('fooValue'); // WHERE description = 'fooValue' + * $query->filterByDescription('%fooValue%'); // WHERE description LIKE '%fooValue%' + * + * + * @param string $description The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportI18nQuery The current query, for fluid interface + */ + public function filterByDescription($description = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($description)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $description)) { + $description = str_replace('*', '%', $description); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ImportI18nTableMap::DESCRIPTION, $description, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Import object + * + * @param \Thelia\Model\Import|ObjectCollection $import The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportI18nQuery The current query, for fluid interface + */ + public function filterByImport($import, $comparison = null) + { + if ($import instanceof \Thelia\Model\Import) { + return $this + ->addUsingAlias(ImportI18nTableMap::ID, $import->getId(), $comparison); + } elseif ($import instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ImportI18nTableMap::ID, $import->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByImport() only accepts arguments of type \Thelia\Model\Import or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Import relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildImportI18nQuery The current query, for fluid interface + */ + public function joinImport($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Import'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Import'); + } + + return $this; + } + + /** + * Use the Import relation Import object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ImportQuery A secondary query class using the current class as primary query + */ + public function useImportQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinImport($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Import', '\Thelia\Model\ImportQuery'); + } + + /** + * Exclude object from result + * + * @param ChildImportI18n $importI18n Object to remove from the list of results + * + * @return ChildImportI18nQuery The current query, for fluid interface + */ + public function prune($importI18n = null) + { + if ($importI18n) { + $this->addCond('pruneCond0', $this->getAliasedColName(ImportI18nTableMap::ID), $importI18n->getId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(ImportI18nTableMap::LOCALE), $importI18n->getLocale(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); + } + + return $this; + } + + /** + * Deletes all rows from the import_i18n table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportI18nTableMap::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->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ImportI18nTableMap::clearInstancePool(); + ImportI18nTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildImportI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildImportI18n object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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 function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportI18nTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ImportI18nTableMap::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->beginTransaction(); + + + ImportI18nTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ImportI18nTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // ImportI18nQuery diff --git a/core/lib/Thelia/Model/Base/ImportQuery.php b/core/lib/Thelia/Model/Base/ImportQuery.php new file mode 100644 index 000000000..434952923 --- /dev/null +++ b/core/lib/Thelia/Model/Base/ImportQuery.php @@ -0,0 +1,879 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildImport|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ImportTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ImportTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildImport A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `REF`, `IMPORT_CATEGORY_ID`, `POSITION`, `HANDLE_CLASS`, `CREATED_AT`, `UPDATED_AT` FROM `import` WHERE `ID` = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildImport(); + $obj->hydrate($row); + ImportTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildImport|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(ImportTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(ImportTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ImportTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ImportTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ImportTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the ref column + * + * Example usage: + * + * $query->filterByRef('fooValue'); // WHERE ref = 'fooValue' + * $query->filterByRef('%fooValue%'); // WHERE ref LIKE '%fooValue%' + * + * + * @param string $ref The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function filterByRef($ref = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($ref)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $ref)) { + $ref = str_replace('*', '%', $ref); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ImportTableMap::REF, $ref, $comparison); + } + + /** + * Filter the query on the import_category_id column + * + * Example usage: + * + * $query->filterByImportCategoryId(1234); // WHERE import_category_id = 1234 + * $query->filterByImportCategoryId(array(12, 34)); // WHERE import_category_id IN (12, 34) + * $query->filterByImportCategoryId(array('min' => 12)); // WHERE import_category_id > 12 + * + * + * @see filterByImportCategory() + * + * @param mixed $importCategoryId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function filterByImportCategoryId($importCategoryId = null, $comparison = null) + { + if (is_array($importCategoryId)) { + $useMinMax = false; + if (isset($importCategoryId['min'])) { + $this->addUsingAlias(ImportTableMap::IMPORT_CATEGORY_ID, $importCategoryId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($importCategoryId['max'])) { + $this->addUsingAlias(ImportTableMap::IMPORT_CATEGORY_ID, $importCategoryId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ImportTableMap::IMPORT_CATEGORY_ID, $importCategoryId, $comparison); + } + + /** + * Filter the query on the position column + * + * Example usage: + * + * $query->filterByPosition(1234); // WHERE position = 1234 + * $query->filterByPosition(array(12, 34)); // WHERE position IN (12, 34) + * $query->filterByPosition(array('min' => 12)); // WHERE position > 12 + * + * + * @param mixed $position The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function filterByPosition($position = null, $comparison = null) + { + if (is_array($position)) { + $useMinMax = false; + if (isset($position['min'])) { + $this->addUsingAlias(ImportTableMap::POSITION, $position['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($position['max'])) { + $this->addUsingAlias(ImportTableMap::POSITION, $position['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ImportTableMap::POSITION, $position, $comparison); + } + + /** + * Filter the query on the handle_class column + * + * Example usage: + * + * $query->filterByHandleClass('fooValue'); // WHERE handle_class = 'fooValue' + * $query->filterByHandleClass('%fooValue%'); // WHERE handle_class LIKE '%fooValue%' + * + * + * @param string $handleClass The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function filterByHandleClass($handleClass = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($handleClass)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $handleClass)) { + $handleClass = str_replace('*', '%', $handleClass); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ImportTableMap::HANDLE_CLASS, $handleClass, $comparison); + } + + /** + * Filter the query on the created_at column + * + * Example usage: + * + * $query->filterByCreatedAt('2011-03-14'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt('now'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt(array('max' => 'yesterday')); // WHERE created_at > '2011-03-13' + * + * + * @param mixed $createdAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function filterByCreatedAt($createdAt = null, $comparison = null) + { + if (is_array($createdAt)) { + $useMinMax = false; + if (isset($createdAt['min'])) { + $this->addUsingAlias(ImportTableMap::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($createdAt['max'])) { + $this->addUsingAlias(ImportTableMap::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ImportTableMap::CREATED_AT, $createdAt, $comparison); + } + + /** + * Filter the query on the updated_at column + * + * Example usage: + * + * $query->filterByUpdatedAt('2011-03-14'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt('now'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt(array('max' => 'yesterday')); // WHERE updated_at > '2011-03-13' + * + * + * @param mixed $updatedAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function filterByUpdatedAt($updatedAt = null, $comparison = null) + { + if (is_array($updatedAt)) { + $useMinMax = false; + if (isset($updatedAt['min'])) { + $this->addUsingAlias(ImportTableMap::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($updatedAt['max'])) { + $this->addUsingAlias(ImportTableMap::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ImportTableMap::UPDATED_AT, $updatedAt, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\ImportCategory object + * + * @param \Thelia\Model\ImportCategory|ObjectCollection $importCategory The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function filterByImportCategory($importCategory, $comparison = null) + { + if ($importCategory instanceof \Thelia\Model\ImportCategory) { + return $this + ->addUsingAlias(ImportTableMap::IMPORT_CATEGORY_ID, $importCategory->getId(), $comparison); + } elseif ($importCategory instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ImportTableMap::IMPORT_CATEGORY_ID, $importCategory->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByImportCategory() only accepts arguments of type \Thelia\Model\ImportCategory or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the ImportCategory relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function joinImportCategory($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('ImportCategory'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'ImportCategory'); + } + + return $this; + } + + /** + * Use the ImportCategory relation ImportCategory object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ImportCategoryQuery A secondary query class using the current class as primary query + */ + public function useImportCategoryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinImportCategory($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'ImportCategory', '\Thelia\Model\ImportCategoryQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\ImportI18n object + * + * @param \Thelia\Model\ImportI18n|ObjectCollection $importI18n the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function filterByImportI18n($importI18n, $comparison = null) + { + if ($importI18n instanceof \Thelia\Model\ImportI18n) { + return $this + ->addUsingAlias(ImportTableMap::ID, $importI18n->getId(), $comparison); + } elseif ($importI18n instanceof ObjectCollection) { + return $this + ->useImportI18nQuery() + ->filterByPrimaryKeys($importI18n->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByImportI18n() only accepts arguments of type \Thelia\Model\ImportI18n or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the ImportI18n relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function joinImportI18n($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('ImportI18n'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'ImportI18n'); + } + + return $this; + } + + /** + * Use the ImportI18n relation ImportI18n object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\ImportI18nQuery A secondary query class using the current class as primary query + */ + public function useImportI18nQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinImportI18n($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'ImportI18n', '\Thelia\Model\ImportI18nQuery'); + } + + /** + * Exclude object from result + * + * @param ChildImport $import Object to remove from the list of results + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function prune($import = null) + { + if ($import) { + $this->addUsingAlias(ImportTableMap::ID, $import->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the import table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportTableMap::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->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ImportTableMap::clearInstancePool(); + ImportTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildImport or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildImport object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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 function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ImportTableMap::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->beginTransaction(); + + + ImportTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ImportTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + // i18n behavior + + /** + * Adds a JOIN clause to the query using the i18n relation + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function joinI18n($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $relationName = $relationAlias ? $relationAlias : 'ImportI18n'; + + return $this + ->joinImportI18n($relationAlias, $joinType) + ->addJoinCondition($relationName, $relationName . '.Locale = ?', $locale); + } + + /** + * Adds a JOIN clause to the query and hydrates the related I18n object. + * Shortcut for $c->joinI18n($locale)->with() + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function joinWithI18n($locale = 'en_US', $joinType = Criteria::LEFT_JOIN) + { + $this + ->joinI18n($locale, null, $joinType) + ->with('ImportI18n'); + $this->with['ImportI18n']->setIsWithOneToMany(false); + + return $this; + } + + /** + * Use the I18n relation query object + * + * @see useQuery() + * + * @param string $locale Locale to use for the join condition, e.g. 'fr_FR' + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'. Defaults to left join. + * + * @return ChildImportI18nQuery A secondary query class using the current class as primary query + */ + public function useI18nQuery($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinI18n($locale, $relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'ImportI18n', '\Thelia\Model\ImportI18nQuery'); + } + + // timestampable behavior + + /** + * Filter by the latest updated + * + * @param int $nbDays Maximum age of the latest update in days + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function recentlyUpdated($nbDays = 7) + { + return $this->addUsingAlias(ImportTableMap::UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Filter by the latest created + * + * @param int $nbDays Maximum age of in days + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function recentlyCreated($nbDays = 7) + { + return $this->addUsingAlias(ImportTableMap::CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Order by update date desc + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function lastUpdatedFirst() + { + return $this->addDescendingOrderByColumn(ImportTableMap::UPDATED_AT); + } + + /** + * Order by update date asc + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function firstUpdatedFirst() + { + return $this->addAscendingOrderByColumn(ImportTableMap::UPDATED_AT); + } + + /** + * Order by create date desc + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function lastCreatedFirst() + { + return $this->addDescendingOrderByColumn(ImportTableMap::CREATED_AT); + } + + /** + * Order by create date asc + * + * @return ChildImportQuery The current query, for fluid interface + */ + public function firstCreatedFirst() + { + return $this->addAscendingOrderByColumn(ImportTableMap::CREATED_AT); + } + +} // ImportQuery diff --git a/core/lib/Thelia/Model/Brand.php b/core/lib/Thelia/Model/Brand.php index a153e1bc7..76d1f991d 100644 --- a/core/lib/Thelia/Model/Brand.php +++ b/core/lib/Thelia/Model/Brand.php @@ -22,7 +22,7 @@ class Brand extends BaseBrand implements FileModelParentInterface /** * {@inheritDoc} */ - protected function getRewrittenUrlViewName() + public function getRewrittenUrlViewName() { return 'brand'; } @@ -81,7 +81,7 @@ class Brand extends BaseBrand implements FileModelParentInterface */ public function postDelete(ConnectionInterface $con = null) { - $this->markRewritenUrlObsolete(); + $this->markRewrittenUrlObsolete(); $this->dispatchEvent(TheliaEvents::AFTER_DELETEBRAND, new BrandEvent($this)); } diff --git a/core/lib/Thelia/Model/Category.php b/core/lib/Thelia/Model/Category.php index efa96c245..15b18f529 100644 --- a/core/lib/Thelia/Model/Category.php +++ b/core/lib/Thelia/Model/Category.php @@ -31,7 +31,7 @@ class Category extends BaseCategory implements FileModelParentInterface /** * {@inheritDoc} */ - protected function getRewrittenUrlViewName() + public function getRewrittenUrlViewName() { return 'category'; } @@ -166,7 +166,7 @@ class Category extends BaseCategory implements FileModelParentInterface */ public function postDelete(ConnectionInterface $con = null) { - $this->markRewritenUrlObsolete(); + $this->markRewrittenUrlObsolete(); //delete all subcategories $subCategories = CategoryQuery::findAllChild($this->getId()); diff --git a/core/lib/Thelia/Model/Content.php b/core/lib/Thelia/Model/Content.php index f5968bb37..8cfadab74 100644 --- a/core/lib/Thelia/Model/Content.php +++ b/core/lib/Thelia/Model/Content.php @@ -27,7 +27,7 @@ class Content extends BaseContent implements FileModelParentInterface /** * {@inheritDoc} */ - protected function getRewrittenUrlViewName() + public function getRewrittenUrlViewName() { return 'content'; } @@ -170,7 +170,7 @@ class Content extends BaseContent implements FileModelParentInterface public function postDelete(ConnectionInterface $con = null) { - $this->markRewritenUrlObsolete(); + $this->markRewrittenUrlObsolete(); $this->dispatchEvent(TheliaEvents::AFTER_DELETECONTENT, new ContentEvent($this)); } diff --git a/core/lib/Thelia/Model/Export.php b/core/lib/Thelia/Model/Export.php new file mode 100644 index 000000000..fdd9e578b --- /dev/null +++ b/core/lib/Thelia/Model/Export.php @@ -0,0 +1,94 @@ +getHandleClass(); + + if ($class[0] !== "\\") { + $class = "\\" . $class; + } + + if (!class_exists($class)) { + $this->delete(); + + throw new \ErrorException( + Translator::getInstance()->trans( + "The class \"%class\" doesn't exist", + [ + "%class" => $class + ] + ) + ); + } + + $instance = new $class($container); + + if (!$instance instanceof ExportHandler) { + $this->delete(); + + throw new \ErrorException( + Translator::getInstance()->trans( + "The class \"%class\" must extend %baseClass", + [ + "%class" => $class, + "%baseClass" => "Thelia\\ImportExport\\Export\\ExportHandler", + ] + ) + ); + } + + return static::$cache = $instance; + } + + public function hasImages(ContainerInterface $container) + { + if (static::$cache === null) { + $this->getHandleClassInstance($container); + } + + return static::$cache instanceof ImagesExportInterface; + } + + public function hasDocuments(ContainerInterface $container) + { + if (static::$cache === null) { + $this->getHandleClassInstance($container); + } + + return static::$cache instanceof DocumentsExportInterface; + } + + /** + * {@inheritDoc} + */ + public function preInsert(ConnectionInterface $con = null) + { + $this->setPosition($this->getNextPosition()); + + return true; + } +} diff --git a/core/lib/Thelia/Model/ExportCategory.php b/core/lib/Thelia/Model/ExportCategory.php new file mode 100644 index 000000000..f6e155eea --- /dev/null +++ b/core/lib/Thelia/Model/ExportCategory.php @@ -0,0 +1,13 @@ +markRewritenUrlObsolete(); + $this->markRewrittenUrlObsolete(); $this->dispatchEvent(TheliaEvents::AFTER_DELETEFOLDER, new FolderEvent($this)); } diff --git a/core/lib/Thelia/Model/Import.php b/core/lib/Thelia/Model/Import.php new file mode 100644 index 000000000..f7cbb1000 --- /dev/null +++ b/core/lib/Thelia/Model/Import.php @@ -0,0 +1,60 @@ +getHandleClass(); + + if (!class_exists($class)) { + $this->delete(); + + throw new ClassNotFoundException( + Translator::getInstance()->trans( + "The class \"%class\" doesn't exist", + [ + "%class" => $class + ] + ) + ); + } + + $instance = new $class($container); + + if (!$instance instanceof ImportHandler) { + $this->delete(); + + throw new \ErrorException( + Translator::getInstance()->trans( + "The class \"%class\" must extend %baseClass", + [ + "%class" => $class, + "%baseClass" => "Thelia\\ImportExport\\Import\\ImportHandler", + ] + ) + ); + } + + return $instance; + } +} diff --git a/core/lib/Thelia/Model/ImportCategory.php b/core/lib/Thelia/Model/ImportCategory.php new file mode 100644 index 000000000..6aca35800 --- /dev/null +++ b/core/lib/Thelia/Model/ImportCategory.php @@ -0,0 +1,13 @@ + array('Id', 'Locale', 'Title', ), + self::TYPE_STUDLYPHPNAME => array('id', 'locale', 'title', ), + self::TYPE_COLNAME => array(ExportCategoryI18nTableMap::ID, ExportCategoryI18nTableMap::LOCALE, ExportCategoryI18nTableMap::TITLE, ), + self::TYPE_RAW_COLNAME => array('ID', 'LOCALE', 'TITLE', ), + self::TYPE_FIELDNAME => array('id', 'locale', 'title', ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'Locale' => 1, 'Title' => 2, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'locale' => 1, 'title' => 2, ), + self::TYPE_COLNAME => array(ExportCategoryI18nTableMap::ID => 0, ExportCategoryI18nTableMap::LOCALE => 1, ExportCategoryI18nTableMap::TITLE => 2, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'LOCALE' => 1, 'TITLE' => 2, ), + self::TYPE_FIELDNAME => array('id' => 0, 'locale' => 1, 'title' => 2, ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('export_category_i18n'); + $this->setPhpName('ExportCategoryI18n'); + $this->setClassName('\\Thelia\\Model\\ExportCategoryI18n'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addForeignPrimaryKey('ID', 'Id', 'INTEGER' , 'export_category', 'ID', true, null, null); + $this->addPrimaryKey('LOCALE', 'Locale', 'VARCHAR', true, 5, 'en_US'); + $this->addColumn('TITLE', 'Title', 'VARCHAR', true, 255, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('ExportCategory', '\\Thelia\\Model\\ExportCategory', RelationMap::MANY_TO_ONE, array('id' => 'id', ), 'CASCADE', null); + } // buildRelations() + + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by find*() + * and findPk*() calls. + * + * @param \Thelia\Model\ExportCategoryI18n $obj A \Thelia\Model\ExportCategoryI18n object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool($obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if (null === $key) { + $key = serialize(array((string) $obj->getId(), (string) $obj->getLocale())); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A \Thelia\Model\ExportCategoryI18n object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\ExportCategoryI18n) { + $key = serialize(array((string) $value->getId(), (string) $value->getLocale())); + + } elseif (is_array($value) && count($value) === 2) { + // assume we've been passed a primary key"; + $key = serialize(array((string) $value[0], (string) $value[1])); + } elseif ($value instanceof Criteria) { + self::$instances = []; + + return; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or \Thelia\Model\ExportCategoryI18n object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value, true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)])); + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return $pks; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ExportCategoryI18nTableMap::CLASS_DEFAULT : ExportCategoryI18nTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ExportCategoryI18n object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ExportCategoryI18nTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ExportCategoryI18nTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ExportCategoryI18nTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ExportCategoryI18nTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ExportCategoryI18nTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ExportCategoryI18nTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ExportCategoryI18nTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ExportCategoryI18nTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * 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 $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ExportCategoryI18nTableMap::ID); + $criteria->addSelectColumn(ExportCategoryI18nTableMap::LOCALE); + $criteria->addSelectColumn(ExportCategoryI18nTableMap::TITLE); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.LOCALE'); + $criteria->addSelectColumn($alias . '.TITLE'); + } + } + + /** + * Returns the TableMap related to this object. + * 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::getServiceContainer()->getDatabaseMap(ExportCategoryI18nTableMap::DATABASE_NAME)->getTable(ExportCategoryI18nTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ExportCategoryI18nTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ExportCategoryI18nTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ExportCategoryI18nTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ExportCategoryI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ExportCategoryI18n object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportCategoryI18nTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\ExportCategoryI18n) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ExportCategoryI18nTableMap::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); + } + foreach ($values as $value) { + $criterion = $criteria->getNewCriterion(ExportCategoryI18nTableMap::ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(ExportCategoryI18nTableMap::LOCALE, $value[1])); + $criteria->addOr($criterion); + } + } + + $query = ExportCategoryI18nQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ExportCategoryI18nTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ExportCategoryI18nTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the export_category_i18n table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ExportCategoryI18nQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ExportCategoryI18n or Criteria object. + * + * @param mixed $criteria Criteria or ExportCategoryI18n object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface 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($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportCategoryI18nTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ExportCategoryI18n object + } + + + // Set the correct dbName + $query = ExportCategoryI18nQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ExportCategoryI18nTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ExportCategoryI18nTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/ExportCategoryTableMap.php b/core/lib/Thelia/Model/Map/ExportCategoryTableMap.php new file mode 100644 index 000000000..b5888f849 --- /dev/null +++ b/core/lib/Thelia/Model/Map/ExportCategoryTableMap.php @@ -0,0 +1,469 @@ + array('Id', 'Ref', 'Position', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'ref', 'position', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(ExportCategoryTableMap::ID, ExportCategoryTableMap::REF, ExportCategoryTableMap::POSITION, ExportCategoryTableMap::CREATED_AT, ExportCategoryTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'REF', 'POSITION', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'ref', 'position', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'Ref' => 1, 'Position' => 2, 'CreatedAt' => 3, 'UpdatedAt' => 4, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'ref' => 1, 'position' => 2, 'createdAt' => 3, 'updatedAt' => 4, ), + self::TYPE_COLNAME => array(ExportCategoryTableMap::ID => 0, ExportCategoryTableMap::REF => 1, ExportCategoryTableMap::POSITION => 2, ExportCategoryTableMap::CREATED_AT => 3, ExportCategoryTableMap::UPDATED_AT => 4, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'REF' => 1, 'POSITION' => 2, 'CREATED_AT' => 3, 'UPDATED_AT' => 4, ), + self::TYPE_FIELDNAME => array('id' => 0, 'ref' => 1, 'position' => 2, 'created_at' => 3, 'updated_at' => 4, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('export_category'); + $this->setPhpName('ExportCategory'); + $this->setClassName('\\Thelia\\Model\\ExportCategory'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addColumn('REF', 'Ref', 'VARCHAR', true, 255, null); + $this->addColumn('POSITION', 'Position', 'INTEGER', true, null, null); + $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); + $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Export', '\\Thelia\\Model\\Export', RelationMap::ONE_TO_MANY, array('id' => 'export_category_id', ), 'CASCADE', 'RESTRICT', 'Exports'); + $this->addRelation('ExportCategoryI18n', '\\Thelia\\Model\\ExportCategoryI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'ExportCategoryI18ns'); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'i18n' => array('i18n_table' => '%TABLE%_i18n', 'i18n_phpname' => '%PHPNAME%I18n', 'i18n_columns' => 'title', 'locale_column' => 'locale', 'locale_length' => '5', 'default_locale' => '', 'locale_alias' => '', ), + 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), + ); + } // getBehaviors() + /** + * Method to invalidate the instance pool of all tables related to export_category * by a foreign key with ON DELETE CASCADE + */ + public static function clearRelatedInstancePool() + { + // Invalidate objects in ".$this->getClassNameFromBuilder($joinedTableTableMapBuilder)." instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + ExportTableMap::clearInstancePool(); + ExportCategoryI18nTableMap::clearInstancePool(); + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ExportCategoryTableMap::CLASS_DEFAULT : ExportCategoryTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ExportCategory object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ExportCategoryTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ExportCategoryTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ExportCategoryTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ExportCategoryTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ExportCategoryTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ExportCategoryTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ExportCategoryTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ExportCategoryTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * 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 $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ExportCategoryTableMap::ID); + $criteria->addSelectColumn(ExportCategoryTableMap::REF); + $criteria->addSelectColumn(ExportCategoryTableMap::POSITION); + $criteria->addSelectColumn(ExportCategoryTableMap::CREATED_AT); + $criteria->addSelectColumn(ExportCategoryTableMap::UPDATED_AT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.REF'); + $criteria->addSelectColumn($alias . '.POSITION'); + $criteria->addSelectColumn($alias . '.CREATED_AT'); + $criteria->addSelectColumn($alias . '.UPDATED_AT'); + } + } + + /** + * Returns the TableMap related to this object. + * 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::getServiceContainer()->getDatabaseMap(ExportCategoryTableMap::DATABASE_NAME)->getTable(ExportCategoryTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ExportCategoryTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ExportCategoryTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ExportCategoryTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ExportCategory or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ExportCategory object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportCategoryTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\ExportCategory) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ExportCategoryTableMap::DATABASE_NAME); + $criteria->add(ExportCategoryTableMap::ID, (array) $values, Criteria::IN); + } + + $query = ExportCategoryQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ExportCategoryTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ExportCategoryTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the export_category table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ExportCategoryQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ExportCategory or Criteria object. + * + * @param mixed $criteria Criteria or ExportCategory object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface 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($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportCategoryTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ExportCategory object + } + + if ($criteria->containsKey(ExportCategoryTableMap::ID) && $criteria->keyContainsValue(ExportCategoryTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.ExportCategoryTableMap::ID.')'); + } + + + // Set the correct dbName + $query = ExportCategoryQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ExportCategoryTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ExportCategoryTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/ExportI18nTableMap.php b/core/lib/Thelia/Model/Map/ExportI18nTableMap.php new file mode 100644 index 000000000..228a4e288 --- /dev/null +++ b/core/lib/Thelia/Model/Map/ExportI18nTableMap.php @@ -0,0 +1,482 @@ + array('Id', 'Locale', 'Title', 'Description', ), + self::TYPE_STUDLYPHPNAME => array('id', 'locale', 'title', 'description', ), + self::TYPE_COLNAME => array(ExportI18nTableMap::ID, ExportI18nTableMap::LOCALE, ExportI18nTableMap::TITLE, ExportI18nTableMap::DESCRIPTION, ), + self::TYPE_RAW_COLNAME => array('ID', 'LOCALE', 'TITLE', 'DESCRIPTION', ), + self::TYPE_FIELDNAME => array('id', 'locale', 'title', 'description', ), + self::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::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'Locale' => 1, 'Title' => 2, 'Description' => 3, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'locale' => 1, 'title' => 2, 'description' => 3, ), + self::TYPE_COLNAME => array(ExportI18nTableMap::ID => 0, ExportI18nTableMap::LOCALE => 1, ExportI18nTableMap::TITLE => 2, ExportI18nTableMap::DESCRIPTION => 3, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'LOCALE' => 1, 'TITLE' => 2, 'DESCRIPTION' => 3, ), + self::TYPE_FIELDNAME => array('id' => 0, 'locale' => 1, 'title' => 2, 'description' => 3, ), + self::TYPE_NUM => array(0, 1, 2, 3, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('export_i18n'); + $this->setPhpName('ExportI18n'); + $this->setClassName('\\Thelia\\Model\\ExportI18n'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addForeignPrimaryKey('ID', 'Id', 'INTEGER' , 'export', 'ID', true, null, null); + $this->addPrimaryKey('LOCALE', 'Locale', 'VARCHAR', true, 5, 'en_US'); + $this->addColumn('TITLE', 'Title', 'VARCHAR', true, 255, null); + $this->addColumn('DESCRIPTION', 'Description', 'CLOB', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Export', '\\Thelia\\Model\\Export', RelationMap::MANY_TO_ONE, array('id' => 'id', ), 'CASCADE', null); + } // buildRelations() + + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by find*() + * and findPk*() calls. + * + * @param \Thelia\Model\ExportI18n $obj A \Thelia\Model\ExportI18n object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool($obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if (null === $key) { + $key = serialize(array((string) $obj->getId(), (string) $obj->getLocale())); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A \Thelia\Model\ExportI18n object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\ExportI18n) { + $key = serialize(array((string) $value->getId(), (string) $value->getLocale())); + + } elseif (is_array($value) && count($value) === 2) { + // assume we've been passed a primary key"; + $key = serialize(array((string) $value[0], (string) $value[1])); + } elseif ($value instanceof Criteria) { + self::$instances = []; + + return; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or \Thelia\Model\ExportI18n object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value, true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)])); + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return $pks; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ExportI18nTableMap::CLASS_DEFAULT : ExportI18nTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ExportI18n object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ExportI18nTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ExportI18nTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ExportI18nTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ExportI18nTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ExportI18nTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ExportI18nTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ExportI18nTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ExportI18nTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * 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 $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ExportI18nTableMap::ID); + $criteria->addSelectColumn(ExportI18nTableMap::LOCALE); + $criteria->addSelectColumn(ExportI18nTableMap::TITLE); + $criteria->addSelectColumn(ExportI18nTableMap::DESCRIPTION); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.LOCALE'); + $criteria->addSelectColumn($alias . '.TITLE'); + $criteria->addSelectColumn($alias . '.DESCRIPTION'); + } + } + + /** + * Returns the TableMap related to this object. + * 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::getServiceContainer()->getDatabaseMap(ExportI18nTableMap::DATABASE_NAME)->getTable(ExportI18nTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ExportI18nTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ExportI18nTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ExportI18nTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ExportI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ExportI18n object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportI18nTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\ExportI18n) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ExportI18nTableMap::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); + } + foreach ($values as $value) { + $criterion = $criteria->getNewCriterion(ExportI18nTableMap::ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(ExportI18nTableMap::LOCALE, $value[1])); + $criteria->addOr($criterion); + } + } + + $query = ExportI18nQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ExportI18nTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ExportI18nTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the export_i18n table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ExportI18nQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ExportI18n or Criteria object. + * + * @param mixed $criteria Criteria or ExportI18n object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface 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($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportI18nTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ExportI18n object + } + + + // Set the correct dbName + $query = ExportI18nQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ExportI18nTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ExportI18nTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/ExportTableMap.php b/core/lib/Thelia/Model/Map/ExportTableMap.php new file mode 100644 index 000000000..27293ab25 --- /dev/null +++ b/core/lib/Thelia/Model/Map/ExportTableMap.php @@ -0,0 +1,484 @@ + array('Id', 'Ref', 'ExportCategoryId', 'Position', 'HandleClass', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'ref', 'exportCategoryId', 'position', 'handleClass', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(ExportTableMap::ID, ExportTableMap::REF, ExportTableMap::EXPORT_CATEGORY_ID, ExportTableMap::POSITION, ExportTableMap::HANDLE_CLASS, ExportTableMap::CREATED_AT, ExportTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'REF', 'EXPORT_CATEGORY_ID', 'POSITION', 'HANDLE_CLASS', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'ref', 'export_category_id', 'position', 'handle_class', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'Ref' => 1, 'ExportCategoryId' => 2, 'Position' => 3, 'HandleClass' => 4, 'CreatedAt' => 5, 'UpdatedAt' => 6, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'ref' => 1, 'exportCategoryId' => 2, 'position' => 3, 'handleClass' => 4, 'createdAt' => 5, 'updatedAt' => 6, ), + self::TYPE_COLNAME => array(ExportTableMap::ID => 0, ExportTableMap::REF => 1, ExportTableMap::EXPORT_CATEGORY_ID => 2, ExportTableMap::POSITION => 3, ExportTableMap::HANDLE_CLASS => 4, ExportTableMap::CREATED_AT => 5, ExportTableMap::UPDATED_AT => 6, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'REF' => 1, 'EXPORT_CATEGORY_ID' => 2, 'POSITION' => 3, 'HANDLE_CLASS' => 4, 'CREATED_AT' => 5, 'UPDATED_AT' => 6, ), + self::TYPE_FIELDNAME => array('id' => 0, 'ref' => 1, 'export_category_id' => 2, 'position' => 3, 'handle_class' => 4, 'created_at' => 5, 'updated_at' => 6, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('export'); + $this->setPhpName('Export'); + $this->setClassName('\\Thelia\\Model\\Export'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addColumn('REF', 'Ref', 'VARCHAR', true, 255, null); + $this->addForeignKey('EXPORT_CATEGORY_ID', 'ExportCategoryId', 'INTEGER', 'export_category', 'ID', true, null, null); + $this->addColumn('POSITION', 'Position', 'INTEGER', true, null, null); + $this->addColumn('HANDLE_CLASS', 'HandleClass', 'CLOB', true, null, null); + $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); + $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('ExportCategory', '\\Thelia\\Model\\ExportCategory', RelationMap::MANY_TO_ONE, array('export_category_id' => 'id', ), 'CASCADE', 'RESTRICT'); + $this->addRelation('ExportI18n', '\\Thelia\\Model\\ExportI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'ExportI18ns'); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'i18n' => array('i18n_table' => '%TABLE%_i18n', 'i18n_phpname' => '%PHPNAME%I18n', 'i18n_columns' => 'title, description', 'locale_column' => 'locale', 'locale_length' => '5', 'default_locale' => '', 'locale_alias' => '', ), + 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), + ); + } // getBehaviors() + /** + * Method to invalidate the instance pool of all tables related to export * by a foreign key with ON DELETE CASCADE + */ + public static function clearRelatedInstancePool() + { + // Invalidate objects in ".$this->getClassNameFromBuilder($joinedTableTableMapBuilder)." instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + ExportI18nTableMap::clearInstancePool(); + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ExportTableMap::CLASS_DEFAULT : ExportTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (Export object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ExportTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ExportTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ExportTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ExportTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ExportTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ExportTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ExportTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ExportTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * 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 $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ExportTableMap::ID); + $criteria->addSelectColumn(ExportTableMap::REF); + $criteria->addSelectColumn(ExportTableMap::EXPORT_CATEGORY_ID); + $criteria->addSelectColumn(ExportTableMap::POSITION); + $criteria->addSelectColumn(ExportTableMap::HANDLE_CLASS); + $criteria->addSelectColumn(ExportTableMap::CREATED_AT); + $criteria->addSelectColumn(ExportTableMap::UPDATED_AT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.REF'); + $criteria->addSelectColumn($alias . '.EXPORT_CATEGORY_ID'); + $criteria->addSelectColumn($alias . '.POSITION'); + $criteria->addSelectColumn($alias . '.HANDLE_CLASS'); + $criteria->addSelectColumn($alias . '.CREATED_AT'); + $criteria->addSelectColumn($alias . '.UPDATED_AT'); + } + } + + /** + * Returns the TableMap related to this object. + * 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::getServiceContainer()->getDatabaseMap(ExportTableMap::DATABASE_NAME)->getTable(ExportTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ExportTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ExportTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ExportTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a Export or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or Export object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\Export) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ExportTableMap::DATABASE_NAME); + $criteria->add(ExportTableMap::ID, (array) $values, Criteria::IN); + } + + $query = ExportQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ExportTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ExportTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the export table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ExportQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a Export or Criteria object. + * + * @param mixed $criteria Criteria or Export object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface 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($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ExportTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from Export object + } + + if ($criteria->containsKey(ExportTableMap::ID) && $criteria->keyContainsValue(ExportTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.ExportTableMap::ID.')'); + } + + + // Set the correct dbName + $query = ExportQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ExportTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ExportTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/ImportCategoryI18nTableMap.php b/core/lib/Thelia/Model/Map/ImportCategoryI18nTableMap.php new file mode 100644 index 000000000..c4e254f43 --- /dev/null +++ b/core/lib/Thelia/Model/Map/ImportCategoryI18nTableMap.php @@ -0,0 +1,474 @@ + array('Id', 'Locale', 'Title', ), + self::TYPE_STUDLYPHPNAME => array('id', 'locale', 'title', ), + self::TYPE_COLNAME => array(ImportCategoryI18nTableMap::ID, ImportCategoryI18nTableMap::LOCALE, ImportCategoryI18nTableMap::TITLE, ), + self::TYPE_RAW_COLNAME => array('ID', 'LOCALE', 'TITLE', ), + self::TYPE_FIELDNAME => array('id', 'locale', 'title', ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'Locale' => 1, 'Title' => 2, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'locale' => 1, 'title' => 2, ), + self::TYPE_COLNAME => array(ImportCategoryI18nTableMap::ID => 0, ImportCategoryI18nTableMap::LOCALE => 1, ImportCategoryI18nTableMap::TITLE => 2, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'LOCALE' => 1, 'TITLE' => 2, ), + self::TYPE_FIELDNAME => array('id' => 0, 'locale' => 1, 'title' => 2, ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('import_category_i18n'); + $this->setPhpName('ImportCategoryI18n'); + $this->setClassName('\\Thelia\\Model\\ImportCategoryI18n'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addForeignPrimaryKey('ID', 'Id', 'INTEGER' , 'import_category', 'ID', true, null, null); + $this->addPrimaryKey('LOCALE', 'Locale', 'VARCHAR', true, 5, 'en_US'); + $this->addColumn('TITLE', 'Title', 'VARCHAR', true, 255, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('ImportCategory', '\\Thelia\\Model\\ImportCategory', RelationMap::MANY_TO_ONE, array('id' => 'id', ), 'CASCADE', null); + } // buildRelations() + + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by find*() + * and findPk*() calls. + * + * @param \Thelia\Model\ImportCategoryI18n $obj A \Thelia\Model\ImportCategoryI18n object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool($obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if (null === $key) { + $key = serialize(array((string) $obj->getId(), (string) $obj->getLocale())); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A \Thelia\Model\ImportCategoryI18n object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\ImportCategoryI18n) { + $key = serialize(array((string) $value->getId(), (string) $value->getLocale())); + + } elseif (is_array($value) && count($value) === 2) { + // assume we've been passed a primary key"; + $key = serialize(array((string) $value[0], (string) $value[1])); + } elseif ($value instanceof Criteria) { + self::$instances = []; + + return; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or \Thelia\Model\ImportCategoryI18n object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value, true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)])); + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return $pks; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ImportCategoryI18nTableMap::CLASS_DEFAULT : ImportCategoryI18nTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ImportCategoryI18n object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ImportCategoryI18nTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ImportCategoryI18nTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ImportCategoryI18nTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ImportCategoryI18nTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ImportCategoryI18nTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ImportCategoryI18nTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ImportCategoryI18nTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ImportCategoryI18nTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * 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 $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ImportCategoryI18nTableMap::ID); + $criteria->addSelectColumn(ImportCategoryI18nTableMap::LOCALE); + $criteria->addSelectColumn(ImportCategoryI18nTableMap::TITLE); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.LOCALE'); + $criteria->addSelectColumn($alias . '.TITLE'); + } + } + + /** + * Returns the TableMap related to this object. + * 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::getServiceContainer()->getDatabaseMap(ImportCategoryI18nTableMap::DATABASE_NAME)->getTable(ImportCategoryI18nTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ImportCategoryI18nTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ImportCategoryI18nTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ImportCategoryI18nTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ImportCategoryI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ImportCategoryI18n object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportCategoryI18nTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\ImportCategoryI18n) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ImportCategoryI18nTableMap::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); + } + foreach ($values as $value) { + $criterion = $criteria->getNewCriterion(ImportCategoryI18nTableMap::ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(ImportCategoryI18nTableMap::LOCALE, $value[1])); + $criteria->addOr($criterion); + } + } + + $query = ImportCategoryI18nQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ImportCategoryI18nTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ImportCategoryI18nTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the import_category_i18n table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ImportCategoryI18nQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ImportCategoryI18n or Criteria object. + * + * @param mixed $criteria Criteria or ImportCategoryI18n object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface 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($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportCategoryI18nTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ImportCategoryI18n object + } + + + // Set the correct dbName + $query = ImportCategoryI18nQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ImportCategoryI18nTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ImportCategoryI18nTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/ImportCategoryTableMap.php b/core/lib/Thelia/Model/Map/ImportCategoryTableMap.php new file mode 100644 index 000000000..82966e1b1 --- /dev/null +++ b/core/lib/Thelia/Model/Map/ImportCategoryTableMap.php @@ -0,0 +1,469 @@ + array('Id', 'Ref', 'Position', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'ref', 'position', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(ImportCategoryTableMap::ID, ImportCategoryTableMap::REF, ImportCategoryTableMap::POSITION, ImportCategoryTableMap::CREATED_AT, ImportCategoryTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'REF', 'POSITION', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'ref', 'position', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'Ref' => 1, 'Position' => 2, 'CreatedAt' => 3, 'UpdatedAt' => 4, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'ref' => 1, 'position' => 2, 'createdAt' => 3, 'updatedAt' => 4, ), + self::TYPE_COLNAME => array(ImportCategoryTableMap::ID => 0, ImportCategoryTableMap::REF => 1, ImportCategoryTableMap::POSITION => 2, ImportCategoryTableMap::CREATED_AT => 3, ImportCategoryTableMap::UPDATED_AT => 4, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'REF' => 1, 'POSITION' => 2, 'CREATED_AT' => 3, 'UPDATED_AT' => 4, ), + self::TYPE_FIELDNAME => array('id' => 0, 'ref' => 1, 'position' => 2, 'created_at' => 3, 'updated_at' => 4, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('import_category'); + $this->setPhpName('ImportCategory'); + $this->setClassName('\\Thelia\\Model\\ImportCategory'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addColumn('REF', 'Ref', 'VARCHAR', true, 255, null); + $this->addColumn('POSITION', 'Position', 'INTEGER', true, null, null); + $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); + $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Import', '\\Thelia\\Model\\Import', RelationMap::ONE_TO_MANY, array('id' => 'import_category_id', ), 'CASCADE', 'RESTRICT', 'Imports'); + $this->addRelation('ImportCategoryI18n', '\\Thelia\\Model\\ImportCategoryI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'ImportCategoryI18ns'); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'i18n' => array('i18n_table' => '%TABLE%_i18n', 'i18n_phpname' => '%PHPNAME%I18n', 'i18n_columns' => 'title', 'locale_column' => 'locale', 'locale_length' => '5', 'default_locale' => '', 'locale_alias' => '', ), + 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), + ); + } // getBehaviors() + /** + * Method to invalidate the instance pool of all tables related to import_category * by a foreign key with ON DELETE CASCADE + */ + public static function clearRelatedInstancePool() + { + // Invalidate objects in ".$this->getClassNameFromBuilder($joinedTableTableMapBuilder)." instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + ImportTableMap::clearInstancePool(); + ImportCategoryI18nTableMap::clearInstancePool(); + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ImportCategoryTableMap::CLASS_DEFAULT : ImportCategoryTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ImportCategory object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ImportCategoryTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ImportCategoryTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ImportCategoryTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ImportCategoryTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ImportCategoryTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ImportCategoryTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ImportCategoryTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ImportCategoryTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * 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 $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ImportCategoryTableMap::ID); + $criteria->addSelectColumn(ImportCategoryTableMap::REF); + $criteria->addSelectColumn(ImportCategoryTableMap::POSITION); + $criteria->addSelectColumn(ImportCategoryTableMap::CREATED_AT); + $criteria->addSelectColumn(ImportCategoryTableMap::UPDATED_AT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.REF'); + $criteria->addSelectColumn($alias . '.POSITION'); + $criteria->addSelectColumn($alias . '.CREATED_AT'); + $criteria->addSelectColumn($alias . '.UPDATED_AT'); + } + } + + /** + * Returns the TableMap related to this object. + * 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::getServiceContainer()->getDatabaseMap(ImportCategoryTableMap::DATABASE_NAME)->getTable(ImportCategoryTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ImportCategoryTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ImportCategoryTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ImportCategoryTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ImportCategory or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ImportCategory object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportCategoryTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\ImportCategory) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ImportCategoryTableMap::DATABASE_NAME); + $criteria->add(ImportCategoryTableMap::ID, (array) $values, Criteria::IN); + } + + $query = ImportCategoryQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ImportCategoryTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ImportCategoryTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the import_category table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ImportCategoryQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ImportCategory or Criteria object. + * + * @param mixed $criteria Criteria or ImportCategory object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface 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($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportCategoryTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ImportCategory object + } + + if ($criteria->containsKey(ImportCategoryTableMap::ID) && $criteria->keyContainsValue(ImportCategoryTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.ImportCategoryTableMap::ID.')'); + } + + + // Set the correct dbName + $query = ImportCategoryQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ImportCategoryTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ImportCategoryTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/ImportI18nTableMap.php b/core/lib/Thelia/Model/Map/ImportI18nTableMap.php new file mode 100644 index 000000000..98279a3c8 --- /dev/null +++ b/core/lib/Thelia/Model/Map/ImportI18nTableMap.php @@ -0,0 +1,482 @@ + array('Id', 'Locale', 'Title', 'Description', ), + self::TYPE_STUDLYPHPNAME => array('id', 'locale', 'title', 'description', ), + self::TYPE_COLNAME => array(ImportI18nTableMap::ID, ImportI18nTableMap::LOCALE, ImportI18nTableMap::TITLE, ImportI18nTableMap::DESCRIPTION, ), + self::TYPE_RAW_COLNAME => array('ID', 'LOCALE', 'TITLE', 'DESCRIPTION', ), + self::TYPE_FIELDNAME => array('id', 'locale', 'title', 'description', ), + self::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::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'Locale' => 1, 'Title' => 2, 'Description' => 3, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'locale' => 1, 'title' => 2, 'description' => 3, ), + self::TYPE_COLNAME => array(ImportI18nTableMap::ID => 0, ImportI18nTableMap::LOCALE => 1, ImportI18nTableMap::TITLE => 2, ImportI18nTableMap::DESCRIPTION => 3, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'LOCALE' => 1, 'TITLE' => 2, 'DESCRIPTION' => 3, ), + self::TYPE_FIELDNAME => array('id' => 0, 'locale' => 1, 'title' => 2, 'description' => 3, ), + self::TYPE_NUM => array(0, 1, 2, 3, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('import_i18n'); + $this->setPhpName('ImportI18n'); + $this->setClassName('\\Thelia\\Model\\ImportI18n'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addForeignPrimaryKey('ID', 'Id', 'INTEGER' , 'import', 'ID', true, null, null); + $this->addPrimaryKey('LOCALE', 'Locale', 'VARCHAR', true, 5, 'en_US'); + $this->addColumn('TITLE', 'Title', 'VARCHAR', true, 255, null); + $this->addColumn('DESCRIPTION', 'Description', 'CLOB', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Import', '\\Thelia\\Model\\Import', RelationMap::MANY_TO_ONE, array('id' => 'id', ), 'CASCADE', null); + } // buildRelations() + + /** + * Adds an object to the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases you may need to explicitly add objects + * to the cache in order to ensure that the same objects are always returned by find*() + * and findPk*() calls. + * + * @param \Thelia\Model\ImportI18n $obj A \Thelia\Model\ImportI18n object. + * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). + */ + public static function addInstanceToPool($obj, $key = null) + { + if (Propel::isInstancePoolingEnabled()) { + if (null === $key) { + $key = serialize(array((string) $obj->getId(), (string) $obj->getLocale())); + } // if key === null + self::$instances[$key] = $obj; + } + } + + /** + * Removes an object from the instance pool. + * + * Propel keeps cached copies of objects in an instance pool when they are retrieved + * from the database. In some cases -- especially when you override doDelete + * methods in your stub classes -- you may need to explicitly remove objects + * from the cache in order to prevent returning objects that no longer exist. + * + * @param mixed $value A \Thelia\Model\ImportI18n object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\ImportI18n) { + $key = serialize(array((string) $value->getId(), (string) $value->getLocale())); + + } elseif (is_array($value) && count($value) === 2) { + // assume we've been passed a primary key"; + $key = serialize(array((string) $value[0], (string) $value[1])); + } elseif ($value instanceof Criteria) { + self::$instances = []; + + return; + } else { + $e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or \Thelia\Model\ImportI18n object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value, true))); + throw $e; + } + + unset(self::$instances[$key]); + } + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 1 + $offset : static::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)])); + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return $pks; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ImportI18nTableMap::CLASS_DEFAULT : ImportI18nTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ImportI18n object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ImportI18nTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ImportI18nTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ImportI18nTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ImportI18nTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ImportI18nTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ImportI18nTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ImportI18nTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ImportI18nTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * 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 $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ImportI18nTableMap::ID); + $criteria->addSelectColumn(ImportI18nTableMap::LOCALE); + $criteria->addSelectColumn(ImportI18nTableMap::TITLE); + $criteria->addSelectColumn(ImportI18nTableMap::DESCRIPTION); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.LOCALE'); + $criteria->addSelectColumn($alias . '.TITLE'); + $criteria->addSelectColumn($alias . '.DESCRIPTION'); + } + } + + /** + * Returns the TableMap related to this object. + * 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::getServiceContainer()->getDatabaseMap(ImportI18nTableMap::DATABASE_NAME)->getTable(ImportI18nTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ImportI18nTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ImportI18nTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ImportI18nTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ImportI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ImportI18n object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportI18nTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\ImportI18n) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ImportI18nTableMap::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); + } + foreach ($values as $value) { + $criterion = $criteria->getNewCriterion(ImportI18nTableMap::ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(ImportI18nTableMap::LOCALE, $value[1])); + $criteria->addOr($criterion); + } + } + + $query = ImportI18nQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ImportI18nTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ImportI18nTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the import_i18n table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ImportI18nQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ImportI18n or Criteria object. + * + * @param mixed $criteria Criteria or ImportI18n object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface 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($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportI18nTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ImportI18n object + } + + + // Set the correct dbName + $query = ImportI18nQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ImportI18nTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ImportI18nTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/ImportTableMap.php b/core/lib/Thelia/Model/Map/ImportTableMap.php new file mode 100644 index 000000000..56cbe3592 --- /dev/null +++ b/core/lib/Thelia/Model/Map/ImportTableMap.php @@ -0,0 +1,484 @@ + array('Id', 'Ref', 'ImportCategoryId', 'Position', 'HandleClass', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'ref', 'importCategoryId', 'position', 'handleClass', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(ImportTableMap::ID, ImportTableMap::REF, ImportTableMap::IMPORT_CATEGORY_ID, ImportTableMap::POSITION, ImportTableMap::HANDLE_CLASS, ImportTableMap::CREATED_AT, ImportTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'REF', 'IMPORT_CATEGORY_ID', 'POSITION', 'HANDLE_CLASS', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'ref', 'import_category_id', 'position', 'handle_class', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'Ref' => 1, 'ImportCategoryId' => 2, 'Position' => 3, 'HandleClass' => 4, 'CreatedAt' => 5, 'UpdatedAt' => 6, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'ref' => 1, 'importCategoryId' => 2, 'position' => 3, 'handleClass' => 4, 'createdAt' => 5, 'updatedAt' => 6, ), + self::TYPE_COLNAME => array(ImportTableMap::ID => 0, ImportTableMap::REF => 1, ImportTableMap::IMPORT_CATEGORY_ID => 2, ImportTableMap::POSITION => 3, ImportTableMap::HANDLE_CLASS => 4, ImportTableMap::CREATED_AT => 5, ImportTableMap::UPDATED_AT => 6, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'REF' => 1, 'IMPORT_CATEGORY_ID' => 2, 'POSITION' => 3, 'HANDLE_CLASS' => 4, 'CREATED_AT' => 5, 'UPDATED_AT' => 6, ), + self::TYPE_FIELDNAME => array('id' => 0, 'ref' => 1, 'import_category_id' => 2, 'position' => 3, 'handle_class' => 4, 'created_at' => 5, 'updated_at' => 6, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('import'); + $this->setPhpName('Import'); + $this->setClassName('\\Thelia\\Model\\Import'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addColumn('REF', 'Ref', 'VARCHAR', true, 255, null); + $this->addForeignKey('IMPORT_CATEGORY_ID', 'ImportCategoryId', 'INTEGER', 'import_category', 'ID', true, null, null); + $this->addColumn('POSITION', 'Position', 'INTEGER', true, null, null); + $this->addColumn('HANDLE_CLASS', 'HandleClass', 'CLOB', true, null, null); + $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); + $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('ImportCategory', '\\Thelia\\Model\\ImportCategory', RelationMap::MANY_TO_ONE, array('import_category_id' => 'id', ), 'CASCADE', 'RESTRICT'); + $this->addRelation('ImportI18n', '\\Thelia\\Model\\ImportI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'ImportI18ns'); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'i18n' => array('i18n_table' => '%TABLE%_i18n', 'i18n_phpname' => '%PHPNAME%I18n', 'i18n_columns' => 'title, description', 'locale_column' => 'locale', 'locale_length' => '5', 'default_locale' => '', 'locale_alias' => '', ), + 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), + ); + } // getBehaviors() + /** + * Method to invalidate the instance pool of all tables related to import * by a foreign key with ON DELETE CASCADE + */ + public static function clearRelatedInstancePool() + { + // Invalidate objects in ".$this->getClassNameFromBuilder($joinedTableTableMapBuilder)." instance pool, + // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + ImportI18nTableMap::clearInstancePool(); + } + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ImportTableMap::CLASS_DEFAULT : ImportTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (Import object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ImportTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ImportTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ImportTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ImportTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ImportTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ImportTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ImportTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ImportTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * 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 $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ImportTableMap::ID); + $criteria->addSelectColumn(ImportTableMap::REF); + $criteria->addSelectColumn(ImportTableMap::IMPORT_CATEGORY_ID); + $criteria->addSelectColumn(ImportTableMap::POSITION); + $criteria->addSelectColumn(ImportTableMap::HANDLE_CLASS); + $criteria->addSelectColumn(ImportTableMap::CREATED_AT); + $criteria->addSelectColumn(ImportTableMap::UPDATED_AT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.REF'); + $criteria->addSelectColumn($alias . '.IMPORT_CATEGORY_ID'); + $criteria->addSelectColumn($alias . '.POSITION'); + $criteria->addSelectColumn($alias . '.HANDLE_CLASS'); + $criteria->addSelectColumn($alias . '.CREATED_AT'); + $criteria->addSelectColumn($alias . '.UPDATED_AT'); + } + } + + /** + * Returns the TableMap related to this object. + * 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::getServiceContainer()->getDatabaseMap(ImportTableMap::DATABASE_NAME)->getTable(ImportTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ImportTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ImportTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ImportTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a Import or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or Import object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $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, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\Import) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ImportTableMap::DATABASE_NAME); + $criteria->add(ImportTableMap::ID, (array) $values, Criteria::IN); + } + + $query = ImportQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ImportTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ImportTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the import table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ImportQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a Import or Criteria object. + * + * @param mixed $criteria Criteria or Import object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface 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($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ImportTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from Import object + } + + if ($criteria->containsKey(ImportTableMap::ID) && $criteria->keyContainsValue(ImportTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.ImportTableMap::ID.')'); + } + + + // Set the correct dbName + $query = ImportQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ImportTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ImportTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Product.php b/core/lib/Thelia/Model/Product.php index 439132574..3cf54da7b 100644 --- a/core/lib/Thelia/Model/Product.php +++ b/core/lib/Thelia/Model/Product.php @@ -25,7 +25,7 @@ class Product extends BaseProduct implements FileModelParentInterface /** * {@inheritDoc} */ - protected function getRewrittenUrlViewName() + public function getRewrittenUrlViewName() { return 'product'; } @@ -268,7 +268,7 @@ class Product extends BaseProduct implements FileModelParentInterface */ public function postDelete(ConnectionInterface $con = null) { - $this->markRewritenUrlObsolete(); + $this->markRewrittenUrlObsolete(); $this->dispatchEvent(TheliaEvents::AFTER_DELETEPRODUCT, new ProductEvent($this)); } diff --git a/core/lib/Thelia/Model/Tools/UrlRewritingTrait.php b/core/lib/Thelia/Model/Tools/UrlRewritingTrait.php index 79947074f..672c6d143 100644 --- a/core/lib/Thelia/Model/Tools/UrlRewritingTrait.php +++ b/core/lib/Thelia/Model/Tools/UrlRewritingTrait.php @@ -29,7 +29,7 @@ trait UrlRewritingTrait /** * @returns string the view name of the rewritten object (e.g., 'category', 'product') */ - abstract protected function getRewrittenUrlViewName(); + abstract public function getRewrittenUrlViewName(); /** * Get the object URL for the given locale, rewritten if rewriting is enabled. @@ -128,7 +128,7 @@ trait UrlRewritingTrait /** * Mark the current URL as obseolete */ - public function markRewritenUrlObsolete() + public function markRewrittenUrlObsolete() { RewritingUrlQuery::create() ->filterByView($this->getRewrittenUrlViewName()) diff --git a/core/lib/Thelia/Tests/ContainerAwareTestCase.php b/core/lib/Thelia/Tests/ContainerAwareTestCase.php new file mode 100644 index 000000000..daff73ae6 --- /dev/null +++ b/core/lib/Thelia/Tests/ContainerAwareTestCase.php @@ -0,0 +1,78 @@ + + */ +abstract class ContainerAwareTestCase extends \PHPUnit_Framework_TestCase +{ + protected $import; + + /** @var ContainerInterface */ + protected $container; + + /** @var Session */ + protected $session; + + public function getContainer() + { + $container = new \Symfony\Component\DependencyInjection\ContainerBuilder(); + $container->set("thelia.translator", new Translator(new Container())); + + $dispatcher = $this->getMock("Symfony\Component\EventDispatcher\EventDispatcherInterface"); + + $container->set("event_dispatcher", $dispatcher); + + $request = new Request(); + $request->setSession($this->session); + + $container->set("request", $request); + + $container->set("thelia.securitycontext", new SecurityContext($request)); + + $this->buildContainer($container); + + return $container; + } + + public function getSession() + { + return new Session(); + } + + public function setUp() + { + + Tlog::getNewInstance(); + + $this->session = $this->getSession(); + $this->container = $this->getContainer(); + + } + + /** + * Use this method to build the container with the services that you need. + */ + abstract protected function buildContainer(ContainerBuilder $container); +} diff --git a/core/lib/Thelia/Tests/Controller/ControllerTestBase.php b/core/lib/Thelia/Tests/Controller/ControllerTestBase.php new file mode 100644 index 000000000..c81c428ac --- /dev/null +++ b/core/lib/Thelia/Tests/Controller/ControllerTestBase.php @@ -0,0 +1,42 @@ + + */ +abstract class ControllerTestBase extends ContainerAwareTestCase +{ + /** @var BaseController */ + protected $controller; + + public function setUp() + { + parent::setUp(); + + $this->controller = $this->getController(); + $this->controller->setContainer($this->container); + + } + + /** + * @return \Thelia\Controller\BaseController The controller you want to test + */ + abstract protected function getController(); + +} \ No newline at end of file diff --git a/core/lib/Thelia/Tests/Controller/ImportControllerTest.php b/core/lib/Thelia/Tests/Controller/ImportControllerTest.php new file mode 100644 index 000000000..685541b6e --- /dev/null +++ b/core/lib/Thelia/Tests/Controller/ImportControllerTest.php @@ -0,0 +1,239 @@ + + */ +class ImportControllerTrait extends ControllerTestBase +{ + use FormatterManagerTrait; + use ArchiveBuilderManagerTrait; + use ImportExportControllerTrait; + + /** + * @return \Thelia\Controller\BaseController The controller you want to test + */ + protected function getController() + { + return new ImportController(); + } + + public function testCheckFileExtension() + { + $this->controller->checkFileExtension("a.zip", "zip"); + } + + /** + * @expectedException \Thelia\Form\Exception\FormValidationException + * @expectedExceptionMessage The extension ".zip" is not allowed + */ + public function testCheckFileExtensionFail() + { + $this->controller->checkFileExtension("a.zip", null); + } + + /** + * @expectedException \Thelia\Form\Exception\FormValidationException + * @expectedExceptionMessage The extension ".bz2" is not allowed + */ + public function testCheckFileExtensionFailMultipleExt() + { + $this->controller->checkFileExtension("a.tar.bz2", null); + } + + /** + * @expectedException \Thelia\Form\Exception\FormValidationException + * @expectedExceptionMessage The extension "" is not allowed + */ + public function testCheckFileExtensionFailNoExt() + { + $this->controller->checkFileExtension("file", null); + } + + public function testGetFileContentInArchive() + { + /** @var ZipArchiveBuilder $archive */ + $archive = $this->getArchiveBuilderManager($this->container)->get("ZIP"); + $formatter = new XMLFormatter(); + + $archive->addFileFromString("foo", $formatter::FILENAME . "." . $formatter->getExtension()); + + $content = $this->controller->getFileContentInArchive( + $archive, + $this->getFormatterManager($this->container), + [$formatter->getHandledType()] + ); + + $this->assertEquals( + [ + "content" => "foo", + "formatter" => $formatter + ], + $content + ); + } + + /** + * @expectedException \Thelia\Exception\FileNotFoundException + * @expectedExceptionMessage Your archive must contain one of these file and doesn't: + */ + public function testGetFileContentInArchiveFail() + { + /** @var ZipArchiveBuilder $archive */ + $archive = $this->getArchiveBuilderManager($this->container)->get("ZIP"); + $formatter = new XMLFormatter(); + + $archive->addFileFromString("foo", "bar"); + + $this->controller->getFileContentInArchive( + $archive, + $this->getFormatterManager($this->container), + [$formatter->getHandledType()] + ); + } + + public function testRetrieveFormatTools() + { + $handler = $this + ->getMock( + "\\Thelia\\ImportExport\\Import\\ImportHandler", + [ + "getMandatoryColumns", + "retrieveFromFormatterData", + "getHandledTypes" + ], + [ + $this->container + ] + ) + ; + + $handler + ->expects($this->any()) + ->method("getHandledTypes") + ->willReturn(FormatType::UNBOUNDED) + ; + + $tools = $this->controller->retrieveFormatTools( + "foo.xml", + $handler, + $this->getFormatterManager($this->container), + $this->getArchiveBuilderManager($this->container) + ); + + $this->assertArrayHasKey("formatter", $tools); + $this->assertInstanceOf( + "Thelia\\Core\\FileFormat\\Formatting\\AbstractFormatter", + $tools["formatter"] + ); + + $this->assertArrayHasKey("archive_builder", $tools); + $this->assertNull($tools["archive_builder"]); + + $this->assertArrayHasKey("extension", $tools); + $this->assertEquals(".xml", $tools["extension"]); + + $this->assertArrayHasKey("types", $tools); + $this->assertEquals( + FormatType::UNBOUNDED, + $tools["types"] + ); + + $handler = $this + ->getMock( + "\\Thelia\\ImportExport\\Import\\ImportHandler", + [ + "getMandatoryColumns", + "retrieveFromFormatterData", + "getHandledTypes" + ], + [ + $this->container + ] + ) + ; + + $handler + ->expects($this->any()) + ->method("getHandledTypes") + ->willReturn([FormatType::UNBOUNDED]) + ; + + $tools = $this->controller->retrieveFormatTools( + "foo.zip", + $handler, + $this->getFormatterManager($this->container), + $this->getArchiveBuilderManager($this->container) + ); + + $this->assertArrayHasKey("formatter", $tools); + $this->assertNull($tools["formatter"]); + + $this->assertArrayHasKey("archive_builder", $tools); + $this->assertInstanceOf( + "Thelia\\Core\\FileFormat\\Archive\\AbstractArchiveBuilder", + $tools["archive_builder"] + ); + + $this->assertArrayHasKey("extension", $tools); + $this->assertEquals(".zip", $tools["extension"]); + + $this->assertArrayHasKey("types", $tools); + $this->assertEquals( + [FormatType::UNBOUNDED], + $tools["types"] + ); + } + + /** + * @expectedException \Thelia\Form\Exception\FormValidationException + */ + public function testRetrieveFormatToolsFail() + { + $handler = $this + ->getMock( + "\\Thelia\\ImportExport\\Import\\ImportHandler", + [ + "getMandatoryColumns", + "retrieveFromFormatterData", + "getHandledTypes" + ], + [ + $this->container + ] + ) + ; + + $handler + ->expects($this->any()) + ->method("getHandledTypes") + ->willReturn(FormatType::UNBOUNDED) + ; + + $this->controller->retrieveFormatTools( + "foo.csv", + $handler, + $this->getFormatterManager($this->container), + $this->getArchiveBuilderManager($this->container) + ); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Tests/Controller/ImportExportControllerTrait.php b/core/lib/Thelia/Tests/Controller/ImportExportControllerTrait.php new file mode 100644 index 000000000..edd8294bd --- /dev/null +++ b/core/lib/Thelia/Tests/Controller/ImportExportControllerTrait.php @@ -0,0 +1,55 @@ + + */ +trait ImportExportControllerTrait +{ + + /** + * @return mixed + */ + protected function buildContainer(ContainerBuilder $container) + { + $archiveBuilderManager = (new ArchiveBuilderManager("dev")) + ->add(new ZipArchiveBuilder()) + ->add(new TarArchiveBuilder()) + ->add(new TarBz2ArchiveBuilder()) + ->add(new TarGzArchiveBuilder()) + ; + $container->set("thelia.manager.archive_builder_manager", $archiveBuilderManager); + + $formatterManager = (new FormatterManager()) + ->add(new XMLFormatter()) + ->add(new JsonFormatter()) + ->add(new CSVFormatter()) + ; + + $container->set("thelia.manager.formatter_manager", $formatterManager); + } + +} \ No newline at end of file diff --git a/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TarArchiveBuilderTest.php b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TarArchiveBuilderTest.php new file mode 100644 index 000000000..e34acdf76 --- /dev/null +++ b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TarArchiveBuilderTest.php @@ -0,0 +1,291 @@ + + */ +class TarArchiveBuilderTest extends \PHPUnit_Framework_TestCase +{ + /** @var TarArchiveBuilder */ + protected $tar; + + public function setUp() + { + new Translator(new Container()); + + Tlog::getNewInstance(); + + $this->tar = new TarArchiveBuilder(); + $this->tar->setEnvironment("dev"); + } + + public function testAddFileAndDirectory() + { + /** + * File + */ + $tar = $this->tar->addFile( + __DIR__ . DS . "TestResources/test_file" + ); + + $this->assertTrue($tar->hasFile("test_file")); + + $this->assertFalse($tar->hasDirectory("test_file")); + + $tar = $this->tar->addFile( + __DIR__ . DS . "TestResources/test_file", + null, + "TEST.txt" + ); + + $this->assertTrue($tar->hasFile("TEST.txt")); + + $this->assertFalse($tar->hasDirectory("TEST.txt")); + + /** + * Directory + */ + $this->tar->addDirectory("foo"); + + $this->assertTrue($tar->hasDirectory("foo")); + + $this->assertFalse($tar->hasFile("foo")); + + /**s + * File in a directory + */ + $this->tar->addFile( + __DIR__ . DS . "TestResources/test_file", + "bar", + "baz" + ); + + $this->assertTrue($this->tar->hasFile("bar/baz")); + + $this->assertTrue($this->tar->hasDirectory("bar")); + + } + + public function testAddValidFileFromString() + { + $this->tar->addFileFromString( + "foo", "bar" + ); + + $this->assertTrue( + $this->tar->hasFile("bar") + ); + + $this->assertEquals( + "foo", + $this->tar->getFileContent("bar") + ); + + $this->tar->addFileFromString( + "foo", "bar", "baz" + ); + + $this->assertTrue( + $this->tar->hasFile("baz/bar") + ); + + $this->assertEquals( + "foo", + $this->tar->getFileContent("baz/bar") + ); + } + + /** + * @expectedException \ErrorException + */ + public function testAddNotValidFileFromString() + { + $this->tar->addFileFromString( + "foo", $this + ); + } + + /** + * @expectedException \ErrorException + */ + public function testAddNotValidFileValueFromString() + { + $this->tar->addFileFromString( + $this, "foo" + ); + } + + public function testDeleteFile() + { + $this->tar->addFileFromString( + "foo", "bar" + ); + + $this->assertTrue( + $this->tar->hasFile("bar") + ); + + $this->tar->deleteFile("bar"); + + $this->assertFalse( + $this->tar->hasFile("bar") + ); + } + + public function testLoadValidArchive() + { + $tar = $this->tar->loadArchive( + __DIR__ . DS . "TestResources/well_formatted.tar" + ); + + $this->assertInstanceOf( + get_class($this->tar), + $tar + ); + + $this->assertTrue( + $tar->hasFile("LICENSE.txt") + ); + } + + /** + * @expectedException \Thelia\Core\FileFormat\Archive\ArchiveBuilder\Exception\TarArchiveException + */ + public function testLoadInvalidArchive() + { + $tar = $this->tar->loadArchive( + __DIR__ . DS . "TestResources/bad_formatted.tar" + ); + } + + public function testFormatDirectoryPath() + { + $this->assertEquals( + "foo/", + $this->tar->formatDirectoryPath("foo") + ); + + $this->assertEquals( + "foo/", + $this->tar->formatDirectoryPath("/foo") + ); + + $this->assertEquals( + "foo/", + $this->tar->formatDirectoryPath("foo/") + ); + + $this->assertEquals( + "foo/", + $this->tar->formatDirectoryPath("/foo/") + ); + + $this->assertEquals( + "foo/bar/", + $this->tar->formatDirectoryPath("foo/bar") + ); + + $this->assertEquals( + "foo/bar/", + $this->tar->formatDirectoryPath("/foo/bar") + ); + + $this->assertEquals( + "foo/bar/", + $this->tar->formatDirectoryPath("/foo//bar/") + ); + + $this->assertEquals( + "foo/bar/", + $this->tar->formatDirectoryPath("/foo/bar/") + ); + + $this->assertEquals( + "foo/bar/baz/", + $this->tar->formatDirectoryPath("foo/bar/baz") + ); + + $this->assertEquals( + "foo/bar/baz/", + $this->tar->formatDirectoryPath("//foo/bar///baz/") + ); + } + + public function testFormatFilePath() + { + $this->assertEquals( + "foo", + $this->tar->formatFilePath("foo") + ); + + $this->assertEquals( + "foo", + $this->tar->formatFilePath("/foo") + ); + + $this->assertEquals( + "foo", + $this->tar->formatFilePath("foo/") + ); + + $this->assertEquals( + "foo", + $this->tar->formatFilePath("/foo/") + ); + + $this->assertEquals( + "foo/bar", + $this->tar->formatFilePath("foo/bar") + ); + + $this->assertEquals( + "foo/bar", + $this->tar->formatFilePath("/foo/bar") + ); + + $this->assertEquals( + "foo/bar", + $this->tar->formatFilePath("/foo//bar/") + ); + + $this->assertEquals( + "foo/bar", + $this->tar->formatFilePath("/foo/bar/") + ); + + $this->assertEquals( + "foo/bar/baz", + $this->tar->formatFilePath("foo/bar/baz") + ); + + $this->assertEquals( + "foo/bar/baz", + $this->tar->formatFilePath("//foo/bar///baz/") + ); + } + + public function testCompression() + { + $this->assertEquals( + null, + $this->tar->getCompression() + ); + } +} diff --git a/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TarBz2ArchiveBuilderTest.php b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TarBz2ArchiveBuilderTest.php new file mode 100644 index 000000000..a65892424 --- /dev/null +++ b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TarBz2ArchiveBuilderTest.php @@ -0,0 +1,38 @@ + + */ +class TarBz2ArchiveBuilderTest extends TarArchiveBuilderTest +{ + public function setUp() + { + parent::setUp(); + + $this->tar = new TarBz2ArchiveBuilder(); + $this->tar->setEnvironment("dev"); + } + + public function testCompression() + { + $this->assertEquals( + \Phar::BZ2, + $this->tar->getCompression() + ); + } +} diff --git a/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TarGzArchiveBuilderTest.php b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TarGzArchiveBuilderTest.php new file mode 100644 index 000000000..5b1aded6e --- /dev/null +++ b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TarGzArchiveBuilderTest.php @@ -0,0 +1,38 @@ + + */ +class TarGzArchiveBuilderTest extends TarArchiveBuilderTest +{ + public function setUp() + { + parent::setUp(); + + $this->tar = new TarGzArchiveBuilder(); + $this->tar->setEnvironment("dev"); + } + + public function testCompression() + { + $this->assertEquals( + \Phar::GZ, + $this->tar->getCompression() + ); + } +} diff --git a/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/bad_formatted.tar b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/bad_formatted.tar new file mode 100644 index 000000000..e69de29bb diff --git a/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/bad_formatted.zip b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/bad_formatted.zip new file mode 100644 index 000000000..3bd1f0e29 --- /dev/null +++ b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/bad_formatted.zip @@ -0,0 +1,2 @@ +foo +bar diff --git a/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/test_file b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/test_file new file mode 100644 index 000000000..e69de29bb diff --git a/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/well_formatted.tar b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/well_formatted.tar new file mode 100644 index 000000000..3bff92c8e Binary files /dev/null and b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/well_formatted.tar differ diff --git a/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/well_formatted.zip b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/well_formatted.zip new file mode 100644 index 000000000..b19e372b9 Binary files /dev/null and b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/TestResources/well_formatted.zip differ diff --git a/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/ZipArchiveBuilderTest.php b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/ZipArchiveBuilderTest.php new file mode 100644 index 000000000..450af71b2 --- /dev/null +++ b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilder/ZipArchiveBuilderTest.php @@ -0,0 +1,398 @@ + + */ +class ZipArchiveBuilderTest extends \PHPUnit_Framework_TestCase +{ + /** @var ZipArchiveBuilder */ + protected $zip; + + /** @var ZipArchiveBuilder */ + protected $loadedZip; + + public function setUp() + { + new Translator( + new Container() + ); + + Tlog::getNewInstance(); + + $this->zip = new ZipArchiveBuilder(); + + $this->zip->setEnvironment("dev"); + + $this->loadedZip = $this->zip->loadArchive( + __DIR__ . DS . "TestResources/well_formatted.zip" + ); + } + + /** + * This method formats a path to be compatible with \ZipArchive + */ + public function testFormatFilePath() + { + $this->assertEquals( + "foo", + $this->zip->formatFilePath("foo") + ); + + $this->assertEquals( + "foo", + $this->zip->formatFilePath("/foo") + ); + + $this->assertEquals( + "foo", + $this->zip->formatFilePath("foo/") + ); + + $this->assertEquals( + "foo", + $this->zip->formatFilePath("/foo/") + ); + + $this->assertEquals( + "/foo/bar", + $this->zip->formatFilePath("foo/bar") + ); + + $this->assertEquals( + "/foo/bar", + $this->zip->formatFilePath("/foo/bar") + ); + + $this->assertEquals( + "/foo/bar", + $this->zip->formatFilePath("/foo//bar/") + ); + + $this->assertEquals( + "/foo/bar", + $this->zip->formatFilePath("/foo/bar/") + ); + + $this->assertEquals( + "/foo/bar/baz", + $this->zip->formatFilePath("foo/bar/baz") + ); + + $this->assertEquals( + "/foo/bar/baz", + $this->zip->formatFilePath("//foo/bar///baz/") + ); + } + + public function testFormatDirectoryPath() + { + $this->assertEquals( + "/foo/", + $this->zip->formatDirectoryPath("foo") + ); + + $this->assertEquals( + "/foo/", + $this->zip->formatDirectoryPath("/foo") + ); + + $this->assertEquals( + "/foo/", + $this->zip->formatDirectoryPath("foo/") + ); + + $this->assertEquals( + "/foo/", + $this->zip->formatDirectoryPath("/foo/") + ); + + $this->assertEquals( + "/foo/bar/", + $this->zip->formatDirectoryPath("foo/bar") + ); + + $this->assertEquals( + "/foo/bar/", + $this->zip->formatDirectoryPath("/foo/bar") + ); + + $this->assertEquals( + "/foo/bar/", + $this->zip->formatDirectoryPath("/foo//bar/") + ); + + $this->assertEquals( + "/foo/bar/", + $this->zip->formatDirectoryPath("/foo/bar/") + ); + + $this->assertEquals( + "/foo/bar/baz/", + $this->zip->formatDirectoryPath("foo/bar/baz") + ); + + $this->assertEquals( + "/foo/bar/baz/", + $this->zip->formatDirectoryPath("//foo/bar///baz/") + ); + } + + public function testLoadValidZip() + { + $loadedZip = $this->zip->loadArchive( + __DIR__ . DS . "TestResources/well_formatted.zip" + ); + + $this->assertInstanceOf( + get_class($this->loadedZip), + $loadedZip + ); + } + + /** + * @expectedException \Thelia\Core\FileFormat\Archive\ArchiveBuilder\Exception\ZipArchiveException + * @expectedExceptionMessage [Zip Error] The file is not a zip archive + */ + public function testLoadNotValidZip() + { + $this->zip->loadArchive( + __DIR__ . DS . "TestResources/bad_formatted.zip" + ); + } + + /** + * @expectedException \Thelia\Exception\FileNotFoundException + */ + public function testLoadNotExistingFile() + { + $this->zip->loadArchive( + __DIR__ . DS . "TestResources/this_file_doesn_t_exist.zip" + ); + } + + public function testLoadOnlineAvailableAndValidFile() + { + $this->zip->setFileDownloader(FakeFileDownloader::getInstance()); + + $this->zip->loadArchive( + __DIR__ . DS . "TestResources/well_formatted.zip", + true + ); + } + + /** + * @expectedException \Thelia\Core\FileFormat\Archive\ArchiveBuilder\Exception\ZipArchiveException + * @expectedExceptionMessage [Zip Error] The file is not a zip archive + */ + public function testLoadOnlineAvailableAndNotValidFile() + { + $this->zip->setFileDownloader(FakeFileDownloader::getInstance()); + + $this->zip->loadArchive( + __DIR__ . DS . "TestResources/bad_formatted.zip", + true + ); + } + + /** + * @expectedException \Thelia\Exception\FileNotFoundException + */ + public function testLoadOnlineNotExistingFile() + { + $this->zip->setFileDownloader(FakeFileDownloader::getInstance()); + + $this->zip->loadArchive( + __DIR__ . DS . "TestResources/this_file_doesn_t_exist.zip", + true + ); + } + + public function testHasFile() + { + $this->assertTrue( + $this->loadedZip->hasFile("LICENSE.txt") + ); + + $this->assertFalse( + $this->loadedZip->hasFile("foo") + ); + + $this->assertFalse( + $this->loadedZip->hasFile("LICENSE.TXT") + ); + } + + public function testDeleteFile() + { + $this->assertInstanceOf( + get_class($this->loadedZip), + $this->loadedZip->deleteFile("LICENSE.txt") + ); + } + + /** + * @expectedException \Thelia\Exception\FileNotFoundException + */ + public function testDeleteNotExistingFile() + { + $this->loadedZip->deleteFile("foo"); + } + + public function testAddExistingFile() + { + $this->assertInstanceOf( + get_class($this->loadedZip), + $this->loadedZip->addFile( + __DIR__ . DS . "TestResources/test_file", + "/f/f/" + ) + ); + + /** + * Show that even weird paths are correctly interpreted + */ + $this->assertTrue( + $this->loadedZip->hasFile("///f//f/test_file/") + ); + } + + public function testAddExistingFileInNewDirectory() + { + $this->assertInstanceOf( + get_class($this->loadedZip), + $this->loadedZip->addFile( + __DIR__ . DS . "TestResources/test_file", + "testDir" + ) + ); + + /** + * You can create and check the directory and files + * without giving the initial and final slashes + */ + $this->assertTrue( + $this->loadedZip->hasDirectory("testDir") + ); + + $this->assertTrue( + $this->loadedZip->hasDirectory("/testDir") + ); + + $this->assertTrue( + $this->loadedZip->hasDirectory("testDir/") + ); + + $this->assertTrue( + $this->loadedZip->hasDirectory("/testDir/") + ); + + $this->assertTrue( + $this->loadedZip->hasFile("testDir/test_file") + ); + + $this->assertTrue( + $this->loadedZip->hasFile("/testDir/test_file") + ); + + $this->assertTrue( + $this->loadedZip->hasFile("testDir/test_file/") + ); + + $this->assertTrue( + $this->loadedZip->hasFile("/testDir/test_file/") + ); + } + + public function testBuildArchiveResponse() + { + $loadedArchiveResponse = $this->loadedZip + ->buildArchiveResponse("test") + ; + + $loadedArchiveResponseContent = $loadedArchiveResponse->getContent(); + + $content = file_get_contents(__DIR__ . DS . "TestResources/well_formatted.zip"); + + $this->assertEquals( + $content, + $loadedArchiveResponseContent + ); + } + + public function testAddValidFileFromString() + { + $this->loadedZip->addFileFromString( + "foo", "bar" + ); + + $this->assertTrue( + $this->loadedZip->hasFile("bar") + ); + + $this->assertEquals( + "foo", + $this->loadedZip->getFileContent("bar") + ); + + $this->loadedZip->addFileFromString( + "foo", "bar", "baz" + ); + + $this->assertTrue( + $this->loadedZip->hasFile("baz/bar") + ); + + $this->assertEquals( + "foo", + $this->loadedZip->getFileContent("baz/bar") + ); + } + + /** + * @expectedException \Thelia\Exception\FileNotFoundException + */ + public function testGetFileContentFileNotFound() + { + $this->loadedZip->getFileContent("bar"); + } + + /** + * @expectedException \ErrorException + */ + public function testAddNotValidFileFromString() + { + $this->loadedZip->addFileFromString( + "foo", $this + ); + } + + /** + * @expectedException \ErrorException + */ + public function testAddNotValidFileValueFromString() + { + $this->loadedZip->addFileFromString( + $this, "bar" + ); + } + +} diff --git a/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilderManagerTest.php b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilderManagerTest.php new file mode 100644 index 000000000..69fdfdb9a --- /dev/null +++ b/core/lib/Thelia/Tests/FileFormat/Archive/ArchiveBuilderManagerTest.php @@ -0,0 +1,75 @@ + + */ +class ArchiveBuilderManagerTest extends \PHPUnit_Framework_TestCase +{ + /** + * @var ArchiveBuilderManager + */ + protected $manager; + + public function setUp() + { + new Translator( + new Container() + ); + $this->manager = new ArchiveBuilderManager("dev"); + } + + public function testAddArchiveBuilder() + { + /** @var AbstractArchiveBuilder $instance */ + $instance = $this->getMock("Thelia\\Core\\FileFormat\\Archive\\AbstractArchiveBuilder"); + + $this->manager->add($instance); + + $archiveBuilders = $this->manager->getAll(); + + $this->assertTrue( + array_key_exists($instance->getName(), $archiveBuilders) + ); + } + + public function testDeleteArchiveBuilder() + { + /** @var AbstractArchiveBuilder $instance */ + $instance = $this->getMock("Thelia\\Core\\FileFormat\\Archive\\AbstractArchiveBuilder"); + + $this->manager->add($instance); + + $this->manager->delete($instance->getName()); + + $this->assertTrue( + count($this->manager->getAll()) === 0 + ); + } + + /** + * @expectedException \OutOfBoundsException + */ + public function testDeleteNotExistingArchiveBuilder() + { + $this->manager->delete("foo"); + } + +} diff --git a/core/lib/Thelia/Tests/FileFormat/Formatting/Formatter/CSVFormatterTest.php b/core/lib/Thelia/Tests/FileFormat/Formatting/Formatter/CSVFormatterTest.php new file mode 100644 index 000000000..e79a9b28c --- /dev/null +++ b/core/lib/Thelia/Tests/FileFormat/Formatting/Formatter/CSVFormatterTest.php @@ -0,0 +1,134 @@ + + */ +class CSVFormatterTest extends \PHPUnit_Framework_TestCase +{ + /** @var CSVFormatter */ + protected $formatter; + + public function setUp() + { + new Translator(new Container()); + + $this->formatter = new CSVFormatter(); + } + + public function testSimpleEncode() + { + $expected = "\"ref\";\"stock\"\n\"foo\";\"bar\""; + + $data = [ + [ + "ref" => "foo", + "stock" => "bar", + ], + ]; + + $data = (new FormatterData())->setData($data); + + $this->assertEquals( + $expected, + $this->formatter->encode($data) + ); + } + + public function testComplexEncode() + { + $this->formatter->lineReturn = "\n"; + $this->formatter->delimiter = ","; + $expected = "\"foo\",\"bar\",\"baz\"\n\"1\",\"2\",\"3\"\n\"4\",\"5\",\"6\"\n\"1\",\"2\",\"3\""; + + $data = [ + [ + "foo" => "1", + "bar" => "2", + "baz" => "3", + ], + [ + "foo" => "4", + "bar" => "5", + "baz" => "6", + ], + [ + "foo" => "1", + "bar" => "2", + "baz" => "3", + ], + ]; + + $data = (new FormatterData())->setData($data); + + $this->assertEquals( + $expected, + $this->formatter->encode($data) + ); + } + + public function testSimpleDecode() + { + $data = "\"ref\";\"stock\"\n\"foo\";\"bar\""; + + $expected = [ + [ + "ref" => "foo", + "stock" => "bar", + ], + ]; + + $this->assertEquals( + $expected, + $this->formatter->decode($data)->getData() + ); + } + + public function testComplexDecode() + { + $this->formatter->lineReturn = "\n"; + $this->formatter->delimiter = ","; + $data = "\"foo\",\"bar\",baz\n\"1\",\"2\",3\n\"4\",5,\"6\"\n\"1\",\"2\",\"3\""; + + $expected = [ + [ + "foo" => "1", + "bar" => "2", + "baz" => "3", + ], + [ + "foo" => "4", + "bar" => "5", + "baz" => "6", + ], + [ + "foo" => "1", + "bar" => "2", + "baz" => "3", + ], + ]; + + $this->assertEquals( + $expected, + $this->formatter->decode($data)->getData() + ); + } + +} \ No newline at end of file diff --git a/core/lib/Thelia/Tests/FileFormat/Formatting/Formatter/XMLFormatterTest.php b/core/lib/Thelia/Tests/FileFormat/Formatting/Formatter/XMLFormatterTest.php new file mode 100644 index 000000000..85bcbf2a5 --- /dev/null +++ b/core/lib/Thelia/Tests/FileFormat/Formatting/Formatter/XMLFormatterTest.php @@ -0,0 +1,236 @@ + + */ +class XMLFormatterTest extends \PHPUnit_Framework_TestCase +{ + /** @var XMLFormatter */ + protected $formatter; + + public function setUp() + { + new Translator(new Container()); + + $this->formatter = new XMLFormatter(); + } + + public function testMetaData() + { + $this->assertEquals( + "XML", + $this->formatter->getName() + ); + + $this->assertEquals( + "xml", + $this->formatter->getExtension() + ); + + $this->assertEquals( + "application/xml", + $this->formatter->getMimeType() + ); + } + + public function testSimpleEncode() + { + $data = new FormatterData(); + + $data->setData( + [ + "foo" => "bar" + ] + ); + + $dom = new \DOMDocument("1.0"); + + /** @var \DOMElement $node */ + $node =$dom->appendChild(new \DOMElement($this->formatter->root)) + ->appendChild(new \DOMElement($this->formatter->nodeName)); + + $node->setAttribute("name", "foo"); + $node->setAttribute("value", "bar"); + + + $dom->preserveWhiteSpace = false; + $dom->formatOutput = true; + + $this->assertEquals( + $dom->saveXML(), + $this->formatter->encode($data) + ); + } + + public function testComplexEncode() + { + $data = new FormatterData(); + + $data->setData( + [ + "foo" => "bar", + [ + "name" => "banana", + "type" => "fruit", + ], + [ + "orange"=>[ + "type" => "fruit" + ], + "banana"=>[ + "like" => "Yes" + ] + ] + ] + ); + + $dom = new \DOMDocument("1.0"); + $base = $dom->appendChild(new \DOMElement($this->formatter->root)); + /** @var \DOMElement $node */ + $node = $base->appendChild(new \DOMElement($this->formatter->nodeName)); + $node->setAttribute("name", "foo"); + $node->setAttribute("value", "bar"); + + $baz = $base->appendChild(new \DOMElement($this->formatter->rowName)); + $node = $baz->appendChild(new \DOMElement($this->formatter->nodeName)); + $node->setAttribute("name", "name"); + $node->setAttribute("value", "banana"); + $node = $baz->appendChild(new \DOMElement($this->formatter->nodeName)); + $node->setAttribute("name", "type"); + $node->setAttribute("value", "fruit"); + + $baz = $base->appendChild(new \DOMElement($this->formatter->rowName)); + $orange = $baz->appendChild(new \DOMElement("orange")); + $node = $orange->appendChild(new \DOMElement($this->formatter->nodeName)); + $node->setAttribute("name","type"); + $node->setAttribute("value","fruit"); + $banana = $baz->appendChild(new \DOMElement("banana")); + $node = $banana->appendChild(new \DOMElement($this->formatter->nodeName)); + $node->setAttribute("name", "like"); + $node->setAttribute("value", "Yes"); + + $dom->preserveWhiteSpace = false; + $dom->formatOutput = true; + + $this->assertEquals( + $dom->saveXML(), + $this->formatter->encode($data) + ); + } + + public function testSimpleDecode() + { + $dom = new \DOMDocument("1.0"); + $node =$dom->appendChild(new \DOMElement($this->formatter->root)) + ->appendChild(new \DOMElement($this->formatter->nodeName)); + + $node->setAttribute("name", "foo"); + $node->setAttribute("value", "bar"); + + $dom->preserveWhiteSpace = false; + $dom->formatOutput = true; + + $raw = $dom->saveXML(); + + $data = $this->formatter->decode($raw); + + $this->assertEquals(["foo" => "bar"], $data->getData()); + } + + public function testComplexDecode() + { + $expectedData = + [ + [ + "name" => "foo", + "value" => "bar", + ], + "row" => [ + [ + "name" => "fruit", + "value" => "banana", + ], + [ + "name" => "type", + "value" => "fruit", + ], + "orange"=> [ + [ + "name" => "type", + "value" => "fruit", + ] + ], + "banana"=> [ + [ + "name" => "like", + "value" => "Yes", + ] + ] + ] + ]; + + $dom = new \DOMDocument("1.0"); + $base = $dom->appendChild(new \DOMElement($this->formatter->root)); + /** @var \DOMElement $node */ + $node = $base->appendChild(new \DOMElement($this->formatter->nodeName)); + $node->setAttribute("name", "foo"); + $node->setAttribute("value", "bar"); + + $baz = $base->appendChild(new \DOMElement($this->formatter->rowName)); + $node = $baz->appendChild(new \DOMElement($this->formatter->nodeName)); + $node->setAttribute("name", "fruit"); + $node->setAttribute("value", "banana"); + $node = $baz->appendChild(new \DOMElement($this->formatter->nodeName)); + $node->setAttribute("name", "type"); + $node->setAttribute("value", "fruit"); + + $baz = $base->appendChild(new \DOMElement($this->formatter->rowName)); + $orange = $baz->appendChild(new \DOMElement("orange")); + $node = $orange->appendChild(new \DOMElement($this->formatter->nodeName)); + $node->setAttribute("name","type"); + $node->setAttribute("value","fruit"); + $banana = $baz->appendChild(new \DOMElement("banana")); + $node = $banana->appendChild(new \DOMElement($this->formatter->nodeName)); + $node->setAttribute("name", "like"); + $node->setAttribute("value", "Yes"); + + $data = $this->formatter->rawDecode($dom->saveXML()); + $this->assertEquals($expectedData, $data); + + $expectedData = [ + "foo" => "bar", + "row" => [ + "fruit" => "banana", + "type" => "fruit", + "orange"=>[ + "type" => "fruit" + ], + "banana"=>[ + "like" => "Yes" + ] + ], + ]; + + $data = $this->formatter->decode($dom->saveXML()); + + $this->assertEquals($expectedData, $data->getData()); + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Tests/FileFormat/Formatting/FormatterDataTest.php b/core/lib/Thelia/Tests/FileFormat/Formatting/FormatterDataTest.php new file mode 100644 index 000000000..d9558e192 --- /dev/null +++ b/core/lib/Thelia/Tests/FileFormat/Formatting/FormatterDataTest.php @@ -0,0 +1,464 @@ + + */ +class FormatterDataTest extends \PHPUnit_Framework_TestCase +{ + + public function setUp() + { + new Translator(new Container()); + } + + public function testFormatSimpleQuery() + { + $formatterData = new FormatterData(); + + $query = ConfigQuery::create() + ->limit(1) + ; + + $formattedData = $formatterData + ->loadModelCriteria($query) + ->getData() + ; + + /** @var \Thelia\Model\Config $result */ + $result = $query->findOne(); + + $formattedResult = [ + [ + "config.id" => $result->getId(), + "config.name" => $result->getName(), + "config.value" => $result->getValue(), + "config.created_at" => $result->getCreatedAt(), + "config.updated_at" => $result->getUpdatedAt(), + "config.hidden" => $result->getHidden(), + "config.secured" => $result->getHidden(), + ], + ]; + + $this->assertEquals($formattedResult,$formattedData); + } + + public function testFormatSimpleQueryWithAliases() + { + /** + * Aliases must not be case sensitive + */ + $aliases = [ + "coNfiG.iD" => "id", + "conFig.NaMe" => "name", + "CoNfIg.Value" => "value", + "config.hidden" => "hidden", + "ConFig.Secured" => "secured", + ]; + + $formatterData = new FormatterData($aliases); + + $query = ConfigQuery::create() + ->limit(1) + ; + + $formattedData = $formatterData + ->loadModelCriteria($query) + ->getData() + ; + + /** @var \Thelia\Model\Config $result */ + $result = $query->findOne(); + + $formattedResult = [ + [ + "id" => $result->getId(), + "name" => $result->getName(), + "value" => $result->getValue(), + "config.created_at" => $result->getCreatedAt(), + "config.updated_at" => $result->getUpdatedAt(), + "hidden" => $result->getHidden(), + "secured" => $result->getHidden(), + ], + ]; + + $this->assertEquals($formattedResult,$formattedData); + } + + public function testFormatComplexQuery() + { + $formatterData = new FormatterData(); + + $query = ProductSaleElementsQuery::create() + ->useProductQuery() + ->addAsColumn("\"".ProductTableMap::ID."\"", ProductTableMap::ID) + ->endUse() + ->select( + [ + ProductSaleElementsTableMap::ID, + ProductSaleElementsTableMap::QUANTITY, + ] + ) + ->limit(1) + ; + + $formattedData = $formatterData + ->loadModelCriteria($query) + ->getData() + ; + /** @var array $data */ + $data = $query->findOne(); + + $expectedData = [ + [ + "product.id" => $data["product.ID"], + "product_sale_elements.id" => $data["product_sale_elements.ID"], + "product_sale_elements.quantity" => $data["product_sale_elements.QUANTITY"], + ] + ]; + + $this->assertEquals($expectedData, $formattedData); + } + + public function testFormatComplexQueryWithAliases() + { + $aliases = [ + "product.id" => "pid", + "product_sale_elements.id" => "pseid", + "product_sale_elements.quantity" => "stock" + ]; + + $formatterData = new FormatterData($aliases); + + $query = ProductSaleElementsQuery::create() + ->useProductQuery() + ->addAsColumn("\"".ProductTableMap::ID."\"", ProductTableMap::ID) + ->endUse() + ->select( + [ + ProductSaleElementsTableMap::ID, + ProductSaleElementsTableMap::QUANTITY, + ] + ) + ->limit(1) + ; + + $formattedData = $formatterData + ->loadModelCriteria($query) + ->getData() + ; + /** @var array $data */ + $data = $query->findOne(); + + $expectedData = [ + [ + "pid" => $data["product.ID"], + "pseid" => $data["product_sale_elements.ID"], + "stock" => $data["product_sale_elements.QUANTITY"], + ] + ]; + + $this->assertEquals($expectedData, $formattedData); + } + + public function testSetRawDataDepth1() { + $formatterData = new FormatterData(); + + $data = [ + "foo" => "bar", + "baz" => "foo", + ]; + + $formattedData = $formatterData + ->setData($data) + ->getData() + ; + + $this->assertEquals($data,$formattedData); + } + + public function testSetRawDataDepth1WithAliases() { + $aliases = [ + "FoO" => "orange", + "Baz" => "banana", + ]; + + $formatterData = new FormatterData($aliases); + + $data = [ + "fOo" => "bar", + "bAZ" => "foo", + ]; + + $expectedData = [ + "orange" => "bar", + "banana" => "foo", + ]; + + $formattedData = $formatterData + ->setData($data) + ->getData() + ; + + $this->assertEquals($expectedData,$formattedData); + } + + public function testSetRawDataDepth2() { + $formatterData = new FormatterData(); + + $data = [ + [ + "orange" => "banana", + "apple" => "pear", + ], + [ + "strawberry" => "raspberry", + "blackberry" => "cranberry", + ] + ]; + + $formattedData = $formatterData + ->setData($data) + ->getData() + ; + + $this->assertEquals($data,$formattedData); + } + + public function testSetRawDataDepth2WithAliases() { + $aliases = [ + "orange" => "cherry", + "blackberry" => "banana", + ]; + + $formatterData = new FormatterData($aliases); + + $data = [ + [ + "orange" => "banana", + "apple" => "pear", + ], + [ + "strawberry" => "raspberry", + "blackberry" => "cranberry", + ] + ]; + + $expectedData = [ + [ + "cherry" => "banana", + "apple" => "pear", + ], + [ + "strawberry" => "raspberry", + "banana" => "cranberry", + ] + ]; + + $formattedData = $formatterData + ->setData($data) + ->getData() + ; + + $this->assertEquals($expectedData,$formattedData); + } + + public function testSetRawDataMultipleDepth() { + $formatterData = new FormatterData(); + + $data = [ + [ + "orange" => "banana", + "apple" => "pear", + ], + [ + "strawberry" => "raspberry", + "blackberry" => "cranberry", + ] + ]; + + $formattedData = $formatterData + ->setData($data) + ->getData() + ; + + $this->assertEquals($data,$formattedData); + } + + public function testSetRawDataMultipleDepthWithAliases() { + $aliases = [ + "orange" => "cherry", + "blackberry" => "banana", + ]; + + $formatterData = new FormatterData($aliases); + + $data = [ + "orange" => "banana", + "apple" => "pear", + [ + "orange" => "tomato", + "pepper" => "pear", + ], + [ + [ + "strawberry" => "raspberry", + "blackberry" => "cranberry", + ], + [ + "cherry" => "lemon", + "mango" => "cranberry", + ] + ], + ]; + + $expectedData = [ + "cherry" => "banana", + "apple" => "pear", + [ + "cherry" => "tomato", + "pepper" => "pear", + ], + [ + [ + "strawberry" => "raspberry", + "banana" => "cranberry", + ], + [ + "cherry" => "lemon", + "mango" => "cranberry", + ] + ], + ]; + + $formattedData = $formatterData + ->setData($data) + ->getData() + ; + + $this->assertEquals($expectedData,$formattedData); + } + + public function testSetRawDataMultipleDepthWithReverseAliases() { + $aliases = [ + "orange" => "foo", + "blackberry" => "banana", + ]; + + $formatterData = new FormatterData($aliases); + + $data = [ + "orange" => "banana", + "apple" => "pear", + [ + "orange" => "tomato", + "pepper" => "pear", + ], + [ + [ + "strawberry" => "raspberry", + "blackberry" => "cranberry", + ], + [ + "cherry" => "lemon", + "mango" => "cranberry", + ] + ], + ]; + + $formattedData = $formatterData + ->setData($data) + ->getDataReverseAliases() + ; + + $this->assertEquals($data,$formattedData); + } + + /** + * That's why an alias MUST not be the same as a present value + */ + public function testSetRawDataMultipleDepthWithReverseAliasesFail() { + $aliases = [ + "orange" => "cherry", + "blackberry" => "banana", + ]; + + $formatterData = new FormatterData($aliases); + + $data = [ + "orange" => "banana", + "apple" => "pear", + [ + "orange" => "tomato", + "pepper" => "pear", + ], + [ + [ + "strawberry" => "raspberry", + "blackberry" => "cranberry", + ], + [ + "cherry" => "lemon", + "mango" => "cranberry", + ] + ], + ]; + + $formattedData = $formatterData + ->setData($data) + ->getDataReverseAliases() + ; + + $this->assertNotEquals($data,$formattedData); + } + + public function testAddRow() + { + $data = new FormatterData(); + + $row = [ + "title" => "A super book", + "author" => "Manu", + ]; + + $data->addRow($row); + + $this->assertEquals([$row], $data->getData()); + $this->assertEquals($row, $data->getRow()); + } + + public function testPopRow() + { + $data = new FormatterData(); + + $row = [ + "title" => "A super book", + "author" => "Manu", + ]; + + $data->addRow($row); + + $this->assertEquals($row, $data->popRow()); + $this->assertFalse($data->getRow()); + } +} diff --git a/core/lib/Thelia/Tests/FileFormat/Formatting/FormatterManagerTest.php b/core/lib/Thelia/Tests/FileFormat/Formatting/FormatterManagerTest.php new file mode 100644 index 000000000..b28a2cb88 --- /dev/null +++ b/core/lib/Thelia/Tests/FileFormat/Formatting/FormatterManagerTest.php @@ -0,0 +1,74 @@ + + */ +class FormatterManagerTest extends \PHPUnit_Framework_TestCase +{ + /** + * @var FormatterManager + */ + protected $manager; + + public function setUp() + { + new Translator( + new Container() + ); + $this->manager = new FormatterManager(); + } + + public function testAddFormatter() + { + /** @var AbstractFormatter $instance */ + $instance = $this->getMock("Thelia\\Core\\FileFormat\\Formatting\\AbstractFormatter"); + + $this->manager->add($instance); + + $archiveBuilders = $this->manager->getAll(); + + $this->assertTrue( + array_key_exists($instance->getName(), $archiveBuilders) + ); + } + + public function testDeleteFormatter() + { + /** @var AbstractFormatter $instance */ + $instance = $this->getMock("Thelia\\Core\\FileFormat\\Formatting\\AbstractFormatter"); + + $this->manager->add($instance); + + $this->manager->delete($instance->getName()); + + $this->assertTrue( + count($this->manager->getAll()) === 0 + ); + } + + /** + * @expectedException \OutOfBoundsException + */ + public function testDeleteNotExistingFormatter() + { + $this->manager->delete("foo"); + } +} diff --git a/core/lib/Thelia/Tests/ImportExport/Export/ContentExportTest.php b/core/lib/Thelia/Tests/ImportExport/Export/ContentExportTest.php new file mode 100644 index 000000000..8ecdfd00a --- /dev/null +++ b/core/lib/Thelia/Tests/ImportExport/Export/ContentExportTest.php @@ -0,0 +1,217 @@ + + */ +class ContentExportTest extends \PHPUnit_Framework_TestCase +{ + /** @var Lang */ + protected $lang; + + /** @var ContentExport */ + protected $handler; + + public function setUp() + { + new Translator(new Container()); + + $this->lang = Lang::getDefaultLanguage(); + $this->handler = new ContentExport(new Container()); + } + + public function testQuery() + { + $data = $this->handler->buildData($this->lang)->getData(); + + + $max = count($data); + if ($max > 50) { + $max = 50; + } + + for ($i = 0; $i < $max;) { + $content = ContentQuery::create()->findPk($data[$i]["id"]); + + $this->assertNotNull($content); + + $content->setLocale($this->lang->getLocale()); + + $this->assertEquals($content->getTitle(), $data[$i]["title"]); + $this->assertEquals($content->getDescription(), $data[$i]["description"]); + $this->assertEquals($content->getChapo(), $data[$i]["chapo"]); + $this->assertEquals($content->getPostscriptum(), $data[$i]["conclusion"]); + $this->assertEquals($content->getMetaTitle(), $data[$i]["seo_title"]); + $this->assertEquals($content->getMetaDescription(), $data[$i]["seo_description"]); + $this->assertEquals($content->getMetaKeywords(), $data[$i]["seo_keywords"]); + + + do { + if (null !== $data[$i]["folder_id"]) { + $folder = FolderQuery::create()->findPk($data[$i]["folder_id"]); + + $this->assertNotNull($folder); + + $contentFolder = ContentFolderQuery::create() + ->filterByContent($content) + ->filterByFolder($folder) + ->findOne() + ; + + $this->assertNotNull($contentFolder); + + $folder->setLocale($this->lang->getLocale()); + + $this->assertEquals( + $folder->getTitle(), + $data[$i]["folder_title"] + ); + + $this->assertEquals( + $contentFolder->getDefaultFolder(), + (bool)((int)$data[$i]["is_default_folder"]) + ); + } + } while ( + isset($data[++$i]["id"]) && + $data[$i-1]["id"] === $data[$i]["id"] && + ++$max + ); + } + } + + public function testQueryImages() + { + $data = $this->handler + ->setImageExport(true) + ->buildData($this->lang) + ->getData() + ; + + $max = count($data); + if ($max > 50) { + $max = 50; + } + + for ($i = 0; $i < $max; ++$i) { + $images = ContentImageQuery::create() + ->filterByContentId($data[$i]["id"]) + ->select(ContentImageTableMap::FILE) + ->find() + ->toArray() + ; + + $imagesString = implode(",", $images); + + if (empty($data[$i]["content_images"])) { + $j = 1; + while ($data[$i-$j]["id"] === $data[$i]["id"]) { + if (!empty($data[$i - $j++]["content_images"])) { + $data[$i]["content_images"] = $data[$i-$j+1]["content_images"]; + break; + } + } + } + + $this->assertEquals($imagesString, $data[$i]["content_images"]); + + $folderImages = FolderImageQuery::create() + ->useFolderQuery() + ->useContentFolderQuery() + ->filterByContentId($data[$i]["id"]) + ->filterByFolderId($data[$i]["folder_id"]) + ->endUse() + ->endUse() + ->select(FolderImageTableMap::FILE) + ->find() + ->toArray() + ; + + $folderImages = implode(",", $folderImages); + + $this->assertEquals($folderImages, $data[$i]["folder_images"]); + } + } + + public function testQueryDocument() + { + $data = $this->handler + ->setDocumentExport(true) + ->buildData($this->lang) + ->getData() + ; + + $max = count($data); + if ($max > 50) { + $max = 50; + } + + for ($i = 0; $i < $max; ++$i) { + $documents = ContentDocumentQuery::create() + ->filterByContentId($data[$i]["id"]) + ->select(ContentDocumentTableMap::FILE) + ->find() + ->toArray() + ; + + $documentsString = implode(",", $documents); + + if (empty($data[$i]["content_documents"])) { + $j = 1; + while ($data[$i-$j]["id"] === $data[$i]["id"]) { + if (!empty($data[$i - $j++]["content_documents"])) { + $data[$i]["content_documents"] = $data[$i-$j+1]["content_documents"]; + break; + } + } + } + + $this->assertEquals($documentsString, $data[$i]["content_documents"]); + + $folderDocuments = FolderDocumentQuery::create() + ->useFolderQuery() + ->useContentFolderQuery() + ->filterByContentId($data[$i]["id"]) + ->filterByFolderId($data[$i]["folder_id"]) + ->endUse() + ->endUse() + ->select(FolderDocumentTableMap::FILE) + ->find() + ->toArray() + ; + + $folderDocuments = implode(",", $folderDocuments); + + $this->assertEquals($folderDocuments, $data[$i]["folder_documents"]); + } + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Tests/ImportExport/Export/CustomerExportTest.php b/core/lib/Thelia/Tests/ImportExport/Export/CustomerExportTest.php new file mode 100644 index 000000000..55fb66ab2 --- /dev/null +++ b/core/lib/Thelia/Tests/ImportExport/Export/CustomerExportTest.php @@ -0,0 +1,194 @@ + + */ +class CustomerExportTest extends \PHPUnit_Framework_TestCase +{ + public function testQuery() + { + new Translator(new Container()); + + $handler = new CustomerExport(new Container()); + + $lang = Lang::getDefaultLanguage(); + $data = $handler->buildData($lang); + + $keys = ["ref","title","last_name","first_name","email","label", + "discount","is_registered_to_newsletter","sign_up_date", + "total_orders","last_order_amount","last_order_date", + "address_first_name","address_last_name","company","address1", + "address2","address3","zipcode","city","country","phone", + "cellphone","is_default_address","address_title"]; + + sort($keys); + + $rawData = $data->getData(); + + $max = CustomerQuery::create()->count(); + /** + * 30 customers that has more than 1 addresses or enough + */ + if (30 < $max) { + $max = 30; + } + + for ($i = 0; $i < $max;) { + $row = $rawData[$i]; + + $rowKeys = array_keys($row); + sort($rowKeys); + + $this->assertEquals($rowKeys, $keys); + + $customer = CustomerQuery::create() + ->findOneByRef($row["ref"]) + ; + + $this->assertNotNull($customer); + + $this->assertEquals($customer->getFirstname(), $row["first_name"]); + $this->assertEquals($customer->getLastname(), $row["last_name"]); + $this->assertEquals($customer->getEmail(), $row["email"]); + $this->assertEquals($customer->getCreatedAt()->format($lang->getDatetimeFormat()), $row["sign_up_date"]); + $this->assertEquals($customer->getDiscount(), $row["discount"]); + + $title = CustomerTitleQuery::create()->findPk($customer->getTitleId()); + $this->assertEquals($title->getShort(), $row["title"]); + + $total = 0; + foreach ($customer->getOrders() as $order) { + $amount = $order->getTotalAmount($tax); + + if (0 < $rate = $order->getCurrencyRate()) { + $amount = round($amount / $rate, 2); + } + + $total += $amount; + } + + $defaultCurrencyCode = Currency::getDefaultCurrency()->getCode(); + $this->assertEquals($total . " " . $defaultCurrencyCode, $row["total_orders"]); + + $lastOrder = OrderQuery::create() + ->filterByCustomer($customer) + ->orderByCreatedAt(Criteria::DESC) + ->orderById(Criteria::DESC) + ->findOne() + ; + + if (null !== $lastOrder) { + $expectedPrice = $lastOrder->getTotalAmount($tax_) . " " . $lastOrder->getCurrency()->getCode(); + $expectedDate = $lastOrder->getCreatedAt()->format($lang->getDatetimeFormat()); + } else { + $expectedPrice = ""; + $expectedDate = ""; + } + + $this->assertEquals( + $expectedPrice, + $row["last_order_amount"] + ); + + $this->assertEquals( + $expectedDate, + $row["last_order_date"] + ); + + $newsletter = NewsletterQuery::create() + ->findOneByEmail($customer->getEmail()) + ; + + $this->assertEquals( + $newsletter === null ? 0 : 1, + $row["is_registered_to_newsletter"] + ); + + do { + $address = AddressQuery::create() + ->filterByCustomer($customer) + ->filterByAddress1($rawData[$i]["address1"]) + ->filterByAddress2($rawData[$i]["address2"]) + ->filterByAddress3($rawData[$i]["address3"]) + ->filterByFirstname($rawData[$i]["address_first_name"]) + ->filterByLastname($rawData[$i]["address_last_name"]) + ->filterByCountryId( + CountryI18nQuery::create() + ->filterByLocale($lang->getLocale()) + ->findOneByTitle($rawData[$i]["country"]) + ->getId() + ) + ->filterByCompany($rawData[$i]["company"]) + ->_if(empty($rawData[$i]["company"])) + ->_or() + ->filterByCompany(null, Criteria::ISNULL) + ->_endif() + ->filterByZipcode($rawData[$i]["zipcode"]) + ->filterByCity($rawData[$i]["city"]) + ->filterByIsDefault($rawData[$i]["is_default_address"]) + ->filterByCellphone($rawData[$i]["cellphone"]) + ->_if(empty($rawData[$i]["cellphone"])) + ->_or() + ->filterByCellphone(null, Criteria::ISNULL) + ->_endif() + ->filterByPhone($rawData[$i]["phone"]) + ->_if(empty($rawData[$i]["phone"])) + ->_or() + ->filterByPhone(null, Criteria::ISNULL) + ->_endif() + ->filterByLabel($rawData[$i]["label"]) + ->_if(empty($rawData[$i]["label"])) + ->_or() + ->filterByLabel(null, Criteria::ISNULL) + ->_endif() + ->filterByTitleId( + CustomerTitleI18nQuery::create() + ->filterByLocale($lang->getLocale()) + ->findOneByShort($rawData[$i]["address_title"]) + ->getId() + ) + ->findOne() + ; + + $this->assertNotNull($address); + + $rowKeys = array_keys($rawData[$i]); + sort($rowKeys); + + $this->assertEquals($rowKeys, $keys); + } while ( + isset($rawData[++$i]["ref"]) && + $rawData[$i-1]["ref"] === $rawData[$i]["ref"] && + ++$max + ); + + } + } +} diff --git a/core/lib/Thelia/Tests/ImportExport/Export/ExportHandlerTest.php b/core/lib/Thelia/Tests/ImportExport/Export/ExportHandlerTest.php new file mode 100644 index 000000000..197f16db4 --- /dev/null +++ b/core/lib/Thelia/Tests/ImportExport/Export/ExportHandlerTest.php @@ -0,0 +1,121 @@ + + */ +class ExportHandlerTest extends ContainerAwareTestCase +{ + /** @var \Thelia\ImportExport\Export\ExportHandler */ + protected $handler; + + /** + * Use this method to build the container with the services that you need. + */ + protected function buildContainer(ContainerBuilder $container) + { + $container->setParameter( + "Thelia.parser.loops", [ + "address" => "Thelia\\Core\\Template\\Loop\\Address", + ] + ); + } + + public function setUp() + { + parent::setUp(); + + $this->handler = $this->getMock( + "Thelia\\ImportExport\\Export\\ExportHandler", + [ + "getHandledTypes", + "buildDataSet" + ], + [ + $this->container + ] + ); + + $this->handler->expects($this->any()) + ->method("getHandledTypes") + ->willReturn([FormatType::TABLE, FormatType::UNBOUNDED]) + ; + } + + public function testRenderLoop() + { + $customerId = CustomerQuery::create() + ->findOne() + ->getId(); + + $this->handler + ->expects($this->any()) + ->method("buildDataSet") + ->willReturn($this->handler->renderLoop("address", ["customer"=>$customerId])) + ; + + $lang = Lang::getDefaultLanguage(); + + $loop = $this->handler->buildDataSet($lang); + + $this->assertInstanceOf( + "Thelia\\Core\\Template\\Loop\\Address", + $loop + ); + + $data = $this->handler->buildData($lang); + + $addresses = AddressQuery::create() + ->filterByCustomerId($customerId) + ->find() + ->toArray("Id") + ; + + foreach ($data->getData() as $row) { + $this->assertArrayHasKey("id", $row); + + $this->assertArrayHasKey($row["id"], $addresses); + + $this->assertEquals(count($addresses), $row["loop_total"]); + + $address = $addresses[$row["id"]]; + + $this->assertEquals($row["address1"], $address["Address1"]); + $this->assertEquals($row["address2"], $address["Address2"]); + $this->assertEquals($row["address3"], $address["Address3"]); + $this->assertEquals($row["cellphone"], $address["Cellphone"]); + $this->assertEquals($row["city"], $address["City"]); + $this->assertEquals($row["company"], $address["Company"]); + $this->assertEquals($row["country"], $address["CountryId"]); + $this->assertEquals($row["create_date"], $address["CreatedAt"]); + $this->assertEquals($row["update_date"], $address["UpdatedAt"]); + $this->assertEquals($row["firstname"], $address["Firstname"]); + $this->assertEquals($row["lastname"], $address["Lastname"]); + $this->assertEquals($row["id"], $address["Id"]); + $this->assertEquals($row["label"], $address["Label"]); + $this->assertEquals($row["phone"], $address["Phone"]); + $this->assertEquals($row["title"], $address["TitleId"]); + $this->assertEquals($row["zipcode"], $address["Zipcode"]); + } + + } +} diff --git a/core/lib/Thelia/Tests/ImportExport/Export/MailingExportTest.php b/core/lib/Thelia/Tests/ImportExport/Export/MailingExportTest.php new file mode 100644 index 000000000..99be26579 --- /dev/null +++ b/core/lib/Thelia/Tests/ImportExport/Export/MailingExportTest.php @@ -0,0 +1,52 @@ + + */ +class MailingExportTest extends \PHPUnit_Framework_TestCase +{ + /** @var \Thelia\ImportExport\Export\Type\MailingExport $handler */ + protected $handler; + + public function setUp() + { + $container = new Container(); + + new Translator($container); + + $this->handler = new \Thelia\ImportExport\Export\Type\MailingExport($container); + } + + public function testExport() + { + $data = $this->handler->buildData(Lang::getDefaultLanguage()); + + } + + public function testType() + { + $this->assertEquals( + [\Thelia\Core\FileFormat\FormatType::TABLE, FormatType::UNBOUNDED], + $this->handler->getHandledTypes() + ); + } +} diff --git a/core/lib/Thelia/Tests/ImportExport/Export/OrderExportTest.php b/core/lib/Thelia/Tests/ImportExport/Export/OrderExportTest.php new file mode 100644 index 000000000..5fd2b7c53 --- /dev/null +++ b/core/lib/Thelia/Tests/ImportExport/Export/OrderExportTest.php @@ -0,0 +1,150 @@ + + */ +class OrderExportTest extends \PHPUnit_Framework_TestCase +{ + public function testQuery() + { + $container = new Container(); + new Translator($container); + + $handler = new OrderExport($container); + + $lang = Lang::getDefaultLanguage(); + $locale = $lang->getLocale(); + + $data = $handler->buildData($lang)->getData(); + + $ordersProductQuery = OrderProductQuery::create(); + $orders = OrderQuery::create()->find(); + + $count = $ordersProductQuery->count(); + $this->assertEquals(count($data), $count); + + /** + * For the rest of the test, 50 orders are much enough + */ + if ($count > 50) { + $count = 50; + } + + $current = 0; + + for ($i = 0; $i < $count; ++$current) { + $row = $data[$i]; + /** @var \Thelia\Model\Order $order */ + $order = $orders->get($current); + + $this->assertEquals( + $ref = $order->getRef(), $row["ref"] + ); + + $this->assertEquals( + $order->getCustomer()->getRef(), $row["customer_ref"] + ); + + $coupons = OrderCouponQuery::create() + ->filterByOrder($order) + ->select(OrderCouponTableMap::TITLE) + ->find() + ->toArray() + ; + $coupons = implode(",", $coupons); + + $this->assertTrue( + empty($coupons) ? + empty($row["coupons"]): + $coupons === $row["coupons"] + ); + + $this->assertEquals( + $order->getCreatedAt()->format($lang->getDatetimeFormat()), + $row["date"] + ); + + $this->assertEquals($order->getCurrency()->getCode(), $row["currency"]); + $this->assertEquals($order->getCustomer()->getRef(), $row["customer_ref"]); + $this->assertEquals($order->getOrderStatus()->setLocale($locale)->getTitle(), $row["status"]); + + $this->assertEquals($order->getDeliveryRef(), $row["delivery_ref"]); + $this->assertEquals($order->getModuleRelatedByDeliveryModuleId()->getCode(), $row["delivery_module"]); + $this->assertEquals($order->getInvoiceRef(), $row["invoice_ref"]); + $this->assertEquals($order->getModuleRelatedByPaymentModuleId()->getCode(), $row["payment_module"]); + + $this->assertEquals($order->getTotalAmount($tax, false, false), $row["total_including_taxes"]); + $this->assertEquals($order->getTotalAmount($tax, false, true), $row["total_with_discount"]); + $this->assertEquals($order->getTotalAmount($tax, true, true), $row["total_discount_and_postage"]); + + $invoiceAddress = $order->getOrderAddressRelatedByInvoiceOrderAddressId(); + $deliveryAddress = $order->getOrderAddressRelatedByDeliveryOrderAddressId(); + + $addresses = [ + "delivery" => $deliveryAddress, + "invoice" => $invoiceAddress + ]; + + /** @var \Thelia\Model\OrderAddress $address */ + foreach ($addresses as $prefix => $address) { + $this->assertEquals($address->getCustomerTitle()->setLocale($locale)->getShort(), $row[$prefix."_title"]); + $this->assertEquals($address->getAddress1(), $row[$prefix."_address1"]); + $this->assertEquals($address->getAddress2(), $row[$prefix."_address2"]); + $this->assertEquals($address->getAddress3(), $row[$prefix."_address3"]); + $this->assertEquals($address->getCity(), $row[$prefix."_city"]); + $this->assertEquals($address->getZipcode(), $row[$prefix."_zip_code"]); + $this->assertEquals($address->getCompany(), $row[$prefix."_company"]); + $this->assertEquals($address->getFirstname(), $row[$prefix."_first_name"]); + $this->assertEquals($address->getLastname(), $row[$prefix."_last_name"]); + $this->assertEquals($address->getCountry()->setLocale($locale)->getTitle(), $row[$prefix."_country"]); + $this->assertEquals($address->getPhone(), $row[$prefix."_phone"]); + } + + while ($data[$i]["ref"] === $ref) { + /** @var \Thelia\Model\OrderProduct $product */ + $product = OrderProductQuery::create() + ->filterByTitle($data[$i]["product_title"]) + ->filterByTaxRuleTitle($data[$i]["tax_title"]) + ->filterByWasInPromo($data[$i]["was_in_promo"]) + ->_if((bool) ((int) $data[$i]["was_in_promo"])) + ->filterByPromoPrice($data[$i]["price"]) + ->_else() + ->filterByPrice($data[$i]["price"]) + ->_endif() + ->filterByQuantity($data[$i]["quantity"]) + ->findOne() + ; + $this->assertNotNull($product); + + $sum = 0; + foreach ($product->getOrderProductTaxes() as $tax) { + $sum += $product->getWasInPromo() ? $tax->getPromoAmount() : $tax->getAmount(); + } + + $this->assertEquals($sum, $data[$i++]["tax_amount"]); + } + } + } +} diff --git a/core/lib/Thelia/Tests/ImportExport/Export/ProductPricesExportTest.php b/core/lib/Thelia/Tests/ImportExport/Export/ProductPricesExportTest.php new file mode 100644 index 000000000..689dbcee8 --- /dev/null +++ b/core/lib/Thelia/Tests/ImportExport/Export/ProductPricesExportTest.php @@ -0,0 +1,88 @@ + + */ +class ProductPricesExportTest extends \PHPUnit_Framework_TestCase +{ + public function testQuery() + { + new Translator(new Container()); + $export = new ProductPricesExport(new Container()); + + $data = $export->buildData(Lang::getDefaultLanguage()); + + $keys = ["attributes","currency","ean","price","product_id","promo","promo_price","ref","title"]; + + $rawData = $data->getData(); + + $max = count($rawData); + + /** + * If there's more that 50 entries, + * just pick 50, it would be faster and as tested as if we test 1000 entries. + */ + if ($max > 50) { + $max = 50; + } + + for ($i = 0; $i < $max; ++$i) { + $row = $rawData[$i]; + + $rowKeys = array_keys($row); + + $this->assertTrue(sort($rowKeys)); + $this->assertEquals($keys, $rowKeys); + + $pse = ProductSaleElementsQuery::create() + ->findOneByRef($row["ref"]) + ; + + $this->assertNotNull($pse); + $this->assertEquals($pse->getEanCode(),$row["ean"]); + $this->assertEquals($pse->getPromo(),$row["promo"]); + + $currency = CurrencyQuery::create()->findOneByCode($row["currency"]); + $this->assertNotNull($currency); + + $price = $pse->getPricesByCurrency($currency); + $this->assertEquals($price->getPrice(), $row["price"]); + $this->assertEquals($price->getPromoPrice(), $row["promo_price"]); + $this->assertEquals($pse->getProduct()->getTitle(), $row["title"]); + + $attributeCombinations = $pse->getAttributeCombinations(); + $attributes = []; + + foreach ($attributeCombinations as $attributeCombination) { + $attributes[] = $attributeCombination->getAttributeAv()->getTitle(); + } + + $rowAttributes = explode(",", $row["attributes"]); + + sort($rowAttributes); + sort($attributes); + + $this->assertEquals($attributes, $rowAttributes); + } + } +} diff --git a/core/lib/Thelia/Tests/ImportExport/Export/ProductSEOExportTest.php b/core/lib/Thelia/Tests/ImportExport/Export/ProductSEOExportTest.php new file mode 100644 index 000000000..5325de093 --- /dev/null +++ b/core/lib/Thelia/Tests/ImportExport/Export/ProductSEOExportTest.php @@ -0,0 +1,67 @@ + + */ +class ProductSEOExportTest extends \PHPUnit_Framework_TestCase +{ + public function testQuery() + { + new Translator(new Container()); + $export = new ProductSEOExport(new Container()); + + $data = $export->buildData(Lang::getDefaultLanguage()); + + $keys=["ref","visible","product_title","url","page_title","meta_description","meta_keywords",]; + sort($keys); + $rawData = $data->getData(); + + $max = count($rawData); + + /** + * If there's more that 50 entries, + * just pick 50, it would be faster and as tested as if we test 1000 entries. + */ + if ($max > 50) { + $max = 50; + } + + for ($i = 0; $i < $max; ++$i) { + $row = $rawData[$i]; + $rowKeys = array_keys($row); + + $this->assertTrue(sort($rowKeys)); + $this->assertEquals($keys, $rowKeys); + + $product = ProductQuery::create()->findOneByRef($row["ref"]); + $this->assertNotNull($product); + + $this->assertEquals($product->getVisible(), $row["visible"]); + $this->assertEquals($product->getTitle(), $row["product_title"]); + + $this->assertEquals($product->getMetaTitle(), $row["page_title"]); + $this->assertEquals($product->getMetaDescription(), $row["meta_description"]); + $this->assertEquals($product->getMetaKeywords(), $row["meta_keywords"]); + $this->assertEquals($product->getRewrittenUrl("en_US"), $row["url"]); + } + } +} diff --git a/core/lib/Thelia/Tests/ImportExport/Export/ProductTaxedPricesExportTest.php b/core/lib/Thelia/Tests/ImportExport/Export/ProductTaxedPricesExportTest.php new file mode 100644 index 000000000..d50001d39 --- /dev/null +++ b/core/lib/Thelia/Tests/ImportExport/Export/ProductTaxedPricesExportTest.php @@ -0,0 +1,50 @@ + + */ +class ProductTaxedPricesExportTest extends \PHPUnit_Framework_TestCase +{ + public function testPrices() + { + $container = new Container(); + new Translator($container); + + $handler = new ProductTaxedPricesExport($container); + + $lang = Lang::getDefaultLanguage(); + $data = $handler->buildData($lang)->getData(); + + foreach ($data as $line) { + $product = ProductSaleElementsQuery::create()->findOneByRef($line["ref"]); + $currency = CurrencyQuery::create()->findOneByCode($line["currency"]); + + $this->assertNotNull($product); + + $prices = $product->getPricesByCurrency($currency); + + $this->assertEquals($prices->getPrice(), $line["price"]); + $this->assertEquals($prices->getPromoPrice(), $line["promo_price"]); + } + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Tests/ImportExport/Import/ProductPricesImportTest.php b/core/lib/Thelia/Tests/ImportExport/Import/ProductPricesImportTest.php new file mode 100644 index 000000000..8bf56ee54 --- /dev/null +++ b/core/lib/Thelia/Tests/ImportExport/Import/ProductPricesImportTest.php @@ -0,0 +1,112 @@ + + */ +class ProductPricesImportTest extends ControllerTestBase +{ + /** + * Use this method to build the container with the services that you need. + */ + protected function buildContainer(ContainerBuilder $container) + { + + } + + /** + * @return \Thelia\Controller\BaseController The controller you want to test + */ + protected function getController() + { + return new ImportController(); + } + + public function setUp() + { + parent::setUp(); + + $this->import = new ProductPricesImport($this->container); + + } + + public function testImport() + { + $currency = Currency::getDefaultCurrency(); + + $query = ProductSaleElementsQuery::create() + ->addAscendingOrderByColumn('RAND()') + ->limit(3) + ->find() + ; + + $jsonData = []; + $data = []; + + /** @var \Thelia\Model\ProductSaleElements $pse */ + foreach ($query as $pse) { + + $entry = []; + + $entry["ref"] = $pse->getRef(); + + /** + * Be sure to get a different value. + */ + while ($pse->getPricesByCurrency($currency)->getPrice() === $entry["price"] = rand(0, 1000)); + while ($pse->getPricesByCurrency($currency)->getPromoPrice() === $entry["promo_price"] = rand(0, 1000)); + while ($pse->getPromo() === $entry["promo_price"] = rand(0, 1000)); + + $data[$pse->getId()] = $entry; + + $jsonData[] = $entry; + } + + $jsonString = json_encode($jsonData); + + $this->assertEquals( + "Import successfully done, 3 row(s) have been changed", + $this->controller->processImport( + $jsonString, + $this->import, + new JsonFormatter(), + null + ) + ); + + $query = ProductSaleElementsQuery::create()->findPks(array_keys($data)); + + /** @var \Thelia\Model\ProductSaleElements $entry */ + foreach ($query as $entry) { + $this->assertEquals( + $data[$entry->getId()], + [ + "price" => $entry->getPricesByCurrency($currency)->getPrice(), + "promo_price" => $entry->getPricesByCurrency($currency)->getPromoPrice(), + "ref" => $entry->getRef() + ] + ); + } + } + +} diff --git a/core/lib/Thelia/Tests/ImportExport/Import/ProductStockImportTest.php b/core/lib/Thelia/Tests/ImportExport/Import/ProductStockImportTest.php new file mode 100644 index 000000000..dded4e914 --- /dev/null +++ b/core/lib/Thelia/Tests/ImportExport/Import/ProductStockImportTest.php @@ -0,0 +1,94 @@ + + */ +class ProductStockImportTest extends ControllerTestBase +{ + use ImportExportControllerTrait; + + /** + * @return \Thelia\Controller\BaseController The controller you want to test + */ + protected function getController() + { + return new ImportController(); + } + + public function setUp() + { + parent::setUp(); + + $this->import = new ProductStockImport($this->container); + } + + public function testUpdateStock() + { + $query = ProductSaleElementsQuery::create() + ->addAscendingOrderByColumn('RAND()') + ->limit(3) + ->find() + ; + + $jsonData = []; + $data = []; + + /** @var \Thelia\Model\ProductSaleElements $pse */ + foreach ($query as $pse) { + + $entry = []; + + $entry["ref"] = $pse->getRef(); + /** + * Be sure to get a different value. + */ + while ($pse->getQuantity() === $entry["stock"] = rand(0, 1000)); + + $data[$pse->getId()] = $entry["stock"]; + + $jsonData[] = $entry; + } + + $jsonString = json_encode($jsonData); + + $this->assertEquals( + "Import successfully done, 3 row(s) have been changed", + $this->controller->processImport( + $jsonString, + $this->import, + new JsonFormatter(), + null + ) + ); + + $query = ProductSaleElementsQuery::create()->findPks(array_keys($data)); + + /** @var \Thelia\Model\ProductSaleElements $entry */ + foreach ($query as $entry) { + $this->assertEquals( + $data[$entry->getId()], + $entry->getQuantity() + ); + } + } +} diff --git a/core/lib/Thelia/Tests/Tools/FakeFileDownloader.php b/core/lib/Thelia/Tests/Tools/FakeFileDownloader.php new file mode 100644 index 000000000..20f4d4682 --- /dev/null +++ b/core/lib/Thelia/Tests/Tools/FakeFileDownloader.php @@ -0,0 +1,41 @@ + + */ +class FakeFileDownloader extends FileDownloader +{ + /** + * @throws \Thelia\Exception\FileNotFoundException + * @throws \ErrorException + * @throws \HttpUrlException + * + * Downloads the file $url in $pathToStore + */ + public function download($url, $pathToStore) + { + if (!file_exists($url) || !is_readable($url)) { + throw new FileNotFoundException(); + } + + if (!copy($url, $pathToStore)) { + throw new \ErrorException(); + } + } +} diff --git a/core/lib/Thelia/Tests/Tools/FileDownloaderTest.php b/core/lib/Thelia/Tests/Tools/FileDownloaderTest.php new file mode 100644 index 000000000..e62840494 --- /dev/null +++ b/core/lib/Thelia/Tests/Tools/FileDownloaderTest.php @@ -0,0 +1,63 @@ + + */ +class FileDownloaderTest extends \PHPUnit_Framework_TestCase +{ + /** @var FileDownloader */ + protected $downloader; + + public function setUp() + { + $logger = Tlog::getNewInstance(); + $translator = new Translator( + new Container() + ); + + $this->downloader = new FileDownloader( + $logger, + $translator + ); + } + + /** + * @expectedException \Thelia\Exception\HttpUrlException + * @expectedExceptionMessage Tried to download a file, but the URL was not valid: foo + */ + public function testFileDownloadInvalidURL() + { + $this->downloader->download("foo", "bar"); + } + + /** + * @expectedException \Thelia\Exception\FileNotFoundException + */ + public function testFileDownloadNonExistingFile() + { + $this->downloader->download("https://github.com/foo/bar/baz", "baz"); + } + + public function testFileDownloadSuccess() + { + $this->downloader->download("https://github.com/thelia/thelia", "php://temp"); + } +} diff --git a/core/lib/Thelia/Tools/FileDownload/FileDownloader.php b/core/lib/Thelia/Tools/FileDownload/FileDownloader.php new file mode 100644 index 000000000..2f77226cf --- /dev/null +++ b/core/lib/Thelia/Tools/FileDownload/FileDownloader.php @@ -0,0 +1,143 @@ + + */ +class FileDownloader implements FileDownloaderInterface +{ + /** @var LoggerInterface */ + protected $logger; + + /** @var Translator */ + protected $translator; + + public function __construct(LoggerInterface $logger, Translator $translator) + { + $this->logger = $logger; + + $this->translator = $translator; + } + + public static function getInstance() + { + return new static(Tlog::getInstance(), TheliaTranslator::getInstance()); + } + + /** + * @param string $url + * @param string $pathToStore + * @throws \Thelia\Exception\FileNotFoundException + * @throws \ErrorException + * @throws \HttpUrlException + * + * Downloads the file $url in $pathToStore + */ + public function download($url, $pathToStore) + { + if (!URL::checkUrl($url)) { + /** + * The URL is not valid + */ + throw new HttpUrlException( + $this->translator->trans( + "Tried to download a file, but the URL was not valid: %url", + [ + "%url" => $url + ] + ) + ); + } + + /** + * Try to get the file if it is online + */ + $con = curl_init($url); + curl_setopt($con, CURLOPT_RETURNTRANSFER, true); + + $response = curl_exec($con); + $errno = curl_errno($con); + $curlErrorMessage = curl_error($con); + + $httpCode = curl_getinfo($con, CURLINFO_HTTP_CODE); + + curl_close($con); + + if (false === $response || $errno !== 0 || + ($httpCode != "200" && $httpCode != "204") + ) { + /** + * The server is down ? The file doesn't exist ? Anything else ? + */ + $errorMessage = $this->translator->trans( + "cURL errno %errno, http code %http_code on link \"%path\": %error", + [ + "%errno" => $errno, + "%path" => $url, + "%error" => $curlErrorMessage, + "%http_code" => $httpCode, + ] + ); + + $this->logger + ->error($errorMessage) + ; + + throw new FileNotFoundException($errorMessage); + } + + /** + * Inform that you've downloaded a file + */ + $this->logger + ->info( + $this->translator->trans( + "The file %path has been successfully downloaded", + [ + "%path" => $url + ] + ) + ) + ; + + /** + * Then try to write it on the disk + */ + $file = @fopen($pathToStore, "w"); + + if ($file === false) { + $translatedErrorMessage = $this->translator->trans( + "Failed to open a writing stream on the file: %file", + [ + "%file" => $pathToStore + ] + ); + + $this->logger->error($translatedErrorMessage); + throw new \ErrorException($translatedErrorMessage); + } + + fputs($file, $response); + fclose($file); + } +} diff --git a/core/lib/Thelia/Tools/FileDownload/FileDownloaderAwareTrait.php b/core/lib/Thelia/Tools/FileDownload/FileDownloaderAwareTrait.php new file mode 100644 index 000000000..78347bdd9 --- /dev/null +++ b/core/lib/Thelia/Tools/FileDownload/FileDownloaderAwareTrait.php @@ -0,0 +1,47 @@ + + */ +trait FileDownloaderAwareTrait +{ + /** @var FileDownloaderInterface */ + protected $fileDownloader; + + /** + * @return FileDownloaderInterface + */ + public function getFileDownloader() + { + if (!$this->fileDownloader instanceof FileDownloaderInterface) { + $this->fileDownloader = FileDownloader::getInstance(); + } + + return $this->fileDownloader; + } + + /** + * @param FileDownloaderInterface $fileDownloader + * @return $this + */ + public function setFileDownloader(FileDownloaderInterface $fileDownloader) + { + $this->fileDownloader = $fileDownloader; + + return $this; + } +} diff --git a/core/lib/Thelia/Tools/FileDownload/FileDownloaderInterface.php b/core/lib/Thelia/Tools/FileDownload/FileDownloaderInterface.php new file mode 100644 index 000000000..4c29daf29 --- /dev/null +++ b/core/lib/Thelia/Tools/FileDownload/FileDownloaderInterface.php @@ -0,0 +1,43 @@ + + */ +interface FileDownloaderInterface +{ + /** + * @param string $url + * @param string $pathToStore + * @throws \Thelia\Exception\FileNotFoundException + * @throws \ErrorException + * @throws \HttpUrlException + * + * Downloads the file $url in $pathToStore + */ + public function download($url, $pathToStore); + + public function __construct(LoggerInterface $logger, Translator $translator); + + /** + * @return $this + * + * Returns an hydrated instance + */ + public static function getInstance(); +} diff --git a/core/lib/Thelia/Tools/I18n.php b/core/lib/Thelia/Tools/I18n.php index 57bf92e0b..87acbefd4 100644 --- a/core/lib/Thelia/Tools/I18n.php +++ b/core/lib/Thelia/Tools/I18n.php @@ -12,6 +12,7 @@ namespace Thelia\Tools; +use Propel\Runtime\ActiveQuery\ModelCriteria; use Thelia\Model\Lang; /** @@ -27,6 +28,8 @@ use Thelia\Model\Lang; */ class I18n { + protected static $defaultLocale; + /** * Create a \DateTime from a date picker form input * The date format is the same as the one from the current User Session @@ -78,4 +81,61 @@ class I18n return $i18n; } + + public static function addI18nCondition( + ModelCriteria $query, + $i18nTableName, + $tableIdColumn, + $i18nIdColumn, + $localeColumn, + $locale + ) { + if (null === static::$defaultLocale) { + static::$defaultLocale = Lang::getDefaultLanguage()->getLocale(); + } + + $locale = static::real_escape($locale); + $defaultLocale = static::real_escape(static::$defaultLocale); + + $query + ->_and() + ->where( + "CASE WHEN ".$tableIdColumn." IN". + "(SELECT DISTINCT ".$i18nIdColumn." ". + "FROM `".$i18nTableName."` ". + "WHERE locale=$locale) ". + + "THEN ".$localeColumn." = $locale ". + "ELSE ".$localeColumn." = $defaultLocale ". + "END" + ) + ; + } + + /** + * @param $str + * @return string + * + * Really escapes a string for SQL query. + */ + public static function real_escape($str) + { + $str = trim($str, "\"'"); + + $return = "CONCAT("; + $len = strlen($str); + + for ($i = 0; $i < $len; ++$i) { + $return .= "CHAR(".ord($str[$i])."),"; + } + + if ($i > 0) { + $return = substr($return, 0, -1); + } else { + $return = "\"\""; + } + $return .= ")"; + + return $return; + } } diff --git a/core/lib/Thelia/Tools/URL.php b/core/lib/Thelia/Tools/URL.php index 65a03ed65..54ed6a42d 100644 --- a/core/lib/Thelia/Tools/URL.php +++ b/core/lib/Thelia/Tools/URL.php @@ -13,6 +13,7 @@ namespace Thelia\Tools; use Symfony\Component\Routing\RequestContext; +use Symfony\Component\Validator\Constraints\UrlValidator; use Thelia\Model\ConfigQuery; use Thelia\Rewriting\RewritingResolver; use Thelia\Rewriting\RewritingRetriever; @@ -170,12 +171,11 @@ class URL // url could contain anchor $pos = strrpos($base, '#'); - if($pos !== false) { + if ($pos !== false) { $anchor = substr($base, $pos); $base = substr($base, 0, $pos); } - $base = rtrim($base, "?&"); $sepChar = strstr($base, '?') === false ? '?' : '&'; @@ -313,4 +313,11 @@ class URL strtolower($clean) : $clean; } + + public static function checkUrl($url, array $protocols = ["http", "https"]) + { + $pattern = sprintf(UrlValidator::PATTERN, implode('|', $protocols)); + + return (bool) preg_match($pattern, $url); + } } diff --git a/local/config/schema.xml b/local/config/schema.xml index f65b90d57..74cbe189c 100644 --- a/local/config/schema.xml +++ b/local/config/schema.xml @@ -1512,4 +1512,74 @@ + + + + + + + + + + + + +
    + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/setup/thelia.sql b/setup/thelia.sql index 024809a76..38f5f61bf 100644 --- a/setup/thelia.sql +++ b/setup/thelia.sql @@ -1873,6 +1873,90 @@ CREATE TABLE `form_firewall` INDEX `idx_form_firewall_ip_address` (`ip_address`) ) ENGINE=InnoDB; +-- --------------------------------------------------------------------- +-- import_category +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `import_category`; + +CREATE TABLE `import_category` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `ref` VARCHAR(255) NOT NULL, + `position` INTEGER NOT NULL, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + UNIQUE INDEX `ref_UNIQUE` (`ref`) +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- export_category +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `export_category`; + +CREATE TABLE `export_category` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `ref` VARCHAR(255) NOT NULL, + `position` INTEGER NOT NULL, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + UNIQUE INDEX `ref_UNIQUE` (`ref`) +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- import +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `import`; + +CREATE TABLE `import` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `ref` VARCHAR(255) NOT NULL, + `import_category_id` INTEGER NOT NULL, + `position` INTEGER NOT NULL, + `handle_class` LONGTEXT NOT NULL, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + UNIQUE INDEX `ref_UNIQUE` (`ref`), + INDEX `idx_import_import_category_id` (`import_category_id`), + CONSTRAINT `fk_import_import_category_id` + FOREIGN KEY (`import_category_id`) + REFERENCES `import_category` (`id`) + ON UPDATE RESTRICT + ON DELETE CASCADE +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- export +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `export`; + +CREATE TABLE `export` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `ref` VARCHAR(255) NOT NULL, + `export_category_id` INTEGER NOT NULL, + `position` INTEGER NOT NULL, + `handle_class` LONGTEXT NOT NULL, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + UNIQUE INDEX `ref_UNIQUE` (`ref`), + INDEX `idx_export_export_category_id` (`export_category_id`), + CONSTRAINT `fk_export_export_category_id` + FOREIGN KEY (`export_category_id`) + REFERENCES `export_category` (`id`) + ON UPDATE RESTRICT + ON DELETE CASCADE +) ENGINE=InnoDB; + -- --------------------------------------------------------------------- -- category_i18n -- --------------------------------------------------------------------- @@ -2568,6 +2652,80 @@ CREATE TABLE `brand_image_i18n` ON DELETE CASCADE ) ENGINE=InnoDB; +-- --------------------------------------------------------------------- +-- import_category_i18n +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `import_category_i18n`; + +CREATE TABLE `import_category_i18n` +( + `id` INTEGER NOT NULL, + `locale` VARCHAR(5) DEFAULT 'en_US' NOT NULL, + `title` VARCHAR(255) NOT NULL, + PRIMARY KEY (`id`,`locale`), + CONSTRAINT `import_category_i18n_FK_1` + FOREIGN KEY (`id`) + REFERENCES `import_category` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- export_category_i18n +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `export_category_i18n`; + +CREATE TABLE `export_category_i18n` +( + `id` INTEGER NOT NULL, + `locale` VARCHAR(5) DEFAULT 'en_US' NOT NULL, + `title` VARCHAR(255) NOT NULL, + PRIMARY KEY (`id`,`locale`), + CONSTRAINT `export_category_i18n_FK_1` + FOREIGN KEY (`id`) + REFERENCES `export_category` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- import_i18n +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `import_i18n`; + +CREATE TABLE `import_i18n` +( + `id` INTEGER NOT NULL, + `locale` VARCHAR(5) DEFAULT 'en_US' NOT NULL, + `title` VARCHAR(255) NOT NULL, + `description` LONGTEXT, + PRIMARY KEY (`id`,`locale`), + CONSTRAINT `import_i18n_FK_1` + FOREIGN KEY (`id`) + REFERENCES `import` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- export_i18n +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `export_i18n`; + +CREATE TABLE `export_i18n` +( + `id` INTEGER NOT NULL, + `locale` VARCHAR(5) DEFAULT 'en_US' NOT NULL, + `title` VARCHAR(255) NOT NULL, + `description` LONGTEXT, + PRIMARY KEY (`id`,`locale`), + CONSTRAINT `export_i18n_FK_1` + FOREIGN KEY (`id`) + REFERENCES `export` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB; + -- --------------------------------------------------------------------- -- category_version -- --------------------------------------------------------------------- diff --git a/setup/update/2.0.3.sql b/setup/update/2.0.3.sql index 9a1095558..5b67a63d9 100644 --- a/setup/update/2.0.3.sql +++ b/setup/update/2.0.3.sql @@ -329,6 +329,91 @@ CREATE TABLE `form_firewall` INDEX `idx_form_firewall_ip_address` (`ip_address`) ) ENGINE=InnoDB; +-- --------------------------------------------------------------------- +-- import_category +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `import_category`; + +CREATE TABLE `import_category` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `ref` VARCHAR(255) NOT NULL, + `position` INTEGER NOT NULL, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + UNIQUE INDEX `ref_UNIQUE` (`ref`) +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- export_category +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `export_category`; + +CREATE TABLE `export_category` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `ref` VARCHAR(255) NOT NULL, + `position` INTEGER NOT NULL, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + UNIQUE INDEX `ref_UNIQUE` (`ref`) +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- import +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `import`; + +CREATE TABLE `import` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `ref` VARCHAR(255) NOT NULL, + `import_category_id` INTEGER NOT NULL, + `position` INTEGER NOT NULL, + `handle_class` LONGTEXT NOT NULL, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + UNIQUE INDEX `ref_UNIQUE` (`ref`), + INDEX `idx_import_import_category_id` (`import_category_id`), + CONSTRAINT `fk_import_import_category_id` + FOREIGN KEY (`import_category_id`) + REFERENCES `import_category` (`id`) + ON UPDATE RESTRICT + ON DELETE CASCADE +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- export +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `export`; + +CREATE TABLE `export` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `ref` VARCHAR(255) NOT NULL, + `export_category_id` INTEGER NOT NULL, + `position` INTEGER NOT NULL, + `handle_class` LONGTEXT NOT NULL, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + UNIQUE INDEX `ref_UNIQUE` (`ref`), + INDEX `idx_export_export_category_id` (`export_category_id`), + CONSTRAINT `fk_export_export_category_id` + FOREIGN KEY (`export_category_id`) + REFERENCES `export_category` (`id`) + ON UPDATE RESTRICT + ON DELETE CASCADE +) ENGINE=InnoDB; + + INSERT INTO `config`(`name`, `value`, `secured`, `hidden`, `created_at`, `updated_at`) VALUES ('form_firewall_bruteforce_time_to_wait', '10', 0, 0, NOW(), NOW()), diff --git a/templates/backOffice/default/ajax/export-modal.html b/templates/backOffice/default/ajax/export-modal.html new file mode 100644 index 000000000..efd0931e0 --- /dev/null +++ b/templates/backOffice/default/ajax/export-modal.html @@ -0,0 +1,126 @@ +{form name="thelia.export"} + + {form_hidden_fields form=$form} + + +{/form} \ No newline at end of file diff --git a/templates/backOffice/default/ajax/import-modal.html b/templates/backOffice/default/ajax/import-modal.html new file mode 100644 index 000000000..a22a8cd8d --- /dev/null +++ b/templates/backOffice/default/ajax/import-modal.html @@ -0,0 +1,55 @@ +{form name="thelia.import"} +
    + {form_hidden_fields form=$form} + +
    +{/form} \ No newline at end of file diff --git a/templates/backOffice/default/export-page.html b/templates/backOffice/default/export-page.html new file mode 100644 index 000000000..69417131a --- /dev/null +++ b/templates/backOffice/default/export-page.html @@ -0,0 +1,206 @@ +{extends file="admin-layout.tpl"} + +{block name="no-return-functions"} + {$admin_current_location = 'tools'} +{/block} + +{block name="page-title"}{intl l='Export'}: {$TITLE}{/block} + +{block name="check-resource"}admin.export{/block} +{block name="check-access"}view{/block} + +{block name="main-content"} +
    + + + + {form name="thelia.export"} + + {if $form_error} +
    +
    +
    {$form_error_message}
    +
    +
    + {/if} + +
    +
    +
    + +
    + {intl l='Export'}: {$TITLE} +
    + + {if $DESCRIPTION} +
    +
    +
    + {$DESCRIPTION nofilter} +
    +
    +
    + {/if} + +
    + {form_hidden_fields form=$form} +
    +
    + {ifloop rel="export-formatters"} +
    +
    + {form_field form=$form field="formatter"} +
    + + + {if $error} +
    {$message}
    + {/if} +
    + {/form_field} +
    +
    + {form_field form=$form field="language"} + + + {/form_field} +
    +
    + {form_field form=$form field="do_compress"} + +
    + +
    + {/form_field} +
    +
    +
    +
    + {form_field form=$form field="archive_builder"} +
    + + + + {if $error} +
    {$message}
    + {/if} +
    + {/form_field} +
    + {if $HAS_IMAGES} +
    + {form_field form=$form field="images"} + + +
    + +
    + {/form_field} +
    + {/if} + {if $HAS_DOCUMENTS} +
    + {form_field form=$form field="documents"} + + +
    + +
    + {/form_field} +
    + {/if} +
    + {/ifloop} + {elseloop rel="export-formatters"} +
    +
    +
    + {intl l="You can't do exports, you don't have any formatter that handles this."} +
    +
    +
    + {/elseloop} +
    +
    + + +
    +
    +
    +
    +
    + + {/form} +{/block} + +{block name="javascript-initialization"} + {javascripts file='assets/js/bootstrap-switch/bootstrap-switch.js'} + + {/javascripts} +{/block} + +{block name="javascript-last-call"} + + {module_include location='configuration-js'} +{/block} \ No newline at end of file diff --git a/templates/backOffice/default/export.html b/templates/backOffice/default/export.html index 7bc7efd2e..47bc6c0f8 100644 --- a/templates/backOffice/default/export.html +++ b/templates/backOffice/default/export.html @@ -10,6 +10,15 @@ {block name="check-access"}view{/block} {block name="main-content"} + {if $category_order != "manual"} + {assign url_category "category_order="|cat:$category_order} + {/if} + {if $export_order != "manual"} + {assign url_export "export_order="|cat:$export_order} + {/if} + +
    +
    @@ -24,35 +33,211 @@ {module_include location='tools_top'} -
    - -
    - + {/loop} + + {elseloop rel="export-category"} +
    + {intl l="You don't have any export"} +
    + {/elseloop} + + {module_include location='configuration_bottom'}
    {/block} +{block name="javascript-initialization"} + {javascripts file='assets/js/bootstrap-switch/bootstrap-switch.js'} + + {/javascripts} + + {javascripts file='assets/js/bootstrap-editable/bootstrap-editable.js'} + + {/javascripts} + +{/block} + {block name="javascript-last-call"} + {module_include location='configuration-js'} {/block} \ No newline at end of file diff --git a/templates/backOffice/default/import-page.html b/templates/backOffice/default/import-page.html new file mode 100644 index 000000000..381a932d3 --- /dev/null +++ b/templates/backOffice/default/import-page.html @@ -0,0 +1,96 @@ +{extends file="admin-layout.tpl"} + +{block name="no-return-functions"} + {$admin_current_location = 'tools'} +{/block} + +{block name="page-title"}{intl l='Import'}: {$TITLE}{/block} + +{block name="check-resource"}admin.import{/block} +{block name="check-access"}view{/block} + +{block name="main-content"} +
    + + + + {form name="thelia.import"} + {if $form_error} +
    +
    +
    {$form_error_message}
    +
    +
    + {/if} + + {if $success_message} +
    +
    +
    {$success_message}
    +
    +
    + {/if} + +
    +
    +
    + +
    + {intl l='Import'}: {$TITLE} +
    + + {if $DESCRIPTION} +
    +
    +
    + {$DESCRIPTION nofilter} +
    +
    +
    + {/if} +
    + {form_hidden_fields form=$form} +
    +
    + {form_field form=$form field="language"} + + + {/form_field} +
    +
    +
    +
    + {form_field form=$form field="file_upload"} + + + +
    Accepted formats: {$ALLOWED_EXTENSIONS}
    + {/form_field} +
    +
    + +
    +
    +
    +
    + {/form} +{/block} + +{block name="javascript-last-call"} + {module_include location='configuration-js'} +{/block} \ No newline at end of file diff --git a/templates/backOffice/default/import.html b/templates/backOffice/default/import.html new file mode 100644 index 000000000..ac455134f --- /dev/null +++ b/templates/backOffice/default/import.html @@ -0,0 +1,146 @@ +{extends file="admin-layout.tpl"} + +{block name="no-return-functions"} + {$admin_current_location = 'tools'} +{/block} + +{block name="page-title"}{intl l='Imports'}{/block} + +{block name="check-resource"}admin.import{/block} +{block name="check-access"}view{/block} + +{block name="main-content"} + {if $category_order != "manual"} + {assign url_category "category_order="|cat:$category_order} + {/if} + {if $import_order != "manual"} + {assign url_import "import_order="|cat:$import_order} + {/if} + +
    + +
    + +
    + + + + {module_include location='tools_top'} + + {loop name="import-category" type="import-category" order=$category_order} + {assign category_title $TITLE} +
    +
    +
    +
    + + + + + + + + + + + + {loop name="import-categ-list" type="import" order=$import_order category=$ID} + + + + + + + {/loop} + +
    + + + + {$POSITION} + + + + {$TITLE} +
    + + {intl l="ID"} + + + + {intl l="Name"} + + + + {intl l="Position"} + + + {intl l="Actions"} +
    + {$ID} + + {$TITLE} + + + + + {$POSITION} + + + + +
    + + + +
    +
    +
    +
    +
    + +
    + {/loop} + + {elseloop rel="import-category"} +
    + {intl l="You don't have any import"} +
    + {/elseloop} + + {module_include location='configuration_bottom'} +
    +
    +{/block} + +{block name="javascript-last-call"} + + {module_include location='configuration-js'} +{/block} \ No newline at end of file diff --git a/templates/backOffice/default/includes/export-form-definition.html b/templates/backOffice/default/includes/export-form-definition.html new file mode 100644 index 000000000..e69de29bb diff --git a/templates/backOffice/default/tools.html b/templates/backOffice/default/tools.html index 99a90b330..216643c44 100644 --- a/templates/backOffice/default/tools.html +++ b/templates/backOffice/default/tools.html @@ -54,6 +54,12 @@ {/loop} + {loop name="auth-import" type="auth" role="ADMIN" resource="admin.import" access="VIEW"} + + {intl l="Import"} + + + {/loop} {module_include location='tools_col1_bottom'}