From dc6b231301902069f6b9303e9e3b1fe534976234 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 19 Jun 2014 15:10:21 +0200 Subject: [PATCH 01/64] Fixed coupon table versionning --- local/config/schema.xml | 154 ++++------------------------------------ setup/update/2.0.3.sql | 4 ++ 2 files changed, 19 insertions(+), 139 deletions(-) diff --git a/local/config/schema.xml b/local/config/schema.xml index 5f86bb9e8..9539cca25 100644 --- a/local/config/schema.xml +++ b/local/config/schema.xml @@ -1,11 +1,6 @@ - - + - - - - - +
@@ -38,7 +33,7 @@ - + @@ -110,9 +105,6 @@ - - - @@ -162,11 +154,6 @@ - - - - -
@@ -226,11 +213,6 @@ - - - - -
@@ -250,10 +232,6 @@ - - - -
@@ -330,11 +308,6 @@ - - - - -
@@ -376,7 +349,7 @@
- + @@ -392,12 +365,12 @@ - - - + + +
@@ -462,9 +435,6 @@ - - -
@@ -523,10 +493,6 @@ - - - - @@ -554,7 +520,7 @@
- + @@ -635,12 +601,6 @@ - - - - - - @@ -736,9 +696,6 @@ - - - @@ -920,7 +877,6 @@ - @@ -952,7 +908,10 @@ - + + + +
@@ -1088,10 +1047,6 @@ - - - - @@ -1112,10 +1067,6 @@ - - - - @@ -1136,10 +1087,6 @@ - - - - @@ -1256,6 +1203,9 @@ + + + @@ -1296,10 +1246,6 @@ - - - - @@ -1345,7 +1291,6 @@ - @@ -1354,73 +1299,4 @@
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - -
- - - - - - - - - - - - - - - - -
diff --git a/setup/update/2.0.3.sql b/setup/update/2.0.3.sql index 7c94478b1..cde550b0e 100644 --- a/setup/update/2.0.3.sql +++ b/setup/update/2.0.3.sql @@ -45,4 +45,8 @@ CREATE TABLE `order_version` ON DELETE CASCADE ) ENGINE=InnoDB CHARACTER SET='utf8'; +# Add missing columns to coupon (version_created_at, version_created_by) +ALTER TABLE `order` ADD `version_created_at` DATE AFTER `version`; +ALTER TABLE `order` ADD `version_created_by` VARCHAR(100) AFTER `version_created_at`; + SET FOREIGN_KEY_CHECKS = 1; \ No newline at end of file From 9cb145e644dd1dd4dc8c5c67cb6a9107d9762772 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 19 Jun 2014 17:56:01 +0200 Subject: [PATCH 02/64] Fix for #490 --- .../Plugins/outputfilter.trimwhitespace.php | 75 +++++++++++++++++++ .../Core/Template/Smarty/SmartyParser.php | 7 +- 2 files changed, 76 insertions(+), 6 deletions(-) create mode 100644 core/lib/Thelia/Core/Template/Smarty/Plugins/outputfilter.trimwhitespace.php diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/outputfilter.trimwhitespace.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/outputfilter.trimwhitespace.php new file mode 100644 index 000000000..000fea9ab --- /dev/null +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/outputfilter.trimwhitespace.php @@ -0,0 +1,75 @@ + + * Type: outputfilter
+ * Name: trimwhitespace
+ * Date: Jan 25, 2003
+ * Purpose: trim leading white space and blank lines from + * template source after it gets interpreted, cleaning + * up code and saving bandwidth. Does not affect + * <
>
and blocks.
+ * Install: Drop into the plugin directory, call + * $smarty->load_filter('output','trimwhitespace'); + * from application. + * @author Monte Ohrt + * @author Contributions from Lars Noschinski + * @version 1.3 + * @param string + * @param Smarty + */ +function smarty_outputfilter_trimwhitespace($source, &$smarty) +{ + // Pull out the script blocks + preg_match_all("!]*?>.*?!is", $source, $match); + $_script_blocks = $match[0]; + $source = preg_replace("!]*?>.*?!is", + '@@@SMARTY:TRIM:SCRIPT@@@', $source); + + // Pull out the pre blocks + preg_match_all("!]*?>.*?!is", $source, $match); + $_pre_blocks = $match[0]; + $source = preg_replace("!]*?>.*?!is", + '@@@SMARTY:TRIM:PRE@@@', $source); + + // Pull out the textarea blocks + preg_match_all("!]*?>.*?!is", $source, $match); + $_textarea_blocks = $match[0]; + $source = preg_replace("!]*?>.*?!is", + '@@@SMARTY:TRIM:TEXTAREA@@@', $source); + + // remove all leading spaces, tabs and carriage returns NOT + // preceeded by a php close tag. + $source = trim(preg_replace('/((?)\n)[\s]+/m', '\1', $source)); + + // replace textarea blocks + smarty_outputfilter_trimwhitespace_replace("@@@SMARTY:TRIM:TEXTAREA@@@",$_textarea_blocks, $source); + + // replace pre blocks + smarty_outputfilter_trimwhitespace_replace("@@@SMARTY:TRIM:PRE@@@",$_pre_blocks, $source); + + // replace script blocks + smarty_outputfilter_trimwhitespace_replace("@@@SMARTY:TRIM:SCRIPT@@@",$_script_blocks, $source); + + return $source; +} + +function smarty_outputfilter_trimwhitespace_replace($search_str, $replace, &$subject) { + $_len = strlen($search_str); + $_pos = 0; + for ($_i=0, $_count=count($replace); $_i<$_count; $_i++) + if (($_pos=strpos($subject, $search_str, $_pos))!==false) + $subject = substr_replace($subject, $replace[$_i], $_pos, $_len); + else + break; + +} + +?> \ No newline at end of file diff --git a/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php b/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php index bcc915018..807ef2438 100644 --- a/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php +++ b/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php @@ -95,7 +95,7 @@ class SmartyParser extends Smarty implements ParserInterface // The default HTTP status $this->status = 200; - $this->registerFilter('output', array($this, "removeBlankLines")); + $this->loadFilter('output', "trimwhitespace"); $this->registerFilter('variable', array(__CLASS__, "theliaEscape")); } @@ -139,11 +139,6 @@ class SmartyParser extends Smarty implements ParserInterface return $this->templateDirectories[$templateType]; } - public function removeBlankLines($tpl_source, \Smarty_Internal_Template $template) - { - return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $tpl_source); - } - public static function theliaEscape($content, $smarty) { if (is_scalar($content)) { From b49f8a642385ee65a9ad2fd6865184301445f284 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Sat, 21 Jun 2014 12:00:37 +0200 Subject: [PATCH 03/64] Fixes #495 --- templates/frontOffice/default/password.html | 87 +++++++++++---------- 1 file changed, 44 insertions(+), 43 deletions(-) diff --git a/templates/frontOffice/default/password.html b/templates/frontOffice/default/password.html index 65aa7408d..065655517 100644 --- a/templates/frontOffice/default/password.html +++ b/templates/frontOffice/default/password.html @@ -1,43 +1,44 @@ -{extends file="layout.tpl"} - -{* Body Class *} -{block name="body-class"}page-password{/block} - -{* Breadcrumb *} -{block name='no-return-functions' append} - {$breadcrumbs = [ - ['title' => {intl l="Password"}, 'url'=>{url path="/password"}] - ]} -{/block} - - -{block name="main-content"} -
-
-

{intl l="Password Forgotten"}

- {form name="thelia.front.customer.lostpassword"} -
- {form_hidden_fields form=$form} -

{intl l="Please enter your email address below."} {intl l="You will receive a link to reset your password."}

- {form_field form=$form field="email"} -
- -
- - {if $error} - {$message} - {elseif !$error && $value != ""} - {intl l="You will receive a link to reset your password."} - {/if} -
-
- {/form_field} -
- {intl l="Cancel"} - -
-
- {/form} -
-
-{/block} +{extends file="layout.tpl"} + +{* Body Class *} +{block name="body-class"}page-password{/block} + +{* Breadcrumb *} +{block name='no-return-functions' append} + {$breadcrumbs = [ + ['title' => {intl l="Password"}, 'url'=>{url path="/password"}] + ]} +{/block} + + +{block name="main-content"} +
+
+

{intl l="Password Forgotten"}

+ {form name="thelia.front.customer.lostpassword"} +
+ {form_hidden_fields form=$form} +

{intl l="Please enter your email address below."} {intl l="You will receive a link to reset your password."}

+ {if $form_error}
{$form_error_message}
{/if} + {form_field form=$form field="email"} +
+ +
+ + {if $error} + {$message} + {elseif !$error && $value != ""} + {intl l="You will receive a link to reset your password."} + {/if} +
+
+ {/form_field} +
+ {intl l="Cancel"} + +
+
+ {/form} +
+
+{/block} From 114a55c1e8d1a86a024e53acae74d1d7d7df1902 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 26 Jun 2014 10:36:12 +0200 Subject: [PATCH 04/64] Refactoring of images and documents management --- core/lib/Thelia/Action/BaseCachedFile.php | 34 +- core/lib/Thelia/Action/Document.php | 30 +- core/lib/Thelia/Action/Image.php | 38 +- core/lib/Thelia/Config/Resources/config.xml | 31 + .../Controller/Admin/BaseAdminController.php | 10 +- .../Controller/Admin/FileController.php | 430 +++++---- .../Document/DocumentCreateOrUpdateEvent.php | 43 +- .../Event/Document/DocumentDeleteEvent.php | 44 +- .../Event/Image/ImageCreateOrUpdateEvent.php | 45 +- .../Core/Event/Image/ImageDeleteEvent.php | 42 +- .../Plugins/outputfilter.trimwhitespace.php | 5 +- core/lib/Thelia/Exception/FileException.php | 25 + core/lib/Thelia/Files/FileManager.php | 265 ++++++ core/lib/Thelia/Files/FileModelInterface.php | 113 +++ .../Thelia/Files/FileModelParentInterface.php | 21 + .../Form/Image/DocumentModification.php | 121 ++- .../Thelia/Form/Image/ImageModification.php | 120 ++- core/lib/Thelia/Model/CategoryImage.php | 88 +- core/lib/Thelia/Model/Content.php | 12 +- core/lib/Thelia/Model/ContentDocument.php | 88 +- core/lib/Thelia/Model/ContentImage.php | 88 +- core/lib/Thelia/Model/Folder.php | 3 +- core/lib/Thelia/Model/FolderDocument.php | 84 +- core/lib/Thelia/Model/FolderImage.php | 86 +- core/lib/Thelia/Model/OrderVersionQuery.php | 1 - core/lib/Thelia/Model/Product.php | 3 +- core/lib/Thelia/Model/ProductDocument.php | 87 +- core/lib/Thelia/Model/ProductImage.php | 88 +- .../Thelia/Tests/Files/FileManagerTest.php | 398 ++++++++ core/lib/Thelia/Tests/Files/fixtures/test.gif | Bin 0 -> 35 bytes core/lib/Thelia/Tests/Files/fixtures/test.txt | Bin 0 -> 35 bytes .../Thelia/Tests/Tools/FileManagerTest.php | 901 ------------------ core/lib/Thelia/Tools/FileManager.php | 667 ------------- 33 files changed, 1795 insertions(+), 2216 deletions(-) create mode 100644 core/lib/Thelia/Exception/FileException.php create mode 100644 core/lib/Thelia/Files/FileManager.php create mode 100644 core/lib/Thelia/Files/FileModelInterface.php create mode 100644 core/lib/Thelia/Files/FileModelParentInterface.php create mode 100644 core/lib/Thelia/Tests/Files/FileManagerTest.php create mode 100644 core/lib/Thelia/Tests/Files/fixtures/test.gif create mode 100644 core/lib/Thelia/Tests/Files/fixtures/test.txt delete mode 100644 core/lib/Thelia/Tests/Tools/FileManagerTest.php delete mode 100644 core/lib/Thelia/Tools/FileManager.php diff --git a/core/lib/Thelia/Action/BaseCachedFile.php b/core/lib/Thelia/Action/BaseCachedFile.php index ce70eed47..505615c97 100644 --- a/core/lib/Thelia/Action/BaseCachedFile.php +++ b/core/lib/Thelia/Action/BaseCachedFile.php @@ -12,6 +12,7 @@ namespace Thelia\Action; use Thelia\Core\Event\CachedFileEvent; +use Thelia\Files\FileManager; use Thelia\Tools\URL; /** @@ -32,6 +33,16 @@ use Thelia\Tools\URL; */ abstract class BaseCachedFile extends BaseAction { + /** + * @var FileManager + */ + protected $fileManager; + + public function __construct(FileManager $fileManager) + { + $this->fileManager = $fileManager; + } + /** * @return string root of the file cache directory in web space */ @@ -60,6 +71,7 @@ abstract class BaseCachedFile extends BaseAction { $iterator = new \DirectoryIterator($path); + /** @var \DirectoryIterator $fileinfo */ foreach ($iterator as $fileinfo) { if ($fileinfo->isDot()) continue; @@ -75,8 +87,8 @@ abstract class BaseCachedFile extends BaseAction /** * Return the absolute URL to the cached file * - * @param string $subdir the subdirectory related to cache base - * @param string $filename the safe filename, as returned by getCacheFilePath() + * @param string $subdir the subdirectory related to cache base + * @param string $safe_filename the safe filename, as returned by getCacheFilePath() * @return string the absolute URL to the cached file */ protected function getCacheFileURL($subdir, $safe_filename) @@ -89,10 +101,10 @@ abstract class BaseCachedFile extends BaseAction /** * Return the full path of the cached file * - * @param string $subdir the subdirectory related to cache base - * @param string $filename the filename - * @param string $hashed_options a hash of transformation options, or null if no transformations have been applied - * @param boolean $forceOriginalDocument if true, the original file path in the cache dir is returned. + * @param string $subdir the subdirectory related to cache base + * @param string $filename the filename + * @param boolean $forceOriginalFile if true, the original file path in the cache dir is returned. + * @param string $hashed_options a hash of transformation options, or null if no transformations have been applied * @return string the cache directory path relative to Web Root */ protected function getCacheFilePath($subdir, $filename, $forceOriginalFile = false, $hashed_options = null) @@ -132,9 +144,13 @@ abstract class BaseCachedFile extends BaseAction /** * Return the absolute cache directory path * - * @param string $subdir the subdirectory related to cache base, or null to get the cache base directory. - * @throws \RuntimeException if cache directory cannot be created - * @return string the absolute cache directory path + * @param string $subdir the subdirectory related to cache base, or null to get the cache base directory. + * @param bool $create_if_not_exists create the directory if it is not found + * + * @throws \RuntimeException if cache directory cannot be created + * @throws \InvalidArgumentException ii path is invalid, e.g. not in the cache dir + * + * @return string the absolute cache directory path */ protected function getCachePath($subdir = null, $create_if_not_exists = true) { diff --git a/core/lib/Thelia/Action/Document.php b/core/lib/Thelia/Action/Document.php index b41ea920c..ef3f17bf2 100644 --- a/core/lib/Thelia/Action/Document.php +++ b/core/lib/Thelia/Action/Document.php @@ -12,19 +12,16 @@ namespace Thelia\Action; use Symfony\Component\EventDispatcher\EventSubscriberInterface; - use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent; use Thelia\Core\Event\Document\DocumentDeleteEvent; use Thelia\Core\Event\Document\DocumentEvent; +use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\UpdateFilePositionEvent; +use Thelia\Exception\DocumentException; use Thelia\Exception\ImageException; use Thelia\Model\ConfigQuery; -use Thelia\Tools\FileManager; use Thelia\Tools\URL; -use Thelia\Exception\DocumentException; -use Thelia\Core\Event\TheliaEvents; - /** * * Document management actions. This class handles document processing an caching. @@ -71,7 +68,7 @@ class Document extends BaseCachedFile implements EventSubscriberInterface */ public function processDocument(DocumentEvent $event) { - $subdir = $event->getCacheSubdirectory(); + $subdir = $event->getCacheSubdirectory(); $sourceFile = $event->getSourceFilepath(); if (null == $subdir || null == $sourceFile) { @@ -118,7 +115,6 @@ class Document extends BaseCachedFile implements EventSubscriberInterface */ public function saveDocument(DocumentCreateOrUpdateEvent $event) { - $fileManager = new FileManager(); $model = $event->getModelDocument(); $nbModifiedLines = $model->save(); @@ -128,15 +124,15 @@ class Document extends BaseCachedFile implements EventSubscriberInterface if (!$nbModifiedLines) { throw new ImageException( sprintf( - 'Document "%s" with parent id %s (%s) failed to be saved', + 'Document "%s" with parent id %s failed to be saved', $event->getParentName(), - $event->getParentId(), - $event->getDocumentType() + $event->getParentId() ) ); } - $newUploadedFile = $fileManager->copyUploadedFile($event->getParentId(), $event->getDocumentType(), $event->getModelDocument(), $event->getUploadedFile(), FileManager::FILE_TYPE_DOCUMENTS); + $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelDocument(), $event->getUploadedFile()); + $event->setUploadedFile($newUploadedFile); } @@ -154,14 +150,15 @@ class Document extends BaseCachedFile implements EventSubscriberInterface $event->getModelDocument()->setTitle($event->getUploadedFile()->getClientOriginalName()); } - $fileManager = new FileManager(); // Copy and save file if ($event->getUploadedFile()) { // Remove old picture file from file storage - $url = $fileManager->getUploadDir($event->getDocumentType(), FileManager::FILE_TYPE_DOCUMENTS) . '/' . $event->getOldModelDocument()->getFile(); + $url = $event->getModelDocument()->getUploadDir() . '/' . $event->getOldModelDocument()->getFile(); + unlink(str_replace('..', '', $url)); - $newUploadedFile = $fileManager->copyUploadedFile($event->getParentId(), $event->getDocumentType(), $event->getModelDocument(), $event->getUploadedFile(), FileManager::FILE_TYPE_DOCUMENTS); + $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelDocument(), $event->getUploadedFile()); + $event->setUploadedFile($newUploadedFile); } @@ -181,13 +178,10 @@ class Document extends BaseCachedFile implements EventSubscriberInterface * @param \Thelia\Core\Event\Document\DocumentDeleteEvent $event Image event * * @throws \Exception - * @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action */ public function deleteDocument(DocumentDeleteEvent $event) { - $fileManager = new FileManager(); - - $fileManager->deleteFile($event->getDocumentToDelete(), $event->getDocumentType(), FileManager::FILE_TYPE_DOCUMENTS); + $this->fileManager->deleteFile($event->getDocumentToDelete()); } public static function getSubscribedEvents() diff --git a/core/lib/Thelia/Action/Image.php b/core/lib/Thelia/Action/Image.php index ef76254bf..2f38775bc 100644 --- a/core/lib/Thelia/Action/Image.php +++ b/core/lib/Thelia/Action/Image.php @@ -12,23 +12,20 @@ namespace Thelia\Action; +use Imagine\Image\Box; +use Imagine\Image\Color; +use Imagine\Image\ImageInterface; +use Imagine\Image\ImagineInterface; +use Imagine\Image\Point; use Symfony\Component\EventDispatcher\EventSubscriberInterface; - use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent; use Thelia\Core\Event\Image\ImageDeleteEvent; use Thelia\Core\Event\Image\ImageEvent; -use Thelia\Core\Event\UpdateFilePositionEvent; -use Thelia\Model\ConfigQuery; -use Thelia\Tools\FileManager; -use Thelia\Tools\URL; - -use Imagine\Image\ImagineInterface; -use Imagine\Image\ImageInterface; -use Imagine\Image\Box; -use Imagine\Image\Color; -use Imagine\Image\Point; -use Thelia\Exception\ImageException; use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\Event\UpdateFilePositionEvent; +use Thelia\Exception\ImageException; +use Thelia\Model\ConfigQuery; +use Thelia\Tools\URL; /** * @@ -242,7 +239,6 @@ class Image extends BaseCachedFile implements EventSubscriberInterface */ public function saveImage(ImageCreateOrUpdateEvent $event) { - $fileManager = new FileManager(); $model = $event->getModelImage(); $nbModifiedLines = $model->save(); @@ -251,15 +247,14 @@ class Image extends BaseCachedFile implements EventSubscriberInterface if (!$nbModifiedLines) { throw new ImageException( sprintf( - 'Image "%s" with parent id %s (%s) failed to be saved', + 'Image "%s" with parent id %s failed to be saved', $event->getParentName(), - $event->getParentId(), - $event->getImageType() + $event->getParentId() ) ); } - $newUploadedFile = $fileManager->copyUploadedFile($event->getParentId(), $event->getImageType(), $event->getModelImage(), $event->getUploadedFile(), FileManager::FILE_TYPE_IMAGES); + $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelImage(), $event->getUploadedFile()); $event->setUploadedFile($newUploadedFile); } @@ -273,14 +268,13 @@ class Image extends BaseCachedFile implements EventSubscriberInterface */ public function updateImage(ImageCreateOrUpdateEvent $event) { - $fileManager = new FileManager(); // Copy and save file if ($event->getUploadedFile()) { // Remove old picture file from file storage - $url = $fileManager->getUploadDir($event->getImageType(), FileManager::FILE_TYPE_IMAGES) . '/' . $event->getOldModelImage()->getFile(); + $url = $event->getModelImage()->getUploadDir() . '/' . $event->getOldModelImage()->getFile(); unlink(str_replace('..', '', $url)); - $newUploadedFile = $fileManager->copyUploadedFile($event->getParentId(), $event->getImageType(), $event->getModelImage(), $event->getUploadedFile(), FileManager::FILE_TYPE_IMAGES); + $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelImage(), $event->getUploadedFile()); $event->setUploadedFile($newUploadedFile); } @@ -304,9 +298,7 @@ class Image extends BaseCachedFile implements EventSubscriberInterface */ public function deleteImage(ImageDeleteEvent $event) { - $fileManager = new FileManager(); - - $fileManager->deleteFile($event->getImageToDelete(), $event->getImageType(), FileManager::FILE_TYPE_IMAGES); + $this->fileManager->deleteFile($event->getImageToDelete()); } /** diff --git a/core/lib/Thelia/Config/Resources/config.xml b/core/lib/Thelia/Config/Resources/config.xml index 5e4e30140..81ffc3333 100644 --- a/core/lib/Thelia/Config/Resources/config.xml +++ b/core/lib/Thelia/Config/Resources/config.xml @@ -9,8 +9,34 @@ Symfony\Component\HttpKernel\EventListener\EsiListener Symfony\Component\HttpKernel\Fragment\EsiFragmentRenderer Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer + + + + + Thelia\Model\ProductDocument + Thelia\Model\ProductImage + + Thelia\Model\CategoryDocument + Thelia\Model\CategoryImage + + Thelia\Model\ContentDocument + Thelia\Model\ContentImage + + Thelia\Model\FolderDocument + Thelia\Model\FolderImage + + Thelia\Model\BrandDocument + Thelia\Model\BrandImage + + + @@ -80,6 +106,11 @@ %kernel.debug% + + + %file_model.classes% + + diff --git a/core/lib/Thelia/Controller/Admin/BaseAdminController.php b/core/lib/Thelia/Controller/Admin/BaseAdminController.php index 27bf724cc..d6bb0b51f 100644 --- a/core/lib/Thelia/Controller/Admin/BaseAdminController.php +++ b/core/lib/Thelia/Controller/Admin/BaseAdminController.php @@ -329,12 +329,12 @@ class BaseAdminController extends BaseController * Return the current list order identifier for a given object name, * updating in using the current request. * - * @param unknown $objectName the object name (e.g. 'attribute', 'message') - * @param unknown $requestParameterName the name of the request parameter that defines the list order - * @param unknown $defaultListOrder the default order to use, if none is defined - * @param string $updateSession if true, the session will be updated with the current order. + * @param string $objectName the object name (e.g. 'attribute', 'message') + * @param string $requestParameterName the name of the request parameter that defines the list order + * @param string $defaultListOrder the default order to use, if none is defined + * @param bool $updateSession if true, the session will be updated with the current order. * - * @return String the current liste order. + * @return String the current list order. */ protected function getListOrderFromSession($objectName, $requestParameterName, $defaultListOrder, $updateSession = true) { diff --git a/core/lib/Thelia/Controller/Admin/FileController.php b/core/lib/Thelia/Controller/Admin/FileController.php index 3b8bd0507..eb493aa13 100644 --- a/core/lib/Thelia/Controller/Admin/FileController.php +++ b/core/lib/Thelia/Controller/Admin/FileController.php @@ -14,27 +14,20 @@ namespace Thelia\Controller\Admin; use Propel\Runtime\Exception\PropelException; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Thelia\Core\Event\UpdateFilePositionEvent; -use Thelia\Core\HttpFoundation\Response; -use Thelia\Core\Security\Resource\AdminResources; use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent; use Thelia\Core\Event\Document\DocumentDeleteEvent; use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent; use Thelia\Core\Event\Image\ImageDeleteEvent; use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\Event\UpdateFilePositionEvent; +use Thelia\Core\HttpFoundation\Response; use Thelia\Core\Security\AccessManager; +use Thelia\Core\Security\Resource\AdminResources; +use Thelia\Files\FileManager; +use Thelia\Files\FileModelInterface; use Thelia\Form\Exception\FormValidationException; use Thelia\Log\Tlog; -use Thelia\Model\CategoryDocument; -use Thelia\Model\CategoryImage; -use Thelia\Model\ContentDocument; -use Thelia\Model\ContentImage; -use Thelia\Model\FolderDocument; -use Thelia\Model\FolderImage; use Thelia\Model\Lang; -use Thelia\Model\ProductDocument; -use Thelia\Model\ProductImage; -use Thelia\Tools\FileManager; use Thelia\Tools\Rest\ResponseRest; use Thelia\Tools\URL; @@ -52,6 +45,15 @@ use Thelia\Tools\URL; */ class FileController extends BaseAdminController { + /** + * Get the FileManager + * + * @return FileManager + */ + public function getFileManager() + { + return $this->container->get('thelia.file_manager'); + } /** * Manage how a image collection has to be saved @@ -66,78 +68,81 @@ class FileController extends BaseAdminController $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkXmlHttpRequest(); - if ($this->isParentTypeValid($parentType)) { - if ($this->getRequest()->isMethod('POST')) { + if ($this->getRequest()->isMethod('POST')) { - /** @var UploadedFile $fileBeingUploaded */ - $fileBeingUploaded = $this->getRequest()->files->get('file'); + /** @var UploadedFile $fileBeingUploaded */ + $fileBeingUploaded = $this->getRequest()->files->get('file'); - $fileManager = new FileManager(); + $fileManager = $this->getFileManager(); - // Validate if file is too big - if ($fileBeingUploaded->getError() == 1) { - $message = $this->getTranslator() + // Validate if file is too big + if ($fileBeingUploaded->getError() == 1) { + $message = $this->getTranslator() + ->trans( + 'File is too heavy, please retry with a file having a size less than %size%.', + array('%size%' => ini_get('upload_max_filesize')), + 'core' + ); + + return new ResponseRest($message, 'text', 403); + } + // Validate if it is a image or file + if (!$fileManager->isImage($fileBeingUploaded->getMimeType())) { + $message = $this->getTranslator() ->trans( - 'File is too heavy, please retry with a file having a size less than %size%.', - array('%size%' => ini_get('upload_max_filesize')), - 'core' + 'You can only upload images (.png, .jpg, .jpeg, .gif)', + array(), + 'image' ); - return new ResponseRest($message, 'text', 403); - } - // Validate if it is a image or file - if (!$fileManager->isImage($fileBeingUploaded->getMimeType())) { - $message = $this->getTranslator() - ->trans( - 'You can only upload images (.png, .jpg, .jpeg, .gif)', - array(), - 'image' - ); - - return new ResponseRest($message, 'text', 415); - } - - $parentModel = $fileManager->getParentFileModel($parentType, $parentId); - $imageModel = $fileManager->getImageModel($parentType); - - if ($parentModel === null || $imageModel === null || $fileBeingUploaded === null) { - return new Response('', 404); - } - - $defaultTitle = $parentModel->getTitle(); - $imageModel->setParentId($parentId); - $imageModel->setTitle($defaultTitle); - - $imageCreateOrUpdateEvent = new ImageCreateOrUpdateEvent( - $parentType, - $parentId - ); - $imageCreateOrUpdateEvent->setModelImage($imageModel); - $imageCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded); - $imageCreateOrUpdateEvent->setParentName($parentModel->getTitle()); - - // Dispatch Event to the Action - $this->dispatch( - TheliaEvents::IMAGE_SAVE, - $imageCreateOrUpdateEvent - ); - - $this->adminLogAppend( - AdminResources::retrieve($parentType), - AccessManager::UPDATE, - $this->container->get('thelia.translator')->trans( - 'Saving images for %parentName% parent id %parentId% (%parentType%)', - array( - '%parentName%' => $imageCreateOrUpdateEvent->getParentName(), - '%parentId%' => $imageCreateOrUpdateEvent->getParentId(), - '%parentType%' => $imageCreateOrUpdateEvent->getImageType() - ), - 'image' - ) - ); - - return new ResponseRest(array('status' => true, 'message' => '')); + return new ResponseRest($message, 'text', 415); } + + $imageModel = $fileManager->getModelInstance('image', $parentType); + + $parentModel = $imageModel->getParentFileModel(); + + if ($parentModel === null || $imageModel === null || $fileBeingUploaded === null) { + return new Response('', 404); + } + + $defaultTitle = $parentModel->getTitle(); + + if (empty($defaultTitle)) { + $defaultTitle = $fileBeingUploaded->getClientOriginalName(); + } + + $imageModel + ->setParentId($parentId) + ->setLocale(Lang::getDefaultLanguage()->getLocale()) + ->setTitle($defaultTitle) + ; + + $imageCreateOrUpdateEvent = new ImageCreateOrUpdateEvent($parentId); + $imageCreateOrUpdateEvent->setModelImage($imageModel); + $imageCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded); + $imageCreateOrUpdateEvent->setParentName($parentModel->getTitle()); + + // Dispatch Event to the Action + $this->dispatch( + TheliaEvents::IMAGE_SAVE, + $imageCreateOrUpdateEvent + ); + + $this->adminLogAppend( + AdminResources::retrieve($parentType), + AccessManager::UPDATE, + $this->container->get('thelia.translator')->trans( + 'Saving images for %parentName% parent id %parentId%', + array( + '%parentName%' => $imageCreateOrUpdateEvent->getParentName(), + '%parentId%' => $imageCreateOrUpdateEvent->getParentId() + ), + 'image' + ) + ); + + return new ResponseRest(array('status' => true, 'message' => '')); } return new Response('', 404); @@ -156,67 +161,62 @@ class FileController extends BaseAdminController $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkXmlHttpRequest(); - if ($this->isParentTypeValid($parentType)) { - if ($this->getRequest()->isMethod('POST')) { + if ($this->getRequest()->isMethod('POST')) { - /** @var UploadedFile $fileBeingUploaded */ - $fileBeingUploaded = $this->getRequest()->files->get('file'); + /** @var UploadedFile $fileBeingUploaded */ + $fileBeingUploaded = $this->getRequest()->files->get('file'); - $fileManager = new FileManager(); + $fileManager = $this->getFileManager(); - // Validate if file is too big - if ($fileBeingUploaded->getError() == 1) { - $message = $this->getTranslator() - ->trans( - 'File is too heavy, please retry with a file having a size less than %size%.', - array('%size%' => ini_get('post_max_size')), - 'document' - ); - - return new ResponseRest($message, 'text', 403); - } - - $parentModel = $fileManager->getParentFileModel($parentType, $parentId); - $documentModel = $fileManager->getDocumentModel($parentType); - - if ($parentModel === null || $documentModel === null || $fileBeingUploaded === null) { - return new Response('', 404); - } - - $documentModel->setParentId($parentId); - $documentModel->setLocale(Lang::getDefaultLanguage()->getLocale()); - $documentModel->setTitle($fileBeingUploaded->getClientOriginalName()); - - $documentCreateOrUpdateEvent = new DocumentCreateOrUpdateEvent( - $parentType, - $parentId - ); - $documentCreateOrUpdateEvent->setModelDocument($documentModel); - $documentCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded); - $documentCreateOrUpdateEvent->setParentName($parentModel->getTitle()); - - // Dispatch Event to the Action - $this->dispatch( - TheliaEvents::DOCUMENT_SAVE, - $documentCreateOrUpdateEvent - ); - - $this->adminLogAppend( - AdminResources::retrieve($parentType), - AccessManager::UPDATE, - $this->container->get('thelia.translator')->trans( - 'Saving documents for %parentName% parent id %parentId% (%parentType%)', - array( - '%parentName%' => $documentCreateOrUpdateEvent->getParentName(), - '%parentId%' => $documentCreateOrUpdateEvent->getParentId(), - '%parentType%' => $documentCreateOrUpdateEvent->getDocumentType() - ), + // Validate if file is too big + if ($fileBeingUploaded->getError() == 1) { + $message = $this->getTranslator() + ->trans( + 'File is too large, please retry with a file having a size less than %size%.', + array('%size%' => ini_get('post_max_size')), 'document' - ) - ); + ); - return new ResponseRest(array('status' => true, 'message' => '')); + return new ResponseRest($message, 'text', 403); } + + $documentModel = $fileManager->getModelInstance('document', $parentType); + $parentModel = $documentModel->getParentFileModel($parentType, $parentId); + + if ($parentModel === null || $documentModel === null || $fileBeingUploaded === null) { + return new Response('', 404); + } + + $documentModel->setParentId($parentId); + $documentModel->setLocale(Lang::getDefaultLanguage()->getLocale()); + $documentModel->setTitle($fileBeingUploaded->getClientOriginalName()); + + $documentCreateOrUpdateEvent = new DocumentCreateOrUpdateEvent($parentId); + + $documentCreateOrUpdateEvent->setModelDocument($documentModel); + $documentCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded); + $documentCreateOrUpdateEvent->setParentName($parentModel->getTitle()); + + // Dispatch Event to the Action + $this->dispatch( + TheliaEvents::DOCUMENT_SAVE, + $documentCreateOrUpdateEvent + ); + + $this->adminLogAppend( + AdminResources::retrieve($parentType), + AccessManager::UPDATE, + $this->container->get('thelia.translator')->trans( + 'Saving document for %parentName% parent id %parentId%', + array( + '%parentName%' => $documentCreateOrUpdateEvent->getParentName(), + '%parentId%' => $documentCreateOrUpdateEvent->getParentId() + ), + 'document' + ) + ); + + return new ResponseRest(array('status' => true, 'message' => '')); } return new Response('', 404); @@ -303,21 +303,25 @@ class FileController extends BaseAdminController if (null !== $response = $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE)) { return $response; } - try { - $fileManager = new FileManager(); - $image = $fileManager->getImageModelQuery($parentType)->findPk($imageId); - $redirectUrl = $fileManager->getRedirectionUrl($parentType, $image->getParentId(), FileManager::FILE_TYPE_IMAGES); + $fileManager = $this->getFileManager(); + $imageModel = $fileManager->getModelInstance('image', $parentType); - return $this->render('image-edit', array( - 'imageId' => $imageId, - 'imageType' => $parentType, - 'redirectUrl' => $redirectUrl, - 'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_IMAGES), - 'breadcrumb' => $image->getBreadcrumb($this->getRouter($this->getCurrentRouter()), $this->container, 'images') - )); - } catch (\Exception $e) { - $this->pageNotFound(); - } + $redirectUrl = $imageModel->getRedirectionUrl($imageId); + + $image = $imageModel->getQueryInstance()->findPk($imageId); + + return $this->render('image-edit', array( + 'imageId' => $imageId, + 'imageType' => $parentType, + 'redirectUrl' => $redirectUrl, + 'formId' => $imageModel->getUpdateFormId(), + 'breadcrumb' => $image->getBreadcrumb( + $this->getRouter($this->getCurrentRouter()), + $this->container, + 'images', + $this->getCurrentEditionLocale() + ) + )); } /** @@ -333,21 +337,26 @@ class FileController extends BaseAdminController if (null !== $response = $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE)) { return $response; } - try { - $fileManager = new FileManager(); - $document = $fileManager->getDocumentModelQuery($parentType)->findPk($documentId); - $redirectUrl = $fileManager->getRedirectionUrl($parentType, $document->getParentId(), FileManager::FILE_TYPE_DOCUMENTS); - return $this->render('document-edit', array( - 'documentId' => $documentId, - 'documentType' => $parentType, - 'redirectUrl' => $redirectUrl, - 'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_DOCUMENTS), - 'breadcrumb' => $document->getBreadcrumb($this->getRouter($this->getCurrentRouter()), $this->container, 'documents') - )); - } catch (\Exception $e) { - $this->pageNotFound(); - } + $fileManager = $this->getFileManager(); + $documentModel = $fileManager->getModelInstance('document', $parentType); + + $document = $documentModel->getQueryInstance()->findPk($documentId); + + $redirectUrl = $documentModel->getRedirectionUrl($documentId); + + return $this->render('document-edit', array( + 'documentId' => $documentId, + 'documentType' => $parentType, + 'redirectUrl' => $redirectUrl, + 'formId' => $documentModel->getUpdateFormId(), + 'breadcrumb' => $document->getBreadcrumb( + $this->getRouter($this->getCurrentRouter()), + $this->container, + 'documents', + $this->getCurrentEditionLocale() + ) + )); } /** @@ -366,12 +375,18 @@ class FileController extends BaseAdminController $message = false; - $fileManager = new FileManager(); - $imageModification = $fileManager->getImageForm($parentType, $this->getRequest()); + $fileManager = $this->getFileManager(); + + $modelInstance = $fileManager->getModelInstance('image', $parentType); + + $imageModification = $modelInstance->getUpdateFormInstance($this->getRequest()); + + /** @var FileModelInterface $image */ + $image = $modelInstance->getQueryInstance()->findPk($imageId); try { - $image = $fileManager->getImageModelQuery($parentType)->findPk($imageId); $oldImage = clone $image; + if (null === $image) { throw new \InvalidArgumentException(sprintf('%d image id does not exist', $imageId)); } @@ -394,7 +409,7 @@ class FileController extends BaseAdminController $this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE, sprintf('Image with Ref %s (ID %d) modified', $imageUpdated->getTitle(), $imageUpdated->getId())); if ($this->getRequest()->get('save_mode') == 'close') { - $this->redirect(URL::getInstance()->absoluteUrl($fileManager->getRedirectionUrl($parentType, $image->getParentId(), FileManager::FILE_TYPE_IMAGES))); + $this->redirect(URL::getInstance()->absoluteUrl($modelInstance->getRedirectionUrl($imageId))); } else { $this->redirectSuccess($imageModification); } @@ -417,13 +432,13 @@ class FileController extends BaseAdminController ->setGeneralError($message); } - $redirectUrl = $fileManager->getRedirectionUrl($parentType, $image->getParentId(), FileManager::FILE_TYPE_IMAGES); + $redirectUrl = $modelInstance->getRedirectionUrl($imageId); return $this->render('image-edit', array( 'imageId' => $imageId, 'imageType' => $parentType, - 'redirectUrl' => $redirectUrl, - 'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_IMAGES) + 'redirectUrl' => $redirectUrl, + 'formId' => $modelInstance->getUpdateFormId() )); } @@ -443,12 +458,18 @@ class FileController extends BaseAdminController $message = false; - $fileManager = new FileManager(); - $documentModification = $fileManager->getDocumentForm($parentType, $this->getRequest()); + $fileManager = $this->getFileManager(); + + $modelInstance = $fileManager->getModelInstance('document', $parentType); + + $documentModification = $modelInstance->getUpdateFormInstance($this->getRequest()); + + /** @var FileModelInterface $document */ + $document = $modelInstance->getQueryInstance()->findPk($documentId); try { - $document = $fileManager->getDocumentModelQuery($parentType)->findPk($documentId); $oldDocument = clone $document; + if (null === $document) { throw new \InvalidArgumentException(sprintf('%d document id does not exist', $documentId)); } @@ -471,7 +492,7 @@ class FileController extends BaseAdminController $this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE, sprintf('Document with Ref %s (ID %d) modified', $documentUpdated->getTitle(), $documentUpdated->getId())); if ($this->getRequest()->get('save_mode') == 'close') { - $this->redirect(URL::getInstance()->absoluteUrl($fileManager->getRedirectionUrl($parentType, $document->getParentId(), FileManager::FILE_TYPE_DOCUMENTS))); + $this->redirect(URL::getInstance()->absoluteUrl($modelInstance->getRedirectionUrl($documentId))); } else { $this->redirectSuccess($documentModification); } @@ -494,13 +515,13 @@ class FileController extends BaseAdminController ->setGeneralError($message); } - $redirectUrl = $fileManager->getRedirectionUrl($parentType, $document->getParentId(), FileManager::FILE_TYPE_DOCUMENTS); + $redirectUrl = $modelInstance->getRedirectionUrl($documentId); return $this->render('document-edit', array( 'documentId' => $documentId, 'documentType' => $parentType, 'redirectUrl' => $redirectUrl, - 'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_DOCUMENTS) + 'formId' => $modelInstance->getUpdateFormId() )); } @@ -519,9 +540,10 @@ class FileController extends BaseAdminController $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkXmlHttpRequest(); - $fileManager = new FileManager(); - $imageModelQuery = $fileManager->getImageModelQuery($parentType); - $model = $imageModelQuery->findPk($imageId); + $fileManager = $this->getFileManager(); + $modelInstance = $fileManager->getModelInstance('image', $parentType); + + $model = $modelInstance->getQueryInstance()->findPk($imageId); if ($model == null) { return $this->pageNotFound(); @@ -590,7 +612,7 @@ class FileController extends BaseAdminController return new Response($message); } - public function updateImagePositionAction($parentType, $parentId) + public function updateImagePositionAction($parentType, /** @noinspection PhpUnusedParameterInspection */ $parentId) { $message = null; @@ -600,9 +622,9 @@ class FileController extends BaseAdminController $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkXmlHttpRequest(); - $fileManager = new FileManager(); - $imageModelQuery = $fileManager->getImageModelQuery($parentType); - $model = $imageModelQuery->findPk($imageId); + $fileManager = $this->getFileManager(); + $modelInstance = $fileManager->getModelInstance('image', $parentType); + $model = $modelInstance->getQueryInstance()->findPk($imageId); if ($model === null || $position === null) { return $this->pageNotFound(); @@ -610,7 +632,7 @@ class FileController extends BaseAdminController // Feed event $imageUpdateImagePositionEvent = new UpdateFilePositionEvent( - $fileManager->getImageModelQuery($parentType), + $modelInstance->getQueryInstance($parentType), $imageId, UpdateFilePositionEvent::POSITION_ABSOLUTE, $position @@ -644,7 +666,7 @@ class FileController extends BaseAdminController return new Response($message); } - public function updateDocumentPositionAction($parentType, $parentId) + public function updateDocumentPositionAction($parentType, /** @noinspection PhpUnusedParameterInspection */ $parentId) { $message = null; @@ -654,9 +676,9 @@ class FileController extends BaseAdminController $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkXmlHttpRequest(); - $fileManager = new FileManager(); - $documentModelQuery = $fileManager->getDocumentModelQuery($parentType); - $model = $documentModelQuery->findPk($documentId); + $fileManager = $this->getFileManager(); + $modelInstance = $fileManager->getModelInstance('document', $parentType); + $model = $modelInstance->getQueryInstance()->findPk($documentId); if ($model === null || $position === null) { return $this->pageNotFound(); @@ -664,7 +686,7 @@ class FileController extends BaseAdminController // Feed event $documentUpdateDocumentPositionEvent = new UpdateFilePositionEvent( - $fileManager->getDocumentModelQuery($parentType), + $modelInstance->getQueryInstance(), $documentId, UpdateFilePositionEvent::POSITION_ABSOLUTE, $position @@ -711,9 +733,9 @@ class FileController extends BaseAdminController $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkXmlHttpRequest(); - $fileManager = new FileManager(); - $documentModelQuery = $fileManager->getDocumentModelQuery($parentType); - $model = $documentModelQuery->findPk($documentId); + $fileManager = $this->getFileManager(); + $modelInstance = $fileManager->getModelInstance('document', $parentType); + $model = $modelInstance->getQueryInstance()->findPk($documentId); if ($model == null) { return $this->pageNotFound(); @@ -793,30 +815,19 @@ class FileController extends BaseAdminController return $this; } - /** - * Check if parent type is valid or not - * - * @param string $parentType Parent type - * - * @return bool - */ - public function isParentTypeValid($parentType) - { - return (in_array($parentType, FileManager::getAvailableTypes())); - } - /** * Create Image Event instance * - * @param string $parentType Parent Type owning images being saved - * @param CategoryImage|ProductImage|ContentImage|FolderImage $model Image model - * @param array $data Post data + * @param string $parentType Parent Type owning images being saved + * @param FileModelInterface $model the model + * @param array $data Post data * * @return ImageCreateOrUpdateEvent */ protected function createImageEventInstance($parentType, $model, $data) { - $imageCreateEvent = new ImageCreateOrUpdateEvent($parentType, null); + $imageCreateEvent = new ImageCreateOrUpdateEvent(null); + $model->setLocale($data['locale']); if (isset($data['title'])) { @@ -843,15 +854,16 @@ class FileController extends BaseAdminController /** * Create Document Event instance * - * @param string $parentType Parent Type owning documents being saved - * @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $model Document model - * @param array $data Post data + * @param string $parentType Parent Type owning documents being saved + * @param FileModelInterface $model the model + * @param array $data Post data * * @return DocumentCreateOrUpdateEvent */ protected function createDocumentEventInstance($parentType, $model, $data) { - $documentCreateEvent = new DocumentCreateOrUpdateEvent($parentType, null); + $documentCreateEvent = new DocumentCreateOrUpdateEvent(null); + $model->setLocale($data['locale']); if (isset($data['title'])) { $model->setTitle($data['title']); diff --git a/core/lib/Thelia/Core/Event/Document/DocumentCreateOrUpdateEvent.php b/core/lib/Thelia/Core/Event/Document/DocumentCreateOrUpdateEvent.php index 0e639b069..422f4a889 100644 --- a/core/lib/Thelia/Core/Event/Document/DocumentCreateOrUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/Document/DocumentCreateOrUpdateEvent.php @@ -13,6 +13,7 @@ namespace Thelia\Core\Event\Document; use Symfony\Component\HttpFoundation\File\UploadedFile; use Thelia\Core\Event\ActionEvent; +use Thelia\Files\FileModelInterface; use Thelia\Model\CategoryDocument; use Thelia\Model\ContentDocument; use Thelia\Model\FolderDocument; @@ -44,29 +45,23 @@ class DocumentCreateOrUpdateEvent extends ActionEvent /** @var int Document parent id */ protected $parentId = null; - /** @var string Document type */ - protected $documentType = null; - /** @var string Parent name */ protected $parentName = null; /** * Constructor * - * @param string $documentType Document type - * ex : FileManager::TYPE_CATEGORY - * @param int $parentId Document parent id + * @param int $parentId Document parent id */ - public function __construct($documentType, $parentId) + public function __construct($parentId) { - $this->documentType = $documentType; $this->parentId = $parentId; } /** * Set Document to save * - * @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $document Document to save + * @param FileModelInterface $document Document to save * * @return $this */ @@ -80,37 +75,13 @@ class DocumentCreateOrUpdateEvent extends ActionEvent /** * Get Document being saved * - * @return CategoryDocument|ProductDocument|ContentDocument|FolderDocument + * @return FileModelInterface */ public function getModelDocument() { return $this->modelDocument; } - /** - * Set document type - * - * @param string $documentType Document type - * - * @return $this - */ - public function setDocumentType($documentType) - { - $this->documentType = $documentType; - - return $this; - } - - /** - * Get document type - * - * @return string - */ - public function getDocumentType() - { - return $this->documentType; - } - /** * Set Document parent id * @@ -186,7 +157,7 @@ class DocumentCreateOrUpdateEvent extends ActionEvent /** * Set old model value * - * @param CategoryDocument|ContentDocument|FolderDocument|ProductDocument $oldModelDocument + * @param FileModelInterface $oldModelDocument */ public function setOldModelDocument($oldModelDocument) { @@ -196,7 +167,7 @@ class DocumentCreateOrUpdateEvent extends ActionEvent /** * Get old model value * - * @return CategoryDocument|ContentDocument|FolderDocument|ProductDocument + * @return FileModelInterface */ public function getOldModelDocument() { diff --git a/core/lib/Thelia/Core/Event/Document/DocumentDeleteEvent.php b/core/lib/Thelia/Core/Event/Document/DocumentDeleteEvent.php index 493fb0432..d97ddcd23 100644 --- a/core/lib/Thelia/Core/Event/Document/DocumentDeleteEvent.php +++ b/core/lib/Thelia/Core/Event/Document/DocumentDeleteEvent.php @@ -13,10 +13,7 @@ namespace Thelia\Core\Event\Document; use Thelia\Core\Event\ActionEvent; -use Thelia\Model\CategoryDocument; -use Thelia\Model\ContentDocument; -use Thelia\Model\FolderDocument; -use Thelia\Model\ProductDocument; +use Thelia\Files\FileModelInterface; /** * Created by JetBrains PhpStorm. @@ -31,53 +28,24 @@ use Thelia\Model\ProductDocument; */ class DocumentDeleteEvent extends ActionEvent { - /** @var string Document type */ - protected $documentType = null; - /** @var CategoryDocument|ProductDocument|ContentDocument|FolderDocument Document about to be deleted */ + /** @var FileModelInterface Document about to be deleted */ protected $documentToDelete = null; /** * Constructor * - * @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $documentToDelete Document about to be deleted - * @param string $documentType Document type - * ex : FileManager::TYPE_CATEGORY + * @param FileModelInterface $documentToDelete Document about to be deleted */ - public function __construct($documentToDelete, $documentType) + public function __construct($documentToDelete) { $this->documentToDelete = $documentToDelete; - $this->documentType = $documentType; - } - - /** - * Set picture type - * - * @param string $documentType Document type - * - * @return $this - */ - public function setDocumentType($documentType) - { - $this->documentType = $documentType; - - return $this; - } - - /** - * Get picture type - * - * @return string - */ - public function getDocumentType() - { - return $this->documentType; } /** * Set Document about to be deleted * - * @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $documentToDelete Document about to be deleted + * @param FileModelInterface $documentToDelete Document about to be deleted * * @return $this */ @@ -91,7 +59,7 @@ class DocumentDeleteEvent extends ActionEvent /** * Get Document about to be deleted * - * @return CategoryDocument|ProductDocument|ContentDocument|FolderDocument + * @return FileModelInterface */ public function getDocumentToDelete() { diff --git a/core/lib/Thelia/Core/Event/Image/ImageCreateOrUpdateEvent.php b/core/lib/Thelia/Core/Event/Image/ImageCreateOrUpdateEvent.php index 5a3485abe..562a79609 100644 --- a/core/lib/Thelia/Core/Event/Image/ImageCreateOrUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/Image/ImageCreateOrUpdateEvent.php @@ -13,6 +13,7 @@ namespace Thelia\Core\Event\Image; use Symfony\Component\HttpFoundation\File\UploadedFile; use Thelia\Core\Event\ActionEvent; +use Thelia\Files\FileModelInterface; /** * Created by JetBrains PhpStorm. @@ -28,10 +29,10 @@ use Thelia\Core\Event\ActionEvent; class ImageCreateOrUpdateEvent extends ActionEvent { - /** @var \Thelia\Model\CategoryImage|\Thelia\Model\ProductImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage model to save */ + /** @var FileModelInterface model to save */ protected $modelImage = array(); - /** @var \Thelia\Model\CategoryImage|\Thelia\Model\ProductImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage model to save */ + /** @var FileModelInterface model to save */ protected $oldModelImage = array(); /** @var UploadedFile Image file to save */ @@ -40,9 +41,6 @@ class ImageCreateOrUpdateEvent extends ActionEvent /** @var int Image parent id */ protected $parentId = null; - /** @var string Image type */ - protected $imageType = null; - /** @var string Parent name */ protected $parentName = null; @@ -51,18 +49,15 @@ class ImageCreateOrUpdateEvent extends ActionEvent /** * Constructor * - * @param string $imageType Image type - * ex : FileManager::TYPE_CATEGORY - * @param int $parentId Image parent id + * @param int $parentId Image parent id */ - public function __construct($imageType, $parentId) + public function __construct($parentId) { - $this->imageType = $imageType; $this->parentId = $parentId; } /** - * @param mixed $locale + * @param string $locale */ public function setLocale($locale) { @@ -82,7 +77,7 @@ class ImageCreateOrUpdateEvent extends ActionEvent /** * Set Image to save * - * @param $image \Thelia\Model\CategoryImage|\Thelia\Model\ProductImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage + * @param FileModelInterface $image * * @return $this */ @@ -96,37 +91,13 @@ class ImageCreateOrUpdateEvent extends ActionEvent /** * Get Image being saved * - * @return \Thelia\Model\CategoryImage|\Thelia\Model\ProductImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage + * @return FileModelInterface */ public function getModelImage() { return $this->modelImage; } - /** - * Set picture type - * - * @param string $imageType Image type - * - * @return $this - */ - public function setImageType($imageType) - { - $this->imageType = $imageType; - - return $this; - } - - /** - * Get picture type - * - * @return string - */ - public function getImageType() - { - return $this->imageType; - } - /** * Set Image parent id * diff --git a/core/lib/Thelia/Core/Event/Image/ImageDeleteEvent.php b/core/lib/Thelia/Core/Event/Image/ImageDeleteEvent.php index cef4982b5..4021a27e9 100644 --- a/core/lib/Thelia/Core/Event/Image/ImageDeleteEvent.php +++ b/core/lib/Thelia/Core/Event/Image/ImageDeleteEvent.php @@ -13,10 +13,7 @@ namespace Thelia\Core\Event\Image; use Thelia\Core\Event\ActionEvent; -use Thelia\Model\CategoryImage; -use Thelia\Model\ContentImage; -use Thelia\Model\FolderImage; -use Thelia\Model\ProductImage; +use Thelia\Files\FileModelInterface; /** * Created by JetBrains PhpStorm. @@ -34,50 +31,23 @@ class ImageDeleteEvent extends ActionEvent /** @var string Image type */ protected $imageType = null; - /** @var CategoryImage|ProductImage|ContentImage|FolderImage Image about to be deleted */ + /** @var FileModelInterface Image about to be deleted */ protected $imageToDelete = null; /** * Constructor * - * @param CategoryImage|ProductImage|ContentImage|FolderImage $imageToDelete Image about to be deleted - * @param string $imageType Image type - * ex : FileManager::TYPE_CATEGORY + * @param FileModelInterface $imageToDelete Image about to be deleted */ - public function __construct($imageToDelete, $imageType) + public function __construct($imageToDelete) { $this->imageToDelete = $imageToDelete; - $this->imageType = $imageType; - } - - /** - * Set picture type - * - * @param string $imageType Image type - * - * @return $this - */ - public function setImageType($imageType) - { - $this->imageType = $imageType; - - return $this; - } - - /** - * Get picture type - * - * @return string - */ - public function getImageType() - { - return $this->imageType; } /** * Set Image about to be deleted * - * @param CategoryImage|ProductImage|ContentImage|FolderImage $imageToDelete Image about to be deleted + * @param FileModelInterface $imageToDelete Image about to be deleted * * @return $this */ @@ -91,7 +61,7 @@ class ImageDeleteEvent extends ActionEvent /** * Get Image about to be deleted * - * @return CategoryImage|ProductImage|ContentImage|FolderImage + * @return FileModelInterface */ public function getImageToDelete() { diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/outputfilter.trimwhitespace.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/outputfilter.trimwhitespace.php index 000fea9ab..2d7d00c74 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/outputfilter.trimwhitespace.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/outputfilter.trimwhitespace.php @@ -61,7 +61,8 @@ function smarty_outputfilter_trimwhitespace($source, &$smarty) return $source; } -function smarty_outputfilter_trimwhitespace_replace($search_str, $replace, &$subject) { +function smarty_outputfilter_trimwhitespace_replace($search_str, $replace, &$subject) +{ $_len = strlen($search_str); $_pos = 0; for ($_i=0, $_count=count($replace); $_i<$_count; $_i++) @@ -71,5 +72,3 @@ function smarty_outputfilter_trimwhitespace_replace($search_str, $replace, &$sub break; } - -?> \ No newline at end of file diff --git a/core/lib/Thelia/Exception/FileException.php b/core/lib/Thelia/Exception/FileException.php new file mode 100644 index 000000000..02aff3891 --- /dev/null +++ b/core/lib/Thelia/Exception/FileException.php @@ -0,0 +1,25 @@ +addError($message); + + parent::__construct($message, $code, $previous); + } +} diff --git a/core/lib/Thelia/Files/FileManager.php b/core/lib/Thelia/Files/FileManager.php new file mode 100644 index 000000000..19fa7adf8 --- /dev/null +++ b/core/lib/Thelia/Files/FileManager.php @@ -0,0 +1,265 @@ +, Franck Allimant + * + */ +class FileManager +{ + protected $supportedFileModels = array(); + + /** + * Create a new FileManager instance. + * + * @param array $supportedFileModels The key should have form type.parent, where type is the file type (document or image) and parent is the parent object of the file, form example product, brand, folder, etc. + */ + public function __construct($supportedFileModels) { + + $this->supportedFileModels = $supportedFileModels; + } + + /** + * Create the file type identifier, to access the related class in the supportedFileModels table. + * + * @param string $fileType the file type, e.g. document or image. + * @param string $parentType the parent object type, e.g. product, folder, brand, etc. + * @return string + */ + protected function getFileTypeIdentifier($fileType, $parentType) { + return strtolower("$fileType.$parentType"); + } + /** + * Create a new FileModelInterface instance, from the supportedFileModels table + * + * @param string $fileType the file type, such as document, image, etc. + * @param string $parentType the parent type, such as product, category, etc. + * + * @return FileModelInterface a file model interface instance + * + * @throws FileException if the file type is not supported, or if the class does not implements FileModelInterface + */ + public function getModelInstance($fileType, $parentType) { + + if (! isset($this->supportedFileModels[$this->getFileTypeIdentifier($fileType, $parentType)])) { + throw new FileException( + sprintf("Unsupported file type '%s' for parent type '%s'", $fileType, $parentType) + ); + } + + $className = $this->supportedFileModels[$this->getFileTypeIdentifier($fileType, $parentType)]; + + $instance = new $className; + + if (! $instance instanceof FileModelInterface) { + throw new FileException( + sprintf("Wrong class type for file type '%s', parent type '%s'. Class '%s' should implements FileModelInterface", + $fileType, $parentType, $className + ) + ); + } + + return $instance; + } + + /** + * A a new FileModelInterface class name to the supported class list. + * + * @param string $fileType the file type, such as document, image, etc. + * @param string $parentType the parent type, such as Product, Category, etc. + * @param string $fullyQualifiedClassName the fully qualified class name + */ + public function addFileModel($fileType, $parentType, $fullyQualifiedClassName) { + $this->supportedFileModels[$this->getFileTypeIdentifier($fileType, $parentType)] = $fullyQualifiedClassName; + } + + /** + * Copy UploadedFile into the server storage directory + * + * @param FileModelInterface $model Model saved + * @param UploadedFile $uploadedFile Ready to be uploaded file + * + * @throws \Thelia\Exception\ImageException + * @return UploadedFile + */ + public function copyUploadedFile($model, $uploadedFile) + { + $newUploadedFile = null; + + if ($uploadedFile !== null) { + + $directory = $model->getUploadDir(); + + $fileName = $this->renameFile($model->getId(), $uploadedFile); + + $newUploadedFile = $uploadedFile->move($directory, $fileName); + $model->setFile($fileName); + + if (!$model->save()) { + throw new ImageException( + sprintf( + 'Failed to update model after copy of uploaded file %s to %s', + $uploadedFile, + $model->getFile() + ) + ); + } + } + + return $newUploadedFile; + } + /** + * Save file into the database + * + * @param int $parentId the parent object ID + * @param FileModelInterface $fileModel the file model object (image or document) to save. + * + * @return int number of modified rows in database + * + * @throws \Thelia\Exception\ImageException + */ + protected function saveFile($parentId, $fileModel) + { + $nbModifiedLines = 0; + + if ($fileModel->getFile() !== null) { + + $fileModel->setParentId($parentId); + + $nbModifiedLines = $fileModel->save(); + + if (!$nbModifiedLines) { + throw new ImageException( + sprintf( + 'Failed to update %s file model', + $fileModel->getFile() + ) + ); + } + } + + return $nbModifiedLines; + } + + /** + * Save file into the database + * + * @param ImageCreateOrUpdateEvent $event the event + * @param FileModelInterface $imageModel the file model object (image or document) to save. + * + * @return int number of modified rows in database + */ + public function saveImage($event, $imageModel) + { + return $this->saveFile($event->getParentId(), $imageModel); + } + + /** + * Save file into the database + * + * @param DocumentCreateOrUpdateEvent $event the event + * @param FileModelInterface $documentModel the file model object (image or document) to save. + * + * @return int number of modified rows in database + */ + public function saveDocument($event, $documentModel) + { + return $this->saveFile($event->getParentId(), $documentModel); + } + + /** + * Sanitizes a filename replacing whitespace with dashes + * + * Removes special characters that are illegal in filenames on certain + * operating systems and special characters requiring special escaping + * to manipulate at the command line. + * + * @param string $string The filename to be sanitized + * + * @return string The sanitized filename + */ + public function sanitizeFileName($string) + { + return strtolower(preg_replace('/[^a-zA-Z0-9-_\.]/', '', $string)); + } + + /** + * Delete image from file storage and database + * + * @param FileModelInterface $model File being deleted + */ + public function c($model) + { + $url = $model->getUploadDir() . DS . $model->getFile(); + + @unlink(str_replace('..', '', $url)); + + $model->delete(); + } + + /** + * Rename file with image model id + * + * @param int $modelId Model id + * @param UploadedFile $uploadedFile File being saved + * + * @return string + */ + public function renameFile($modelId, $uploadedFile) + { + $extension = $uploadedFile->getClientOriginalExtension(); + if (!empty($extension)) { + $extension = '.' . strtolower($extension); + } + $fileName = $this->sanitizeFileName( + str_replace( + $extension, + '', + $uploadedFile->getClientOriginalName() + ) . '-' . $modelId . $extension + ); + + return $fileName; + } + + /** + * Check if a file is an image + * Check based on mime type + * + * @param string $mimeType File mime type + * + * @return bool + */ + public function isImage($mimeType) + { + $isValid = false; + + $allowedType = array('image/jpeg' , 'image/png' ,'image/gif'); + + if (in_array($mimeType, $allowedType)) { + $isValid = true; + } + + return $isValid; + } +} diff --git a/core/lib/Thelia/Files/FileModelInterface.php b/core/lib/Thelia/Files/FileModelInterface.php new file mode 100644 index 000000000..781070044 --- /dev/null +++ b/core/lib/Thelia/Files/FileModelInterface.php @@ -0,0 +1,113 @@ +form attribute : - * - * $this->form->add('name', 'text') - * ->add('email', 'email', array( - * 'attr' => array( - * 'class' => 'field' - * ), - * 'label' => 'email', - * 'constraints' => array( - * new NotBlank() - * ) - * ) - * ) - * ->add('age', 'integer'); - * - * @return null + * @inheritdoc */ protected function buildForm() { @@ -56,68 +39,80 @@ abstract class DocumentModification extends BaseForm 'file', 'file', array( + 'required' => false, 'constraints' => array(), 'label' => Translator::getInstance()->trans('Replace current document by this file'), 'label_attr' => array( 'for' => 'file' ) ) - ); - - $this->formBuilder - ->add( - 'title', - 'text', - array( - 'constraints' => array( - new NotBlank() - ), - 'label' => Translator::getInstance()->trans('Title'), - 'label_attr' => array( - 'for' => 'title' - ) + ) + ->add( + 'title', + 'text', + array( + 'required' => true, + 'constraints' => array( + new NotBlank() + ), + 'label' => Translator::getInstance()->trans('Title'), + 'label_attr' => array( + 'for' => 'title' ) ) - ->add( - 'description', - 'text', - array( - 'constraints' => array(), - 'label' => Translator::getInstance()->trans('Description'), - 'label_attr' => array( - 'for' => 'description' - ) + ) + ->add( + 'description', + 'textarea', + array( + 'required' => false, + 'constraints' => array(), + 'label' => Translator::getInstance()->trans('Description'), + 'label_attr' => array( + 'for' => 'description', + 'rows' => 5 ) ) - ->add( - 'chapo', - 'text', - array( - 'constraints' => array(), - 'label' => Translator::getInstance()->trans('Chapo'), - 'label_attr' => array( - 'for' => 'chapo' - ) + ) + ->add( + 'chapo', + 'textarea', + array( + 'required' => false, + 'constraints' => array(), + 'label' => Translator::getInstance()->trans('Chapo'), + 'label_attr' => array( + 'for' => 'chapo', + 'rows' => 3 ) ) - ->add( - 'postscriptum', - 'text', - array( - 'constraints' => array(), - 'label' => Translator::getInstance()->trans('Post Scriptum'), - 'label_attr' => array( - 'for' => 'postscriptum' - ) + ) + ->add( + 'postscriptum', + 'textarea', + array( + 'required' => false, + 'constraints' => array(), + 'label' => Translator::getInstance()->trans('Post Scriptum'), + 'label_attr' => array( + 'for' => 'postscriptum', + 'rows' => 3 ) ) - - ->add("locale", "text", array( + ) + ->add( + "locale", + "hidden", + array( + 'required' => true, "constraints" => array( new NotBlank() ), - "label_attr" => array("for" => "locale_create") - )) + "label_attr" => array( + "for" => "locale_create" + ) + ) + ) ; } } diff --git a/core/lib/Thelia/Form/Image/ImageModification.php b/core/lib/Thelia/Form/Image/ImageModification.php index 472deb4fb..0af0eaeb2 100644 --- a/core/lib/Thelia/Form/Image/ImageModification.php +++ b/core/lib/Thelia/Form/Image/ImageModification.php @@ -33,24 +33,7 @@ abstract class ImageModification extends BaseForm { /** - * - * in this function you add all the fields you need for your Form. - * Form this you have to call add method on $this->form attribute : - * - * $this->form->add('name', 'text') - * ->add('email', 'email', array( - * 'attr' => array( - * 'class' => 'field' - * ), - * 'label' => 'email', - * 'constraints' => array( - * new NotBlank() - * ) - * ) - * ) - * ->add('age', 'integer'); - * - * @return null + * @inheritdoc */ protected function buildForm() { @@ -58,6 +41,7 @@ abstract class ImageModification extends BaseForm 'file', 'file', array( + 'required' => false, 'constraints' => array( new Image( array( @@ -71,61 +55,73 @@ abstract class ImageModification extends BaseForm 'for' => 'file' ) ) - ); - - $this->formBuilder - ->add( - 'title', - 'text', - array( - 'constraints' => array( - new NotBlank() - ), - 'label' => Translator::getInstance()->trans('Title'), - 'label_attr' => array( - 'for' => 'title' - ) + ) + ->add( + 'title', + 'text', + array( + 'required' => true, + 'constraints' => array( + new NotBlank() + ), + 'label' => Translator::getInstance()->trans('Title'), + 'label_attr' => array( + 'for' => 'title' ) ) - ->add( - 'description', - 'text', - array( - 'constraints' => array(), - 'label' => Translator::getInstance()->trans('Description'), - 'label_attr' => array( - 'for' => 'description' - ) + ) + ->add( + 'description', + 'textarea', + array( + 'required' => false, + 'constraints' => array(), + 'label' => Translator::getInstance()->trans('Description'), + 'label_attr' => array( + 'for' => 'description', + 'rows' => 5 ) ) - ->add( - 'chapo', - 'text', - array( - 'constraints' => array(), - 'label' => Translator::getInstance()->trans('Chapo'), - 'label_attr' => array( - 'for' => 'chapo' - ) + ) + ->add( + 'chapo', + 'textarea', + array( + 'required' => false, + 'constraints' => array(), + 'label' => Translator::getInstance()->trans('Chapo'), + 'label_attr' => array( + 'for' => 'chapo', + 'rows' => 3 ) ) - ->add( - 'postscriptum', - 'text', - array( - 'constraints' => array(), - 'label' => Translator::getInstance()->trans('Post Scriptum'), - 'label_attr' => array( - 'for' => 'postscriptum' - ) + ) + ->add( + 'postscriptum', + 'textarea', + array( + 'required' => false, + 'constraints' => array(), + 'label' => Translator::getInstance()->trans('Post Scriptum'), + 'label_attr' => array( + 'for' => 'postscriptum', + 'rows' => 3 ) ) - ->add("locale", "text", array( + ) + ->add( + "locale", + "hidden", + array( + 'required' => true, "constraints" => array( new NotBlank() ), - "label_attr" => array("for" => "locale_create") - )) + "label_attr" => array( + "for" => "locale_create" + ) + ) + ) ; } } diff --git a/core/lib/Thelia/Model/CategoryImage.php b/core/lib/Thelia/Model/CategoryImage.php index 5c277eba6..4f95e026b 100644 --- a/core/lib/Thelia/Model/CategoryImage.php +++ b/core/lib/Thelia/Model/CategoryImage.php @@ -2,16 +2,23 @@ namespace Thelia\Model; +use Propel\Runtime\ActiveQuery\ModelCriteria; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Router; +use Thelia\Core\HttpFoundation\Request; +use Thelia\Files\FileModelParentInterface; +use Thelia\Form\BaseForm; +use Thelia\Form\CategoryImageModification; use Thelia\Model\Base\CategoryImage as BaseCategoryImage; use Propel\Runtime\Connection\ConnectionInterface; +use Thelia\Model\Base\CategoryImageQuery; use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait; +use Thelia\Files\FileModelInterface; use Thelia\Model\Tools\ModelEventDispatcherTrait; use Thelia\Model\Tools\PositionManagementTrait; -class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface +class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface, FileModelInterface { use ModelEventDispatcherTrait; use PositionManagementTrait; @@ -19,6 +26,8 @@ class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface /** * Calculate next position relative to our parent + * + * @param CategoryImageQuery $query */ protected function addCriteriaToPositionQuery($query) { @@ -36,11 +45,7 @@ class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface } /** - * Set Image parent id - * - * @param int $parentId parent id - * - * @return $this + * @inheritdoc */ public function setParentId($parentId) { @@ -50,9 +55,7 @@ class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface } /** - * Get Image parent id - * - * @return int parent id + * @inheritdoc */ public function getParentId() { @@ -71,13 +74,68 @@ class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface } /** - * - * return the complete breadcrumb for a given resource. - * - * @return array + * @inheritdoc */ - public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) + public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale) { - return $this->getCategoryBreadcrumb($router, $container, $tab); + return $this->getCategoryBreadcrumb($router, $container, $tab, $locale); + } + + /** + * @return FileModelParentInterface the parent file model + */ + public function getParentFileModel() + { + return new Category(); + } + + /** + * Get the ID of the form used to change this object information + * + * @return BaseForm the form + */ + public function getUpdateFormId() + { + return 'thelia.admin.category.image.modification'; + } + + /** + * Get the form instance used to change this object information + * + * @param \Thelia\Core\HttpFoundation\Request $request + * + * @return BaseForm the form + */ + public function getUpdateFormInstance(Request $request) + { + return new CategoryImageModification($request); + } + + /** + * @return string the path to the upload directory where files are stored, without final slash + */ + public function getUploadDir() + { + return THELIA_LOCAL_DIR . 'media'.DS.'images'.DS.'category'; + } + + /** + * @param int $objectId the ID of the object + * + * @return string the URL to redirect to after update from the back-office + */ + public function getRedirectionUrl($objectId) + { + return '/admin/categories/update?category_id=' . $objectId . '?current_tab=image'; + } + + /** + * Get the Query instance for this object + * + * @return ModelCriteria + */ + public function getQueryInstance() + { + return CategoryImageQuery::create(); } } diff --git a/core/lib/Thelia/Model/Content.php b/core/lib/Thelia/Model/Content.php index 2a7936fe6..f5968bb37 100644 --- a/core/lib/Thelia/Model/Content.php +++ b/core/lib/Thelia/Model/Content.php @@ -6,19 +6,23 @@ use Propel\Runtime\ActiveQuery\Criteria; use Propel\Runtime\Propel; use Thelia\Core\Event\Content\ContentEvent; use Thelia\Core\Event\TheliaEvents; +use Thelia\Files\FileModelParentInterface; use Thelia\Model\Base\Content as BaseContent; use Thelia\Model\Map\ContentTableMap; use Propel\Runtime\Connection\ConnectionInterface; +use Thelia\Model\Tools\ModelEventDispatcherTrait; +use Thelia\Model\Tools\PositionManagementTrait; +use Thelia\Model\Tools\UrlRewritingTrait; -class Content extends BaseContent +class Content extends BaseContent implements FileModelParentInterface { - use \Thelia\Model\Tools\ModelEventDispatcherTrait; + use ModelEventDispatcherTrait; - use \Thelia\Model\Tools\PositionManagementTrait; + use PositionManagementTrait; - use \Thelia\Model\Tools\UrlRewritingTrait; + use UrlRewritingTrait; /** * {@inheritDoc} diff --git a/core/lib/Thelia/Model/ContentDocument.php b/core/lib/Thelia/Model/ContentDocument.php index bd3e16ec9..f766eed22 100644 --- a/core/lib/Thelia/Model/ContentDocument.php +++ b/core/lib/Thelia/Model/ContentDocument.php @@ -2,14 +2,21 @@ namespace Thelia\Model; +use Propel\Runtime\ActiveQuery\ModelCriteria; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Router; +use Thelia\Core\HttpFoundation\Request; +use Thelia\Files\FileModelParentInterface; +use Thelia\Form\BaseForm; +use Thelia\Form\ContentDocumentModification; use Thelia\Model\Base\ContentDocument as BaseContentDocument; use Propel\Runtime\Connection\ConnectionInterface; +use Thelia\Model\Base\ContentDocumentQuery; use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait; +use Thelia\Files\FileModelInterface; -class ContentDocument extends BaseContentDocument implements BreadcrumbInterface +class ContentDocument extends BaseContentDocument implements BreadcrumbInterface, FileModelInterface { use \Thelia\Model\Tools\ModelEventDispatcherTrait; use \Thelia\Model\Tools\PositionManagementTrait; @@ -17,6 +24,8 @@ class ContentDocument extends BaseContentDocument implements BreadcrumbInterface /** * Calculate next position relative to our parent + * + * @param ContentDocumentQuery $query */ protected function addCriteriaToPositionQuery($query) { @@ -34,11 +43,7 @@ class ContentDocument extends BaseContentDocument implements BreadcrumbInterface } /** - * Set Document parent id - * - * @param int $parentId parent id - * - * @return $this + * @inheritdoc */ public function setParentId($parentId) { @@ -48,9 +53,7 @@ class ContentDocument extends BaseContentDocument implements BreadcrumbInterface } /** - * Get Document parent id - * - * @return int parent id + * @inheritdoc */ public function getParentId() { @@ -69,13 +72,68 @@ class ContentDocument extends BaseContentDocument implements BreadcrumbInterface } /** - * - * return the complete breadcrumb for a given resource. - * - * @return array + * @inheritdoc */ - public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) + public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale) { - return $this->getContentBreadcrumb($router, $container, $tab); + return $this->getContentBreadcrumb($router, $container, $tab, $locale); + } + + /** + * @return FileModelParentInterface the parent file model + */ + public function getParentFileModel() + { + return new Content(); + } + + /** + * Get the ID of the form used to change this object information + * + * @return BaseForm the form + */ + public function getUpdateFormId() + { + return 'thelia.admin.content.document.modification'; + } + + /** + * Get the form instance used to change this object information + * + * @param \Thelia\Core\HttpFoundation\Request $request + * + * @return BaseForm the form + */ + public function getUpdateFormInstance(Request $request) + { + return new ContentDocumentModification($request); + } + + /** + * @return string the path to the upload directory where files are stored, without final slash + */ + public function getUploadDir() + { + return THELIA_LOCAL_DIR . 'media'.DS.'documents'.DS.'content'; + } + + /** + * @param int $objectId the ID of the object + * + * @return string the URL to redirect to after update from the back-office + */ + public function getRedirectionUrl($objectId) + { + return '/admin/content/update/' . $objectId . '?current_tab=document'; + } + + /** + * Get the Query instance for this object + * + * @return ModelCriteria + */ + public function getQueryInstance() + { + return ContentDocumentQuery::create(); } } diff --git a/core/lib/Thelia/Model/ContentImage.php b/core/lib/Thelia/Model/ContentImage.php index 98fe5a669..7172e8b51 100644 --- a/core/lib/Thelia/Model/ContentImage.php +++ b/core/lib/Thelia/Model/ContentImage.php @@ -2,14 +2,20 @@ namespace Thelia\Model; +use Propel\Runtime\ActiveQuery\ModelCriteria; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Router; +use Thelia\Core\HttpFoundation\Request; +use Thelia\Files\FileModelParentInterface; +use Thelia\Form\BaseForm; +use Thelia\Form\ContentImageModification; use Thelia\Model\Base\ContentImage as BaseContentImage; use Propel\Runtime\Connection\ConnectionInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait; +use Thelia\Files\FileModelInterface; -class ContentImage extends BaseContentImage implements BreadcrumbInterface +class ContentImage extends BaseContentImage implements BreadcrumbInterface, FileModelInterface { use \Thelia\Model\Tools\ModelEventDispatcherTrait; use \Thelia\Model\Tools\PositionManagementTrait; @@ -17,6 +23,8 @@ class ContentImage extends BaseContentImage implements BreadcrumbInterface /** * Calculate next position relative to our parent + * + * @param ContentImageQuery $query */ protected function addCriteriaToPositionQuery($query) { @@ -34,11 +42,7 @@ class ContentImage extends BaseContentImage implements BreadcrumbInterface } /** - * Set Image parent id - * - * @param int $parentId parent id - * - * @return $this + * @inheritdoc */ public function setParentId($parentId) { @@ -48,9 +52,7 @@ class ContentImage extends BaseContentImage implements BreadcrumbInterface } /** - * Get Image parent id - * - * @return int parent id + * @inheritdoc */ public function getParentId() { @@ -69,13 +71,69 @@ class ContentImage extends BaseContentImage implements BreadcrumbInterface } /** - * - * return the complete breadcrumb for a given resource. - * - * @return array + * @inheritdoc */ - public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) + public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale) { - return $this->getContentBreadcrumb($router, $container, $tab); + return $this->getContentBreadcrumb($router, $container, $tab, $locale); } + + /** + * @return FileModelParentInterface the parent file model + */ + public function getParentFileModel() + { + return new Content(); + } + + /** + * Get the ID of the form used to change this object information + * + * @return BaseForm the form + */ + public function getUpdateFormId() + { + return 'thelia.admin.content.image.modification'; + } + + /** + * Get the form instance used to change this object information + * + * @param \Thelia\Core\HttpFoundation\Request $request + * + * @return BaseForm the form + */ + public function getUpdateFormInstance(Request $request) + { + return new ContentImageModification($request); + } + + /** + * @return string the path to the upload directory where files are stored, without final slash + */ + public function getUploadDir() + { + return THELIA_LOCAL_DIR . 'media'.DS.'images'.DS.'content'; + } + + /** + * @param int $objectId the ID of the object + * + * @return string the URL to redirect to after update from the back-office + */ + public function getRedirectionUrl($objectId) + { + return '/admin/content/update/' . $objectId . '?current_tab=image'; + } + + /** + * Get the Query instance for this object + * + * @return ModelCriteria + */ + public function getQueryInstance() + { + return ContentImageQuery::create(); + } + } diff --git a/core/lib/Thelia/Model/Folder.php b/core/lib/Thelia/Model/Folder.php index e8bc43498..43fda79c0 100644 --- a/core/lib/Thelia/Model/Folder.php +++ b/core/lib/Thelia/Model/Folder.php @@ -4,11 +4,12 @@ namespace Thelia\Model; use Thelia\Core\Event\Folder\FolderEvent; use Thelia\Core\Event\TheliaEvents; +use Thelia\Files\FileModelParentInterface; use Thelia\Model\Base\Folder as BaseFolder; use Propel\Runtime\Connection\ConnectionInterface; -class Folder extends BaseFolder +class Folder extends BaseFolder implements FileModelParentInterface { use \Thelia\Model\Tools\ModelEventDispatcherTrait; diff --git a/core/lib/Thelia/Model/FolderDocument.php b/core/lib/Thelia/Model/FolderDocument.php index 9e38d37fc..caae33b31 100644 --- a/core/lib/Thelia/Model/FolderDocument.php +++ b/core/lib/Thelia/Model/FolderDocument.php @@ -2,14 +2,20 @@ namespace Thelia\Model; +use Propel\Runtime\ActiveQuery\ModelCriteria; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Router; +use Thelia\Core\HttpFoundation\Request; +use Thelia\Files\FileModelParentInterface; +use Thelia\Form\BaseForm; +use Thelia\Form\FolderDocumentModification; use Thelia\Model\Base\FolderDocument as BaseFolderDocument; use Propel\Runtime\Connection\ConnectionInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait; +use Thelia\Files\FileModelInterface; -class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface +class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface, FileModelInterface { use \Thelia\Model\Tools\ModelEventDispatcherTrait; use \Thelia\Model\Tools\PositionManagementTrait; @@ -17,6 +23,8 @@ class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface /** * Calculate next position relative to our parent + * + * @param FolderDocumentQuery $query */ protected function addCriteriaToPositionQuery($query) { @@ -34,11 +42,7 @@ class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface } /** - * Set Document parent id - * - * @param int $parentId parent id - * - * @return $this + * @inheritdoc */ public function setParentId($parentId) { @@ -48,9 +52,7 @@ class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface } /** - * Get Document parent id - * - * @return int parent id + * @inheritdoc */ public function getParentId() { @@ -68,8 +70,68 @@ class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface return true; } - public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) + /** + * @inheritdoc + */ + public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale) { - return $this->getFolderBreadcrumb($router, $container, $tab); + return $this->getFolderBreadcrumb($router, $container, $tab, $locale); + } + + /** + * @return FileModelParentInterface the parent file model + */ + public function getParentFileModel() + { + return new Folder(); + } + + /** + * Get the ID of the form used to change this object information + * + * @return BaseForm the form + */ + public function getUpdateFormId() + { + return 'thelia.admin.folder.document.modification'; + } + + /** + * Get the form instance used to change this object information + * + * @param \Thelia\Core\HttpFoundation\Request $request + * + * @return BaseForm the form + */ + public function getUpdateFormInstance(Request $request) + { + return new FolderDocumentModification($request); + } + + /** + * @return string the path to the upload directory where files are stored, without final slash + */ + public function getUploadDir() + { + return THELIA_LOCAL_DIR . 'media'.DS.'documents'.DS.'folder'; + } + + /** + * @param int $objectId the ID of the parent object + * @return string the URL to redirect to after update from the back-office + */ + public function getRedirectionUrl($objectId) + { + return '/admin/folder/update/' . $objectId . '?current_tab=image'; + } + + /** + * Get the Query instance for this object + * + * @return ModelCriteria + */ + public function getQueryInstance() + { + return FolderDocumentQuery::create(); } } diff --git a/core/lib/Thelia/Model/FolderImage.php b/core/lib/Thelia/Model/FolderImage.php index dfc630190..5082d089b 100644 --- a/core/lib/Thelia/Model/FolderImage.php +++ b/core/lib/Thelia/Model/FolderImage.php @@ -2,14 +2,20 @@ namespace Thelia\Model; +use Propel\Runtime\ActiveQuery\ModelCriteria; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Router; +use Thelia\Core\HttpFoundation\Request; +use Thelia\Files\FileModelParentInterface; +use Thelia\Form\BaseForm; +use Thelia\Form\FolderImageModification; use Thelia\Model\Base\FolderImage as BaseFolderImage; use Propel\Runtime\Connection\ConnectionInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait; +use Thelia\Files\FileModelInterface; -class FolderImage extends BaseFolderImage implements BreadcrumbInterface +class FolderImage extends BaseFolderImage implements BreadcrumbInterface, FileModelInterface { use \Thelia\Model\Tools\ModelEventDispatcherTrait; use \Thelia\Model\Tools\PositionManagementTrait; @@ -17,6 +23,8 @@ class FolderImage extends BaseFolderImage implements BreadcrumbInterface /** * Calculate next position relative to our parent + * + * @param FolderImageQuery $query */ protected function addCriteriaToPositionQuery($query) { @@ -34,11 +42,7 @@ class FolderImage extends BaseFolderImage implements BreadcrumbInterface } /** - * Set Image parent id - * - * @param int $parentId parent id - * - * @return $this + * @inheritdoc */ public function setParentId($parentId) { @@ -48,9 +52,7 @@ class FolderImage extends BaseFolderImage implements BreadcrumbInterface } /** - * Get Image parent id - * - * @return int parent id + * @inheritdoc */ public function getParentId() { @@ -69,13 +71,67 @@ class FolderImage extends BaseFolderImage implements BreadcrumbInterface } /** - * - * return the complete breadcrumb for a given resource. - * - * @return array + * @inheritdoc */ - public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) + public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale) { - return $this->getFolderBreadcrumb($router, $container, $tab); + return $this->getFolderBreadcrumb($router, $container, $tab, $locale); + } + + /** + * @return FileModelParentInterface the parent file model + */ + public function getParentFileModel() + { + return new Folder(); + } + + /** + * Get the ID of the form used to change this object information + * + * @return BaseForm the form + */ + public function getUpdateFormId() + { + return 'thelia.admin.folder.image.modification'; + } + + /** + * Get the form instance used to change this object information + * + * @param \Thelia\Core\HttpFoundation\Request $request + * + * @return BaseForm the form + */ + public function getUpdateFormInstance(Request $request) + { + return new FolderImageModification($request); + } + + /** + * @return string the path to the upload directory where files are stored, without final slash + */ + public function getUploadDir() + { + return THELIA_LOCAL_DIR . 'media'.DS.'images'.DS.'folder'; + } + + /** + * @param int $objectId the ID of the parent object + * @return string the URL to redirect to after update from the back-office + */ + public function getRedirectionUrl($objectId) + { + return '/admin/folder/update/' . $objectId . '?current_tab=image'; + } + + /** + * Get the Query instance for this object + * + * @return ModelCriteria + */ + public function getQueryInstance() + { + return FolderImageQuery::create(); } } diff --git a/core/lib/Thelia/Model/OrderVersionQuery.php b/core/lib/Thelia/Model/OrderVersionQuery.php index 4aef18cd0..fafa5a81c 100644 --- a/core/lib/Thelia/Model/OrderVersionQuery.php +++ b/core/lib/Thelia/Model/OrderVersionQuery.php @@ -4,7 +4,6 @@ namespace Thelia\Model; use Thelia\Model\Base\OrderVersionQuery as BaseOrderVersionQuery; - /** * Skeleton subclass for performing query and update operations on the 'order_version' table. * diff --git a/core/lib/Thelia/Model/Product.php b/core/lib/Thelia/Model/Product.php index 1d73c939d..439132574 100644 --- a/core/lib/Thelia/Model/Product.php +++ b/core/lib/Thelia/Model/Product.php @@ -3,6 +3,7 @@ namespace Thelia\Model; use Propel\Runtime\Exception\PropelException; +use Thelia\Files\FileModelParentInterface; use Thelia\Model\Base\Product as BaseProduct; use Thelia\TaxEngine\Calculator; @@ -13,7 +14,7 @@ use Propel\Runtime\ActiveQuery\Criteria; use Propel\Runtime\Propel; use Thelia\Model\Map\ProductTableMap; -class Product extends BaseProduct +class Product extends BaseProduct implements FileModelParentInterface { use \Thelia\Model\Tools\ModelEventDispatcherTrait; diff --git a/core/lib/Thelia/Model/ProductDocument.php b/core/lib/Thelia/Model/ProductDocument.php index cd00bdb1b..1706e2cd4 100644 --- a/core/lib/Thelia/Model/ProductDocument.php +++ b/core/lib/Thelia/Model/ProductDocument.php @@ -2,16 +2,22 @@ namespace Thelia\Model; +use Propel\Runtime\ActiveQuery\ModelCriteria; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Router; +use Thelia\Core\HttpFoundation\Request; +use Thelia\Files\FileModelParentInterface; +use Thelia\Form\BaseForm; +use Thelia\Form\ProductDocumentModification; use Thelia\Model\Base\ProductDocument as BaseProductDocument; use Propel\Runtime\Connection\ConnectionInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait; +use Thelia\Files\FileModelInterface; use Thelia\Model\Tools\PositionManagementTrait; use Thelia\Model\Tools\ModelEventDispatcherTrait; -class ProductDocument extends BaseProductDocument implements BreadcrumbInterface +class ProductDocument extends BaseProductDocument implements BreadcrumbInterface, FileModelInterface { use ModelEventDispatcherTrait; use PositionManagementTrait; @@ -19,6 +25,8 @@ class ProductDocument extends BaseProductDocument implements BreadcrumbInterface /** * Calculate next position relative to our parent + * + * @param ProductDocumentQuery $query */ protected function addCriteriaToPositionQuery($query) { @@ -36,11 +44,7 @@ class ProductDocument extends BaseProductDocument implements BreadcrumbInterface } /** - * Set Document parent id - * - * @param int $parentId parent id - * - * @return $this + * @inheritdoc */ public function setParentId($parentId) { @@ -50,9 +54,7 @@ class ProductDocument extends BaseProductDocument implements BreadcrumbInterface } /** - * Get Document parent id - * - * @return int parent id + * @inheritdoc */ public function getParentId() { @@ -71,13 +73,68 @@ class ProductDocument extends BaseProductDocument implements BreadcrumbInterface } /** - * - * return the complete breadcrumb for a given resource. - * - * @return array + * @inheritdoc */ - public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) + public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale) { - return $this->getProductBreadcrumb($router, $container, $tab); + return $this->getProductBreadcrumb($router, $container, $tab, $locale); + } + + /** + * @return FileModelParentInterface the parent file model + */ + public function getParentFileModel() + { + return new Product(); + } + + /** + * Get the ID of the form used to change this object information + * + * @return BaseForm the form + */ + public function getUpdateFormId() + { + return 'thelia.admin.product.document.modification'; + } + + /** + * Get the form instance used to change this object information + * + * @param \Thelia\Core\HttpFoundation\Request $request + * + * @return BaseForm the form + */ + public function getUpdateFormInstance(Request $request) + { + return new ProductDocumentModification($request); + } + + /** + * @return string the path to the upload directory where files are stored, without final slash + */ + public function getUploadDir() + { + return THELIA_LOCAL_DIR . 'media'.DS.'documents'.DS.'product'; + } + + /** + * @param int $objectId the ID of the object + * + * @return string the URL to redirect to after update from the back-office + */ + public function getRedirectionUrl($objectId) + { + return '/admin/products/update?product_id=' . $objectId . '?current_tab=document'; + } + + /** + * Get the Query instance for this object + * + * @return ModelCriteria + */ + public function getQueryInstance() + { + return ProductDocumentQuery::create(); } } diff --git a/core/lib/Thelia/Model/ProductImage.php b/core/lib/Thelia/Model/ProductImage.php index dba12e0e8..d6a753cea 100644 --- a/core/lib/Thelia/Model/ProductImage.php +++ b/core/lib/Thelia/Model/ProductImage.php @@ -2,16 +2,21 @@ namespace Thelia\Model; +use Propel\Runtime\ActiveQuery\ModelCriteria; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Router; +use Thelia\Core\HttpFoundation\Request; +use Thelia\Form\BaseForm; +use Thelia\Form\ProductImageModification; use Thelia\Model\Base\ProductImage as BaseProductImage; use Propel\Runtime\Connection\ConnectionInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait; +use Thelia\Files\FileModelInterface; use Thelia\Model\Tools\ModelEventDispatcherTrait; use Thelia\Model\Tools\PositionManagementTrait; -class ProductImage extends BaseProductImage implements BreadcrumbInterface +class ProductImage extends BaseProductImage implements BreadcrumbInterface, FileModelInterface { use ModelEventDispatcherTrait; use PositionManagementTrait; @@ -19,6 +24,8 @@ class ProductImage extends BaseProductImage implements BreadcrumbInterface /** * Calculate next position relative to our parent + * + * @param ProductImageQuery $query */ protected function addCriteriaToPositionQuery($query) { @@ -26,7 +33,7 @@ class ProductImage extends BaseProductImage implements BreadcrumbInterface } /** - * {@inheritDoc} + * @inheritDoc */ public function preInsert(ConnectionInterface $con = null) { @@ -36,11 +43,7 @@ class ProductImage extends BaseProductImage implements BreadcrumbInterface } /** - * Set Image parent id - * - * @param int $parentId parent id - * - * @return $this + * @inheritdoc */ public function setParentId($parentId) { @@ -50,9 +53,7 @@ class ProductImage extends BaseProductImage implements BreadcrumbInterface } /** - * Get Image parent id - * - * @return int parent id + * @inheritdoc */ public function getParentId() { @@ -71,13 +72,68 @@ class ProductImage extends BaseProductImage implements BreadcrumbInterface } /** - * - * return the complete breadcrumb for a given resource. - * - * @return array + * @inheritdoc */ - public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) + public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale) { - return $this->getProductBreadcrumb($router, $container, $tab); + return $this->getProductBreadcrumb($router, $container, $tab, $locale); + } + + /** + * @return FileModelParentInterface the parent file model + */ + public function getParentFileModel() + { + return new Product(); + } + + /** + * Get the ID of the form used to change this object information + * + * @return BaseForm the form + */ + public function getUpdateFormId() + { + return 'thelia.admin.product.image.modification'; + } + + /** + * Get the form instance used to change this object information + * + * @param \Thelia\Core\HttpFoundation\Request $request + * + * @return BaseForm the form + */ + public function getUpdateFormInstance(Request $request) + { + return new ProductImageModification($request); + } + + /** + * @return string the path to the upload directory where files are stored, without final slash + */ + public function getUploadDir() + { + return THELIA_LOCAL_DIR . 'media'.DS.'images'.DS.'product'; + } + + /** + * @param int $objectId the ID of the object + * + * @return string the URL to redirect to after update from the back-office + */ + public function getRedirectionUrl($objectId) + { + return '/admin/products/update?product_id=' . $objectId . '?current_tab=image'; + } + + /** + * Get the Query instance for this object + * + * @return ModelCriteria + */ + public function getQueryInstance() + { + return ProductImageQuery::create(); } } diff --git a/core/lib/Thelia/Tests/Files/FileManagerTest.php b/core/lib/Thelia/Tests/Files/FileManagerTest.php new file mode 100644 index 000000000..78ad73aee --- /dev/null +++ b/core/lib/Thelia/Tests/Files/FileManagerTest.php @@ -0,0 +1,398 @@ +container = new ContainerBuilder(); + + $this->fileManager = new FileManager([ + "document.product" => "Thelia\\Model\\ProductDocument", + "image.product" => "Thelia\\Model\\ProductImage", + + "document.category" => "Thelia\\Model\\CategoryDocument", + "image.category" => "Thelia\\Model\\CategoryImage", + + "document.content" => "Thelia\\Model\\ContentDocument", + "image.content" => "Thelia\\Model\\ContentImage", + + "document.folder" => "Thelia\\Model\\FolderDocument", + "image.folder" => "Thelia\\Model\\FolderImage", + + "document.brand" => "Thelia\\Model\\BrandDocument", + "image.brand" => "Thelia\\Model\\BrandImage", + ]); + + $this->container->set("thelia.file_manager", $this->fileManager); + } + + public function testGetFileTypeIdentifier() { + $obj = $this->fileManager->getModelInstance('document', 'product'); + $this->assertInstanceOf("Thelia\\Model\\ProductDocument", $obj); + + $obj = $this->fileManager->getModelInstance('image', 'product'); + $this->assertInstanceOf("Thelia\\Model\\ProductImage", $obj); + + $obj = $this->fileManager->getModelInstance('document', 'category'); + $this->assertInstanceOf("Thelia\\Model\\CategoryDocument", $obj); + + $obj = $this->fileManager->getModelInstance('image', 'category'); + $this->assertInstanceOf("Thelia\\Model\\CategoryImage", $obj); + + $obj = $this->fileManager->getModelInstance('document', 'content'); + $this->assertInstanceOf("Thelia\\Model\\ContentDocument", $obj); + + $obj = $this->fileManager->getModelInstance('image', 'content'); + $this->assertInstanceOf("Thelia\\Model\\ContentImage", $obj); + + $obj = $this->fileManager->getModelInstance('document', 'folder'); + $this->assertInstanceOf("Thelia\\Model\\FolderDocument", $obj); + + $obj = $this->fileManager->getModelInstance('image', 'folder'); + $this->assertInstanceOf("Thelia\\Model\\FolderImage", $obj); + + $obj = $this->fileManager->getModelInstance('document', 'brand'); + $this->assertInstanceOf("Thelia\\Model\\BrandDocument", $obj); + + $obj = $this->fileManager->getModelInstance('image', 'brand'); + $this->assertInstanceOf("Thelia\\Model\\BrandImage", $obj); + } + + /** + * @expectedException \Thelia\Exception\FileException + */ + public function testGetFileTypeIdentifierWrongType() { + $obj = $this->fileManager->getModelInstance('docment', 'product'); + } + + /** + * @expectedException \Thelia\Exception\FileException + */ + public function testGetFileTypeIdentifierWrongObject() { + $obj = $this->fileManager->getModelInstance('document', 'poney'); + } + + /** + * @expectedException \Thelia\Exception\FileException + */ + public function testGetFileTypeIdentifierWrongTypeAndObject() { + $obj = $this->fileManager->getModelInstance('licorne', 'poney'); + } + + public function testAddFileModel() { + $this->fileManager->addFileModel("licorne", "poney", "Thelia\\Model\\ProductDocument"); + + $obj = $this->fileManager->getModelInstance('licorne', 'poney'); + + $this->assertInstanceOf("Thelia\\Model\\ProductDocument", $obj); + } + + /** + * @expectedException \Thelia\Exception\FileException + */ + public function addFileModelWrongClassTest() { + $this->fileManager->addFileModel("licorne", "poney", "Thelia\\Model\\Product"); + + $obj = $this->fileManager->getModelInstance('licorne', 'poney'); + } + + public function dotTestImageUpload($model, $type) { + + $old_file = $model->getFile(); + + $model->setFile(null)->save(); + + $testFile = __DIR__ .DS. 'fixtures' .DS. 'move-test.gif'; + $targetFile = THELIA_LOCAL_DIR . 'media'.DS.'images'.DS.$type.DS."original-".$model->getId().".gif"; + + @unlink($testFile); + @unlink($targetFile); + + copy(__DIR__ .DS. 'fixtures' .DS. 'test.gif', $testFile); + + $uploadedFile = new UploadedFile( + $testFile, + 'original.gif', + 'image/gif', + filesize($testFile), + UPLOAD_ERR_OK, + true + ); + + $file = $this->fileManager->copyUploadedFile($model, $uploadedFile); + + $this->assertEquals("".$file, $targetFile); + + $this->assertEquals(basename($targetFile), $model->getFile()); + + $this->assertFileExists($targetFile); + + @unlink($targetFile); + @unlink($testFile); + + $model->setFile($old_file)->save(); + } + + public function dotTestDocumentUpload($model, $type) { + + $old_file = $model->getFile(); + + $model->setFile(null)->save(); + + $testFile = __DIR__ .DS. 'fixtures' .DS. 'move-test.txt'; + $targetFile = THELIA_LOCAL_DIR . 'media'.DS.'documents'.DS.$type.DS."original-".$model->getId().".txt"; + + @unlink($testFile); + @unlink($targetFile); + + copy(__DIR__ .DS. 'fixtures' .DS. 'test.txt', $testFile); + + $uploadedFile = new UploadedFile( + $testFile, + 'original.txt', + 'plain/text', + filesize($testFile), + UPLOAD_ERR_OK, + true + ); + + $file = $this->fileManager->copyUploadedFile($model, $uploadedFile); + + $this->assertEquals("".$file, $targetFile); + + $this->assertEquals(basename($targetFile), $model->getFile()); + + $this->assertFileExists($targetFile); + + @unlink($targetFile); + @unlink($testFile); + + $model->setFile($old_file)->save(); + } + + public function testCopyUploadedFileProductImage() { + $this->dotTestImageUpload( + ProductImageQuery::create()->findOne(), + 'product' + ); + } + + public function testCopyUploadedFileCategoryImage() { + $this->dotTestImageUpload( + CategoryImageQuery::create()->findOne(), + 'category' + ); + } + + public function testCopyUploadedFileContentImage() { + $this->dotTestImageUpload( + ContentImageQuery::create()->findOne(), + 'content' + ); + } + + public function testCopyUploadedFileFolderImage() { + $this->dotTestImageUpload( + FolderImageQuery::create()->findOne(), + 'folder' + ); + } + + public function testCopyUploadedFileBrandImage() { + $this->dotTestImageUpload( + BrandImageQuery::create()->findOne(), + 'brand' + ); + } + + public function testCopyUploadedFileProductDocument() { + $this->dotTestDocumentUpload( + ProductDocumentQuery::create()->findOne(), + 'product' + ); + } + + public function testCopyUploadedFileCategoryDocument() { + $this->dotTestDocumentUpload( + CategoryDocumentQuery::create()->findOne(), + 'category' + ); + } + + public function testCopyUploadedFileContentDocument() { + $this->dotTestDocumentUpload( + ContentDocumentQuery::create()->findOne(), + 'content' + ); + } + + public function testCopyUploadedFileFolderDocument() { + $this->dotTestDocumentUpload( + FolderDocumentQuery::create()->findOne(), + 'folder' + ); + } + + public function testCopyUploadedFileBrandDocument() { + $this->dotTestDocumentUpload( + BrandDocumentQuery::create()->findOne(), + 'brand' + ); + } + + public function testSanitizeFileName() { + $file = $this->fileManager->sanitizeFileName("C:\\../test/\\..file/%ù^name \t\n\r²&²:.txt"); + + $this->assertEquals("c..test..filename.txt", $file); + + $file = $this->fileManager->sanitizeFileName("/etc/passwd"); + + $this->assertEquals("etcpasswd", $file); + } + + public function doTestDeleteFile($model, $modelParent, $type, $obj) { + + $targetFile = THELIA_LOCAL_DIR . 'media'.DS.$type.DS.$obj.DS."original-".$model->getId().".txt"; + + $model->setParentId($modelParent->getId())->setFile(basename($targetFile))->save(); + + @unlink($targetFile); + + copy(__DIR__ .DS. 'fixtures' .DS. 'test.txt', $targetFile); + + $this->assertFileExists($targetFile); + + $this->fileManager->deleteFile($model); + + $this->assertFileNotExists($targetFile); + } + + public function testDeleteFileProductDocument() { + $this->doTestDeleteFile( + new ProductDocument(), + ProductQuery::create()->findOne(), + 'documents', 'product' + ); + } + + public function testDeleteFileProductImage() { + $this->doTestDeleteFile( + new ProductImage(), + ProductQuery::create()->findOne(), + 'images', 'product' + ); + } + + + public function testDeleteFileCategoryDocument() { + $this->doTestDeleteFile( + new CategoryDocument(), + CategoryQuery::create()->findOne(), + 'documents', 'category' + ); + } + + public function testDeleteFileCategoryImage() { + $this->doTestDeleteFile( + new CategoryImage(), + CategoryQuery::create()->findOne(), + 'images', 'category' + ); + } + public function testDeleteFileFolderDocument() { + $this->doTestDeleteFile( + new FolderDocument(), + FolderQuery::create()->findOne(), + 'documents', 'folder' + ); + } + + public function testDeleteFileFolderImage() { + $this->doTestDeleteFile( + new FolderImage(), + FolderQuery::create()->findOne(), + 'images', 'folder' + ); + } + + public function testDeleteFileContentDocument() { + $this->doTestDeleteFile( + new ContentDocument(), + ContentQuery::create()->findOne(), + 'documents', 'content' + ); + } + + public function testDeleteFileContentImage() { + $this->doTestDeleteFile( + new ContentImage(), + ContentQuery::create()->findOne(), + 'images', 'content' + ); + } + public function testDeleteFileBrandDocument() { + $this->doTestDeleteFile( + new BrandDocument(), + BrandQuery::create()->findOne(), + 'documents', 'brand' + ); + } + + public function testDeleteFileBrandImage() { + $this->doTestDeleteFile( + new BrandImage(), + BrandQuery::create()->findOne(), + 'images', 'brand' + ); + } + +} \ No newline at end of file diff --git a/core/lib/Thelia/Tests/Files/fixtures/test.gif b/core/lib/Thelia/Tests/Files/fixtures/test.gif new file mode 100644 index 0000000000000000000000000000000000000000..b636f4b8df536b0a85e7cea1a6cf3f0bd3179b96 GIT binary patch literal 35 jcmZ?wbh9u|WMp7uXkcLY4+c66KmZb9U}AD%WUvMRyAlZ1 literal 0 HcmV?d00001 diff --git a/core/lib/Thelia/Tests/Files/fixtures/test.txt b/core/lib/Thelia/Tests/Files/fixtures/test.txt new file mode 100644 index 0000000000000000000000000000000000000000..b636f4b8df536b0a85e7cea1a6cf3f0bd3179b96 GIT binary patch literal 35 jcmZ?wbh9u|WMp7uXkcLY4+c66KmZb9U}AD%WUvMRyAlZ1 literal 0 HcmV?d00001 diff --git a/core/lib/Thelia/Tests/Tools/FileManagerTest.php b/core/lib/Thelia/Tests/Tools/FileManagerTest.php deleted file mode 100644 index 8c9de5965..000000000 --- a/core/lib/Thelia/Tests/Tools/FileManagerTest.php +++ /dev/null @@ -1,901 +0,0 @@ -markTestIncomplete( - 'This test has not been implemented yet : Mock issue' - ); - - $stubTranslator = $this->getMockBuilder('\Thelia\Core\Translation\Translator') - ->disableOriginalConstructor() - ->getMock(); - $stubTranslator->expects($this->any()) - ->method('trans') - ->will($this->returnValue('translated')); - - $stubRequest = $this->getMockBuilder('\Thelia\Core\HttpFoundation\Request') - ->disableOriginalConstructor() - ->getMock(); - - $stubSecurity = $this->getMockBuilder('\Thelia\Core\Security\SecurityContext') - ->disableOriginalConstructor() - ->getMock(); - $stubSecurity->expects($this->any()) - ->method('getAdminUser') - ->will($this->returnValue(new Admin())); - - // Create a map of arguments to return values. - $map = array( - array('thelia.translator', $stubTranslator), - array('request', $stubRequest), - array('thelia.securityContext', $stubSecurity) - ); - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - $stubContainer->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - - $stubProductImage = $this->getMockBuilder('\Thelia\Model\ProductImage') - ->disableOriginalConstructor() - ->getMock(); - $stubProductImage->expects($this->any()) - ->method('getUploadDir') - ->will($this->returnValue(THELIA_LOCAL_DIR . 'media/images/product')); - $stubProductImage->expects($this->any()) - ->method('getId') - ->will($this->returnValue(42)); - $stubProductImage->expects($this->any()) - ->method('setFile') - ->will($this->returnValue(true)); - $stubProductImage->expects($this->any()) - ->method('save') - ->will($this->returnValue(0)); - - $stubUploadedFile = $this->getMockBuilder('\Symfony\Component\HttpFoundation\File\UploadedFile') - ->disableOriginalConstructor() - ->getMock(); - $stubUploadedFile->expects($this->any()) - ->method('getClientOriginalName') - ->will($this->returnValue('goodName')); - $stubUploadedFile->expects($this->any()) - ->method('getClientOriginalExtension') - ->will($this->returnValue('png')); - $stubUploadedFile->expects($this->any()) - ->method('move') - ->will($this->returnValue($stubUploadedFile)); - - $fileManager = new FileManager($stubContainer); - - $newUploadedFiles = array(); - - $actual = $fileManager->copyUploadedFile(24, FileManager::TYPE_PRODUCT, $stubProductImage, $stubUploadedFile, $newUploadedFiles, FileManager::FILE_TYPE_IMAGES); - - $this->assertCount(1, $actual); - }*/ - - /** - * @covers Thelia\Tools\FileManager::copyUploadedFile - * @expectedException \Thelia\Exception\ImageException - */ - /*public function testCopyUploadedFileExceptionImageException() - { - $this->markTestIncomplete( - 'This test has not been implemented yet : Mock issue' - ); - - $stubTranslator = $this->getMockBuilder('\Thelia\Core\Translation\Translator') - ->disableOriginalConstructor() - ->getMock(); - $stubTranslator->expects($this->any()) - ->method('trans') - ->will($this->returnValue('translated')); - - $stubRequest = $this->getMockBuilder('\Thelia\Core\HttpFoundation\Request') - ->disableOriginalConstructor() - ->getMock(); - - $stubSecurity = $this->getMockBuilder('\Thelia\Core\Security\SecurityContext') - ->disableOriginalConstructor() - ->getMock(); - $stubSecurity->expects($this->any()) - ->method('getAdminUser') - ->will($this->returnValue(new Admin())); - - // Create a map of arguments to return values. - $map = array( - array('thelia.translator', $stubTranslator), - array('request', $stubRequest), - array('thelia.securityContext', $stubSecurity) - ); - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - $stubContainer->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - - $stubProductImage = $this->getMockBuilder('\Thelia\Model\ProductImage') - ->disableOriginalConstructor() - ->getMock(); - $stubProductImage->expects($this->any()) - ->method('getUploadDir') - ->will($this->returnValue(THELIA_LOCAL_DIR . 'media/images/product')); - $stubProductImage->expects($this->any()) - ->method('getId') - ->will($this->returnValue(42)); - $stubProductImage->expects($this->any()) - ->method('setFile') - ->will($this->returnValue(true)); - $stubProductImage->expects($this->any()) - ->method('save') - ->will($this->returnValue(0)); - - $stubUploadedFile = $this->getMockBuilder('\Symfony\Component\HttpFoundation\File\UploadedFile') - ->disableOriginalConstructor() - ->getMock(); - $stubUploadedFile->expects($this->any()) - ->method('getClientOriginalName') - ->will($this->returnValue('goodName')); - $stubUploadedFile->expects($this->any()) - ->method('getClientOriginalExtension') - ->will($this->returnValue('png')); - $stubUploadedFile->expects($this->any()) - ->method('move') - ->will($this->returnValue($stubUploadedFile)); - - $fileManager = new FileManager($stubContainer); - - $newUploadedFiles = array(); - - $actual = $fileManager->copyUploadedFile(24, FileManager::TYPE_PRODUCT, $stubProductImage, $stubUploadedFile, $newUploadedFiles, FileManager::FILE_TYPE_DOCUMENTS); - - }*/ - - /** - * @covers Thelia\Tools\FileManager::saveImage - */ - public function testSaveImageProductImage() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $stubProductImage = $this->getMockBuilder('\Thelia\Model\ProductImage') - ->disableOriginalConstructor() - ->getMock(); - $stubProductImage->expects($this->any()) - ->method('save') - ->will($this->returnValue(10)); - $stubProductImage->expects($this->any()) - ->method('getFile') - ->will($this->returnValue('file')); - - $fileManager = new FileManager(); - - $event = new ImageCreateOrUpdateEvent(FileManager::TYPE_PRODUCT, 24); - - $expected = 10; - $actual = $fileManager->saveImage($event, $stubProductImage); - - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::saveDocument - */ - public function testSaveDocumentProductDocument() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $stubProductDocument = $this->getMockBuilder('\Thelia\Model\ProductDocument') - ->disableOriginalConstructor() - ->getMock(); - $stubProductDocument->expects($this->any()) - ->method('save') - ->will($this->returnValue(10)); - $stubProductDocument->expects($this->any()) - ->method('getFile') - ->will($this->returnValue('file')); - - $fileManager = new FileManager(); - - $event = new DocumentCreateOrUpdateEvent(FileManager::TYPE_PRODUCT, 24); - - $expected = 10; - $actual = $fileManager->saveDocument($event, $stubProductDocument); - - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::saveImage - */ - public function testSaveImageCategoryImage() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $stubCategoryImage = $this->getMockBuilder('\Thelia\Model\CategoryImage') - ->disableOriginalConstructor() - ->getMock(); - $stubCategoryImage->expects($this->any()) - ->method('save') - ->will($this->returnValue(10)); - $stubCategoryImage->expects($this->any()) - ->method('getFile') - ->will($this->returnValue('file')); - - $fileManager = new FileManager(); - - $event = new ImageCreateOrUpdateEvent(FileManager::TYPE_CATEGORY, 24); - - $expected = 10; - $actual = $fileManager->saveImage($event, $stubCategoryImage); - - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::saveDocument - */ - public function testSaveDocumentCategoryDocument() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $stubCategoryDocument = $this->getMockBuilder('\Thelia\Model\CategoryDocument') - ->disableOriginalConstructor() - ->getMock(); - $stubCategoryDocument->expects($this->any()) - ->method('save') - ->will($this->returnValue(10)); - $stubCategoryDocument->expects($this->any()) - ->method('getFile') - ->will($this->returnValue('file')); - - $fileManager = new FileManager(); - - $event = new DocumentCreateOrUpdateEvent(FileManager::TYPE_CATEGORY, 24); - - $expected = 10; - $actual = $fileManager->saveDocument($event, $stubCategoryDocument); - - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::saveImage - */ - public function testSaveImageFolderImage() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $stubFolderImage = $this->getMockBuilder('\Thelia\Model\FolderImage') - ->disableOriginalConstructor() - ->getMock(); - $stubFolderImage->expects($this->any()) - ->method('save') - ->will($this->returnValue(10)); - $stubFolderImage->expects($this->any()) - ->method('getFile') - ->will($this->returnValue('file')); - - $fileManager = new FileManager(); - - $event = new ImageCreateOrUpdateEvent(FileManager::TYPE_FOLDER, 24); - - $expected = 10; - $actual = $fileManager->saveImage($event, $stubFolderImage); - - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::saveDocument - */ - public function testSaveDocumentFolderDocument() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $stubFolderDocument = $this->getMockBuilder('\Thelia\Model\FolderDocument') - ->disableOriginalConstructor() - ->getMock(); - $stubFolderDocument->expects($this->any()) - ->method('save') - ->will($this->returnValue(10)); - $stubFolderDocument->expects($this->any()) - ->method('getFile') - ->will($this->returnValue('file')); - - $fileManager = new FileManager(); - - $event = new DocumentCreateOrUpdateEvent(FileManager::TYPE_FOLDER, 24); - - $expected = 10; - $actual = $fileManager->saveDocument($event, $stubFolderDocument); - - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::saveImage - */ - public function testSaveImageContentImage() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $stubContentImage = $this->getMockBuilder('\Thelia\Model\ContentImage') - ->disableOriginalConstructor() - ->getMock(); - $stubContentImage->expects($this->any()) - ->method('save') - ->will($this->returnValue(10)); - $stubContentImage->expects($this->any()) - ->method('getFile') - ->will($this->returnValue('file')); - - $fileManager = new FileManager(); - - $event = new ImageCreateOrUpdateEvent(FileManager::TYPE_CONTENT, 24); - - $expected = 10; - $actual = $fileManager->saveImage($event, $stubContentImage); - - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::saveDocument - */ - public function testSaveDocumentContentDocument() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $stubContentDocument = $this->getMockBuilder('\Thelia\Model\ContentDocument') - ->disableOriginalConstructor() - ->getMock(); - $stubContentDocument->expects($this->any()) - ->method('save') - ->will($this->returnValue(10)); - $stubContentDocument->expects($this->any()) - ->method('getFile') - ->will($this->returnValue('file')); - - $fileManager = new FileManager(); - - $event = new DocumentCreateOrUpdateEvent(FileManager::TYPE_CONTENT, 24); - - $expected = 10; - $actual = $fileManager->saveDocument($event, $stubContentDocument); - - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::saveImage - * @expectedException \Thelia\Exception\ImageException - */ - public function testSaveImageExceptionImageException() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - $fileManager = new FileManager(); - - $stubProductImage = $this->getMockBuilder('\Thelia\Model\ProductImage') - ->disableOriginalConstructor() - ->getMock(); - $stubProductImage->expects($this->any()) - ->method('save') - ->will($this->returnValue(10)); - $stubProductImage->expects($this->any()) - ->method('getFile') - ->will($this->returnValue('file')); - - $event = new ImageCreateOrUpdateEvent('bad', 24); - - $fileManager->saveImage($event, $stubProductImage); - } - - /** - * @covers Thelia\Tools\FileManager::saveDocument - * @expectedException \Thelia\Model\Exception\InvalidArgumentException - */ - public function testSaveDocumentExceptionDocumentException() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - $fileManager = new FileManager(); - - $stubProductDocument = $this->getMockBuilder('\Thelia\Model\ProductDocument') - ->disableOriginalConstructor() - ->getMock(); - $stubProductDocument->expects($this->any()) - ->method('save') - ->will($this->returnValue(10)); - $stubProductDocument->expects($this->any()) - ->method('getFile') - ->will($this->returnValue('file')); - - $event = new DocumentCreateOrUpdateEvent('bad', 24); - - $fileManager->saveDocument($event, $stubProductDocument); - } - - /** - * @covers Thelia\Tools\FileManager::saveImage - * @expectedException \Thelia\Exception\ImageException - */ - public function testSaveImageExceptionImageException2() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - $fileManager = new FileManager(); - - $stubProductImage = $this->getMockBuilder('\Thelia\Model\ProductImage') - ->disableOriginalConstructor() - ->getMock(); - $stubProductImage->expects($this->any()) - ->method('save') - ->will($this->returnValue(0)); - $stubProductImage->expects($this->any()) - ->method('getFile') - ->will($this->returnValue('file')); - - $event = new ImageCreateOrUpdateEvent(FileManager::TYPE_PRODUCT, 24); - - $fileManager->saveImage($event, $stubProductImage); - } - - /** - * @covers Thelia\Tools\FileManager::saveDocument - * @expectedException \Thelia\Model\Exception\InvalidArgumentException - */ - public function testSaveDocumentExceptionDocumentException2() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - $fileManager = new FileManager(); - - $stubProductDocument = $this->getMockBuilder('\Thelia\Model\ProductDocument') - ->disableOriginalConstructor() - ->getMock(); - $stubProductDocument->expects($this->any()) - ->method('save') - ->will($this->returnValue(0)); - $stubProductDocument->expects($this->any()) - ->method('getFile') - ->will($this->returnValue('file')); - - $event = new DocumentCreateOrUpdateEvent(FileManager::TYPE_PRODUCT, 24); - - $fileManager->saveDocument($event, $stubProductDocument); - } - - /** - * @covers Thelia\Tools\FileManager::sanitizeFileName - */ - public function testSanitizeFileName() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $fileManager = new FileManager(); - $badFileName = 'a/ze\érà~çè§^"$*+-_°)(&é<>@#ty2/[\/:*?"<>|]/fi?.fUPPERile.exel../e*'; - - $expected = 'azer-_ty2fi.fupperile.exel..e'; - $actual = $fileManager->sanitizeFileName($badFileName); - - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::getImageModel - */ - public function testGetImageModel() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $fileManager = new FileManager(); - $actual = $fileManager->getImageModel(FileManager::TYPE_PRODUCT); - $this->assertInstanceOf('\Thelia\Model\ProductImage', $actual); - $actual = $fileManager->getImageModel(FileManager::TYPE_CATEGORY); - $this->assertInstanceOf('\Thelia\Model\CategoryImage', $actual); - $actual = $fileManager->getImageModel(FileManager::TYPE_CONTENT); - $this->assertInstanceOf('\Thelia\Model\ContentImage', $actual); - $actual = $fileManager->getImageModel(FileManager::TYPE_FOLDER); - $this->assertInstanceOf('\Thelia\Model\FolderImage', $actual); - $actual = $fileManager->getImageModel('bad'); - $this->assertNull($actual); - } - - /** - * @covers Thelia\Tools\FileManager::getDocumentModel - */ - public function testGetDocumentModel() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $fileManager = new FileManager(); - $actual = $fileManager->getDocumentModel(FileManager::TYPE_PRODUCT); - $this->assertInstanceOf('\Thelia\Model\ProductDocument', $actual); - $actual = $fileManager->getDocumentModel(FileManager::TYPE_CATEGORY); - $this->assertInstanceOf('\Thelia\Model\CategoryDocument', $actual); - $actual = $fileManager->getDocumentModel(FileManager::TYPE_CONTENT); - $this->assertInstanceOf('\Thelia\Model\ContentDocument', $actual); - $actual = $fileManager->getDocumentModel(FileManager::TYPE_FOLDER); - $this->assertInstanceOf('\Thelia\Model\FolderDocument', $actual); - $actual = $fileManager->getDocumentModel('bad'); - $this->assertNull($actual); - } - - /** - * @covers Thelia\Tools\FileManager::getImageModelQuery - */ - public function testGetImageModelQuery() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $fileManager = new FileManager(); - $actual = $fileManager->getImageModelQuery(FileManager::TYPE_PRODUCT); - $this->assertInstanceOf('\Thelia\Model\ProductImageQuery', $actual); - $actual = $fileManager->getImageModelQuery(FileManager::TYPE_CATEGORY); - $this->assertInstanceOf('\Thelia\Model\CategoryImageQuery', $actual); - $actual = $fileManager->getImageModelQuery(FileManager::TYPE_CONTENT); - $this->assertInstanceOf('\Thelia\Model\ContentImageQuery', $actual); - $actual = $fileManager->getImageModelQuery(FileManager::TYPE_FOLDER); - $this->assertInstanceOf('\Thelia\Model\FolderImageQuery', $actual); - $actual = $fileManager->getImageModelQuery('bad'); - $this->assertNull($actual); - } - - /** - * @covers Thelia\Tools\FileManager::getDocumentModelQuery - */ - public function testGetDocumentModelQuery() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $fileManager = new FileManager(); - $actual = $fileManager->getDocumentModelQuery(FileManager::TYPE_PRODUCT); - $this->assertInstanceOf('\Thelia\Model\ProductDocumentQuery', $actual); - $actual = $fileManager->getDocumentModelQuery(FileManager::TYPE_CATEGORY); - $this->assertInstanceOf('\Thelia\Model\CategoryDocumentQuery', $actual); - $actual = $fileManager->getDocumentModelQuery(FileManager::TYPE_CONTENT); - $this->assertInstanceOf('\Thelia\Model\ContentDocumentQuery', $actual); - $actual = $fileManager->getDocumentModelQuery(FileManager::TYPE_FOLDER); - $this->assertInstanceOf('\Thelia\Model\FolderDocumentQuery', $actual); - $actual = $fileManager->getDocumentModelQuery('bad'); - $this->assertNull($actual); - } - - /** - * @covers Thelia\Tools\FileManager::getParentFileModel - */ - public function testGetParentFileModel() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $fileManager = new FileManager(); - $actual = $fileManager->getParentFileModel(FileManager::TYPE_PRODUCT, ProductQuery::create()->findOne()->getId()); - $this->assertInstanceOf('\Thelia\Model\Product', $actual); - $actual = $fileManager->getParentFileModel(FileManager::TYPE_CATEGORY, CategoryQuery::create()->findOne()->getId()); - $this->assertInstanceOf('\Thelia\Model\Category', $actual); - $actual = $fileManager->getParentFileModel(FileManager::TYPE_CONTENT, ContentQuery::create()->findOne()->getId()); - $this->assertInstanceOf('\Thelia\Model\Content', $actual); - $actual = $fileManager->getParentFileModel(FileManager::TYPE_FOLDER, FolderQuery::create()->findOne()->getId()); - $this->assertInstanceOf('\Thelia\Model\Folder', $actual, 1); - $actual = $fileManager->getParentFileModel('bad', 1); - $this->assertNull($actual); - } - - /** - * @covers Thelia\Tools\FileManager::getImageForm - */ -/* public function testGetImageForm() - { - // Mock issue - $this->markTestIncomplete( - 'This test has not been implemented yet.' - ); - }*/ - /** - * @covers Thelia\Tools\FileManager::getDocumentForm - */ -/* public function testGetDocumentForm() - { - // Mock issue - $this->markTestIncomplete( - 'This test has not been implemented yet.' - ); - }*/ - - /** - * @covers Thelia\Tools\FileManager::getUploadDir - */ - public function testGetUploadDir() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $fileManager = new FileManager(); - - $actual = $fileManager->getUploadDir(FileManager::TYPE_PRODUCT, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals(THELIA_LOCAL_DIR . 'media/images/product', $actual); - $actual = $fileManager->getUploadDir(FileManager::TYPE_CATEGORY, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals(THELIA_LOCAL_DIR . 'media/images/category', $actual); - $actual = $fileManager->getUploadDir(FileManager::TYPE_CONTENT, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals(THELIA_LOCAL_DIR . 'media/images/content', $actual); - $actual = $fileManager->getUploadDir(FileManager::TYPE_FOLDER, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals(THELIA_LOCAL_DIR . 'media/images/folder', $actual); - $actual = $fileManager->getUploadDir('bad', FileManager::FILE_TYPE_IMAGES); - $this->assertEquals(false, $actual); - - $actual = $fileManager->getUploadDir(FileManager::TYPE_PRODUCT, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals(THELIA_LOCAL_DIR . 'media/documents/product', $actual); - $actual = $fileManager->getUploadDir(FileManager::TYPE_CATEGORY, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals(THELIA_LOCAL_DIR . 'media/documents/category', $actual); - $actual = $fileManager->getUploadDir(FileManager::TYPE_CONTENT, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals(THELIA_LOCAL_DIR . 'media/documents/content', $actual); - $actual = $fileManager->getUploadDir(FileManager::TYPE_FOLDER, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals(THELIA_LOCAL_DIR . 'media/documents/folder', $actual); - $actual = $fileManager->getUploadDir('bad', FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals(false, $actual); - - $actual = $fileManager->getUploadDir(FileManager::TYPE_FOLDER, 'bad'); - $this->assertEquals(false, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::getRedirectionUrl - */ - public function testGetRedirectionUrl() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $fileManager = new FileManager(); - - $actual = $fileManager->getRedirectionUrl(FileManager::TYPE_PRODUCT, 1, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals('/admin/products/update?product_id=1¤t_tab=images', $actual); - $actual = $fileManager->getRedirectionUrl(FileManager::TYPE_CATEGORY, 1, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals('/admin/categories/update?category_id=1¤t_tab=images', $actual); - $actual = $fileManager->getRedirectionUrl(FileManager::TYPE_CONTENT, 1, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals('/admin/content/update/1?current_tab=images', $actual); - $actual = $fileManager->getRedirectionUrl(FileManager::TYPE_FOLDER, 1, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals('/admin/folders/update/1?current_tab=images', $actual); - $actual = $fileManager->getRedirectionUrl('bad', 1, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals(false, $actual); - - $actual = $fileManager->getRedirectionUrl(FileManager::TYPE_PRODUCT, 1, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals('/admin/products/update?product_id=1¤t_tab=documents', $actual); - $actual = $fileManager->getRedirectionUrl(FileManager::TYPE_CATEGORY, 1, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals('/admin/categories/update?category_id=1¤t_tab=documents', $actual); - $actual = $fileManager->getRedirectionUrl(FileManager::TYPE_CONTENT, 1, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals('/admin/content/update/1?current_tab=documents', $actual); - $actual = $fileManager->getRedirectionUrl(FileManager::TYPE_FOLDER, 1, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals('/admin/folders/update/1?current_tab=documents', $actual); - $actual = $fileManager->getRedirectionUrl('bad', 1, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals(false, $actual); - - $actual = $fileManager->getRedirectionUrl(FileManager::TYPE_FOLDER, 1, 'bad'); - $this->assertEquals(false, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::getFormId - */ - public function testGetFormId() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $fileManager = new FileManager(); - - $actual = $fileManager->getFormId(FileManager::TYPE_PRODUCT, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals('thelia.admin.product.image.modification', $actual); - $actual = $fileManager->getFormId(FileManager::TYPE_CATEGORY, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals('thelia.admin.category.image.modification', $actual); - $actual = $fileManager->getFormId(FileManager::TYPE_CONTENT, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals('thelia.admin.content.image.modification', $actual); - $actual = $fileManager->getFormId(FileManager::TYPE_FOLDER, FileManager::FILE_TYPE_IMAGES); - $this->assertEquals('thelia.admin.folder.image.modification', $actual); - $actual = $fileManager->getFormId('bad', FileManager::FILE_TYPE_IMAGES); - $this->assertEquals(false, $actual); - - $actual = $fileManager->getFormId(FileManager::TYPE_PRODUCT, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals('thelia.admin.product.document.modification', $actual); - $actual = $fileManager->getFormId(FileManager::TYPE_CATEGORY, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals('thelia.admin.category.document.modification', $actual); - $actual = $fileManager->getFormId(FileManager::TYPE_CONTENT, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals('thelia.admin.content.document.modification', $actual); - $actual = $fileManager->getFormId(FileManager::TYPE_FOLDER, FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals('thelia.admin.folder.document.modification', $actual); - $actual = $fileManager->getFormId('bad', FileManager::FILE_TYPE_DOCUMENTS); - $this->assertEquals(false, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::renameFile - */ - public function testRenameFile() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $stubUploadedFile = $this->getMockBuilder('\Symfony\Component\HttpFoundation\File\UploadedFile') - ->setConstructorArgs([__DIR__ . '/fixtures/test.xml', 'test.xml']) - ->getMock(); - $stubUploadedFile->expects($this->any()) - ->method('getClientOriginalExtension') - ->will($this->returnValue('yml')); - $stubUploadedFile->expects($this->any()) - ->method('getClientOriginalName') - ->will($this->returnValue('or1-g_n?al*/&é"filen@me#')); - - $fileManager = new FileManager(); - - $expected = 'or1-g_nalfilenme-1.yml'; - $actual = $fileManager->renameFile(1, $stubUploadedFile); - - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::renameFile - */ - public function testRenameFileWithoutExtension() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $stubUploadedFile = $this->getMockBuilder('\Symfony\Component\HttpFoundation\File\UploadedFile') - ->setConstructorArgs([__DIR__ . '/fixtures/test.xml', 'test.xml']) - ->getMock(); - - $stubUploadedFile->expects($this->any()) - ->method('getClientOriginalExtension') - ->will($this->returnValue('')); - $stubUploadedFile->expects($this->any()) - ->method('getClientOriginalName') - ->will($this->returnValue('or1-g_n?al*/&é"filen@me#')); - - $fileManager = new FileManager(); - - $expected = 'or1-g_nalfilenme-1'; - $actual = $fileManager->renameFile(1, $stubUploadedFile); - - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::isImage - */ - public function testIsImage() - { - $stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface') - ->disableOriginalConstructor() - ->getMock(); - - $fileManager = new FileManager(); - - $actual = $fileManager->isImage('image/jpeg'); - $this->assertTrue($actual); - $actual = $fileManager->isImage('image/png'); - $this->assertTrue($actual); - $actual = $fileManager->isImage('image/gif'); - $this->assertTrue($actual); - - $actual = $fileManager->isImage('bad'); - $this->assertFalse($actual); - $actual = $fileManager->isImage('image/jpg'); - $this->assertFalse($actual); - $actual = $fileManager->isImage('application/x-msdownload'); - $this->assertFalse($actual); - $actual = $fileManager->isImage('application/x-sh'); - $this->assertFalse($actual); - - } - - /** - * @covers Thelia\Tools\FileManager::getAvailableTypes - */ - public function testGetAvailableTypes() - { - $expected = array( - FileManager::TYPE_CATEGORY, - FileManager::TYPE_CONTENT, - FileManager::TYPE_FOLDER, - FileManager::TYPE_PRODUCT, - FileManager::TYPE_MODULE, - ); - $actual = FileManager::getAvailableTypes(); - - $this->assertEquals($expected, $actual); - } - - /** - * @covers Thelia\Tools\FileManager::adminLogAppend - */ -/* public function testAdminLogAppend() - { - $this->markTestIncomplete( - 'This test has not been implemented yet.' - ); - }*/ - - /** - * @covers Thelia\Tools\FileManager::deleteFile - */ - /* public function testDeleteFile() - { - // @todo see http://tech.vg.no/2011/03/09/mocking-the-file-system-using-phpunit-and-vfsstream/ - $this->markTestIncomplete( - 'This test has not been implemented yet.' - ); - }*/ -} diff --git a/core/lib/Thelia/Tools/FileManager.php b/core/lib/Thelia/Tools/FileManager.php deleted file mode 100644 index 351283d8c..000000000 --- a/core/lib/Thelia/Tools/FileManager.php +++ /dev/null @@ -1,667 +0,0 @@ - - * - */ -class FileManager -{ - CONST TYPE_PRODUCT = 'product'; - CONST TYPE_CATEGORY = 'category'; - CONST TYPE_CONTENT = 'content'; - CONST TYPE_FOLDER = 'folder'; - CONST TYPE_MODULE = 'module'; - - CONST FILE_TYPE_IMAGES = 'images'; - CONST FILE_TYPE_DOCUMENTS = 'documents'; - - /** - * Copy UploadedFile into the server storage directory - * - * @param int $parentId Parent id - * @param string $parentType Image type - * @param FolderImage|ContentImage|CategoryImage|ProductImage|FolderDocument|ContentDocument|CategoryDocument|ProductDocument $model Model saved - * @param UploadedFile $uploadedFile Ready to be uploaded file - * @param string $fileType File type ex FileManager::FILE_TYPE_IMAGES - * - * @throws \Thelia\Exception\ImageException - * @return UploadedFile - */ - public function copyUploadedFile($parentId, $parentType, $model, $uploadedFile, $fileType) - { - $newUploadedFile = null; - if ($uploadedFile !== null) { - $directory = $this->getUploadDir($parentType, $fileType); - $fileName = $this->renameFile($model->getId(), $uploadedFile); - - $newUploadedFile = $uploadedFile->move($directory, $fileName); - $model->setFile($fileName); - - if (!$model->save()) { - throw new ImageException( - sprintf( - '%s %s (%s) failed to be saved (image file)', - ucfirst($parentType), - $model->getFile(), - $fileType - ) - ); - } - } - - return $newUploadedFile; - } - - /** - * Save image into the database - * - * @param ImageCreateOrUpdateEvent $event Image event - * @param FolderImage|ContentImage|CategoryImage|ProductImage $modelImage Image to save - * - * @return int Nb lines modified - * @throws \Thelia\Exception\ImageException - * @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action - */ - public function saveImage(ImageCreateOrUpdateEvent $event, $modelImage) - { - $nbModifiedLines = 0; - - if ($modelImage->getFile() !== null) { - switch ($event->getImageType()) { - case self::TYPE_PRODUCT: - /** @var ProductImage $modelImage */ - $modelImage->setProductId($event->getParentId()); - break; - case self::TYPE_CATEGORY: - /** @var CategoryImage $modelImage */ - $modelImage->setCategoryId($event->getParentId()); - break; - case self::TYPE_CONTENT: - /** @var ContentImage $modelImage */ - $modelImage->setContentId($event->getParentId()); - break; - case self::TYPE_FOLDER: - /** @var FolderImage $modelImage */ - $modelImage->setFolderId($event->getParentId()); - break; - default: - throw new ImageException( - sprintf( - 'Picture parent type is unknown (available types : %s)', - implode( - ',', - self::getAvailableTypes() - ) - ) - ); - } - - $nbModifiedLines = $modelImage->save(); - if (!$nbModifiedLines) { - throw new ImageException( - sprintf( - 'Image %s failed to be saved (image content)', - $modelImage->getFile() - ) - ); - } - } - - return $nbModifiedLines; - } - - /** - * Save document into the database - * - * @param DocumentCreateOrUpdateEvent $event Image event - * @param FolderDocument|ContentDocument|CategoryDocument|ProductDocument $modelDocument Document to save - * - * @throws \Thelia\Model\Exception\InvalidArgumentException - * @return int Nb lines modified - * @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action - */ - public function saveDocument(DocumentCreateOrUpdateEvent $event, $modelDocument) - { - $nbModifiedLines = 0; - - if ($modelDocument->getFile() !== null) { - switch ($event->getDocumentType()) { - case self::TYPE_PRODUCT: - /** @var ProductImage $modelImage */ - $modelDocument->setProductId($event->getParentId()); - break; - case self::TYPE_CATEGORY: - /** @var CategoryImage $modelImage */ - $modelDocument->setCategoryId($event->getParentId()); - break; - case self::TYPE_CONTENT: - /** @var ContentImage $modelImage */ - $modelDocument->setContentId($event->getParentId()); - break; - case self::TYPE_FOLDER: - /** @var FolderImage $modelImage */ - $modelDocument->setFolderId($event->getParentId()); - break; - default: - throw new InvalidArgumentException( - sprintf( - 'Document parent type is unknown (available types : %s)', - implode( - ',', - self::getAvailableTypes() - ) - ) - ); - } - - $nbModifiedLines = $modelDocument->save(); - if (!$nbModifiedLines) { - throw new InvalidArgumentException( - sprintf( - 'Document %s failed to be saved (document content)', - $modelDocument->getFile() - ) - ); - } - } - - return $nbModifiedLines; - } - - /** - * Sanitizes a filename replacing whitespace with dashes - * - * Removes special characters that are illegal in filenames on certain - * operating systems and special characters requiring special escaping - * to manipulate at the command line. - * - * @param string $string The filename to be sanitized - * - * @return string The sanitized filename - */ - public function sanitizeFileName($string) - { - return strtolower(preg_replace('/[^a-zA-Z0-9-_\.]/', '', $string)); - } - - /** - * Delete image from file storage and database - * - * @param CategoryImage|ProductImage|ContentImage|FolderImage|CategoryDocument|ProductDocument|ContentDocument|FolderDocument $model File being deleted - * @param string $parentType Parent type ex : self::TYPE_PRODUCT - * @param string $fileType File type ex FileManager::FILE_TYPE_DOCUMENTS - * - * @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action - */ - public function deleteFile($model, $parentType, $fileType) - { - $url = $this->getUploadDir($parentType, $fileType) . '/' . $model->getFile(); - unlink(str_replace('..', '', $url)); - $model->delete(); - } - - /** - * Get image model from type - * - * @param string $parentType Parent type ex : self::TYPE_PRODUCT - * - * @return null|\Thelia\Model\CategoryImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage|\Thelia\Model\ProductImage - * - * @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action - */ - public function getImageModel($parentType) - { - switch ($parentType) { - case self::TYPE_PRODUCT: - $model = new ProductImage(); - break; - case self::TYPE_CATEGORY: - $model = new CategoryImage(); - break; - case self::TYPE_CONTENT: - $model = new ContentImage(); - break; - case self::TYPE_FOLDER: - $model = new FolderImage(); - break; - default: - $model = null; - } - - return $model; - } - - /** - * Get document model from type - * - * @param string $parentType Parent type ex : self::TYPE_PRODUCT - * - * @return null|ProductDocument|CategoryDocument|ContentDocument|FolderDocument - * - * @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action - */ - public function getDocumentModel($parentType) - { - switch ($parentType) { - case self::TYPE_PRODUCT: - $model = new ProductDocument(); - break; - case self::TYPE_CATEGORY: - $model = new CategoryDocument(); - break; - case self::TYPE_CONTENT: - $model = new ContentDocument(); - break; - case self::TYPE_FOLDER: - $model = new FolderDocument(); - break; - default: - $model = null; - } - - return $model; - } - - /** - * Get image model query from type - * - * @param string $parentType Parent type ex : self::TYPE_PRODUCT - * - * @return null|\Thelia\Model\CategoryImageQuery|\Thelia\Model\ContentImageQuery|\Thelia\Model\FolderImageQuery|\Thelia\Model\ProductImageQuery - * - * @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action - */ - public function getImageModelQuery($parentType) - { - switch ($parentType) { - case self::TYPE_PRODUCT: - $model = new ProductImageQuery(); - break; - case self::TYPE_CATEGORY: - $model = new CategoryImageQuery(); - break; - case self::TYPE_CONTENT: - $model = new ContentImageQuery(); - break; - case self::TYPE_FOLDER: - $model = new FolderImageQuery(); - break; - default: - $model = null; - } - - return $model; - } - - /** - * Get document model query from type - * - * @param string $parentType Parent type ex : self::TYPE_PRODUCT - * - * @return null|ProductDocumentQuery|CategoryDocumentQuery|ContentDocumentQuery|FolderDocumentQuery - * - * @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action - */ - public function getDocumentModelQuery($parentType) - { - switch ($parentType) { - case self::TYPE_PRODUCT: - $model = new ProductDocumentQuery(); - break; - case self::TYPE_CATEGORY: - $model = new CategoryDocumentQuery(); - break; - case self::TYPE_CONTENT: - $model = new ContentDocumentQuery(); - break; - case self::TYPE_FOLDER: - $model = new FolderDocumentQuery(); - break; - default: - $model = null; - } - - return $model; - } - - /** - * Get form service id from type - * - * @param string $parentType Parent type ex : self::TYPE_PRODUCT - * @param string $fileType Parent id - * - * @return string - * - * @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action - */ - public function getFormId($parentType, $fileType) - { - switch ($fileType) { - case self::FILE_TYPE_IMAGES: - $type = 'image'; - break; - case self::FILE_TYPE_DOCUMENTS: - $type = 'document'; - break; - default: - return false; - } - - switch ($parentType) { - case self::TYPE_PRODUCT: - $formId = 'thelia.admin.product.' . $type . '.modification'; - break; - case self::TYPE_CATEGORY: - $formId = 'thelia.admin.category.' . $type . '.modification'; - break; - case self::TYPE_CONTENT: - $formId = 'thelia.admin.content.' . $type . '.modification'; - break; - case self::TYPE_FOLDER: - $formId = 'thelia.admin.folder.' . $type . '.modification'; - break; - default: - $formId = false; - } - - return $formId; - } - - /** - * Get image parent model from type - * - * @param string $parentType Parent type ex : self::TYPE_PRODUCT - * @param int $parentId Parent Id - * - * @return null|\Thelia\Model\Category|\Thelia\Model\Content|\Thelia\Model\Folder|\Thelia\Model\Product - * - * @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action - */ - public function getParentFileModel($parentType, $parentId) - { - switch ($parentType) { - case self::TYPE_PRODUCT: - $model = ProductQuery::create()->findPk($parentId); - break; - case self::TYPE_CATEGORY: - $model = CategoryQuery::create()->findPk($parentId); - break; - case self::TYPE_CONTENT: - $model = ContentQuery::create()->findPk($parentId); - break; - case self::TYPE_FOLDER: - $model = FolderQuery::create()->findPk($parentId); - break; - default: - $model = null; - } - - return $model; - } - - /** - * Get image parent model from type - * - * @param string $parentType Parent type ex : self::TYPE_PRODUCT - * @param Request $request Request service - * - * @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action - * @return ProductImageModification|CategoryImageModification|ContentImageModification|FolderImageModification - */ - public function getImageForm($parentType, Request $request) - { - switch ($parentType) { - case self::TYPE_PRODUCT: - $form = new ProductImageModification($request); - break; - case self::TYPE_CATEGORY: - $form = new CategoryImageModification($request); - break; - case self::TYPE_CONTENT: - $form = new ContentImageModification($request); - break; - case self::TYPE_FOLDER: - $form = new FolderImageModification($request); - break; - default: - $form = null; - } - - return $form; - - } - - /** - * Get document parent model from type - * - * @param string $parentType Parent type ex : self::TYPE_PRODUCT - * @param Request $request Request service - * - * @todo refactor make all document using propel inheritance and factorise image behaviour into one single clean action - * @return ProductDocumentModification|CategoryDocumentModification|ContentDocumentModification|FolderDocumentModification - */ - public function getDocumentForm($parentType, Request $request) - { - switch ($parentType) { - case self::TYPE_PRODUCT: - $form = new ProductDocumentModification($request); - break; - case self::TYPE_CATEGORY: - $form = new CategoryDocumentModification($request); - break; - case self::TYPE_CONTENT: - $form = new ContentDocumentModification($request); - break; - case self::TYPE_FOLDER: - $form = new FolderDocumentModification($request); - break; - default: - $form = null; - } - - return $form; - - } - - /** - * Get image upload dir - * - * @param string $parentType Parent type ex FileManager::TYPE_PRODUCT - * @param string $fileType File type ex : self::FILE_TYPE_DOCUMENTS - * - * @return string Uri - */ - public function getUploadDir($parentType, $fileType) - { - if (!in_array($fileType, self::$availableFileType)) { - return false; - } - - switch ($parentType) { - case self::TYPE_PRODUCT: - $uri = THELIA_LOCAL_DIR . 'media/' . $fileType . '/' . self::TYPE_PRODUCT; - break; - case self::TYPE_CATEGORY: - $uri = THELIA_LOCAL_DIR . 'media/' . $fileType . '/' . self::TYPE_CATEGORY; - break; - case self::TYPE_CONTENT: - $uri = THELIA_LOCAL_DIR . 'media/' . $fileType . '/' . self::TYPE_CONTENT; - break; - case self::TYPE_FOLDER: - $uri = THELIA_LOCAL_DIR . 'media/' . $fileType . '/' . self::TYPE_FOLDER; - break; - default: - $uri = false; - } - - return $uri; - - } - - /** - * Deduce image redirecting URL from parent type - * - * @param string $parentType Parent type ex : self::TYPE_PRODUCT - * @param int $parentId Parent id - * @param string $fileType File type ex : self::FILE_TYPE_DOCUMENTS - * - * @return string - */ - public function getRedirectionUrl($parentType, $parentId, $fileType) - { - if (!in_array($fileType, self::$availableFileType)) { - return false; - } - - switch ($parentType) { - case self::TYPE_PRODUCT: - $uri = '/admin/products/update?product_id=' . $parentId . '¤t_tab=' . $fileType; - break; - case self::TYPE_CATEGORY: - $uri = '/admin/categories/update?category_id=' . $parentId . '¤t_tab=' . $fileType; - break; - case self::TYPE_CONTENT: - $uri = '/admin/content/update/' . $parentId . '?current_tab=' . $fileType; - break; - case self::TYPE_FOLDER: - $uri = '/admin/folders/update/' . $parentId . '?current_tab=' . $fileType; - break; - default: - $uri = false; - } - - return $uri; - - } - - /** @var array Available file parent type */ - public static $availableType = array( - self::TYPE_PRODUCT, - self::TYPE_CATEGORY, - self::TYPE_CONTENT, - self::TYPE_FOLDER, - self::TYPE_MODULE - ); - - /** @var array Available file type type */ - public static $availableFileType = array( - self::FILE_TYPE_DOCUMENTS, - self::FILE_TYPE_IMAGES - ); - - /** - * Rename file with image model id - * - * @param int $modelId Model id - * @param UploadedFile $uploadedFile File being saved - * - * @return string - */ - public function renameFile($modelId, $uploadedFile) - { - $extension = $uploadedFile->getClientOriginalExtension(); - if (!empty($extension)) { - $extension = '.' . strtolower($extension); - } - $fileName = $this->sanitizeFileName( - str_replace( - $extension, - '', - $uploadedFile->getClientOriginalName() - ) . '-' . $modelId . $extension - ); - - return $fileName; - } - - /** - * Check if a file is an image - * Check based on mime type - * - * @param string $mimeType File mime type - * - * @return bool - */ - public function isImage($mimeType) - { - $isValid = false; - - $allowedType = array('image/jpeg' , 'image/png' ,'image/gif'); - if (in_array($mimeType, $allowedType)) { - $isValid = true; - } - - return $isValid; - } - - /** - * Return all document and image types - * - * @return array - */ - public static function getAvailableTypes() - { - return array( - self::TYPE_CATEGORY, - self::TYPE_CONTENT, - self::TYPE_FOLDER, - self::TYPE_PRODUCT, - self::TYPE_MODULE, - ); - } -} From ce3ed19b678c7f392799321b9f32ce2a01836f0e Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 26 Jun 2014 10:41:26 +0200 Subject: [PATCH 05/64] Introduced the automatic form fields binding. --- .../Smarty/Plugins/AdminUtilities.php | 34 +++++- core/lib/Thelia/Form/SeoFieldsTrait.php | 22 ++-- .../Form/StandardDescriptionFieldsTrait.php | 102 +++++++++++------- .../backOffice/default/document-edit.html | 47 ++------ .../backOffice/default/forms/form-field.html | 90 ++++++++++++++++ .../backOffice/default/forms/form-label.html | 8 ++ templates/backOffice/default/image-edit.html | 49 ++------- .../backOffice/default/includes/seo-tab.html | 51 ++------- .../standard-description-form-fields.html | 47 +------- 9 files changed, 238 insertions(+), 212 deletions(-) create mode 100644 templates/backOffice/default/forms/form-field.html create mode 100644 templates/backOffice/default/forms/form-label.html diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php index 47fb45d8d..0a8fe68e2 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php @@ -142,6 +142,34 @@ class AdminUtilities extends AbstractSmartyPlugin )); } + public function buildFormField($params, &$smarty) + { + $form = $this->getParam($params, 'form', false); + $field_name = $this->getParam($params, 'name', false); + $field_extra_class = $this->getParam($params, 'extra_class', ''); + $field_value = $this->getParam($params, 'value', ''); + + return $this->fetchSnippet($smarty, 'forms'.DS.'form-field', array( + 'form' => $form, + 'field_name' => $field_name, + 'field_extra_class' => $field_extra_class, + 'field_value' => $field_value + )); + } + + public function buildFormFieldLabel($params, &$smarty) + { + $form = $this->getParam($params, 'form', false); + $field_name = $this->getParam($params, 'name', false); + $label_attr = $this->getParam($params, 'label_attr', array()); + + return $this->fetchSnippet($smarty, 'forms'.DS.'form-label', array( + 'form' => $form, + 'field_name' => $field_name, + 'label_attr' => $label_attr + )); + } + /** * Define the various smarty plugins handled by this class * @@ -150,8 +178,10 @@ class AdminUtilities extends AbstractSmartyPlugin public function getPluginDescriptors() { return array( - new SmartyPluginDescriptor('function', 'admin_sortable_header', $this, 'generateSortableColumnHeader'), - new SmartyPluginDescriptor('function', 'admin_position_block' , $this, 'generatePositionChangeBlock'), + new SmartyPluginDescriptor('function', 'admin_sortable_header' , $this, 'generateSortableColumnHeader'), + new SmartyPluginDescriptor('function', 'admin_position_block' , $this, 'generatePositionChangeBlock'), + new SmartyPluginDescriptor('function', 'admin_form_field' , $this, 'buildFormField'), + new SmartyPluginDescriptor('function', 'admin_form_field_label' , $this, 'buildFormFieldLabel'), ); } } diff --git a/core/lib/Thelia/Form/SeoFieldsTrait.php b/core/lib/Thelia/Form/SeoFieldsTrait.php index cb64ad6c0..91ee54f0d 100644 --- a/core/lib/Thelia/Form/SeoFieldsTrait.php +++ b/core/lib/Thelia/Form/SeoFieldsTrait.php @@ -28,13 +28,13 @@ trait SeoFieldsTrait */ protected function addSeoFields($exclude = array()) { - if (! in_array('url', $exclude)) $this->formBuilder ->add('url', 'text', array( 'label' => Translator::getInstance()->trans('Rewriten URL'), 'label_attr' => array( - 'for' => 'rewriten_url_field' + 'for' => 'rewriten_url_field', + 'placeholder' => Translator::getInstance()->trans('Use the keyword phrase in your URL.') ), 'required' => false ) @@ -45,7 +45,9 @@ trait SeoFieldsTrait ->add('meta_title', 'text', array( 'label' => Translator::getInstance()->trans('Page Title'), 'label_attr' => array( - 'for' => 'meta_title' + 'for' => 'meta_title', + 'placeholder' => Translator::getInstance()->trans('Make sure that your title is clear, and contains many of the keywords within the page itself.'), + 'help' => Translator::getInstance()->trans('The HTML TITLE element is the most important element on your web page.') ), 'required' => false ) @@ -53,10 +55,13 @@ trait SeoFieldsTrait if (! in_array('meta_description', $exclude)) $this->formBuilder - ->add('meta_description', 'text', array( + ->add('meta_description', 'textarea', array( 'label' => Translator::getInstance()->trans('Meta Description'), 'label_attr' => array( - 'for' => 'meta_description' + 'for' => 'meta_description', + 'rows' => 6, + 'placeholder' => Translator::getInstance()->trans('Make sure it uses keywords found within the page itself.'), + 'help' => Translator::getInstance()->trans('Keep the most important part of your description in the first 150-160 characters.') ), 'required' => false ) @@ -64,10 +69,13 @@ trait SeoFieldsTrait if (! in_array('meta_keywords', $exclude)) $this->formBuilder - ->add('meta_keywords', 'text', array( + ->add('meta_keywords', 'textarea', array( 'label' => Translator::getInstance()->trans('Meta Keywords'), 'label_attr' => array( - 'for' => 'meta_keywords' + 'for' => 'meta_keywords', + 'rows' => 3, + 'placeholder' => Translator::getInstance()->trans('Don\'t repeat keywords over and over in a row. Rather, put in keyword phrases.'), + 'help' => Translator::getInstance()->trans('You don\'t need to use commas or other punctuations.') ), 'required' => false ) diff --git a/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php b/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php index e050cce1f..ba3beca2b 100644 --- a/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php +++ b/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php @@ -31,50 +31,78 @@ trait StandardDescriptionFieldsTrait protected function addStandardDescFields($exclude = array()) { if (! in_array('locale', $exclude)) - $this->formBuilder - ->add("locale", "hidden", array( - "constraints" => array( - new NotBlank() - ) - ) - ); + $this->formBuilder->add( + 'locale', + 'hidden', + [ + 'constraints' => [ new NotBlank() ], + 'required' => true, + ] + ); if (! in_array('title', $exclude)) - $this->formBuilder - ->add("title", "text", array( - "constraints" => array( - new NotBlank() - ), - "label" => Translator::getInstance()->trans("Title"), - "label_attr" => array("for" => "title_field") - ) + $this->formBuilder->add( + 'title', + 'text', + [ + 'constraints' => [ new NotBlank() ], + 'required' => true, + 'label' => Translator::getInstance()->trans('Title'), + 'label_attr' => [ + 'for' => 'title_field', + 'placeholder' => Translator::getInstance()->trans('A descriptive title') + ] + ] ); if (! in_array('chapo', $exclude)) - $this->formBuilder - ->add("chapo", "text", array( - "label" => Translator::getInstance()->trans("Summary"), - "label_attr" => array( - "for" => "summary_field" - ) - )); + $this->formBuilder->add( + 'chapo', + 'textarea', + [ + 'constraints' => [ ], + 'required' => false, + 'label' => Translator::getInstance()->trans('Summary'), + 'label_attr' => [ + 'for' => 'summary_field', + 'rows' => 3, + 'placeholder' => Translator::getInstance()->trans('Short description text'), + 'help' => Translator::getInstance()->trans('A short description, used when a summary or an introduction is required') + ] + ] + ); if (! in_array('description', $exclude)) - $this->formBuilder - ->add("description", "text", array( - "label" => Translator::getInstance()->trans("Detailed description"), - "label_attr" => array( - "for" => "detailed_description_field" - ) - )); + $this->formBuilder->add( + 'description', + 'textarea', + [ + 'constraints' => [ ], + 'required' => false, + 'label' => Translator::getInstance()->trans('Detailed description'), + 'label_attr' => [ + 'for' => 'detailed_description_field', + 'rows' => 10, + 'help' => Translator::getInstance()->trans('The detailed description.') + ] + ] + ); if (! in_array('postscriptum', $exclude)) - $this->formBuilder - ->add("postscriptum", "text", array( - "label" => Translator::getInstance()->trans("Conclusion"), - "label_attr" => array( - "for" => "conclusion_field" - ) - )); - } + $this->formBuilder->add( + 'postscriptum', + 'textarea', + [ + 'constraints' => [ ], + 'required' => false, + 'label' => Translator::getInstance()->trans('Conclusion'), + 'label_attr' => [ + 'for' => 'conclusion_field', + 'rows' => 3, + 'placeholder' => Translator::getInstance()->trans('Short additional text'), + 'help' => Translator::getInstance()->trans('A short text, used when an additional or supplemental information is required.') + ] + ] + ); + } } diff --git a/templates/backOffice/default/document-edit.html b/templates/backOffice/default/document-edit.html index 7d7e12cf8..c95c2daf2 100644 --- a/templates/backOffice/default/document-edit.html +++ b/templates/backOffice/default/document-edit.html @@ -40,13 +40,8 @@ {form_hidden_fields form=$form} - {form_field form=$form field='success_url'} - - {/form_field} - - {form_field form=$form field='locale'} - - {/form_field} + {admin_form_field form=$form name="success_url" value="{url path="/admin/document/type/{$documentType}/{$ID}/update"}"} + {admin_form_field form=$form name="locale" value="$edit_language_locale"} {if $form_error}
{$form_error_message}
{/if} @@ -62,43 +57,15 @@
- {form_field form=$form field='file'} -
- - -
- {/form_field} - - {form_field form=$form field='title'} -
- - -
- {/form_field} - - {form_field form=$form field='chapo'} -
- - -
- {/form_field} - - {form_field form=$form field='postscriptum'} -
- - -
- {/form_field} + {admin_form_field form=$form name="file"} + {admin_form_field form=$form name="title" value=$TITLE} + {admin_form_field form=$form name="chapo" value=$CHAPO} + {admin_form_field form=$form name="postscriptum" value=$POSTSCRIPTUM}
- {form_field form=$form field='description'} -
- - -
- {/form_field} + {admin_form_field form=$form name="description" value=$DESCRIPTION extra_class="wysiwyg"}
diff --git a/templates/backOffice/default/forms/form-field.html b/templates/backOffice/default/forms/form-field.html new file mode 100644 index 000000000..48bd40471 --- /dev/null +++ b/templates/backOffice/default/forms/form-field.html @@ -0,0 +1,90 @@ +{form_field form=$form field=$field_name} + +{* Use the optionnal $field_value parameter if no value is defined *} +{if empty($value)} + {$value = $field_value} +{/if} + +{* Synthetize an ID if none was given *} +{if empty({$label_attr.for})} + {$label_attr.for = "id-{$field_name}"} +{/if} + +{if $type == 'hidden'} + +{elseif $type == 'checkbox'} + +
+ +
+ +{else} + +
+ + {admin_form_field_label form=$form name=$field_name label_attr=$label_attr} + + {if $multiple} + {intl l='Use Ctrl+click to select (or deselect) more that one item'} + {/if} + + {$lang_code = 0} + {if $label_attr.i18n == 'default'} + {loop type="lang" name="default-lang" default_only="1"} + {$lang_code = $CODE} + {$lang_title = $TITLE} +
+ {/loop} + {/if} + + {if $type == 'choice'} + + + {elseif $type == 'textarea'} + + + + {elseif $type == 'money'} + +
+ + {loop name="input.addon" type="currency" default_only="true"}{$SYMBOL}{/loop} +
+ + {else} + + {$text_types = ['text', 'password', 'number', 'money', 'integer', 'time', 'date', 'datetime', 'email', 'url', 'file']} + + {if in_array($type, $text_types)} + {if $type == 'integer' || $type == 'money'}{$type='number'}{/if} + + + + {else} +
{intl l="Unsupported field type '%type' in form-field.html" type=$type}
+ {/if} + {/if} + + {if $lang_code} + {$lang_title} +
+ {/if} + + {if ! empty($label_attr.help)} + {$label_attr.help} + {/if} +
+{/if} +{/form_field} diff --git a/templates/backOffice/default/forms/form-label.html b/templates/backOffice/default/forms/form-label.html new file mode 100644 index 000000000..ce2af2a58 --- /dev/null +++ b/templates/backOffice/default/forms/form-label.html @@ -0,0 +1,8 @@ + \ No newline at end of file diff --git a/templates/backOffice/default/image-edit.html b/templates/backOffice/default/image-edit.html index 464e3a9ad..4a97112e2 100644 --- a/templates/backOffice/default/image-edit.html +++ b/templates/backOffice/default/image-edit.html @@ -40,13 +40,8 @@ {form_hidden_fields form=$form} - {form_field form=$form field='success_url'} - - {/form_field} - - {form_field form=$form field='locale'} - - {/form_field} + {admin_form_field form=$form name="success_url" value="{url path="/admin/image/type/{$imageType}/{$ID}/update"}"} + {admin_form_field form=$form name="locale" value="$edit_language_locale"} {if $form_error}
{$form_error_message}
{/if} @@ -65,43 +60,15 @@
- {form_field form=$form field='file'} -
- - -
- {/form_field} - - {form_field form=$form field='title'} -
- - -
- {/form_field} - - {form_field form=$form field='chapo'} -
- - -
- {/form_field} - - {form_field form=$form field='postscriptum'} -
- - -
- {/form_field} + {admin_form_field form=$form name="file"} + {admin_form_field form=$form name="title" value=$TITLE} + {admin_form_field form=$form name="chapo" value=$CHAPO} + {admin_form_field form=$form name="postscriptum" value=$POSTSCRIPTUM}
- {form_field form=$form field='description'} -
- - -
- {/form_field} + {admin_form_field form=$form name="description" value=$DESCRIPTION extra_class="wysiwyg"}
@@ -113,8 +80,6 @@ page_url = "{url path="/admin/image/type/{$imageType}/{$ID}/update"}" close_url = "{url path="{$redirectUrl}"}" } - - {/form} diff --git a/templates/backOffice/default/includes/seo-tab.html b/templates/backOffice/default/includes/seo-tab.html index 17d64575c..490078132 100644 --- a/templates/backOffice/default/includes/seo-tab.html +++ b/templates/backOffice/default/includes/seo-tab.html @@ -16,59 +16,26 @@ {form_hidden_fields form=$form} - {form_field form=$form field='success_url'} - - {/form_field} + {admin_form_field form=$form name="success_url"} {* Display error message if exist *} {include file='includes/notifications.html' message=$form_error_message} {form_field form=$form field='url'}
- + + {admin_form_field_label form=$form name='url'} +
- {$url_language|default:{config key="url_site"}} - + {$url_language|default:{config key="url_site"}}/ +
{/form_field} - - {form_field form=$form field='meta_title'} -
- -
- -
-
- {/form_field} - - {form_field form=$form field='meta_description'} -
- - - -
- {/form_field} - - {form_field form=$form field='meta_keywords'} -
- - - -
- {/form_field} + {admin_form_field form=$form name="meta_title"} + {admin_form_field form=$form name="meta_description"} + {admin_form_field form=$form name="meta_keywords"} {include file = "includes/inner-form-toolbar.html" diff --git a/templates/backOffice/default/includes/standard-description-form-fields.html b/templates/backOffice/default/includes/standard-description-form-fields.html index 26f262893..2072d83df 100644 --- a/templates/backOffice/default/includes/standard-description-form-fields.html +++ b/templates/backOffice/default/includes/standard-description-form-fields.html @@ -1,43 +1,6 @@ -{* -The standard description fields, used by many Thelia objects -*} +{* The standard description fields, used by many Thelia objects *} -{form_field form=$form field='title'} -
- - -
-{/form_field} - -{form_field form=$form field='chapo'} -
- - - -
-{/form_field} - -{form_field form=$form field='description'} -
- - - -
-{/form_field} - -{form_field form=$form field='postscriptum'} -
- - - -
-{/form_field} \ No newline at end of file +{admin_form_field form=$form name='title'} +{admin_form_field form=$form name="chapo"} +{admin_form_field form=$form name="description" extra_class="wysiwyg"} +{admin_form_field form=$form name="postscriptum"} \ No newline at end of file From 0b3de508b41708a9628cf5df881dd0d19da775a7 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 26 Jun 2014 10:42:16 +0200 Subject: [PATCH 06/64] Introduced automatic form fields binding --- core/lib/Thelia/Form/SeoForm.php | 21 +++------------------ 1 file changed, 3 insertions(+), 18 deletions(-) diff --git a/core/lib/Thelia/Form/SeoForm.php b/core/lib/Thelia/Form/SeoForm.php index acdb577ef..b1d8663e7 100644 --- a/core/lib/Thelia/Form/SeoForm.php +++ b/core/lib/Thelia/Form/SeoForm.php @@ -25,35 +25,20 @@ class SeoForm extends BaseForm use SeoFieldsTrait; /** - * - * 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 + * @inheritdoc */ protected function buildForm() { $this->formBuilder ->add("id", "hidden", array( + 'required' => true, "constraints" => array( new GreaterThan(array('value' => 0)) ) )) ->add("locale", "hidden", array( + 'required' => true, "constraints" => array( new NotBlank() ) From 2cf405c2679d64827fbb7a012dbff45f835a9c31 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 26 Jun 2014 10:42:57 +0200 Subject: [PATCH 07/64] Refactoring of images and documents management --- core/lib/Thelia/Model/Category.php | 12 ++- core/lib/Thelia/Model/CategoryDocument.php | 87 ++++++++++++++++++---- 2 files changed, 80 insertions(+), 19 deletions(-) diff --git a/core/lib/Thelia/Model/Category.php b/core/lib/Thelia/Model/Category.php index c5ab471a5..298650626 100644 --- a/core/lib/Thelia/Model/Category.php +++ b/core/lib/Thelia/Model/Category.php @@ -3,18 +3,22 @@ namespace Thelia\Model; use Thelia\Core\Event\Category\CategoryEvent; +use Thelia\Files\FileModelParentInterface; use Thelia\Model\Base\Category as BaseCategory; use Thelia\Core\Event\TheliaEvents; use Propel\Runtime\Connection\ConnectionInterface; +use Thelia\Model\Tools\ModelEventDispatcherTrait; +use Thelia\Model\Tools\PositionManagementTrait; +use Thelia\Model\Tools\UrlRewritingTrait; -class Category extends BaseCategory +class Category extends BaseCategory implements FileModelParentInterface { - use \Thelia\Model\Tools\ModelEventDispatcherTrait; + use ModelEventDispatcherTrait; - use \Thelia\Model\Tools\PositionManagementTrait; + use PositionManagementTrait; - use \Thelia\Model\Tools\UrlRewritingTrait; + use UrlRewritingTrait; /** * @return int number of child for the current category diff --git a/core/lib/Thelia/Model/CategoryDocument.php b/core/lib/Thelia/Model/CategoryDocument.php index 4b20d8a59..3e13863bb 100644 --- a/core/lib/Thelia/Model/CategoryDocument.php +++ b/core/lib/Thelia/Model/CategoryDocument.php @@ -2,16 +2,22 @@ namespace Thelia\Model; +use Propel\Runtime\ActiveQuery\ModelCriteria; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Router; +use Thelia\Core\HttpFoundation\Request; +use Thelia\Files\FileModelParentInterface; +use Thelia\Form\BaseForm; +use Thelia\Form\CategoryDocumentModification; use Thelia\Model\Base\CategoryDocument as BaseCategoryDocument; use Propel\Runtime\Connection\ConnectionInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait; +use Thelia\Files\FileModelInterface; use Thelia\Model\Tools\PositionManagementTrait; use Thelia\Model\Tools\ModelEventDispatcherTrait; -class CategoryDocument extends BaseCategoryDocument implements BreadcrumbInterface +class CategoryDocument extends BaseCategoryDocument implements BreadcrumbInterface, FileModelInterface { use ModelEventDispatcherTrait; use PositionManagementTrait; @@ -19,6 +25,8 @@ class CategoryDocument extends BaseCategoryDocument implements BreadcrumbInterfa /** * Calculate next position relative to our parent + * + * @param CategoryDocumentQuery $query */ protected function addCriteriaToPositionQuery($query) { @@ -36,11 +44,7 @@ class CategoryDocument extends BaseCategoryDocument implements BreadcrumbInterfa } /** - * Set Document parent id - * - * @param int $parentId parent id - * - * @return $this + * @inheritdoc */ public function setParentId($parentId) { @@ -50,9 +54,7 @@ class CategoryDocument extends BaseCategoryDocument implements BreadcrumbInterfa } /** - * Get Document parent id - * - * @return int parent id + * @inheritdoc */ public function getParentId() { @@ -71,13 +73,68 @@ class CategoryDocument extends BaseCategoryDocument implements BreadcrumbInterfa } /** - * - * return the complete breadcrumb for a given resource. - * - * @return array + * @inheritdoc */ - public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) + public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale) { - return $this->getCategoryBreadcrumb($router, $container, $tab); + return $this->getCategoryBreadcrumb($router, $container, $tab, $locale); + } + + /** + * @return FileModelParentInterface the parent file model + */ + public function getParentFileModel() + { + return new Category(); + } + + /** + * Get the ID of the form used to change this object information + * + * @return BaseForm the form + */ + public function getUpdateFormId() + { + return 'thelia.admin.category.document.modification'; + } + + /** + * Get the form instance used to change this object information + * + * @param \Thelia\Core\HttpFoundation\Request $request + * + * @return BaseForm the form + */ + public function getUpdateFormInstance(Request $request) + { + return new CategoryDocumentModification($request); + } + + /** + * @return string the path to the upload directory where files are stored, without final slash + */ + public function getUploadDir() + { + return THELIA_LOCAL_DIR . 'media'.DS.'documents'.DS.'category'; + } + + /** + * @param int $objectId the ID of the object + * + * @return string the URL to redirect to after update from the back-office + */ + public function getRedirectionUrl($objectId) + { + return '/admin/categories/update?category_id=' . $objectId . '?current_tab=document'; + } + + /** + * Get the Query instance for this object + * + * @return ModelCriteria + */ + public function getQueryInstance() + { + return CategoryDocumentQuery::create(); } } From 0dde8b888a6820b148b09943edd91102dbf011d0 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 26 Jun 2014 10:52:13 +0200 Subject: [PATCH 08/64] Added brands management --- core/lib/Thelia/Action/Brand.php | 132 + core/lib/Thelia/Config/Resources/action.xml | 6 + core/lib/Thelia/Config/Resources/form.xml | 6 + core/lib/Thelia/Config/Resources/loop.xml | 1 + .../Thelia/Config/Resources/routing/admin.xml | 37 + .../Controller/Admin/BrandController.php | 279 ++ .../Core/Event/Brand/BrandCreateEvent.php | 85 + .../Core/Event/Brand/BrandDeleteEvent.php | 48 + .../Thelia/Core/Event/Brand/BrandEvent.php | 63 + .../Brand/BrandToggleVisibilityEvent.php | 22 + .../Core/Event/Brand/BrandUpdateEvent.php | 115 + core/lib/Thelia/Core/Event/TheliaEvents.php | 20 + .../Core/Security/Resource/AdminResources.php | 2 + core/lib/Thelia/Core/Template/Loop/Brand.php | 193 ++ .../Thelia/Core/Template/Loop/Document.php | 2 +- core/lib/Thelia/Core/Template/Loop/Image.php | 2 +- .../Core/Template/Smarty/SmartyParser.php | 8 +- core/lib/Thelia/Form/BaseForm.php | 2 +- .../Thelia/Form/Brand/BrandCreationForm.php | 78 + .../Form/Brand/BrandDocumentModification.php | 30 + .../Form/Brand/BrandImageModification.php | 30 + .../Form/Brand/BrandModificationForm.php | 66 + core/lib/Thelia/Model/Base/Brand.php | 2918 +++++++++++++++++ core/lib/Thelia/Model/Base/BrandDocument.php | 1990 +++++++++++ .../Thelia/Model/Base/BrandDocumentI18n.php | 1442 ++++++++ .../Model/Base/BrandDocumentI18nQuery.php | 607 ++++ .../Thelia/Model/Base/BrandDocumentQuery.php | 846 +++++ core/lib/Thelia/Model/Base/BrandI18n.php | 1616 +++++++++ core/lib/Thelia/Model/Base/BrandI18nQuery.php | 706 ++++ core/lib/Thelia/Model/Base/BrandImage.php | 2258 +++++++++++++ core/lib/Thelia/Model/Base/BrandImageI18n.php | 1442 ++++++++ .../Thelia/Model/Base/BrandImageI18nQuery.php | 607 ++++ .../lib/Thelia/Model/Base/BrandImageQuery.php | 923 ++++++ core/lib/Thelia/Model/Base/BrandQuery.php | 1089 ++++++ core/lib/Thelia/Model/Base/Coupon.php | 139 +- core/lib/Thelia/Model/Base/CouponQuery.php | 82 +- core/lib/Thelia/Model/Base/CouponVersion.php | 130 +- .../Thelia/Model/Base/CouponVersionQuery.php | 82 +- core/lib/Thelia/Model/Base/Product.php | 185 +- core/lib/Thelia/Model/Base/ProductQuery.php | 128 +- core/lib/Thelia/Model/Base/ProductVersion.php | 106 +- .../Thelia/Model/Base/ProductVersionQuery.php | 47 +- core/lib/Thelia/Model/Base/TaxRule.php | 25 + core/lib/Thelia/Model/Base/Template.php | 25 + core/lib/Thelia/Model/Brand.php | 88 + core/lib/Thelia/Model/BrandDocument.php | 130 + core/lib/Thelia/Model/BrandDocumentI18n.php | 10 + .../Thelia/Model/BrandDocumentI18nQuery.php | 20 + core/lib/Thelia/Model/BrandDocumentQuery.php | 20 + core/lib/Thelia/Model/BrandI18n.php | 16 + core/lib/Thelia/Model/BrandI18nQuery.php | 20 + core/lib/Thelia/Model/BrandImage.php | 130 + core/lib/Thelia/Model/BrandImageI18n.php | 10 + core/lib/Thelia/Model/BrandImageI18nQuery.php | 20 + core/lib/Thelia/Model/BrandImageQuery.php | 20 + core/lib/Thelia/Model/BrandQuery.php | 20 + .../Model/Breadcrumb/BrandBreadcrumbTrait.php | 43 + .../Model/Breadcrumb/BreadcrumbInterface.php | 10 +- .../Breadcrumb/CatalogBreadcrumbTrait.php | 20 +- .../Breadcrumb/FolderBreadcrumbTrait.php | 22 +- .../Model/Map/BrandDocumentI18nTableMap.php | 498 +++ .../Model/Map/BrandDocumentTableMap.php | 476 +++ .../Thelia/Model/Map/BrandI18nTableMap.php | 522 +++ .../Model/Map/BrandImageI18nTableMap.php | 498 +++ .../Thelia/Model/Map/BrandImageTableMap.php | 478 +++ core/lib/Thelia/Model/Map/BrandTableMap.php | 482 +++ .../Model/Map/CouponCustomerCountTableMap.php | 4 +- core/lib/Thelia/Model/Map/CouponTableMap.php | 50 +- .../Model/Map/CouponVersionTableMap.php | 44 +- .../lib/Thelia/Model/Map/CustomerTableMap.php | 4 +- core/lib/Thelia/Model/Map/ProductTableMap.php | 37 +- .../Model/Map/ProductVersionTableMap.php | 40 +- local/config/schema.xml | 210 +- .../Tinymce/AdminIncludes/brand-edit-js.html | 1 + setup/insert.sql | 3 +- setup/thelia.sql | 358 +- setup/update/2.0.3.sql | 101 +- templates/backOffice/default/brand-edit.html | 178 + templates/backOffice/default/brands.html | 304 ++ templates/backOffice/default/tools.html | 7 + 80 files changed, 23250 insertions(+), 264 deletions(-) create mode 100644 core/lib/Thelia/Action/Brand.php create mode 100644 core/lib/Thelia/Controller/Admin/BrandController.php create mode 100644 core/lib/Thelia/Core/Event/Brand/BrandCreateEvent.php create mode 100644 core/lib/Thelia/Core/Event/Brand/BrandDeleteEvent.php create mode 100644 core/lib/Thelia/Core/Event/Brand/BrandEvent.php create mode 100644 core/lib/Thelia/Core/Event/Brand/BrandToggleVisibilityEvent.php create mode 100644 core/lib/Thelia/Core/Event/Brand/BrandUpdateEvent.php create mode 100644 core/lib/Thelia/Core/Template/Loop/Brand.php create mode 100644 core/lib/Thelia/Form/Brand/BrandCreationForm.php create mode 100644 core/lib/Thelia/Form/Brand/BrandDocumentModification.php create mode 100644 core/lib/Thelia/Form/Brand/BrandImageModification.php create mode 100644 core/lib/Thelia/Form/Brand/BrandModificationForm.php create mode 100644 core/lib/Thelia/Model/Base/Brand.php create mode 100644 core/lib/Thelia/Model/Base/BrandDocument.php create mode 100644 core/lib/Thelia/Model/Base/BrandDocumentI18n.php create mode 100644 core/lib/Thelia/Model/Base/BrandDocumentI18nQuery.php create mode 100644 core/lib/Thelia/Model/Base/BrandDocumentQuery.php create mode 100644 core/lib/Thelia/Model/Base/BrandI18n.php create mode 100644 core/lib/Thelia/Model/Base/BrandI18nQuery.php create mode 100644 core/lib/Thelia/Model/Base/BrandImage.php create mode 100644 core/lib/Thelia/Model/Base/BrandImageI18n.php create mode 100644 core/lib/Thelia/Model/Base/BrandImageI18nQuery.php create mode 100644 core/lib/Thelia/Model/Base/BrandImageQuery.php create mode 100644 core/lib/Thelia/Model/Base/BrandQuery.php create mode 100644 core/lib/Thelia/Model/Brand.php create mode 100644 core/lib/Thelia/Model/BrandDocument.php create mode 100644 core/lib/Thelia/Model/BrandDocumentI18n.php create mode 100644 core/lib/Thelia/Model/BrandDocumentI18nQuery.php create mode 100644 core/lib/Thelia/Model/BrandDocumentQuery.php create mode 100644 core/lib/Thelia/Model/BrandI18n.php create mode 100644 core/lib/Thelia/Model/BrandI18nQuery.php create mode 100644 core/lib/Thelia/Model/BrandImage.php create mode 100644 core/lib/Thelia/Model/BrandImageI18n.php create mode 100644 core/lib/Thelia/Model/BrandImageI18nQuery.php create mode 100644 core/lib/Thelia/Model/BrandImageQuery.php create mode 100644 core/lib/Thelia/Model/BrandQuery.php create mode 100644 core/lib/Thelia/Model/Breadcrumb/BrandBreadcrumbTrait.php create mode 100644 core/lib/Thelia/Model/Map/BrandDocumentI18nTableMap.php create mode 100644 core/lib/Thelia/Model/Map/BrandDocumentTableMap.php create mode 100644 core/lib/Thelia/Model/Map/BrandI18nTableMap.php create mode 100644 core/lib/Thelia/Model/Map/BrandImageI18nTableMap.php create mode 100644 core/lib/Thelia/Model/Map/BrandImageTableMap.php create mode 100644 core/lib/Thelia/Model/Map/BrandTableMap.php create mode 100644 local/modules/Tinymce/AdminIncludes/brand-edit-js.html create mode 100644 templates/backOffice/default/brand-edit.html create mode 100644 templates/backOffice/default/brands.html diff --git a/core/lib/Thelia/Action/Brand.php b/core/lib/Thelia/Action/Brand.php new file mode 100644 index 000000000..b362a0ee3 --- /dev/null +++ b/core/lib/Thelia/Action/Brand.php @@ -0,0 +1,132 @@ + + */ +class Brand extends BaseAction implements EventSubscriberInterface +{ + + public function create(BrandCreateEvent $event) + { + $brand = new BrandModel(); + + $brand + ->setVisible($event->getVisible()) + ->setLocale($event->getLocale()) + ->setTitle($event->getTitle()) + ->save() + ; + + $event->setBrand($brand); + } + + /** + * process update brand + * + * @param BrandUpdateEvent $event + */ + public function update(BrandUpdateEvent $event) + { + if (null !== $brand = BrandQuery::create()->findPk($event->getBrandId())) { + $brand->setDispatcher($event->getDispatcher()); + + $brand + ->setVisible($event->getVisible()) + ->setLocale($event->getLocale()) + ->setTitle($event->getTitle()) + ->setDescription($event->getDescription()) + ->setChapo($event->getChapo()) + ->setPostscriptum($event->getPostscriptum()) + ->save() + ; + + $event->setBrand($brand); + } + } + + /** + * Toggle Brand visibility + * + * @param BrandToggleVisibilityEvent $event + */ + public function toggleVisibility(BrandToggleVisibilityEvent $event) + { + $brand = $event->getBrand(); + + $brand + ->setDispatcher($event->getDispatcher()) + ->setVisible(!$brand->getVisible()) + ->save(); + + $event->setBrand($brand); + } + + /** + * Change Brand SEO + * + * @param \Thelia\Core\Event\UpdateSeoEvent $event + * + * @return mixed + */ + public function updateSeo(UpdateSeoEvent $event) + { + return $this->genericUpdateSeo(BrandQuery::create(), $event); + } + + public function delete(BrandDeleteEvent $event) + { + if (null !== $brand = BrandQuery::create()->findPk($event->getBrandId())) { + + $brand->setDispatcher($event->getDispatcher())->delete(); + + $event->setBrand($brand); + } + } + + public function updatePosition(UpdatePositionEvent $event) + { + $this->genericUpdatePosition(BrandQuery::create(), $event); + } + /** + * @inheritdoc + */ + public static function getSubscribedEvents() + { + return array( + TheliaEvents::BRAND_CREATE => array('create', 128), + TheliaEvents::BRAND_UPDATE => array('update', 128), + TheliaEvents::BRAND_DELETE => array('delete', 128), + + TheliaEvents::BRAND_UPDATE_SEO => array('updateSeo', 128), + + TheliaEvents::BRAND_UPDATE_POSITION => array('updatePosition', 128), + TheliaEvents::BRAND_TOGGLE_VISIBILITY => array('toggleVisibility', 128), + ); + } +} diff --git a/core/lib/Thelia/Config/Resources/action.xml b/core/lib/Thelia/Config/Resources/action.xml index 51f0b5fcc..f8ea66a4f 100644 --- a/core/lib/Thelia/Config/Resources/action.xml +++ b/core/lib/Thelia/Config/Resources/action.xml @@ -55,9 +55,11 @@
+ + @@ -121,6 +123,10 @@ + + + + diff --git a/core/lib/Thelia/Config/Resources/form.xml b/core/lib/Thelia/Config/Resources/form.xml index 27e169b7c..758f2c926 100644 --- a/core/lib/Thelia/Config/Resources/form.xml +++ b/core/lib/Thelia/Config/Resources/form.xml @@ -52,6 +52,12 @@
+ + + + + + diff --git a/core/lib/Thelia/Config/Resources/loop.xml b/core/lib/Thelia/Config/Resources/loop.xml index 0e5414ad8..743f33853 100644 --- a/core/lib/Thelia/Config/Resources/loop.xml +++ b/core/lib/Thelia/Config/Resources/loop.xml @@ -14,6 +14,7 @@ + diff --git a/core/lib/Thelia/Config/Resources/routing/admin.xml b/core/lib/Thelia/Config/Resources/routing/admin.xml index b438c10e0..7dcd827b1 100644 --- a/core/lib/Thelia/Config/Resources/routing/admin.xml +++ b/core/lib/Thelia/Config/Resources/routing/admin.xml @@ -1168,6 +1168,43 @@ Thelia\Controller\Admin\CustomerExportController::NewsletterExportAction + + + + + Thelia\Controller\Admin\BrandController::defaultAction + + + + Thelia\Controller\Admin\BrandController::createAction + + + + Thelia\Controller\Admin\BrandController::updateAction + \d+ + + + + Thelia\Controller\Admin\BrandController::processUpdateAction + \d+ + + + + Thelia\Controller\Admin\BrandController::processUpdateSeoAction + + + + Thelia\Controller\Admin\BrandController::setToggleVisibilityAction + + + + Thelia\Controller\Admin\BrandController::updatePositionAction + + + + Thelia\Controller\Admin\BrandController::deleteAction + + diff --git a/core/lib/Thelia/Controller/Admin/BrandController.php b/core/lib/Thelia/Controller/Admin/BrandController.php new file mode 100644 index 000000000..c41332894 --- /dev/null +++ b/core/lib/Thelia/Controller/Admin/BrandController.php @@ -0,0 +1,279 @@ + + */ +class BrandController extends AbstractSeoCrudController +{ + + public function __construct() + { + parent::__construct( + 'brand', + 'manual', + 'order', + + AdminResources::BRAND, + + TheliaEvents::BRAND_CREATE, + TheliaEvents::BRAND_UPDATE, + TheliaEvents::BRAND_DELETE, + TheliaEvents::BRAND_TOGGLE_VISIBILITY, + TheliaEvents::BRAND_UPDATE_POSITION, + TheliaEvents::BRAND_UPDATE_SEO + ); + } + + /** + * Return the creation form for this object + */ + protected function getCreationForm() + { + return new BrandCreationForm($this->getRequest()); + } + + /** + * Return the update form for this object + */ + protected function getUpdateForm() + { + return new BrandModificationForm($this->getRequest()); + } + + /** + * Hydrate the update form for this object, before passing it to the update template + * + * @param Brand $object + * @return BrandModificationForm $object + */ + protected function hydrateObjectForm($object) + { + // Hydrate the "SEO" tab form + $this->hydrateSeoForm($object); + + // Prepare the data that will hydrate the form + $data = [ + 'id' => $object->getId(), + 'locale' => $object->getLocale(), + 'title' => $object->getTitle(), + 'chapo' => $object->getChapo(), + 'description' => $object->getDescription(), + 'postscriptum' => $object->getPostscriptum(), + 'visible' => $object->getVisible() ? true : false + ]; + + // Setup the object form + return new BrandModificationForm($this->getRequest(), "form", $data); + } + + /** + * Creates the creation event with the provided form data + * + * @param array $formData + * @return BrandCreateEvent + */ + protected function getCreationEvent($formData) + { + $brandCreateEvent = new BrandCreateEvent(); + + $brandCreateEvent + ->setLocale($formData['locale']) + ->setTitle($formData['title']) + ->setVisible($formData['visible']) + ; + + return $brandCreateEvent; + } + + /** + * Creates the update event with the provided form data + * + * @param array $formData + * @return BrandUpdateEvent + */ + protected function getUpdateEvent($formData) + { + $brandUpdateEvent = new BrandUpdateEvent($formData['id']); + + $brandUpdateEvent + ->setLocale($formData['locale']) + ->setTitle($formData['title']) + ->setChapo($formData['chapo']) + ->setDescription($formData['description']) + ->setPostscriptum($formData['postscriptum']) + ->setVisible($formData['visible']) + ; + + return $brandUpdateEvent; + } + + /** + * Creates the delete event with the provided form data + * + * @return BrandDeleteEvent + */ + protected function getDeleteEvent() + { + return new BrandDeleteEvent($this->getRequest()->get('brand_id')); + } + + /** + * Return true if the event contains the object, e.g. the action has updated the object in the event. + * + * @param BrandEvent $event + * @return bool + */ + protected function eventContainsObject($event) + { + return $event->hasBrand(); + } + + /** + * Get the created object from an event. + * + * @param $event \Thelia\Core\Event\Brand\BrandEvent + * + * @return null|\Thelia\Model\Brand + */ + protected function getObjectFromEvent($event) + { + return $event->getBrand(); + } + + /** + * Load an existing object from the database + * + * @return \Thelia\Model\Brand + */ + protected function getExistingObject() + { + $brand = BrandQuery::create() + ->findOneById($this->getRequest()->get('brand_id', 0)); + + if (null !== $brand) { + $brand->setLocale($this->getCurrentEditionLocale()); + } + + return $brand; + } + + /** + * Returns the object label form the object event (name, title, etc.) + * + * @param $object \Thelia\Model\Brand + * + * @return string brand title + */ + protected function getObjectLabel($object) + { + return $object->getTitle(); + } + + /** + * Returns the object ID from the object + * + * @param $object \Thelia\Model\Brand + * + * @return int brand id + */ + protected function getObjectId($object) + { + return $object->getId(); + } + + /** + * Render the main list template + * + * @param string $currentOrder, if any, null otherwise. + * + * @return Response + */ + protected function renderListTemplate($currentOrder) + { + $this->getListOrderFromSession('brand', 'order', 'manual'); + + return $this->render('brands', [ + 'order' => $currentOrder, + ]); + } + + protected function getEditionArguments() + { + return [ + 'brand_id' => $this->getRequest()->get('brand_id', 0), + 'current_tab' => $this->getRequest()->get('current_tab', 'general') + ]; + } + + /** + * Render the edition template + */ + protected function renderEditionTemplate() + { + return $this->render('brand-edit', $this->getEditionArguments()); + } + + /** + * Redirect to the edition template + */ + protected function redirectToEditionTemplate() + { + $this->redirect($this->getRoute('admin.brand.update', $this->getEditionArguments())); + } + + /** + * Redirect to the list template + */ + protected function redirectToListTemplate() + { + $this->redirectToRoute('admin.brand.default'); + } + + /** + * @return BrandToggleVisibilityEvent|void + */ + protected function createToggleVisibilityEvent() + { + return new BrandToggleVisibilityEvent($this->getExistingObject()); + } + + /** + * @inheritdoc + */ + protected function createUpdatePositionEvent($positionChangeMode, $positionValue) + { + return new UpdatePositionEvent( + $this->getRequest()->get('brand_id', null), + $positionChangeMode, + $positionValue + ); + } + +} diff --git a/core/lib/Thelia/Core/Event/Brand/BrandCreateEvent.php b/core/lib/Thelia/Core/Event/Brand/BrandCreateEvent.php new file mode 100644 index 000000000..70721b11a --- /dev/null +++ b/core/lib/Thelia/Core/Event/Brand/BrandCreateEvent.php @@ -0,0 +1,85 @@ + + */ +class BrandCreateEvent extends BrandEvent +{ + protected $title; + protected $locale; + protected $visible; + + /** + * @param string $locale + * + * @return BrandCreateEvent $this + */ + public function setLocale($locale) + { + $this->locale = $locale; + + return $this; + } + + /** + * @return string + */ + public function getLocale() + { + return $this->locale; + } + + /** + * @param string $title + * + * @return BrandCreateEvent $this + */ + public function setTitle($title) + { + $this->title = $title; + + return $this; + } + + /** + * @return string + */ + public function getTitle() + { + return $this->title; + } + + /** + * @param bool $visible + * + * @return BrandCreateEvent $this + */ + public function setVisible($visible) + { + $this->visible = $visible; + + return $this; + } + + /** + * @return bool + */ + public function getVisible() + { + return $this->visible; + } +} diff --git a/core/lib/Thelia/Core/Event/Brand/BrandDeleteEvent.php b/core/lib/Thelia/Core/Event/Brand/BrandDeleteEvent.php new file mode 100644 index 000000000..e7d9d1fec --- /dev/null +++ b/core/lib/Thelia/Core/Event/Brand/BrandDeleteEvent.php @@ -0,0 +1,48 @@ + + */ +class BrandDeleteEvent extends BrandEvent +{ + protected $brand_id; + + public function __construct($brand_id) + { + $this->brand_id = $brand_id; + } + + /** + * @param int $brand_id + * + * @return BrandDeleteEvent $this + */ + public function setBrandId($brand_id) + { + $this->brand_id = $brand_id; + + return $this; + } + + /** + * @return int + */ + public function getBrandId() + { + return $this->brand_id; + } +} diff --git a/core/lib/Thelia/Core/Event/Brand/BrandEvent.php b/core/lib/Thelia/Core/Event/Brand/BrandEvent.php new file mode 100644 index 000000000..6bcd9b0db --- /dev/null +++ b/core/lib/Thelia/Core/Event/Brand/BrandEvent.php @@ -0,0 +1,63 @@ + + */ +class BrandEvent extends ActionEvent +{ + /** + * @var \Thelia\Model\Brand + */ + protected $brand; + + public function __construct(Brand $brand = null) + { + $this->brand = $brand; + } + + /** + * @param \Thelia\Model\Brand $brand + * @return BrandEvent + */ + public function setBrand(Brand $brand) + { + $this->brand = $brand; + + return $this; + } + + /** + * @return \Thelia\Model\Brand + */ + public function getBrand() + { + return $this->brand; + } + + /** + * check if brand exists + * + * @return bool + */ + public function hasBrand() + { + return null !== $this->brand; + } +} diff --git a/core/lib/Thelia/Core/Event/Brand/BrandToggleVisibilityEvent.php b/core/lib/Thelia/Core/Event/Brand/BrandToggleVisibilityEvent.php new file mode 100644 index 000000000..db5b7faa9 --- /dev/null +++ b/core/lib/Thelia/Core/Event/Brand/BrandToggleVisibilityEvent.php @@ -0,0 +1,22 @@ + + */ +class BrandToggleVisibilityEvent extends BrandEvent +{ +} diff --git a/core/lib/Thelia/Core/Event/Brand/BrandUpdateEvent.php b/core/lib/Thelia/Core/Event/Brand/BrandUpdateEvent.php new file mode 100644 index 000000000..ffd2456d8 --- /dev/null +++ b/core/lib/Thelia/Core/Event/Brand/BrandUpdateEvent.php @@ -0,0 +1,115 @@ + + */ +class BrandUpdateEvent extends BrandCreateEvent +{ + protected $brandId; + + protected $chapo; + protected $description; + protected $postscriptum; + + /** + * @param int $brandId + */ + public function __construct($brandId) + { + $this->brandId = $brandId; + } + + /** + * @param string $chapo + * + * @return BrandUpdateEvent $this + */ + public function setChapo($chapo) + { + $this->chapo = $chapo; + + return $this; + } + + /** + * @return string + */ + public function getChapo() + { + return $this->chapo; + } + + /** + * @param int $brandId + * + * @return BrandUpdateEvent $this + */ + public function setBrandId($brandId) + { + $this->brandId = $brandId; + + return $this; + } + + /** + * @return int + */ + public function getBrandId() + { + return $this->brandId; + } + + /** + * @param string $description + * + * @return BrandUpdateEvent $this + */ + public function setDescription($description) + { + $this->description = $description; + + return $this; + } + + /** + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * @param string $postscriptum + * + * @return BrandUpdateEvent $this + */ + public function setPostscriptum($postscriptum) + { + $this->postscriptum = $postscriptum; + + return $this; + } + + /** + * @return string + */ + public function getPostscriptum() + { + return $this->postscriptum; + } +} diff --git a/core/lib/Thelia/Core/Event/TheliaEvents.php b/core/lib/Thelia/Core/Event/TheliaEvents.php index 571604b69..82cac917a 100644 --- a/core/lib/Thelia/Core/Event/TheliaEvents.php +++ b/core/lib/Thelia/Core/Event/TheliaEvents.php @@ -736,4 +736,24 @@ final class TheliaEvents const BEFORE_DELETELANG = 'action.lang.beforeDelete'; const AFTER_DELETELANG = 'action.lang.afterDelete'; + + // -- Brands management ----------------------------------------------- + + const BRAND_CREATE = "action.createBrand"; + const BRAND_UPDATE = "action.updateBrand"; + const BRAND_DELETE = "action.deleteBrand"; + + const BRAND_UPDATE_POSITION = "action.updateBrandPosition"; + const BRAND_TOGGLE_VISIBILITY = "action.toggleBrandVisibility"; + + const BRAND_UPDATE_SEO = "action.updateBrandSeo"; + + const BEFORE_CREATEBRAND = "action.before_createBrand"; + const AFTER_CREATEBRAND = "action.after_createBrand"; + + const BEFORE_DELETEBRAND = "action.before_deleteBrand"; + const AFTER_DELETEBRAND = "action.after_deleteBrand"; + + const BEFORE_UPDATEBRAND = "action.before_updateBrand"; + const AFTER_UPDATEBRAND = "action.after_updateBrand"; } diff --git a/core/lib/Thelia/Core/Security/Resource/AdminResources.php b/core/lib/Thelia/Core/Security/Resource/AdminResources.php index 107aef017..2ddea9877 100644 --- a/core/lib/Thelia/Core/Security/Resource/AdminResources.php +++ b/core/lib/Thelia/Core/Security/Resource/AdminResources.php @@ -51,6 +51,8 @@ final class AdminResources const ATTRIBUTE = "admin.configuration.attribute"; + const BRAND = "admin.brand"; + const CATEGORY = "admin.category"; const CONFIG = "admin.configuration"; diff --git a/core/lib/Thelia/Core/Template/Loop/Brand.php b/core/lib/Thelia/Core/Template/Loop/Brand.php new file mode 100644 index 000000000..0a9774221 --- /dev/null +++ b/core/lib/Thelia/Core/Template/Loop/Brand.php @@ -0,0 +1,193 @@ + + */ +class Brand extends BaseI18nLoop implements PropelSearchLoopInterface, SearchLoopInterface +{ + protected $timestampable = true; + + /** + * @return ArgumentCollection + */ + protected function getArgDefinitions() + { + return new ArgumentCollection( + Argument::createIntListTypeArgument('id'), + Argument::createBooleanOrBothTypeArgument('visible', 1), + Argument::createAnyTypeArgument('title'), + new Argument( + 'order', + new TypeCollection( + new Type\EnumListType( + array( + 'id', + 'id-reverse', + 'alpha', + 'alpha-reverse', + 'manual', + 'manual-reverse', + 'random', + 'created', + 'created-reverse', + 'updated', + 'updated-reverse' + ) + ) + ), + 'alpha' + ), + Argument::createIntListTypeArgument('exclude') + ); + } + + /** + * @return array of available field to search in + */ + public function getSearchIn() + { + return [ + "title" + ]; + } + + public function doSearch(&$search, $searchTerm, $searchIn, $searchCriteria) + { + $search->_and(); + + $search->where("CASE WHEN NOT ISNULL(`requested_locale_i18n`.ID) THEN `requested_locale_i18n`.`TITLE` ELSE `default_locale_i18n`.`TITLE` END ".$searchCriteria." ?", $searchTerm, \PDO::PARAM_STR); + } + + public function buildModelCriteria() + { + + $search = BrandQuery::create(); + + /* manage translations */ + $this->configureI18nProcessing($search, array('TITLE', 'CHAPO', 'DESCRIPTION', 'POSTSCRIPTUM', 'META_TITLE', 'META_DESCRIPTION', 'META_KEYWORDS')); + + $id = $this->getId(); + + if (!is_null($id)) { + $search->filterById($id, Criteria::IN); + } + + $visible = $this->getVisible(); + + if ($visible !== BooleanOrBothType::ANY) $search->filterByVisible($visible ? 1 : 0); + + $title = $this->getTitle(); + + if (!is_null($title)) { + $search->where("CASE WHEN NOT ISNULL(`requested_locale_i18n`.ID) THEN `requested_locale_i18n`.`TITLE` ELSE `default_locale_i18n`.`TITLE` END ".Criteria::LIKE." ?", "%".$title."%", \PDO::PARAM_STR); + } + + $orders = $this->getOrder(); + + foreach ($orders as $order) { + switch ($order) { + case 'id': + $search->orderById(Criteria::ASC); + break; + case 'id-reverse': + $search->orderById(Criteria::DESC); + break; + case "alpha": + $search->addAscendingOrderByColumn('i18n_TITLE'); + break; + case "alpha-reverse": + $search->addDescendingOrderByColumn('i18n_TITLE'); + break; + case "manual": + $search->orderByPosition(Criteria::ASC); + break; + case "manual-reverse": + $search->orderByPosition(Criteria::DESC); + break; + case "random": + $search->clearOrderByColumns(); + $search->addAscendingOrderByColumn('RAND()'); + break(2); + case "created": + $search->addAscendingOrderByColumn('created_at'); + break; + case "created-reverse": + $search->addDescendingOrderByColumn('created_at'); + break; + case "updated": + $search->addAscendingOrderByColumn('updated_at'); + break; + case "updated-reverse": + $search->addDescendingOrderByColumn('updated_at'); + break; + } + } + + $exclude = $this->getExclude(); + + if (!is_null($exclude)) { + $search->filterById($exclude, Criteria::NOT_IN); + } + + return $search; + + } + + public function parseResults(LoopResult $loopResult) + { + /** @var \Thelia\Model\Brand $brand */ + foreach ($loopResult->getResultDataCollection() as $brand) { + $loopResultRow = new LoopResultRow($brand); + + $loopResultRow->set("ID" , $brand->getId()) + ->set("IS_TRANSLATED" , $brand->getVirtualColumn('IS_TRANSLATED')) + ->set("LOCALE" , $this->locale) + ->set("TITLE" , $brand->getVirtualColumn('i18n_TITLE')) + ->set("CHAPO" , $brand->getVirtualColumn('i18n_CHAPO')) + ->set("DESCRIPTION" , $brand->getVirtualColumn('i18n_DESCRIPTION')) + ->set("POSTSCRIPTUM" , $brand->getVirtualColumn('i18n_POSTSCRIPTUM')) + ->set("URL" , $brand->getUrl($this->locale)) + ->set("META_TITLE" , $brand->getVirtualColumn('i18n_META_TITLE')) + ->set("META_DESCRIPTION" , $brand->getVirtualColumn('i18n_META_DESCRIPTION')) + ->set("META_KEYWORDS" , $brand->getVirtualColumn('i18n_META_KEYWORDS')) + ->set("POSITION" , $brand->getPosition()) + ->set("VISIBLE" , $brand->getVisible()) + ; + + $loopResult->addRow($loopResultRow); + } + + return $loopResult; + } +} diff --git a/core/lib/Thelia/Core/Template/Loop/Document.php b/core/lib/Thelia/Core/Template/Loop/Document.php index 77a38587e..586a74ab7 100644 --- a/core/lib/Thelia/Core/Template/Loop/Document.php +++ b/core/lib/Thelia/Core/Template/Loop/Document.php @@ -41,7 +41,7 @@ class Document extends BaseI18nLoop implements PropelSearchLoopInterface /** * @var array Possible document sources */ - protected $possible_sources = array('category', 'product', 'folder', 'content'); + protected $possible_sources = array('category', 'product', 'folder', 'content', 'brand'); /** * @return \Thelia\Core\Template\Loop\Argument\ArgumentCollection diff --git a/core/lib/Thelia/Core/Template/Loop/Image.php b/core/lib/Thelia/Core/Template/Loop/Image.php index 2a94655b3..234ed26de 100644 --- a/core/lib/Thelia/Core/Template/Loop/Image.php +++ b/core/lib/Thelia/Core/Template/Loop/Image.php @@ -41,7 +41,7 @@ class Image extends BaseI18nLoop implements PropelSearchLoopInterface /** * @var array Possible image sources */ - protected $possible_sources = array('category', 'product', 'folder', 'content', 'module'); + protected $possible_sources = array('category', 'product', 'folder', 'content', 'module', 'brand'); /** * @return \Thelia\Core\Template\Loop\Argument\ArgumentCollection diff --git a/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php b/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php index 807ef2438..53adfc88b 100644 --- a/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php +++ b/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php @@ -95,10 +95,16 @@ class SmartyParser extends Smarty implements ParserInterface // The default HTTP status $this->status = 200; - $this->loadFilter('output', "trimwhitespace"); + $this->registerFilter('output', array($this, "removeBlankLines")); + //$this->loadFilter('output', "trimwhitespace"); $this->registerFilter('variable', array(__CLASS__, "theliaEscape")); } + public function removeBlankLines($tpl_source, \Smarty_Internal_Template $template) + { + return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $tpl_source); + } + /** * Add a template directory to the current template list * diff --git a/core/lib/Thelia/Form/BaseForm.php b/core/lib/Thelia/Form/BaseForm.php index 332d8eff6..cea9bbba7 100644 --- a/core/lib/Thelia/Form/BaseForm.php +++ b/core/lib/Thelia/Form/BaseForm.php @@ -96,7 +96,7 @@ abstract class BaseForm // If not already set, define the success_url field if (! $this->formBuilder->has('success_url')) { - $this->formBuilder->add("success_url", "text"); + $this->formBuilder->add("success_url", "hidden"); } if (! $this->formBuilder->has('error_message')) { diff --git a/core/lib/Thelia/Form/Brand/BrandCreationForm.php b/core/lib/Thelia/Form/Brand/BrandCreationForm.php new file mode 100644 index 000000000..65e0efb7b --- /dev/null +++ b/core/lib/Thelia/Form/Brand/BrandCreationForm.php @@ -0,0 +1,78 @@ + + */ +class BrandCreationForm extends BaseForm +{ + protected function buildForm() + { + $this->formBuilder + // Brand title + ->add( + 'title', + 'text', + [ + 'constraints' => [ new NotBlank() ], + 'required' => true, + 'label' => Translator::getInstance()->trans('Brand name'), + 'label_attr' => [ + 'for' => 'title', + 'placeholder' => Translator::getInstance()->trans('The brand name or title'), + 'help' => Translator::getInstance()->trans( + 'Enter here the brand name in the default language (%title%)', + [ '%title%' => Lang::getDefaultLanguage()->getTitle()] + ), + 'i18n' => 'default' + ] + ] + ) + // Current locale + ->add( + 'locale', + 'hidden', + [ + 'constraints' => [ new NotBlank() ], + 'required' => true, + ] + ) + // Is this brand online ? + ->add( + 'visible', + 'checkbox', + [ + 'constraints' => [ ], + 'required' => true, + 'label' => Translator::getInstance()->trans('This brand is online'), + 'label_attr' => [ + 'for' => 'visible_create' + ] + ] + ); + } + + public function getName() + { + return 'thelia_brand_creation'; + } +} diff --git a/core/lib/Thelia/Form/Brand/BrandDocumentModification.php b/core/lib/Thelia/Form/Brand/BrandDocumentModification.php new file mode 100644 index 000000000..4934db1f1 --- /dev/null +++ b/core/lib/Thelia/Form/Brand/BrandDocumentModification.php @@ -0,0 +1,30 @@ + + */ +class BrandDocumentModification extends DocumentModification +{ + + /** + * @inheritdoc + */ + public function getName() + { + return 'thelia_brand_document_modification'; + } +} diff --git a/core/lib/Thelia/Form/Brand/BrandImageModification.php b/core/lib/Thelia/Form/Brand/BrandImageModification.php new file mode 100644 index 000000000..8772fe052 --- /dev/null +++ b/core/lib/Thelia/Form/Brand/BrandImageModification.php @@ -0,0 +1,30 @@ + + */ +class BrandImageModification extends ImageModification +{ + + /** + * @inheritdoc + */ + public function getName() + { + return 'thelia_brand_image_modification'; + } +} diff --git a/core/lib/Thelia/Form/Brand/BrandModificationForm.php b/core/lib/Thelia/Form/Brand/BrandModificationForm.php new file mode 100644 index 000000000..fa0ba3015 --- /dev/null +++ b/core/lib/Thelia/Form/Brand/BrandModificationForm.php @@ -0,0 +1,66 @@ + + */ +class BrandModificationForm extends BrandCreationForm +{ + use StandardDescriptionFieldsTrait; + + protected function buildForm() + { + parent::buildForm(); + + $this->formBuilder + ->add( + 'id', + 'hidden', + [ + 'constraints' => [ new GreaterThan(['value' => 0]) ], + 'required' => true, + ] + ) + // Brand title + ->add( + 'title', + 'text', + [ + 'constraints' => [ new NotBlank() ], + 'required' => true, + 'label' => Translator::getInstance()->trans('Brand name'), + 'label_attr' => [ + 'for' => 'title', + 'placeholder' => Translator::getInstance()->trans('The brand name or title'), + ] + ] + ) + ; + + // Add standard description fields, excluding title and locale, which are already defined + $this->addStandardDescFields(array('title', 'locale')); + } + + public function getName() + { + return "thelia_brand_modification"; + } +} diff --git a/core/lib/Thelia/Model/Base/Brand.php b/core/lib/Thelia/Model/Base/Brand.php new file mode 100644 index 000000000..4cb60bb4c --- /dev/null +++ b/core/lib/Thelia/Model/Base/Brand.php @@ -0,0 +1,2918 @@ +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 Brand instance. If + * obj is an instance of Brand, delegates to + * equals(Brand). 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 Brand 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 Brand 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 [visible] column value. + * + * @return int + */ + public function getVisible() + { + + return $this->visible; + } + + /** + * Get the [position] column value. + * + * @return int + */ + public function getPosition() + { + + return $this->position; + } + + /** + * Get the [logo_image_id] column value. + * + * @return int + */ + public function getLogoImageId() + { + + return $this->logo_image_id; + } + + /** + * 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\Brand 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[BrandTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [visible] column. + * + * @param int $v new value + * @return \Thelia\Model\Brand The current object (for fluent API support) + */ + public function setVisible($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->visible !== $v) { + $this->visible = $v; + $this->modifiedColumns[BrandTableMap::VISIBLE] = true; + } + + + return $this; + } // setVisible() + + /** + * Set the value of [position] column. + * + * @param int $v new value + * @return \Thelia\Model\Brand 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[BrandTableMap::POSITION] = true; + } + + + return $this; + } // setPosition() + + /** + * Set the value of [logo_image_id] column. + * + * @param int $v new value + * @return \Thelia\Model\Brand The current object (for fluent API support) + */ + public function setLogoImageId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->logo_image_id !== $v) { + $this->logo_image_id = $v; + $this->modifiedColumns[BrandTableMap::LOGO_IMAGE_ID] = true; + } + + if ($this->aBrandImageRelatedByLogoImageId !== null && $this->aBrandImageRelatedByLogoImageId->getId() !== $v) { + $this->aBrandImageRelatedByLogoImageId = null; + } + + + return $this; + } // setLogoImageId() + + /** + * 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\Brand 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[BrandTableMap::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\Brand 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[BrandTableMap::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 : BrandTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : BrandTableMap::translateFieldName('Visible', TableMap::TYPE_PHPNAME, $indexType)]; + $this->visible = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : BrandTableMap::translateFieldName('Position', TableMap::TYPE_PHPNAME, $indexType)]; + $this->position = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : BrandTableMap::translateFieldName('LogoImageId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->logo_image_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : BrandTableMap::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 ? 5 + $startcol : BrandTableMap::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 + 6; // 6 = BrandTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\Brand 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->aBrandImageRelatedByLogoImageId !== null && $this->logo_image_id !== $this->aBrandImageRelatedByLogoImageId->getId()) { + $this->aBrandImageRelatedByLogoImageId = 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(BrandTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildBrandQuery::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->aBrandImageRelatedByLogoImageId = null; + $this->collProducts = null; + + $this->collBrandDocuments = null; + + $this->collBrandImagesRelatedByBrandId = null; + + $this->collBrandI18ns = null; + + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see Brand::setDeleted() + * @see Brand::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(BrandTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildBrandQuery::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(BrandTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + // timestampable behavior + if (!$this->isColumnModified(BrandTableMap::CREATED_AT)) { + $this->setCreatedAt(time()); + } + if (!$this->isColumnModified(BrandTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } else { + $ret = $ret && $this->preUpdate($con); + // timestampable behavior + if ($this->isModified() && !$this->isColumnModified(BrandTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + BrandTableMap::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->aBrandImageRelatedByLogoImageId !== null) { + if ($this->aBrandImageRelatedByLogoImageId->isModified() || $this->aBrandImageRelatedByLogoImageId->isNew()) { + $affectedRows += $this->aBrandImageRelatedByLogoImageId->save($con); + } + $this->setBrandImageRelatedByLogoImageId($this->aBrandImageRelatedByLogoImageId); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + if ($this->productsScheduledForDeletion !== null) { + if (!$this->productsScheduledForDeletion->isEmpty()) { + foreach ($this->productsScheduledForDeletion as $product) { + // need to save related object because we set the relation to null + $product->save($con); + } + $this->productsScheduledForDeletion = null; + } + } + + if ($this->collProducts !== null) { + foreach ($this->collProducts as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->brandDocumentsScheduledForDeletion !== null) { + if (!$this->brandDocumentsScheduledForDeletion->isEmpty()) { + \Thelia\Model\BrandDocumentQuery::create() + ->filterByPrimaryKeys($this->brandDocumentsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->brandDocumentsScheduledForDeletion = null; + } + } + + if ($this->collBrandDocuments !== null) { + foreach ($this->collBrandDocuments as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->brandImagesRelatedByBrandIdScheduledForDeletion !== null) { + if (!$this->brandImagesRelatedByBrandIdScheduledForDeletion->isEmpty()) { + \Thelia\Model\BrandImageQuery::create() + ->filterByPrimaryKeys($this->brandImagesRelatedByBrandIdScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->brandImagesRelatedByBrandIdScheduledForDeletion = null; + } + } + + if ($this->collBrandImagesRelatedByBrandId !== null) { + foreach ($this->collBrandImagesRelatedByBrandId as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->brandI18nsScheduledForDeletion !== null) { + if (!$this->brandI18nsScheduledForDeletion->isEmpty()) { + \Thelia\Model\BrandI18nQuery::create() + ->filterByPrimaryKeys($this->brandI18nsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->brandI18nsScheduledForDeletion = null; + } + } + + if ($this->collBrandI18ns !== null) { + foreach ($this->collBrandI18ns 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[BrandTableMap::ID] = true; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . BrandTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(BrandTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(BrandTableMap::VISIBLE)) { + $modifiedColumns[':p' . $index++] = '`VISIBLE`'; + } + if ($this->isColumnModified(BrandTableMap::POSITION)) { + $modifiedColumns[':p' . $index++] = '`POSITION`'; + } + if ($this->isColumnModified(BrandTableMap::LOGO_IMAGE_ID)) { + $modifiedColumns[':p' . $index++] = '`LOGO_IMAGE_ID`'; + } + if ($this->isColumnModified(BrandTableMap::CREATED_AT)) { + $modifiedColumns[':p' . $index++] = '`CREATED_AT`'; + } + if ($this->isColumnModified(BrandTableMap::UPDATED_AT)) { + $modifiedColumns[':p' . $index++] = '`UPDATED_AT`'; + } + + $sql = sprintf( + 'INSERT INTO `brand` (%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 '`VISIBLE`': + $stmt->bindValue($identifier, $this->visible, PDO::PARAM_INT); + break; + case '`POSITION`': + $stmt->bindValue($identifier, $this->position, PDO::PARAM_INT); + break; + case '`LOGO_IMAGE_ID`': + $stmt->bindValue($identifier, $this->logo_image_id, 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 = BrandTableMap::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->getVisible(); + break; + case 2: + return $this->getPosition(); + break; + case 3: + return $this->getLogoImageId(); + break; + case 4: + return $this->getCreatedAt(); + break; + case 5: + 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['Brand'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['Brand'][$this->getPrimaryKey()] = true; + $keys = BrandTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getVisible(), + $keys[2] => $this->getPosition(), + $keys[3] => $this->getLogoImageId(), + $keys[4] => $this->getCreatedAt(), + $keys[5] => $this->getUpdatedAt(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aBrandImageRelatedByLogoImageId) { + $result['BrandImageRelatedByLogoImageId'] = $this->aBrandImageRelatedByLogoImageId->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->collProducts) { + $result['Products'] = $this->collProducts->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collBrandDocuments) { + $result['BrandDocuments'] = $this->collBrandDocuments->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collBrandImagesRelatedByBrandId) { + $result['BrandImagesRelatedByBrandId'] = $this->collBrandImagesRelatedByBrandId->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collBrandI18ns) { + $result['BrandI18ns'] = $this->collBrandI18ns->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 = BrandTableMap::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->setVisible($value); + break; + case 2: + $this->setPosition($value); + break; + case 3: + $this->setLogoImageId($value); + break; + case 4: + $this->setCreatedAt($value); + break; + case 5: + $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 = BrandTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setVisible($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setPosition($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setLogoImageId($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setCreatedAt($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setUpdatedAt($arr[$keys[5]]); + } + + /** + * 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(BrandTableMap::DATABASE_NAME); + + if ($this->isColumnModified(BrandTableMap::ID)) $criteria->add(BrandTableMap::ID, $this->id); + if ($this->isColumnModified(BrandTableMap::VISIBLE)) $criteria->add(BrandTableMap::VISIBLE, $this->visible); + if ($this->isColumnModified(BrandTableMap::POSITION)) $criteria->add(BrandTableMap::POSITION, $this->position); + if ($this->isColumnModified(BrandTableMap::LOGO_IMAGE_ID)) $criteria->add(BrandTableMap::LOGO_IMAGE_ID, $this->logo_image_id); + if ($this->isColumnModified(BrandTableMap::CREATED_AT)) $criteria->add(BrandTableMap::CREATED_AT, $this->created_at); + if ($this->isColumnModified(BrandTableMap::UPDATED_AT)) $criteria->add(BrandTableMap::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(BrandTableMap::DATABASE_NAME); + $criteria->add(BrandTableMap::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\Brand (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->setVisible($this->getVisible()); + $copyObj->setPosition($this->getPosition()); + $copyObj->setLogoImageId($this->getLogoImageId()); + $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->getProducts() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addProduct($relObj->copy($deepCopy)); + } + } + + foreach ($this->getBrandDocuments() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addBrandDocument($relObj->copy($deepCopy)); + } + } + + foreach ($this->getBrandImagesRelatedByBrandId() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addBrandImageRelatedByBrandId($relObj->copy($deepCopy)); + } + } + + foreach ($this->getBrandI18ns() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addBrandI18n($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\Brand 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 ChildBrandImage object. + * + * @param ChildBrandImage $v + * @return \Thelia\Model\Brand The current object (for fluent API support) + * @throws PropelException + */ + public function setBrandImageRelatedByLogoImageId(ChildBrandImage $v = null) + { + if ($v === null) { + $this->setLogoImageId(NULL); + } else { + $this->setLogoImageId($v->getId()); + } + + $this->aBrandImageRelatedByLogoImageId = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildBrandImage object, it will not be re-added. + if ($v !== null) { + $v->addBrandRelatedByLogoImageId($this); + } + + + return $this; + } + + + /** + * Get the associated ChildBrandImage object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildBrandImage The associated ChildBrandImage object. + * @throws PropelException + */ + public function getBrandImageRelatedByLogoImageId(ConnectionInterface $con = null) + { + if ($this->aBrandImageRelatedByLogoImageId === null && ($this->logo_image_id !== null)) { + $this->aBrandImageRelatedByLogoImageId = ChildBrandImageQuery::create()->findPk($this->logo_image_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->aBrandImageRelatedByLogoImageId->addBrandsRelatedByLogoImageId($this); + */ + } + + return $this->aBrandImageRelatedByLogoImageId; + } + + + /** + * 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 ('Product' == $relationName) { + return $this->initProducts(); + } + if ('BrandDocument' == $relationName) { + return $this->initBrandDocuments(); + } + if ('BrandImageRelatedByBrandId' == $relationName) { + return $this->initBrandImagesRelatedByBrandId(); + } + if ('BrandI18n' == $relationName) { + return $this->initBrandI18ns(); + } + } + + /** + * Clears out the collProducts 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 addProducts() + */ + public function clearProducts() + { + $this->collProducts = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collProducts collection loaded partially. + */ + public function resetPartialProducts($v = true) + { + $this->collProductsPartial = $v; + } + + /** + * Initializes the collProducts collection. + * + * By default this just sets the collProducts collection to an empty array (like clearcollProducts()); + * 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 initProducts($overrideExisting = true) + { + if (null !== $this->collProducts && !$overrideExisting) { + return; + } + $this->collProducts = new ObjectCollection(); + $this->collProducts->setModel('\Thelia\Model\Product'); + } + + /** + * Gets an array of ChildProduct 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 ChildBrand 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|ChildProduct[] List of ChildProduct objects + * @throws PropelException + */ + public function getProducts($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collProductsPartial && !$this->isNew(); + if (null === $this->collProducts || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collProducts) { + // return empty collection + $this->initProducts(); + } else { + $collProducts = ChildProductQuery::create(null, $criteria) + ->filterByBrand($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collProductsPartial && count($collProducts)) { + $this->initProducts(false); + + foreach ($collProducts as $obj) { + if (false == $this->collProducts->contains($obj)) { + $this->collProducts->append($obj); + } + } + + $this->collProductsPartial = true; + } + + reset($collProducts); + + return $collProducts; + } + + if ($partial && $this->collProducts) { + foreach ($this->collProducts as $obj) { + if ($obj->isNew()) { + $collProducts[] = $obj; + } + } + } + + $this->collProducts = $collProducts; + $this->collProductsPartial = false; + } + } + + return $this->collProducts; + } + + /** + * Sets a collection of Product 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 $products A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildBrand The current object (for fluent API support) + */ + public function setProducts(Collection $products, ConnectionInterface $con = null) + { + $productsToDelete = $this->getProducts(new Criteria(), $con)->diff($products); + + + $this->productsScheduledForDeletion = $productsToDelete; + + foreach ($productsToDelete as $productRemoved) { + $productRemoved->setBrand(null); + } + + $this->collProducts = null; + foreach ($products as $product) { + $this->addProduct($product); + } + + $this->collProducts = $products; + $this->collProductsPartial = false; + + return $this; + } + + /** + * Returns the number of related Product objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related Product objects. + * @throws PropelException + */ + public function countProducts(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collProductsPartial && !$this->isNew(); + if (null === $this->collProducts || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collProducts) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getProducts()); + } + + $query = ChildProductQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByBrand($this) + ->count($con); + } + + return count($this->collProducts); + } + + /** + * Method called to associate a ChildProduct object to this object + * through the ChildProduct foreign key attribute. + * + * @param ChildProduct $l ChildProduct + * @return \Thelia\Model\Brand The current object (for fluent API support) + */ + public function addProduct(ChildProduct $l) + { + if ($this->collProducts === null) { + $this->initProducts(); + $this->collProductsPartial = true; + } + + if (!in_array($l, $this->collProducts->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddProduct($l); + } + + return $this; + } + + /** + * @param Product $product The product object to add. + */ + protected function doAddProduct($product) + { + $this->collProducts[]= $product; + $product->setBrand($this); + } + + /** + * @param Product $product The product object to remove. + * @return ChildBrand The current object (for fluent API support) + */ + public function removeProduct($product) + { + if ($this->getProducts()->contains($product)) { + $this->collProducts->remove($this->collProducts->search($product)); + if (null === $this->productsScheduledForDeletion) { + $this->productsScheduledForDeletion = clone $this->collProducts; + $this->productsScheduledForDeletion->clear(); + } + $this->productsScheduledForDeletion[]= $product; + $product->setBrand(null); + } + + return $this; + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Brand is new, it will return + * an empty collection; or if this Brand has previously + * been saved, it will retrieve related Products from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in Brand. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildProduct[] List of ChildProduct objects + */ + public function getProductsJoinTaxRule($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildProductQuery::create(null, $criteria); + $query->joinWith('TaxRule', $joinBehavior); + + return $this->getProducts($query, $con); + } + + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Brand is new, it will return + * an empty collection; or if this Brand has previously + * been saved, it will retrieve related Products from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in Brand. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildProduct[] List of ChildProduct objects + */ + public function getProductsJoinTemplate($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildProductQuery::create(null, $criteria); + $query->joinWith('Template', $joinBehavior); + + return $this->getProducts($query, $con); + } + + /** + * Clears out the collBrandDocuments 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 addBrandDocuments() + */ + public function clearBrandDocuments() + { + $this->collBrandDocuments = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collBrandDocuments collection loaded partially. + */ + public function resetPartialBrandDocuments($v = true) + { + $this->collBrandDocumentsPartial = $v; + } + + /** + * Initializes the collBrandDocuments collection. + * + * By default this just sets the collBrandDocuments collection to an empty array (like clearcollBrandDocuments()); + * 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 initBrandDocuments($overrideExisting = true) + { + if (null !== $this->collBrandDocuments && !$overrideExisting) { + return; + } + $this->collBrandDocuments = new ObjectCollection(); + $this->collBrandDocuments->setModel('\Thelia\Model\BrandDocument'); + } + + /** + * Gets an array of ChildBrandDocument 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 ChildBrand 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|ChildBrandDocument[] List of ChildBrandDocument objects + * @throws PropelException + */ + public function getBrandDocuments($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collBrandDocumentsPartial && !$this->isNew(); + if (null === $this->collBrandDocuments || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collBrandDocuments) { + // return empty collection + $this->initBrandDocuments(); + } else { + $collBrandDocuments = ChildBrandDocumentQuery::create(null, $criteria) + ->filterByBrand($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collBrandDocumentsPartial && count($collBrandDocuments)) { + $this->initBrandDocuments(false); + + foreach ($collBrandDocuments as $obj) { + if (false == $this->collBrandDocuments->contains($obj)) { + $this->collBrandDocuments->append($obj); + } + } + + $this->collBrandDocumentsPartial = true; + } + + reset($collBrandDocuments); + + return $collBrandDocuments; + } + + if ($partial && $this->collBrandDocuments) { + foreach ($this->collBrandDocuments as $obj) { + if ($obj->isNew()) { + $collBrandDocuments[] = $obj; + } + } + } + + $this->collBrandDocuments = $collBrandDocuments; + $this->collBrandDocumentsPartial = false; + } + } + + return $this->collBrandDocuments; + } + + /** + * Sets a collection of BrandDocument 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 $brandDocuments A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildBrand The current object (for fluent API support) + */ + public function setBrandDocuments(Collection $brandDocuments, ConnectionInterface $con = null) + { + $brandDocumentsToDelete = $this->getBrandDocuments(new Criteria(), $con)->diff($brandDocuments); + + + $this->brandDocumentsScheduledForDeletion = $brandDocumentsToDelete; + + foreach ($brandDocumentsToDelete as $brandDocumentRemoved) { + $brandDocumentRemoved->setBrand(null); + } + + $this->collBrandDocuments = null; + foreach ($brandDocuments as $brandDocument) { + $this->addBrandDocument($brandDocument); + } + + $this->collBrandDocuments = $brandDocuments; + $this->collBrandDocumentsPartial = false; + + return $this; + } + + /** + * Returns the number of related BrandDocument objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related BrandDocument objects. + * @throws PropelException + */ + public function countBrandDocuments(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collBrandDocumentsPartial && !$this->isNew(); + if (null === $this->collBrandDocuments || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collBrandDocuments) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getBrandDocuments()); + } + + $query = ChildBrandDocumentQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByBrand($this) + ->count($con); + } + + return count($this->collBrandDocuments); + } + + /** + * Method called to associate a ChildBrandDocument object to this object + * through the ChildBrandDocument foreign key attribute. + * + * @param ChildBrandDocument $l ChildBrandDocument + * @return \Thelia\Model\Brand The current object (for fluent API support) + */ + public function addBrandDocument(ChildBrandDocument $l) + { + if ($this->collBrandDocuments === null) { + $this->initBrandDocuments(); + $this->collBrandDocumentsPartial = true; + } + + if (!in_array($l, $this->collBrandDocuments->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddBrandDocument($l); + } + + return $this; + } + + /** + * @param BrandDocument $brandDocument The brandDocument object to add. + */ + protected function doAddBrandDocument($brandDocument) + { + $this->collBrandDocuments[]= $brandDocument; + $brandDocument->setBrand($this); + } + + /** + * @param BrandDocument $brandDocument The brandDocument object to remove. + * @return ChildBrand The current object (for fluent API support) + */ + public function removeBrandDocument($brandDocument) + { + if ($this->getBrandDocuments()->contains($brandDocument)) { + $this->collBrandDocuments->remove($this->collBrandDocuments->search($brandDocument)); + if (null === $this->brandDocumentsScheduledForDeletion) { + $this->brandDocumentsScheduledForDeletion = clone $this->collBrandDocuments; + $this->brandDocumentsScheduledForDeletion->clear(); + } + $this->brandDocumentsScheduledForDeletion[]= clone $brandDocument; + $brandDocument->setBrand(null); + } + + return $this; + } + + /** + * Clears out the collBrandImagesRelatedByBrandId 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 addBrandImagesRelatedByBrandId() + */ + public function clearBrandImagesRelatedByBrandId() + { + $this->collBrandImagesRelatedByBrandId = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collBrandImagesRelatedByBrandId collection loaded partially. + */ + public function resetPartialBrandImagesRelatedByBrandId($v = true) + { + $this->collBrandImagesRelatedByBrandIdPartial = $v; + } + + /** + * Initializes the collBrandImagesRelatedByBrandId collection. + * + * By default this just sets the collBrandImagesRelatedByBrandId collection to an empty array (like clearcollBrandImagesRelatedByBrandId()); + * 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 initBrandImagesRelatedByBrandId($overrideExisting = true) + { + if (null !== $this->collBrandImagesRelatedByBrandId && !$overrideExisting) { + return; + } + $this->collBrandImagesRelatedByBrandId = new ObjectCollection(); + $this->collBrandImagesRelatedByBrandId->setModel('\Thelia\Model\BrandImage'); + } + + /** + * Gets an array of ChildBrandImage 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 ChildBrand 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|ChildBrandImage[] List of ChildBrandImage objects + * @throws PropelException + */ + public function getBrandImagesRelatedByBrandId($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collBrandImagesRelatedByBrandIdPartial && !$this->isNew(); + if (null === $this->collBrandImagesRelatedByBrandId || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collBrandImagesRelatedByBrandId) { + // return empty collection + $this->initBrandImagesRelatedByBrandId(); + } else { + $collBrandImagesRelatedByBrandId = ChildBrandImageQuery::create(null, $criteria) + ->filterByBrandRelatedByBrandId($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collBrandImagesRelatedByBrandIdPartial && count($collBrandImagesRelatedByBrandId)) { + $this->initBrandImagesRelatedByBrandId(false); + + foreach ($collBrandImagesRelatedByBrandId as $obj) { + if (false == $this->collBrandImagesRelatedByBrandId->contains($obj)) { + $this->collBrandImagesRelatedByBrandId->append($obj); + } + } + + $this->collBrandImagesRelatedByBrandIdPartial = true; + } + + reset($collBrandImagesRelatedByBrandId); + + return $collBrandImagesRelatedByBrandId; + } + + if ($partial && $this->collBrandImagesRelatedByBrandId) { + foreach ($this->collBrandImagesRelatedByBrandId as $obj) { + if ($obj->isNew()) { + $collBrandImagesRelatedByBrandId[] = $obj; + } + } + } + + $this->collBrandImagesRelatedByBrandId = $collBrandImagesRelatedByBrandId; + $this->collBrandImagesRelatedByBrandIdPartial = false; + } + } + + return $this->collBrandImagesRelatedByBrandId; + } + + /** + * Sets a collection of BrandImageRelatedByBrandId 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 $brandImagesRelatedByBrandId A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildBrand The current object (for fluent API support) + */ + public function setBrandImagesRelatedByBrandId(Collection $brandImagesRelatedByBrandId, ConnectionInterface $con = null) + { + $brandImagesRelatedByBrandIdToDelete = $this->getBrandImagesRelatedByBrandId(new Criteria(), $con)->diff($brandImagesRelatedByBrandId); + + + $this->brandImagesRelatedByBrandIdScheduledForDeletion = $brandImagesRelatedByBrandIdToDelete; + + foreach ($brandImagesRelatedByBrandIdToDelete as $brandImageRelatedByBrandIdRemoved) { + $brandImageRelatedByBrandIdRemoved->setBrandRelatedByBrandId(null); + } + + $this->collBrandImagesRelatedByBrandId = null; + foreach ($brandImagesRelatedByBrandId as $brandImageRelatedByBrandId) { + $this->addBrandImageRelatedByBrandId($brandImageRelatedByBrandId); + } + + $this->collBrandImagesRelatedByBrandId = $brandImagesRelatedByBrandId; + $this->collBrandImagesRelatedByBrandIdPartial = false; + + return $this; + } + + /** + * Returns the number of related BrandImage objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related BrandImage objects. + * @throws PropelException + */ + public function countBrandImagesRelatedByBrandId(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collBrandImagesRelatedByBrandIdPartial && !$this->isNew(); + if (null === $this->collBrandImagesRelatedByBrandId || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collBrandImagesRelatedByBrandId) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getBrandImagesRelatedByBrandId()); + } + + $query = ChildBrandImageQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByBrandRelatedByBrandId($this) + ->count($con); + } + + return count($this->collBrandImagesRelatedByBrandId); + } + + /** + * Method called to associate a ChildBrandImage object to this object + * through the ChildBrandImage foreign key attribute. + * + * @param ChildBrandImage $l ChildBrandImage + * @return \Thelia\Model\Brand The current object (for fluent API support) + */ + public function addBrandImageRelatedByBrandId(ChildBrandImage $l) + { + if ($this->collBrandImagesRelatedByBrandId === null) { + $this->initBrandImagesRelatedByBrandId(); + $this->collBrandImagesRelatedByBrandIdPartial = true; + } + + if (!in_array($l, $this->collBrandImagesRelatedByBrandId->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddBrandImageRelatedByBrandId($l); + } + + return $this; + } + + /** + * @param BrandImageRelatedByBrandId $brandImageRelatedByBrandId The brandImageRelatedByBrandId object to add. + */ + protected function doAddBrandImageRelatedByBrandId($brandImageRelatedByBrandId) + { + $this->collBrandImagesRelatedByBrandId[]= $brandImageRelatedByBrandId; + $brandImageRelatedByBrandId->setBrandRelatedByBrandId($this); + } + + /** + * @param BrandImageRelatedByBrandId $brandImageRelatedByBrandId The brandImageRelatedByBrandId object to remove. + * @return ChildBrand The current object (for fluent API support) + */ + public function removeBrandImageRelatedByBrandId($brandImageRelatedByBrandId) + { + if ($this->getBrandImagesRelatedByBrandId()->contains($brandImageRelatedByBrandId)) { + $this->collBrandImagesRelatedByBrandId->remove($this->collBrandImagesRelatedByBrandId->search($brandImageRelatedByBrandId)); + if (null === $this->brandImagesRelatedByBrandIdScheduledForDeletion) { + $this->brandImagesRelatedByBrandIdScheduledForDeletion = clone $this->collBrandImagesRelatedByBrandId; + $this->brandImagesRelatedByBrandIdScheduledForDeletion->clear(); + } + $this->brandImagesRelatedByBrandIdScheduledForDeletion[]= clone $brandImageRelatedByBrandId; + $brandImageRelatedByBrandId->setBrandRelatedByBrandId(null); + } + + return $this; + } + + /** + * Clears out the collBrandI18ns 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 addBrandI18ns() + */ + public function clearBrandI18ns() + { + $this->collBrandI18ns = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collBrandI18ns collection loaded partially. + */ + public function resetPartialBrandI18ns($v = true) + { + $this->collBrandI18nsPartial = $v; + } + + /** + * Initializes the collBrandI18ns collection. + * + * By default this just sets the collBrandI18ns collection to an empty array (like clearcollBrandI18ns()); + * 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 initBrandI18ns($overrideExisting = true) + { + if (null !== $this->collBrandI18ns && !$overrideExisting) { + return; + } + $this->collBrandI18ns = new ObjectCollection(); + $this->collBrandI18ns->setModel('\Thelia\Model\BrandI18n'); + } + + /** + * Gets an array of ChildBrandI18n 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 ChildBrand 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|ChildBrandI18n[] List of ChildBrandI18n objects + * @throws PropelException + */ + public function getBrandI18ns($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collBrandI18nsPartial && !$this->isNew(); + if (null === $this->collBrandI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collBrandI18ns) { + // return empty collection + $this->initBrandI18ns(); + } else { + $collBrandI18ns = ChildBrandI18nQuery::create(null, $criteria) + ->filterByBrand($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collBrandI18nsPartial && count($collBrandI18ns)) { + $this->initBrandI18ns(false); + + foreach ($collBrandI18ns as $obj) { + if (false == $this->collBrandI18ns->contains($obj)) { + $this->collBrandI18ns->append($obj); + } + } + + $this->collBrandI18nsPartial = true; + } + + reset($collBrandI18ns); + + return $collBrandI18ns; + } + + if ($partial && $this->collBrandI18ns) { + foreach ($this->collBrandI18ns as $obj) { + if ($obj->isNew()) { + $collBrandI18ns[] = $obj; + } + } + } + + $this->collBrandI18ns = $collBrandI18ns; + $this->collBrandI18nsPartial = false; + } + } + + return $this->collBrandI18ns; + } + + /** + * Sets a collection of BrandI18n 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 $brandI18ns A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildBrand The current object (for fluent API support) + */ + public function setBrandI18ns(Collection $brandI18ns, ConnectionInterface $con = null) + { + $brandI18nsToDelete = $this->getBrandI18ns(new Criteria(), $con)->diff($brandI18ns); + + + //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->brandI18nsScheduledForDeletion = clone $brandI18nsToDelete; + + foreach ($brandI18nsToDelete as $brandI18nRemoved) { + $brandI18nRemoved->setBrand(null); + } + + $this->collBrandI18ns = null; + foreach ($brandI18ns as $brandI18n) { + $this->addBrandI18n($brandI18n); + } + + $this->collBrandI18ns = $brandI18ns; + $this->collBrandI18nsPartial = false; + + return $this; + } + + /** + * Returns the number of related BrandI18n objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related BrandI18n objects. + * @throws PropelException + */ + public function countBrandI18ns(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collBrandI18nsPartial && !$this->isNew(); + if (null === $this->collBrandI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collBrandI18ns) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getBrandI18ns()); + } + + $query = ChildBrandI18nQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByBrand($this) + ->count($con); + } + + return count($this->collBrandI18ns); + } + + /** + * Method called to associate a ChildBrandI18n object to this object + * through the ChildBrandI18n foreign key attribute. + * + * @param ChildBrandI18n $l ChildBrandI18n + * @return \Thelia\Model\Brand The current object (for fluent API support) + */ + public function addBrandI18n(ChildBrandI18n $l) + { + if ($l && $locale = $l->getLocale()) { + $this->setLocale($locale); + $this->currentTranslations[$locale] = $l; + } + if ($this->collBrandI18ns === null) { + $this->initBrandI18ns(); + $this->collBrandI18nsPartial = true; + } + + if (!in_array($l, $this->collBrandI18ns->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddBrandI18n($l); + } + + return $this; + } + + /** + * @param BrandI18n $brandI18n The brandI18n object to add. + */ + protected function doAddBrandI18n($brandI18n) + { + $this->collBrandI18ns[]= $brandI18n; + $brandI18n->setBrand($this); + } + + /** + * @param BrandI18n $brandI18n The brandI18n object to remove. + * @return ChildBrand The current object (for fluent API support) + */ + public function removeBrandI18n($brandI18n) + { + if ($this->getBrandI18ns()->contains($brandI18n)) { + $this->collBrandI18ns->remove($this->collBrandI18ns->search($brandI18n)); + if (null === $this->brandI18nsScheduledForDeletion) { + $this->brandI18nsScheduledForDeletion = clone $this->collBrandI18ns; + $this->brandI18nsScheduledForDeletion->clear(); + } + $this->brandI18nsScheduledForDeletion[]= clone $brandI18n; + $brandI18n->setBrand(null); + } + + return $this; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->visible = null; + $this->position = null; + $this->logo_image_id = 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->collProducts) { + foreach ($this->collProducts as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collBrandDocuments) { + foreach ($this->collBrandDocuments as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collBrandImagesRelatedByBrandId) { + foreach ($this->collBrandImagesRelatedByBrandId as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collBrandI18ns) { + foreach ($this->collBrandI18ns as $o) { + $o->clearAllReferences($deep); + } + } + } // if ($deep) + + // i18n behavior + $this->currentLocale = 'en_US'; + $this->currentTranslations = null; + + $this->collProducts = null; + $this->collBrandDocuments = null; + $this->collBrandImagesRelatedByBrandId = null; + $this->collBrandI18ns = null; + $this->aBrandImageRelatedByLogoImageId = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(BrandTableMap::DEFAULT_STRING_FORMAT); + } + + // timestampable behavior + + /** + * Mark the current object so that the update date doesn't get updated during next save + * + * @return ChildBrand The current object (for fluent API support) + */ + public function keepUpdateDateUnchanged() + { + $this->modifiedColumns[BrandTableMap::UPDATED_AT] = true; + + return $this; + } + + // i18n behavior + + /** + * Sets the locale for translations + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * + * @return ChildBrand 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 ChildBrandI18n */ + public function getTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!isset($this->currentTranslations[$locale])) { + if (null !== $this->collBrandI18ns) { + foreach ($this->collBrandI18ns as $translation) { + if ($translation->getLocale() == $locale) { + $this->currentTranslations[$locale] = $translation; + + return $translation; + } + } + } + if ($this->isNew()) { + $translation = new ChildBrandI18n(); + $translation->setLocale($locale); + } else { + $translation = ChildBrandI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->findOneOrCreate($con); + $this->currentTranslations[$locale] = $translation; + } + $this->addBrandI18n($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 ChildBrand The current object (for fluent API support) + */ + public function removeTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!$this->isNew()) { + ChildBrandI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->delete($con); + } + if (isset($this->currentTranslations[$locale])) { + unset($this->currentTranslations[$locale]); + } + foreach ($this->collBrandI18ns as $key => $translation) { + if ($translation->getLocale() == $locale) { + unset($this->collBrandI18ns[$key]); + break; + } + } + + return $this; + } + + /** + * Returns the current translation + * + * @param ConnectionInterface $con an optional connection object + * + * @return ChildBrandI18n */ + 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\BrandI18n 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\BrandI18n The current object (for fluent API support) + */ + public function setDescription($v) + { $this->getCurrentTranslation()->setDescription($v); + + return $this; + } + + + /** + * Get the [chapo] column value. + * + * @return string + */ + public function getChapo() + { + return $this->getCurrentTranslation()->getChapo(); + } + + + /** + * Set the value of [chapo] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n The current object (for fluent API support) + */ + public function setChapo($v) + { $this->getCurrentTranslation()->setChapo($v); + + return $this; + } + + + /** + * Get the [postscriptum] column value. + * + * @return string + */ + public function getPostscriptum() + { + return $this->getCurrentTranslation()->getPostscriptum(); + } + + + /** + * Set the value of [postscriptum] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n The current object (for fluent API support) + */ + public function setPostscriptum($v) + { $this->getCurrentTranslation()->setPostscriptum($v); + + return $this; + } + + + /** + * Get the [meta_title] column value. + * + * @return string + */ + public function getMetaTitle() + { + return $this->getCurrentTranslation()->getMetaTitle(); + } + + + /** + * Set the value of [meta_title] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n The current object (for fluent API support) + */ + public function setMetaTitle($v) + { $this->getCurrentTranslation()->setMetaTitle($v); + + return $this; + } + + + /** + * Get the [meta_description] column value. + * + * @return string + */ + public function getMetaDescription() + { + return $this->getCurrentTranslation()->getMetaDescription(); + } + + + /** + * Set the value of [meta_description] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n The current object (for fluent API support) + */ + public function setMetaDescription($v) + { $this->getCurrentTranslation()->setMetaDescription($v); + + return $this; + } + + + /** + * Get the [meta_keywords] column value. + * + * @return string + */ + public function getMetaKeywords() + { + return $this->getCurrentTranslation()->getMetaKeywords(); + } + + + /** + * Set the value of [meta_keywords] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n The current object (for fluent API support) + */ + public function setMetaKeywords($v) + { $this->getCurrentTranslation()->setMetaKeywords($v); + + 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/BrandDocument.php b/core/lib/Thelia/Model/Base/BrandDocument.php new file mode 100644 index 000000000..3e68952ac --- /dev/null +++ b/core/lib/Thelia/Model/Base/BrandDocument.php @@ -0,0 +1,1990 @@ +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 BrandDocument instance. If + * obj is an instance of BrandDocument, delegates to + * equals(BrandDocument). 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 BrandDocument 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 BrandDocument 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 [brand_id] column value. + * + * @return int + */ + public function getBrandId() + { + + return $this->brand_id; + } + + /** + * Get the [file] column value. + * + * @return string + */ + public function getFile() + { + + return $this->file; + } + + /** + * 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\BrandDocument 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[BrandDocumentTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [brand_id] column. + * + * @param int $v new value + * @return \Thelia\Model\BrandDocument The current object (for fluent API support) + */ + public function setBrandId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->brand_id !== $v) { + $this->brand_id = $v; + $this->modifiedColumns[BrandDocumentTableMap::BRAND_ID] = true; + } + + if ($this->aBrand !== null && $this->aBrand->getId() !== $v) { + $this->aBrand = null; + } + + + return $this; + } // setBrandId() + + /** + * Set the value of [file] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandDocument The current object (for fluent API support) + */ + public function setFile($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->file !== $v) { + $this->file = $v; + $this->modifiedColumns[BrandDocumentTableMap::FILE] = true; + } + + + return $this; + } // setFile() + + /** + * Set the value of [position] column. + * + * @param int $v new value + * @return \Thelia\Model\BrandDocument 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[BrandDocumentTableMap::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\BrandDocument 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[BrandDocumentTableMap::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\BrandDocument 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[BrandDocumentTableMap::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 : BrandDocumentTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : BrandDocumentTableMap::translateFieldName('BrandId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->brand_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : BrandDocumentTableMap::translateFieldName('File', TableMap::TYPE_PHPNAME, $indexType)]; + $this->file = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : BrandDocumentTableMap::translateFieldName('Position', TableMap::TYPE_PHPNAME, $indexType)]; + $this->position = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : BrandDocumentTableMap::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 ? 5 + $startcol : BrandDocumentTableMap::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 + 6; // 6 = BrandDocumentTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\BrandDocument 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->aBrand !== null && $this->brand_id !== $this->aBrand->getId()) { + $this->aBrand = 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(BrandDocumentTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildBrandDocumentQuery::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->aBrand = null; + $this->collBrandDocumentI18ns = null; + + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see BrandDocument::setDeleted() + * @see BrandDocument::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(BrandDocumentTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildBrandDocumentQuery::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(BrandDocumentTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + // timestampable behavior + if (!$this->isColumnModified(BrandDocumentTableMap::CREATED_AT)) { + $this->setCreatedAt(time()); + } + if (!$this->isColumnModified(BrandDocumentTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } else { + $ret = $ret && $this->preUpdate($con); + // timestampable behavior + if ($this->isModified() && !$this->isColumnModified(BrandDocumentTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + BrandDocumentTableMap::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->aBrand !== null) { + if ($this->aBrand->isModified() || $this->aBrand->isNew()) { + $affectedRows += $this->aBrand->save($con); + } + $this->setBrand($this->aBrand); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + if ($this->brandDocumentI18nsScheduledForDeletion !== null) { + if (!$this->brandDocumentI18nsScheduledForDeletion->isEmpty()) { + \Thelia\Model\BrandDocumentI18nQuery::create() + ->filterByPrimaryKeys($this->brandDocumentI18nsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->brandDocumentI18nsScheduledForDeletion = null; + } + } + + if ($this->collBrandDocumentI18ns !== null) { + foreach ($this->collBrandDocumentI18ns 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[BrandDocumentTableMap::ID] = true; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . BrandDocumentTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(BrandDocumentTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(BrandDocumentTableMap::BRAND_ID)) { + $modifiedColumns[':p' . $index++] = '`BRAND_ID`'; + } + if ($this->isColumnModified(BrandDocumentTableMap::FILE)) { + $modifiedColumns[':p' . $index++] = '`FILE`'; + } + if ($this->isColumnModified(BrandDocumentTableMap::POSITION)) { + $modifiedColumns[':p' . $index++] = '`POSITION`'; + } + if ($this->isColumnModified(BrandDocumentTableMap::CREATED_AT)) { + $modifiedColumns[':p' . $index++] = '`CREATED_AT`'; + } + if ($this->isColumnModified(BrandDocumentTableMap::UPDATED_AT)) { + $modifiedColumns[':p' . $index++] = '`UPDATED_AT`'; + } + + $sql = sprintf( + 'INSERT INTO `brand_document` (%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 '`BRAND_ID`': + $stmt->bindValue($identifier, $this->brand_id, PDO::PARAM_INT); + break; + case '`FILE`': + $stmt->bindValue($identifier, $this->file, 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 = BrandDocumentTableMap::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->getBrandId(); + break; + case 2: + return $this->getFile(); + break; + case 3: + return $this->getPosition(); + break; + case 4: + return $this->getCreatedAt(); + break; + case 5: + 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['BrandDocument'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['BrandDocument'][$this->getPrimaryKey()] = true; + $keys = BrandDocumentTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getBrandId(), + $keys[2] => $this->getFile(), + $keys[3] => $this->getPosition(), + $keys[4] => $this->getCreatedAt(), + $keys[5] => $this->getUpdatedAt(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aBrand) { + $result['Brand'] = $this->aBrand->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->collBrandDocumentI18ns) { + $result['BrandDocumentI18ns'] = $this->collBrandDocumentI18ns->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 = BrandDocumentTableMap::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->setBrandId($value); + break; + case 2: + $this->setFile($value); + break; + case 3: + $this->setPosition($value); + break; + case 4: + $this->setCreatedAt($value); + break; + case 5: + $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 = BrandDocumentTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setBrandId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setFile($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setPosition($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setCreatedAt($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setUpdatedAt($arr[$keys[5]]); + } + + /** + * 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(BrandDocumentTableMap::DATABASE_NAME); + + if ($this->isColumnModified(BrandDocumentTableMap::ID)) $criteria->add(BrandDocumentTableMap::ID, $this->id); + if ($this->isColumnModified(BrandDocumentTableMap::BRAND_ID)) $criteria->add(BrandDocumentTableMap::BRAND_ID, $this->brand_id); + if ($this->isColumnModified(BrandDocumentTableMap::FILE)) $criteria->add(BrandDocumentTableMap::FILE, $this->file); + if ($this->isColumnModified(BrandDocumentTableMap::POSITION)) $criteria->add(BrandDocumentTableMap::POSITION, $this->position); + if ($this->isColumnModified(BrandDocumentTableMap::CREATED_AT)) $criteria->add(BrandDocumentTableMap::CREATED_AT, $this->created_at); + if ($this->isColumnModified(BrandDocumentTableMap::UPDATED_AT)) $criteria->add(BrandDocumentTableMap::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(BrandDocumentTableMap::DATABASE_NAME); + $criteria->add(BrandDocumentTableMap::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\BrandDocument (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->setBrandId($this->getBrandId()); + $copyObj->setFile($this->getFile()); + $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->getBrandDocumentI18ns() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addBrandDocumentI18n($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\BrandDocument 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 ChildBrand object. + * + * @param ChildBrand $v + * @return \Thelia\Model\BrandDocument The current object (for fluent API support) + * @throws PropelException + */ + public function setBrand(ChildBrand $v = null) + { + if ($v === null) { + $this->setBrandId(NULL); + } else { + $this->setBrandId($v->getId()); + } + + $this->aBrand = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildBrand object, it will not be re-added. + if ($v !== null) { + $v->addBrandDocument($this); + } + + + return $this; + } + + + /** + * Get the associated ChildBrand object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildBrand The associated ChildBrand object. + * @throws PropelException + */ + public function getBrand(ConnectionInterface $con = null) + { + if ($this->aBrand === null && ($this->brand_id !== null)) { + $this->aBrand = ChildBrandQuery::create()->findPk($this->brand_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->aBrand->addBrandDocuments($this); + */ + } + + return $this->aBrand; + } + + + /** + * 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 ('BrandDocumentI18n' == $relationName) { + return $this->initBrandDocumentI18ns(); + } + } + + /** + * Clears out the collBrandDocumentI18ns 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 addBrandDocumentI18ns() + */ + public function clearBrandDocumentI18ns() + { + $this->collBrandDocumentI18ns = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collBrandDocumentI18ns collection loaded partially. + */ + public function resetPartialBrandDocumentI18ns($v = true) + { + $this->collBrandDocumentI18nsPartial = $v; + } + + /** + * Initializes the collBrandDocumentI18ns collection. + * + * By default this just sets the collBrandDocumentI18ns collection to an empty array (like clearcollBrandDocumentI18ns()); + * 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 initBrandDocumentI18ns($overrideExisting = true) + { + if (null !== $this->collBrandDocumentI18ns && !$overrideExisting) { + return; + } + $this->collBrandDocumentI18ns = new ObjectCollection(); + $this->collBrandDocumentI18ns->setModel('\Thelia\Model\BrandDocumentI18n'); + } + + /** + * Gets an array of ChildBrandDocumentI18n 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 ChildBrandDocument 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|ChildBrandDocumentI18n[] List of ChildBrandDocumentI18n objects + * @throws PropelException + */ + public function getBrandDocumentI18ns($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collBrandDocumentI18nsPartial && !$this->isNew(); + if (null === $this->collBrandDocumentI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collBrandDocumentI18ns) { + // return empty collection + $this->initBrandDocumentI18ns(); + } else { + $collBrandDocumentI18ns = ChildBrandDocumentI18nQuery::create(null, $criteria) + ->filterByBrandDocument($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collBrandDocumentI18nsPartial && count($collBrandDocumentI18ns)) { + $this->initBrandDocumentI18ns(false); + + foreach ($collBrandDocumentI18ns as $obj) { + if (false == $this->collBrandDocumentI18ns->contains($obj)) { + $this->collBrandDocumentI18ns->append($obj); + } + } + + $this->collBrandDocumentI18nsPartial = true; + } + + reset($collBrandDocumentI18ns); + + return $collBrandDocumentI18ns; + } + + if ($partial && $this->collBrandDocumentI18ns) { + foreach ($this->collBrandDocumentI18ns as $obj) { + if ($obj->isNew()) { + $collBrandDocumentI18ns[] = $obj; + } + } + } + + $this->collBrandDocumentI18ns = $collBrandDocumentI18ns; + $this->collBrandDocumentI18nsPartial = false; + } + } + + return $this->collBrandDocumentI18ns; + } + + /** + * Sets a collection of BrandDocumentI18n 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 $brandDocumentI18ns A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildBrandDocument The current object (for fluent API support) + */ + public function setBrandDocumentI18ns(Collection $brandDocumentI18ns, ConnectionInterface $con = null) + { + $brandDocumentI18nsToDelete = $this->getBrandDocumentI18ns(new Criteria(), $con)->diff($brandDocumentI18ns); + + + //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->brandDocumentI18nsScheduledForDeletion = clone $brandDocumentI18nsToDelete; + + foreach ($brandDocumentI18nsToDelete as $brandDocumentI18nRemoved) { + $brandDocumentI18nRemoved->setBrandDocument(null); + } + + $this->collBrandDocumentI18ns = null; + foreach ($brandDocumentI18ns as $brandDocumentI18n) { + $this->addBrandDocumentI18n($brandDocumentI18n); + } + + $this->collBrandDocumentI18ns = $brandDocumentI18ns; + $this->collBrandDocumentI18nsPartial = false; + + return $this; + } + + /** + * Returns the number of related BrandDocumentI18n objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related BrandDocumentI18n objects. + * @throws PropelException + */ + public function countBrandDocumentI18ns(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collBrandDocumentI18nsPartial && !$this->isNew(); + if (null === $this->collBrandDocumentI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collBrandDocumentI18ns) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getBrandDocumentI18ns()); + } + + $query = ChildBrandDocumentI18nQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByBrandDocument($this) + ->count($con); + } + + return count($this->collBrandDocumentI18ns); + } + + /** + * Method called to associate a ChildBrandDocumentI18n object to this object + * through the ChildBrandDocumentI18n foreign key attribute. + * + * @param ChildBrandDocumentI18n $l ChildBrandDocumentI18n + * @return \Thelia\Model\BrandDocument The current object (for fluent API support) + */ + public function addBrandDocumentI18n(ChildBrandDocumentI18n $l) + { + if ($l && $locale = $l->getLocale()) { + $this->setLocale($locale); + $this->currentTranslations[$locale] = $l; + } + if ($this->collBrandDocumentI18ns === null) { + $this->initBrandDocumentI18ns(); + $this->collBrandDocumentI18nsPartial = true; + } + + if (!in_array($l, $this->collBrandDocumentI18ns->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddBrandDocumentI18n($l); + } + + return $this; + } + + /** + * @param BrandDocumentI18n $brandDocumentI18n The brandDocumentI18n object to add. + */ + protected function doAddBrandDocumentI18n($brandDocumentI18n) + { + $this->collBrandDocumentI18ns[]= $brandDocumentI18n; + $brandDocumentI18n->setBrandDocument($this); + } + + /** + * @param BrandDocumentI18n $brandDocumentI18n The brandDocumentI18n object to remove. + * @return ChildBrandDocument The current object (for fluent API support) + */ + public function removeBrandDocumentI18n($brandDocumentI18n) + { + if ($this->getBrandDocumentI18ns()->contains($brandDocumentI18n)) { + $this->collBrandDocumentI18ns->remove($this->collBrandDocumentI18ns->search($brandDocumentI18n)); + if (null === $this->brandDocumentI18nsScheduledForDeletion) { + $this->brandDocumentI18nsScheduledForDeletion = clone $this->collBrandDocumentI18ns; + $this->brandDocumentI18nsScheduledForDeletion->clear(); + } + $this->brandDocumentI18nsScheduledForDeletion[]= clone $brandDocumentI18n; + $brandDocumentI18n->setBrandDocument(null); + } + + return $this; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->brand_id = null; + $this->file = 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->collBrandDocumentI18ns) { + foreach ($this->collBrandDocumentI18ns as $o) { + $o->clearAllReferences($deep); + } + } + } // if ($deep) + + // i18n behavior + $this->currentLocale = 'en_US'; + $this->currentTranslations = null; + + $this->collBrandDocumentI18ns = null; + $this->aBrand = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(BrandDocumentTableMap::DEFAULT_STRING_FORMAT); + } + + // timestampable behavior + + /** + * Mark the current object so that the update date doesn't get updated during next save + * + * @return ChildBrandDocument The current object (for fluent API support) + */ + public function keepUpdateDateUnchanged() + { + $this->modifiedColumns[BrandDocumentTableMap::UPDATED_AT] = true; + + return $this; + } + + // i18n behavior + + /** + * Sets the locale for translations + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * + * @return ChildBrandDocument 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 ChildBrandDocumentI18n */ + public function getTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!isset($this->currentTranslations[$locale])) { + if (null !== $this->collBrandDocumentI18ns) { + foreach ($this->collBrandDocumentI18ns as $translation) { + if ($translation->getLocale() == $locale) { + $this->currentTranslations[$locale] = $translation; + + return $translation; + } + } + } + if ($this->isNew()) { + $translation = new ChildBrandDocumentI18n(); + $translation->setLocale($locale); + } else { + $translation = ChildBrandDocumentI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->findOneOrCreate($con); + $this->currentTranslations[$locale] = $translation; + } + $this->addBrandDocumentI18n($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 ChildBrandDocument The current object (for fluent API support) + */ + public function removeTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!$this->isNew()) { + ChildBrandDocumentI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->delete($con); + } + if (isset($this->currentTranslations[$locale])) { + unset($this->currentTranslations[$locale]); + } + foreach ($this->collBrandDocumentI18ns as $key => $translation) { + if ($translation->getLocale() == $locale) { + unset($this->collBrandDocumentI18ns[$key]); + break; + } + } + + return $this; + } + + /** + * Returns the current translation + * + * @param ConnectionInterface $con an optional connection object + * + * @return ChildBrandDocumentI18n */ + 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\BrandDocumentI18n 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\BrandDocumentI18n The current object (for fluent API support) + */ + public function setDescription($v) + { $this->getCurrentTranslation()->setDescription($v); + + return $this; + } + + + /** + * Get the [chapo] column value. + * + * @return string + */ + public function getChapo() + { + return $this->getCurrentTranslation()->getChapo(); + } + + + /** + * Set the value of [chapo] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandDocumentI18n The current object (for fluent API support) + */ + public function setChapo($v) + { $this->getCurrentTranslation()->setChapo($v); + + return $this; + } + + + /** + * Get the [postscriptum] column value. + * + * @return string + */ + public function getPostscriptum() + { + return $this->getCurrentTranslation()->getPostscriptum(); + } + + + /** + * Set the value of [postscriptum] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandDocumentI18n The current object (for fluent API support) + */ + public function setPostscriptum($v) + { $this->getCurrentTranslation()->setPostscriptum($v); + + 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/BrandDocumentI18n.php b/core/lib/Thelia/Model/Base/BrandDocumentI18n.php new file mode 100644 index 000000000..82eb9a675 --- /dev/null +++ b/core/lib/Thelia/Model/Base/BrandDocumentI18n.php @@ -0,0 +1,1442 @@ +locale = 'en_US'; + } + + /** + * Initializes internal state of Thelia\Model\Base\BrandDocumentI18n 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 BrandDocumentI18n instance. If + * obj is an instance of BrandDocumentI18n, delegates to + * equals(BrandDocumentI18n). 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 BrandDocumentI18n 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 BrandDocumentI18n 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; + } + + /** + * Get the [chapo] column value. + * + * @return string + */ + public function getChapo() + { + + return $this->chapo; + } + + /** + * Get the [postscriptum] column value. + * + * @return string + */ + public function getPostscriptum() + { + + return $this->postscriptum; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\BrandDocumentI18n 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[BrandDocumentI18nTableMap::ID] = true; + } + + if ($this->aBrandDocument !== null && $this->aBrandDocument->getId() !== $v) { + $this->aBrandDocument = null; + } + + + return $this; + } // setId() + + /** + * Set the value of [locale] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandDocumentI18n 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[BrandDocumentI18nTableMap::LOCALE] = true; + } + + + return $this; + } // setLocale() + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandDocumentI18n 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[BrandDocumentI18nTableMap::TITLE] = true; + } + + + return $this; + } // setTitle() + + /** + * Set the value of [description] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandDocumentI18n 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[BrandDocumentI18nTableMap::DESCRIPTION] = true; + } + + + return $this; + } // setDescription() + + /** + * Set the value of [chapo] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandDocumentI18n The current object (for fluent API support) + */ + public function setChapo($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->chapo !== $v) { + $this->chapo = $v; + $this->modifiedColumns[BrandDocumentI18nTableMap::CHAPO] = true; + } + + + return $this; + } // setChapo() + + /** + * Set the value of [postscriptum] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandDocumentI18n The current object (for fluent API support) + */ + public function setPostscriptum($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->postscriptum !== $v) { + $this->postscriptum = $v; + $this->modifiedColumns[BrandDocumentI18nTableMap::POSTSCRIPTUM] = true; + } + + + return $this; + } // setPostscriptum() + + /** + * 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 : BrandDocumentI18nTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : BrandDocumentI18nTableMap::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)]; + $this->locale = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : BrandDocumentI18nTableMap::translateFieldName('Title', TableMap::TYPE_PHPNAME, $indexType)]; + $this->title = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : BrandDocumentI18nTableMap::translateFieldName('Description', TableMap::TYPE_PHPNAME, $indexType)]; + $this->description = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : BrandDocumentI18nTableMap::translateFieldName('Chapo', TableMap::TYPE_PHPNAME, $indexType)]; + $this->chapo = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : BrandDocumentI18nTableMap::translateFieldName('Postscriptum', TableMap::TYPE_PHPNAME, $indexType)]; + $this->postscriptum = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 6; // 6 = BrandDocumentI18nTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\BrandDocumentI18n 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->aBrandDocument !== null && $this->id !== $this->aBrandDocument->getId()) { + $this->aBrandDocument = 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(BrandDocumentI18nTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildBrandDocumentI18nQuery::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->aBrandDocument = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see BrandDocumentI18n::setDeleted() + * @see BrandDocumentI18n::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(BrandDocumentI18nTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildBrandDocumentI18nQuery::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(BrandDocumentI18nTableMap::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); + BrandDocumentI18nTableMap::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->aBrandDocument !== null) { + if ($this->aBrandDocument->isModified() || $this->aBrandDocument->isNew()) { + $affectedRows += $this->aBrandDocument->save($con); + } + $this->setBrandDocument($this->aBrandDocument); + } + + 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(BrandDocumentI18nTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(BrandDocumentI18nTableMap::LOCALE)) { + $modifiedColumns[':p' . $index++] = '`LOCALE`'; + } + if ($this->isColumnModified(BrandDocumentI18nTableMap::TITLE)) { + $modifiedColumns[':p' . $index++] = '`TITLE`'; + } + if ($this->isColumnModified(BrandDocumentI18nTableMap::DESCRIPTION)) { + $modifiedColumns[':p' . $index++] = '`DESCRIPTION`'; + } + if ($this->isColumnModified(BrandDocumentI18nTableMap::CHAPO)) { + $modifiedColumns[':p' . $index++] = '`CHAPO`'; + } + if ($this->isColumnModified(BrandDocumentI18nTableMap::POSTSCRIPTUM)) { + $modifiedColumns[':p' . $index++] = '`POSTSCRIPTUM`'; + } + + $sql = sprintf( + 'INSERT INTO `brand_document_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; + case '`CHAPO`': + $stmt->bindValue($identifier, $this->chapo, PDO::PARAM_STR); + break; + case '`POSTSCRIPTUM`': + $stmt->bindValue($identifier, $this->postscriptum, 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 = BrandDocumentI18nTableMap::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; + case 4: + return $this->getChapo(); + break; + case 5: + return $this->getPostscriptum(); + 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['BrandDocumentI18n'][serialize($this->getPrimaryKey())])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['BrandDocumentI18n'][serialize($this->getPrimaryKey())] = true; + $keys = BrandDocumentI18nTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getLocale(), + $keys[2] => $this->getTitle(), + $keys[3] => $this->getDescription(), + $keys[4] => $this->getChapo(), + $keys[5] => $this->getPostscriptum(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aBrandDocument) { + $result['BrandDocument'] = $this->aBrandDocument->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 = BrandDocumentI18nTableMap::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; + case 4: + $this->setChapo($value); + break; + case 5: + $this->setPostscriptum($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 = BrandDocumentI18nTableMap::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]]); + if (array_key_exists($keys[4], $arr)) $this->setChapo($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setPostscriptum($arr[$keys[5]]); + } + + /** + * 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(BrandDocumentI18nTableMap::DATABASE_NAME); + + if ($this->isColumnModified(BrandDocumentI18nTableMap::ID)) $criteria->add(BrandDocumentI18nTableMap::ID, $this->id); + if ($this->isColumnModified(BrandDocumentI18nTableMap::LOCALE)) $criteria->add(BrandDocumentI18nTableMap::LOCALE, $this->locale); + if ($this->isColumnModified(BrandDocumentI18nTableMap::TITLE)) $criteria->add(BrandDocumentI18nTableMap::TITLE, $this->title); + if ($this->isColumnModified(BrandDocumentI18nTableMap::DESCRIPTION)) $criteria->add(BrandDocumentI18nTableMap::DESCRIPTION, $this->description); + if ($this->isColumnModified(BrandDocumentI18nTableMap::CHAPO)) $criteria->add(BrandDocumentI18nTableMap::CHAPO, $this->chapo); + if ($this->isColumnModified(BrandDocumentI18nTableMap::POSTSCRIPTUM)) $criteria->add(BrandDocumentI18nTableMap::POSTSCRIPTUM, $this->postscriptum); + + 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(BrandDocumentI18nTableMap::DATABASE_NAME); + $criteria->add(BrandDocumentI18nTableMap::ID, $this->id); + $criteria->add(BrandDocumentI18nTableMap::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\BrandDocumentI18n (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()); + $copyObj->setChapo($this->getChapo()); + $copyObj->setPostscriptum($this->getPostscriptum()); + 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\BrandDocumentI18n 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 ChildBrandDocument object. + * + * @param ChildBrandDocument $v + * @return \Thelia\Model\BrandDocumentI18n The current object (for fluent API support) + * @throws PropelException + */ + public function setBrandDocument(ChildBrandDocument $v = null) + { + if ($v === null) { + $this->setId(NULL); + } else { + $this->setId($v->getId()); + } + + $this->aBrandDocument = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildBrandDocument object, it will not be re-added. + if ($v !== null) { + $v->addBrandDocumentI18n($this); + } + + + return $this; + } + + + /** + * Get the associated ChildBrandDocument object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildBrandDocument The associated ChildBrandDocument object. + * @throws PropelException + */ + public function getBrandDocument(ConnectionInterface $con = null) + { + if ($this->aBrandDocument === null && ($this->id !== null)) { + $this->aBrandDocument = ChildBrandDocumentQuery::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->aBrandDocument->addBrandDocumentI18ns($this); + */ + } + + return $this->aBrandDocument; + } + + /** + * 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->chapo = null; + $this->postscriptum = 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->aBrandDocument = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(BrandDocumentI18nTableMap::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/BrandDocumentI18nQuery.php b/core/lib/Thelia/Model/Base/BrandDocumentI18nQuery.php new file mode 100644 index 000000000..54d40e962 --- /dev/null +++ b/core/lib/Thelia/Model/Base/BrandDocumentI18nQuery.php @@ -0,0 +1,607 @@ +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 ChildBrandDocumentI18n|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = BrandDocumentI18nTableMap::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(BrandDocumentI18nTableMap::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 ChildBrandDocumentI18n A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `LOCALE`, `TITLE`, `DESCRIPTION`, `CHAPO`, `POSTSCRIPTUM` FROM `brand_document_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 ChildBrandDocumentI18n(); + $obj->hydrate($row); + BrandDocumentI18nTableMap::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 ChildBrandDocumentI18n|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 ChildBrandDocumentI18nQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + $this->addUsingAlias(BrandDocumentI18nTableMap::ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(BrandDocumentI18nTableMap::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 ChildBrandDocumentI18nQuery 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(BrandDocumentI18nTableMap::ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(BrandDocumentI18nTableMap::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 filterByBrandDocument() + * + * @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 ChildBrandDocumentI18nQuery 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(BrandDocumentI18nTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(BrandDocumentI18nTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandDocumentI18nTableMap::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 ChildBrandDocumentI18nQuery 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(BrandDocumentI18nTableMap::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 ChildBrandDocumentI18nQuery 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(BrandDocumentI18nTableMap::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 ChildBrandDocumentI18nQuery 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(BrandDocumentI18nTableMap::DESCRIPTION, $description, $comparison); + } + + /** + * Filter the query on the chapo column + * + * Example usage: + * + * $query->filterByChapo('fooValue'); // WHERE chapo = 'fooValue' + * $query->filterByChapo('%fooValue%'); // WHERE chapo LIKE '%fooValue%' + * + * + * @param string $chapo 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 ChildBrandDocumentI18nQuery The current query, for fluid interface + */ + public function filterByChapo($chapo = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($chapo)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $chapo)) { + $chapo = str_replace('*', '%', $chapo); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(BrandDocumentI18nTableMap::CHAPO, $chapo, $comparison); + } + + /** + * Filter the query on the postscriptum column + * + * Example usage: + * + * $query->filterByPostscriptum('fooValue'); // WHERE postscriptum = 'fooValue' + * $query->filterByPostscriptum('%fooValue%'); // WHERE postscriptum LIKE '%fooValue%' + * + * + * @param string $postscriptum 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 ChildBrandDocumentI18nQuery The current query, for fluid interface + */ + public function filterByPostscriptum($postscriptum = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($postscriptum)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $postscriptum)) { + $postscriptum = str_replace('*', '%', $postscriptum); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(BrandDocumentI18nTableMap::POSTSCRIPTUM, $postscriptum, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\BrandDocument object + * + * @param \Thelia\Model\BrandDocument|ObjectCollection $brandDocument The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandDocumentI18nQuery The current query, for fluid interface + */ + public function filterByBrandDocument($brandDocument, $comparison = null) + { + if ($brandDocument instanceof \Thelia\Model\BrandDocument) { + return $this + ->addUsingAlias(BrandDocumentI18nTableMap::ID, $brandDocument->getId(), $comparison); + } elseif ($brandDocument instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(BrandDocumentI18nTableMap::ID, $brandDocument->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByBrandDocument() only accepts arguments of type \Thelia\Model\BrandDocument or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the BrandDocument relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandDocumentI18nQuery The current query, for fluid interface + */ + public function joinBrandDocument($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('BrandDocument'); + + // 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, 'BrandDocument'); + } + + return $this; + } + + /** + * Use the BrandDocument relation BrandDocument 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\BrandDocumentQuery A secondary query class using the current class as primary query + */ + public function useBrandDocumentQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinBrandDocument($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'BrandDocument', '\Thelia\Model\BrandDocumentQuery'); + } + + /** + * Exclude object from result + * + * @param ChildBrandDocumentI18n $brandDocumentI18n Object to remove from the list of results + * + * @return ChildBrandDocumentI18nQuery The current query, for fluid interface + */ + public function prune($brandDocumentI18n = null) + { + if ($brandDocumentI18n) { + $this->addCond('pruneCond0', $this->getAliasedColName(BrandDocumentI18nTableMap::ID), $brandDocumentI18n->getId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(BrandDocumentI18nTableMap::LOCALE), $brandDocumentI18n->getLocale(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); + } + + return $this; + } + + /** + * Deletes all rows from the brand_document_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(BrandDocumentI18nTableMap::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). + BrandDocumentI18nTableMap::clearInstancePool(); + BrandDocumentI18nTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildBrandDocumentI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildBrandDocumentI18n 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(BrandDocumentI18nTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(BrandDocumentI18nTableMap::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(); + + + BrandDocumentI18nTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + BrandDocumentI18nTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // BrandDocumentI18nQuery diff --git a/core/lib/Thelia/Model/Base/BrandDocumentQuery.php b/core/lib/Thelia/Model/Base/BrandDocumentQuery.php new file mode 100644 index 000000000..4338c2dc2 --- /dev/null +++ b/core/lib/Thelia/Model/Base/BrandDocumentQuery.php @@ -0,0 +1,846 @@ +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 ChildBrandDocument|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = BrandDocumentTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(BrandDocumentTableMap::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 ChildBrandDocument A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `BRAND_ID`, `FILE`, `POSITION`, `CREATED_AT`, `UPDATED_AT` FROM `brand_document` 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 ChildBrandDocument(); + $obj->hydrate($row); + BrandDocumentTableMap::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 ChildBrandDocument|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 ChildBrandDocumentQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(BrandDocumentTableMap::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 ChildBrandDocumentQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(BrandDocumentTableMap::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 ChildBrandDocumentQuery 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(BrandDocumentTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(BrandDocumentTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandDocumentTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the brand_id column + * + * Example usage: + * + * $query->filterByBrandId(1234); // WHERE brand_id = 1234 + * $query->filterByBrandId(array(12, 34)); // WHERE brand_id IN (12, 34) + * $query->filterByBrandId(array('min' => 12)); // WHERE brand_id > 12 + * + * + * @see filterByBrand() + * + * @param mixed $brandId 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 ChildBrandDocumentQuery The current query, for fluid interface + */ + public function filterByBrandId($brandId = null, $comparison = null) + { + if (is_array($brandId)) { + $useMinMax = false; + if (isset($brandId['min'])) { + $this->addUsingAlias(BrandDocumentTableMap::BRAND_ID, $brandId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($brandId['max'])) { + $this->addUsingAlias(BrandDocumentTableMap::BRAND_ID, $brandId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandDocumentTableMap::BRAND_ID, $brandId, $comparison); + } + + /** + * Filter the query on the file column + * + * Example usage: + * + * $query->filterByFile('fooValue'); // WHERE file = 'fooValue' + * $query->filterByFile('%fooValue%'); // WHERE file LIKE '%fooValue%' + * + * + * @param string $file 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 ChildBrandDocumentQuery The current query, for fluid interface + */ + public function filterByFile($file = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($file)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $file)) { + $file = str_replace('*', '%', $file); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(BrandDocumentTableMap::FILE, $file, $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 ChildBrandDocumentQuery 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(BrandDocumentTableMap::POSITION, $position['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($position['max'])) { + $this->addUsingAlias(BrandDocumentTableMap::POSITION, $position['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandDocumentTableMap::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 ChildBrandDocumentQuery 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(BrandDocumentTableMap::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($createdAt['max'])) { + $this->addUsingAlias(BrandDocumentTableMap::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandDocumentTableMap::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 ChildBrandDocumentQuery 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(BrandDocumentTableMap::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($updatedAt['max'])) { + $this->addUsingAlias(BrandDocumentTableMap::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandDocumentTableMap::UPDATED_AT, $updatedAt, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Brand object + * + * @param \Thelia\Model\Brand|ObjectCollection $brand The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandDocumentQuery The current query, for fluid interface + */ + public function filterByBrand($brand, $comparison = null) + { + if ($brand instanceof \Thelia\Model\Brand) { + return $this + ->addUsingAlias(BrandDocumentTableMap::BRAND_ID, $brand->getId(), $comparison); + } elseif ($brand instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(BrandDocumentTableMap::BRAND_ID, $brand->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByBrand() only accepts arguments of type \Thelia\Model\Brand or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Brand relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandDocumentQuery The current query, for fluid interface + */ + public function joinBrand($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Brand'); + + // 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, 'Brand'); + } + + return $this; + } + + /** + * Use the Brand relation Brand 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\BrandQuery A secondary query class using the current class as primary query + */ + public function useBrandQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinBrand($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Brand', '\Thelia\Model\BrandQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\BrandDocumentI18n object + * + * @param \Thelia\Model\BrandDocumentI18n|ObjectCollection $brandDocumentI18n the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandDocumentQuery The current query, for fluid interface + */ + public function filterByBrandDocumentI18n($brandDocumentI18n, $comparison = null) + { + if ($brandDocumentI18n instanceof \Thelia\Model\BrandDocumentI18n) { + return $this + ->addUsingAlias(BrandDocumentTableMap::ID, $brandDocumentI18n->getId(), $comparison); + } elseif ($brandDocumentI18n instanceof ObjectCollection) { + return $this + ->useBrandDocumentI18nQuery() + ->filterByPrimaryKeys($brandDocumentI18n->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByBrandDocumentI18n() only accepts arguments of type \Thelia\Model\BrandDocumentI18n or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the BrandDocumentI18n relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandDocumentQuery The current query, for fluid interface + */ + public function joinBrandDocumentI18n($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('BrandDocumentI18n'); + + // 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, 'BrandDocumentI18n'); + } + + return $this; + } + + /** + * Use the BrandDocumentI18n relation BrandDocumentI18n 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\BrandDocumentI18nQuery A secondary query class using the current class as primary query + */ + public function useBrandDocumentI18nQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinBrandDocumentI18n($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'BrandDocumentI18n', '\Thelia\Model\BrandDocumentI18nQuery'); + } + + /** + * Exclude object from result + * + * @param ChildBrandDocument $brandDocument Object to remove from the list of results + * + * @return ChildBrandDocumentQuery The current query, for fluid interface + */ + public function prune($brandDocument = null) + { + if ($brandDocument) { + $this->addUsingAlias(BrandDocumentTableMap::ID, $brandDocument->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the brand_document 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(BrandDocumentTableMap::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). + BrandDocumentTableMap::clearInstancePool(); + BrandDocumentTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildBrandDocument or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildBrandDocument 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(BrandDocumentTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(BrandDocumentTableMap::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(); + + + BrandDocumentTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + BrandDocumentTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + // timestampable behavior + + /** + * Filter by the latest updated + * + * @param int $nbDays Maximum age of the latest update in days + * + * @return ChildBrandDocumentQuery The current query, for fluid interface + */ + public function recentlyUpdated($nbDays = 7) + { + return $this->addUsingAlias(BrandDocumentTableMap::UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Filter by the latest created + * + * @param int $nbDays Maximum age of in days + * + * @return ChildBrandDocumentQuery The current query, for fluid interface + */ + public function recentlyCreated($nbDays = 7) + { + return $this->addUsingAlias(BrandDocumentTableMap::CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Order by update date desc + * + * @return ChildBrandDocumentQuery The current query, for fluid interface + */ + public function lastUpdatedFirst() + { + return $this->addDescendingOrderByColumn(BrandDocumentTableMap::UPDATED_AT); + } + + /** + * Order by update date asc + * + * @return ChildBrandDocumentQuery The current query, for fluid interface + */ + public function firstUpdatedFirst() + { + return $this->addAscendingOrderByColumn(BrandDocumentTableMap::UPDATED_AT); + } + + /** + * Order by create date desc + * + * @return ChildBrandDocumentQuery The current query, for fluid interface + */ + public function lastCreatedFirst() + { + return $this->addDescendingOrderByColumn(BrandDocumentTableMap::CREATED_AT); + } + + /** + * Order by create date asc + * + * @return ChildBrandDocumentQuery The current query, for fluid interface + */ + public function firstCreatedFirst() + { + return $this->addAscendingOrderByColumn(BrandDocumentTableMap::CREATED_AT); + } + + // 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 ChildBrandDocumentQuery The current query, for fluid interface + */ + public function joinI18n($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $relationName = $relationAlias ? $relationAlias : 'BrandDocumentI18n'; + + return $this + ->joinBrandDocumentI18n($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 ChildBrandDocumentQuery The current query, for fluid interface + */ + public function joinWithI18n($locale = 'en_US', $joinType = Criteria::LEFT_JOIN) + { + $this + ->joinI18n($locale, null, $joinType) + ->with('BrandDocumentI18n'); + $this->with['BrandDocumentI18n']->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 ChildBrandDocumentI18nQuery 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 : 'BrandDocumentI18n', '\Thelia\Model\BrandDocumentI18nQuery'); + } + +} // BrandDocumentQuery diff --git a/core/lib/Thelia/Model/Base/BrandI18n.php b/core/lib/Thelia/Model/Base/BrandI18n.php new file mode 100644 index 000000000..736d62a9c --- /dev/null +++ b/core/lib/Thelia/Model/Base/BrandI18n.php @@ -0,0 +1,1616 @@ +locale = 'en_US'; + } + + /** + * Initializes internal state of Thelia\Model\Base\BrandI18n 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 BrandI18n instance. If + * obj is an instance of BrandI18n, delegates to + * equals(BrandI18n). 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 BrandI18n 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 BrandI18n 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; + } + + /** + * Get the [chapo] column value. + * + * @return string + */ + public function getChapo() + { + + return $this->chapo; + } + + /** + * Get the [postscriptum] column value. + * + * @return string + */ + public function getPostscriptum() + { + + return $this->postscriptum; + } + + /** + * Get the [meta_title] column value. + * + * @return string + */ + public function getMetaTitle() + { + + return $this->meta_title; + } + + /** + * Get the [meta_description] column value. + * + * @return string + */ + public function getMetaDescription() + { + + return $this->meta_description; + } + + /** + * Get the [meta_keywords] column value. + * + * @return string + */ + public function getMetaKeywords() + { + + return $this->meta_keywords; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\BrandI18n 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[BrandI18nTableMap::ID] = true; + } + + if ($this->aBrand !== null && $this->aBrand->getId() !== $v) { + $this->aBrand = null; + } + + + return $this; + } // setId() + + /** + * Set the value of [locale] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n 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[BrandI18nTableMap::LOCALE] = true; + } + + + return $this; + } // setLocale() + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n 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[BrandI18nTableMap::TITLE] = true; + } + + + return $this; + } // setTitle() + + /** + * Set the value of [description] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n 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[BrandI18nTableMap::DESCRIPTION] = true; + } + + + return $this; + } // setDescription() + + /** + * Set the value of [chapo] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n The current object (for fluent API support) + */ + public function setChapo($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->chapo !== $v) { + $this->chapo = $v; + $this->modifiedColumns[BrandI18nTableMap::CHAPO] = true; + } + + + return $this; + } // setChapo() + + /** + * Set the value of [postscriptum] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n The current object (for fluent API support) + */ + public function setPostscriptum($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->postscriptum !== $v) { + $this->postscriptum = $v; + $this->modifiedColumns[BrandI18nTableMap::POSTSCRIPTUM] = true; + } + + + return $this; + } // setPostscriptum() + + /** + * Set the value of [meta_title] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n The current object (for fluent API support) + */ + public function setMetaTitle($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->meta_title !== $v) { + $this->meta_title = $v; + $this->modifiedColumns[BrandI18nTableMap::META_TITLE] = true; + } + + + return $this; + } // setMetaTitle() + + /** + * Set the value of [meta_description] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n The current object (for fluent API support) + */ + public function setMetaDescription($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->meta_description !== $v) { + $this->meta_description = $v; + $this->modifiedColumns[BrandI18nTableMap::META_DESCRIPTION] = true; + } + + + return $this; + } // setMetaDescription() + + /** + * Set the value of [meta_keywords] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandI18n The current object (for fluent API support) + */ + public function setMetaKeywords($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->meta_keywords !== $v) { + $this->meta_keywords = $v; + $this->modifiedColumns[BrandI18nTableMap::META_KEYWORDS] = true; + } + + + return $this; + } // setMetaKeywords() + + /** + * 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 : BrandI18nTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : BrandI18nTableMap::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)]; + $this->locale = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : BrandI18nTableMap::translateFieldName('Title', TableMap::TYPE_PHPNAME, $indexType)]; + $this->title = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : BrandI18nTableMap::translateFieldName('Description', TableMap::TYPE_PHPNAME, $indexType)]; + $this->description = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : BrandI18nTableMap::translateFieldName('Chapo', TableMap::TYPE_PHPNAME, $indexType)]; + $this->chapo = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : BrandI18nTableMap::translateFieldName('Postscriptum', TableMap::TYPE_PHPNAME, $indexType)]; + $this->postscriptum = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : BrandI18nTableMap::translateFieldName('MetaTitle', TableMap::TYPE_PHPNAME, $indexType)]; + $this->meta_title = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : BrandI18nTableMap::translateFieldName('MetaDescription', TableMap::TYPE_PHPNAME, $indexType)]; + $this->meta_description = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : BrandI18nTableMap::translateFieldName('MetaKeywords', TableMap::TYPE_PHPNAME, $indexType)]; + $this->meta_keywords = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 9; // 9 = BrandI18nTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\BrandI18n 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->aBrand !== null && $this->id !== $this->aBrand->getId()) { + $this->aBrand = 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(BrandI18nTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildBrandI18nQuery::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->aBrand = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see BrandI18n::setDeleted() + * @see BrandI18n::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(BrandI18nTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildBrandI18nQuery::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(BrandI18nTableMap::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); + BrandI18nTableMap::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->aBrand !== null) { + if ($this->aBrand->isModified() || $this->aBrand->isNew()) { + $affectedRows += $this->aBrand->save($con); + } + $this->setBrand($this->aBrand); + } + + 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(BrandI18nTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(BrandI18nTableMap::LOCALE)) { + $modifiedColumns[':p' . $index++] = '`LOCALE`'; + } + if ($this->isColumnModified(BrandI18nTableMap::TITLE)) { + $modifiedColumns[':p' . $index++] = '`TITLE`'; + } + if ($this->isColumnModified(BrandI18nTableMap::DESCRIPTION)) { + $modifiedColumns[':p' . $index++] = '`DESCRIPTION`'; + } + if ($this->isColumnModified(BrandI18nTableMap::CHAPO)) { + $modifiedColumns[':p' . $index++] = '`CHAPO`'; + } + if ($this->isColumnModified(BrandI18nTableMap::POSTSCRIPTUM)) { + $modifiedColumns[':p' . $index++] = '`POSTSCRIPTUM`'; + } + if ($this->isColumnModified(BrandI18nTableMap::META_TITLE)) { + $modifiedColumns[':p' . $index++] = '`META_TITLE`'; + } + if ($this->isColumnModified(BrandI18nTableMap::META_DESCRIPTION)) { + $modifiedColumns[':p' . $index++] = '`META_DESCRIPTION`'; + } + if ($this->isColumnModified(BrandI18nTableMap::META_KEYWORDS)) { + $modifiedColumns[':p' . $index++] = '`META_KEYWORDS`'; + } + + $sql = sprintf( + 'INSERT INTO `brand_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; + case '`CHAPO`': + $stmt->bindValue($identifier, $this->chapo, PDO::PARAM_STR); + break; + case '`POSTSCRIPTUM`': + $stmt->bindValue($identifier, $this->postscriptum, PDO::PARAM_STR); + break; + case '`META_TITLE`': + $stmt->bindValue($identifier, $this->meta_title, PDO::PARAM_STR); + break; + case '`META_DESCRIPTION`': + $stmt->bindValue($identifier, $this->meta_description, PDO::PARAM_STR); + break; + case '`META_KEYWORDS`': + $stmt->bindValue($identifier, $this->meta_keywords, 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 = BrandI18nTableMap::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; + case 4: + return $this->getChapo(); + break; + case 5: + return $this->getPostscriptum(); + break; + case 6: + return $this->getMetaTitle(); + break; + case 7: + return $this->getMetaDescription(); + break; + case 8: + return $this->getMetaKeywords(); + 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['BrandI18n'][serialize($this->getPrimaryKey())])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['BrandI18n'][serialize($this->getPrimaryKey())] = true; + $keys = BrandI18nTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getLocale(), + $keys[2] => $this->getTitle(), + $keys[3] => $this->getDescription(), + $keys[4] => $this->getChapo(), + $keys[5] => $this->getPostscriptum(), + $keys[6] => $this->getMetaTitle(), + $keys[7] => $this->getMetaDescription(), + $keys[8] => $this->getMetaKeywords(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aBrand) { + $result['Brand'] = $this->aBrand->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 = BrandI18nTableMap::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; + case 4: + $this->setChapo($value); + break; + case 5: + $this->setPostscriptum($value); + break; + case 6: + $this->setMetaTitle($value); + break; + case 7: + $this->setMetaDescription($value); + break; + case 8: + $this->setMetaKeywords($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 = BrandI18nTableMap::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]]); + if (array_key_exists($keys[4], $arr)) $this->setChapo($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setPostscriptum($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setMetaTitle($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setMetaDescription($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setMetaKeywords($arr[$keys[8]]); + } + + /** + * 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(BrandI18nTableMap::DATABASE_NAME); + + if ($this->isColumnModified(BrandI18nTableMap::ID)) $criteria->add(BrandI18nTableMap::ID, $this->id); + if ($this->isColumnModified(BrandI18nTableMap::LOCALE)) $criteria->add(BrandI18nTableMap::LOCALE, $this->locale); + if ($this->isColumnModified(BrandI18nTableMap::TITLE)) $criteria->add(BrandI18nTableMap::TITLE, $this->title); + if ($this->isColumnModified(BrandI18nTableMap::DESCRIPTION)) $criteria->add(BrandI18nTableMap::DESCRIPTION, $this->description); + if ($this->isColumnModified(BrandI18nTableMap::CHAPO)) $criteria->add(BrandI18nTableMap::CHAPO, $this->chapo); + if ($this->isColumnModified(BrandI18nTableMap::POSTSCRIPTUM)) $criteria->add(BrandI18nTableMap::POSTSCRIPTUM, $this->postscriptum); + if ($this->isColumnModified(BrandI18nTableMap::META_TITLE)) $criteria->add(BrandI18nTableMap::META_TITLE, $this->meta_title); + if ($this->isColumnModified(BrandI18nTableMap::META_DESCRIPTION)) $criteria->add(BrandI18nTableMap::META_DESCRIPTION, $this->meta_description); + if ($this->isColumnModified(BrandI18nTableMap::META_KEYWORDS)) $criteria->add(BrandI18nTableMap::META_KEYWORDS, $this->meta_keywords); + + 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(BrandI18nTableMap::DATABASE_NAME); + $criteria->add(BrandI18nTableMap::ID, $this->id); + $criteria->add(BrandI18nTableMap::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\BrandI18n (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()); + $copyObj->setChapo($this->getChapo()); + $copyObj->setPostscriptum($this->getPostscriptum()); + $copyObj->setMetaTitle($this->getMetaTitle()); + $copyObj->setMetaDescription($this->getMetaDescription()); + $copyObj->setMetaKeywords($this->getMetaKeywords()); + 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\BrandI18n 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 ChildBrand object. + * + * @param ChildBrand $v + * @return \Thelia\Model\BrandI18n The current object (for fluent API support) + * @throws PropelException + */ + public function setBrand(ChildBrand $v = null) + { + if ($v === null) { + $this->setId(NULL); + } else { + $this->setId($v->getId()); + } + + $this->aBrand = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildBrand object, it will not be re-added. + if ($v !== null) { + $v->addBrandI18n($this); + } + + + return $this; + } + + + /** + * Get the associated ChildBrand object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildBrand The associated ChildBrand object. + * @throws PropelException + */ + public function getBrand(ConnectionInterface $con = null) + { + if ($this->aBrand === null && ($this->id !== null)) { + $this->aBrand = ChildBrandQuery::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->aBrand->addBrandI18ns($this); + */ + } + + return $this->aBrand; + } + + /** + * 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->chapo = null; + $this->postscriptum = null; + $this->meta_title = null; + $this->meta_description = null; + $this->meta_keywords = 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->aBrand = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(BrandI18nTableMap::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/BrandI18nQuery.php b/core/lib/Thelia/Model/Base/BrandI18nQuery.php new file mode 100644 index 000000000..86248a84c --- /dev/null +++ b/core/lib/Thelia/Model/Base/BrandI18nQuery.php @@ -0,0 +1,706 @@ +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 ChildBrandI18n|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = BrandI18nTableMap::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(BrandI18nTableMap::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 ChildBrandI18n A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `LOCALE`, `TITLE`, `DESCRIPTION`, `CHAPO`, `POSTSCRIPTUM`, `META_TITLE`, `META_DESCRIPTION`, `META_KEYWORDS` FROM `brand_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 ChildBrandI18n(); + $obj->hydrate($row); + BrandI18nTableMap::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 ChildBrandI18n|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 ChildBrandI18nQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + $this->addUsingAlias(BrandI18nTableMap::ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(BrandI18nTableMap::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 ChildBrandI18nQuery 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(BrandI18nTableMap::ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(BrandI18nTableMap::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 filterByBrand() + * + * @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 ChildBrandI18nQuery 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(BrandI18nTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(BrandI18nTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandI18nTableMap::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 ChildBrandI18nQuery 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(BrandI18nTableMap::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 ChildBrandI18nQuery 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(BrandI18nTableMap::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 ChildBrandI18nQuery 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(BrandI18nTableMap::DESCRIPTION, $description, $comparison); + } + + /** + * Filter the query on the chapo column + * + * Example usage: + * + * $query->filterByChapo('fooValue'); // WHERE chapo = 'fooValue' + * $query->filterByChapo('%fooValue%'); // WHERE chapo LIKE '%fooValue%' + * + * + * @param string $chapo 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 ChildBrandI18nQuery The current query, for fluid interface + */ + public function filterByChapo($chapo = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($chapo)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $chapo)) { + $chapo = str_replace('*', '%', $chapo); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(BrandI18nTableMap::CHAPO, $chapo, $comparison); + } + + /** + * Filter the query on the postscriptum column + * + * Example usage: + * + * $query->filterByPostscriptum('fooValue'); // WHERE postscriptum = 'fooValue' + * $query->filterByPostscriptum('%fooValue%'); // WHERE postscriptum LIKE '%fooValue%' + * + * + * @param string $postscriptum 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 ChildBrandI18nQuery The current query, for fluid interface + */ + public function filterByPostscriptum($postscriptum = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($postscriptum)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $postscriptum)) { + $postscriptum = str_replace('*', '%', $postscriptum); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(BrandI18nTableMap::POSTSCRIPTUM, $postscriptum, $comparison); + } + + /** + * Filter the query on the meta_title column + * + * Example usage: + * + * $query->filterByMetaTitle('fooValue'); // WHERE meta_title = 'fooValue' + * $query->filterByMetaTitle('%fooValue%'); // WHERE meta_title LIKE '%fooValue%' + * + * + * @param string $metaTitle 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 ChildBrandI18nQuery The current query, for fluid interface + */ + public function filterByMetaTitle($metaTitle = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($metaTitle)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $metaTitle)) { + $metaTitle = str_replace('*', '%', $metaTitle); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(BrandI18nTableMap::META_TITLE, $metaTitle, $comparison); + } + + /** + * Filter the query on the meta_description column + * + * Example usage: + * + * $query->filterByMetaDescription('fooValue'); // WHERE meta_description = 'fooValue' + * $query->filterByMetaDescription('%fooValue%'); // WHERE meta_description LIKE '%fooValue%' + * + * + * @param string $metaDescription 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 ChildBrandI18nQuery The current query, for fluid interface + */ + public function filterByMetaDescription($metaDescription = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($metaDescription)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $metaDescription)) { + $metaDescription = str_replace('*', '%', $metaDescription); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(BrandI18nTableMap::META_DESCRIPTION, $metaDescription, $comparison); + } + + /** + * Filter the query on the meta_keywords column + * + * Example usage: + * + * $query->filterByMetaKeywords('fooValue'); // WHERE meta_keywords = 'fooValue' + * $query->filterByMetaKeywords('%fooValue%'); // WHERE meta_keywords LIKE '%fooValue%' + * + * + * @param string $metaKeywords 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 ChildBrandI18nQuery The current query, for fluid interface + */ + public function filterByMetaKeywords($metaKeywords = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($metaKeywords)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $metaKeywords)) { + $metaKeywords = str_replace('*', '%', $metaKeywords); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(BrandI18nTableMap::META_KEYWORDS, $metaKeywords, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Brand object + * + * @param \Thelia\Model\Brand|ObjectCollection $brand The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandI18nQuery The current query, for fluid interface + */ + public function filterByBrand($brand, $comparison = null) + { + if ($brand instanceof \Thelia\Model\Brand) { + return $this + ->addUsingAlias(BrandI18nTableMap::ID, $brand->getId(), $comparison); + } elseif ($brand instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(BrandI18nTableMap::ID, $brand->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByBrand() only accepts arguments of type \Thelia\Model\Brand or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Brand relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandI18nQuery The current query, for fluid interface + */ + public function joinBrand($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Brand'); + + // 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, 'Brand'); + } + + return $this; + } + + /** + * Use the Brand relation Brand 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\BrandQuery A secondary query class using the current class as primary query + */ + public function useBrandQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinBrand($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Brand', '\Thelia\Model\BrandQuery'); + } + + /** + * Exclude object from result + * + * @param ChildBrandI18n $brandI18n Object to remove from the list of results + * + * @return ChildBrandI18nQuery The current query, for fluid interface + */ + public function prune($brandI18n = null) + { + if ($brandI18n) { + $this->addCond('pruneCond0', $this->getAliasedColName(BrandI18nTableMap::ID), $brandI18n->getId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(BrandI18nTableMap::LOCALE), $brandI18n->getLocale(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); + } + + return $this; + } + + /** + * Deletes all rows from the brand_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(BrandI18nTableMap::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). + BrandI18nTableMap::clearInstancePool(); + BrandI18nTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildBrandI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildBrandI18n 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(BrandI18nTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(BrandI18nTableMap::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(); + + + BrandI18nTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + BrandI18nTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // BrandI18nQuery diff --git a/core/lib/Thelia/Model/Base/BrandImage.php b/core/lib/Thelia/Model/Base/BrandImage.php new file mode 100644 index 000000000..48c3d9196 --- /dev/null +++ b/core/lib/Thelia/Model/Base/BrandImage.php @@ -0,0 +1,2258 @@ +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 BrandImage instance. If + * obj is an instance of BrandImage, delegates to + * equals(BrandImage). 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 BrandImage 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 BrandImage 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 [brand_id] column value. + * + * @return int + */ + public function getBrandId() + { + + return $this->brand_id; + } + + /** + * Get the [file] column value. + * + * @return string + */ + public function getFile() + { + + return $this->file; + } + + /** + * 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\BrandImage 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[BrandImageTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [brand_id] column. + * + * @param int $v new value + * @return \Thelia\Model\BrandImage The current object (for fluent API support) + */ + public function setBrandId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->brand_id !== $v) { + $this->brand_id = $v; + $this->modifiedColumns[BrandImageTableMap::BRAND_ID] = true; + } + + if ($this->aBrandRelatedByBrandId !== null && $this->aBrandRelatedByBrandId->getId() !== $v) { + $this->aBrandRelatedByBrandId = null; + } + + + return $this; + } // setBrandId() + + /** + * Set the value of [file] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandImage The current object (for fluent API support) + */ + public function setFile($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->file !== $v) { + $this->file = $v; + $this->modifiedColumns[BrandImageTableMap::FILE] = true; + } + + + return $this; + } // setFile() + + /** + * Set the value of [position] column. + * + * @param int $v new value + * @return \Thelia\Model\BrandImage 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[BrandImageTableMap::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\BrandImage 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[BrandImageTableMap::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\BrandImage 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[BrandImageTableMap::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 : BrandImageTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : BrandImageTableMap::translateFieldName('BrandId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->brand_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : BrandImageTableMap::translateFieldName('File', TableMap::TYPE_PHPNAME, $indexType)]; + $this->file = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : BrandImageTableMap::translateFieldName('Position', TableMap::TYPE_PHPNAME, $indexType)]; + $this->position = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : BrandImageTableMap::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 ? 5 + $startcol : BrandImageTableMap::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 + 6; // 6 = BrandImageTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\BrandImage 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->aBrandRelatedByBrandId !== null && $this->brand_id !== $this->aBrandRelatedByBrandId->getId()) { + $this->aBrandRelatedByBrandId = 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(BrandImageTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildBrandImageQuery::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->aBrandRelatedByBrandId = null; + $this->collBrandsRelatedByLogoImageId = null; + + $this->collBrandImageI18ns = null; + + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see BrandImage::setDeleted() + * @see BrandImage::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(BrandImageTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildBrandImageQuery::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(BrandImageTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + // timestampable behavior + if (!$this->isColumnModified(BrandImageTableMap::CREATED_AT)) { + $this->setCreatedAt(time()); + } + if (!$this->isColumnModified(BrandImageTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } else { + $ret = $ret && $this->preUpdate($con); + // timestampable behavior + if ($this->isModified() && !$this->isColumnModified(BrandImageTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + BrandImageTableMap::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->aBrandRelatedByBrandId !== null) { + if ($this->aBrandRelatedByBrandId->isModified() || $this->aBrandRelatedByBrandId->isNew()) { + $affectedRows += $this->aBrandRelatedByBrandId->save($con); + } + $this->setBrandRelatedByBrandId($this->aBrandRelatedByBrandId); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + if ($this->brandsRelatedByLogoImageIdScheduledForDeletion !== null) { + if (!$this->brandsRelatedByLogoImageIdScheduledForDeletion->isEmpty()) { + foreach ($this->brandsRelatedByLogoImageIdScheduledForDeletion as $brandRelatedByLogoImageId) { + // need to save related object because we set the relation to null + $brandRelatedByLogoImageId->save($con); + } + $this->brandsRelatedByLogoImageIdScheduledForDeletion = null; + } + } + + if ($this->collBrandsRelatedByLogoImageId !== null) { + foreach ($this->collBrandsRelatedByLogoImageId as $referrerFK) { + if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) { + $affectedRows += $referrerFK->save($con); + } + } + } + + if ($this->brandImageI18nsScheduledForDeletion !== null) { + if (!$this->brandImageI18nsScheduledForDeletion->isEmpty()) { + \Thelia\Model\BrandImageI18nQuery::create() + ->filterByPrimaryKeys($this->brandImageI18nsScheduledForDeletion->getPrimaryKeys(false)) + ->delete($con); + $this->brandImageI18nsScheduledForDeletion = null; + } + } + + if ($this->collBrandImageI18ns !== null) { + foreach ($this->collBrandImageI18ns 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[BrandImageTableMap::ID] = true; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . BrandImageTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(BrandImageTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(BrandImageTableMap::BRAND_ID)) { + $modifiedColumns[':p' . $index++] = '`BRAND_ID`'; + } + if ($this->isColumnModified(BrandImageTableMap::FILE)) { + $modifiedColumns[':p' . $index++] = '`FILE`'; + } + if ($this->isColumnModified(BrandImageTableMap::POSITION)) { + $modifiedColumns[':p' . $index++] = '`POSITION`'; + } + if ($this->isColumnModified(BrandImageTableMap::CREATED_AT)) { + $modifiedColumns[':p' . $index++] = '`CREATED_AT`'; + } + if ($this->isColumnModified(BrandImageTableMap::UPDATED_AT)) { + $modifiedColumns[':p' . $index++] = '`UPDATED_AT`'; + } + + $sql = sprintf( + 'INSERT INTO `brand_image` (%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 '`BRAND_ID`': + $stmt->bindValue($identifier, $this->brand_id, PDO::PARAM_INT); + break; + case '`FILE`': + $stmt->bindValue($identifier, $this->file, 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 = BrandImageTableMap::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->getBrandId(); + break; + case 2: + return $this->getFile(); + break; + case 3: + return $this->getPosition(); + break; + case 4: + return $this->getCreatedAt(); + break; + case 5: + 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['BrandImage'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['BrandImage'][$this->getPrimaryKey()] = true; + $keys = BrandImageTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getBrandId(), + $keys[2] => $this->getFile(), + $keys[3] => $this->getPosition(), + $keys[4] => $this->getCreatedAt(), + $keys[5] => $this->getUpdatedAt(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aBrandRelatedByBrandId) { + $result['BrandRelatedByBrandId'] = $this->aBrandRelatedByBrandId->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->collBrandsRelatedByLogoImageId) { + $result['BrandsRelatedByLogoImageId'] = $this->collBrandsRelatedByLogoImageId->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); + } + if (null !== $this->collBrandImageI18ns) { + $result['BrandImageI18ns'] = $this->collBrandImageI18ns->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 = BrandImageTableMap::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->setBrandId($value); + break; + case 2: + $this->setFile($value); + break; + case 3: + $this->setPosition($value); + break; + case 4: + $this->setCreatedAt($value); + break; + case 5: + $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 = BrandImageTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setBrandId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setFile($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setPosition($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setCreatedAt($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setUpdatedAt($arr[$keys[5]]); + } + + /** + * 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(BrandImageTableMap::DATABASE_NAME); + + if ($this->isColumnModified(BrandImageTableMap::ID)) $criteria->add(BrandImageTableMap::ID, $this->id); + if ($this->isColumnModified(BrandImageTableMap::BRAND_ID)) $criteria->add(BrandImageTableMap::BRAND_ID, $this->brand_id); + if ($this->isColumnModified(BrandImageTableMap::FILE)) $criteria->add(BrandImageTableMap::FILE, $this->file); + if ($this->isColumnModified(BrandImageTableMap::POSITION)) $criteria->add(BrandImageTableMap::POSITION, $this->position); + if ($this->isColumnModified(BrandImageTableMap::CREATED_AT)) $criteria->add(BrandImageTableMap::CREATED_AT, $this->created_at); + if ($this->isColumnModified(BrandImageTableMap::UPDATED_AT)) $criteria->add(BrandImageTableMap::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(BrandImageTableMap::DATABASE_NAME); + $criteria->add(BrandImageTableMap::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\BrandImage (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->setBrandId($this->getBrandId()); + $copyObj->setFile($this->getFile()); + $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->getBrandsRelatedByLogoImageId() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addBrandRelatedByLogoImageId($relObj->copy($deepCopy)); + } + } + + foreach ($this->getBrandImageI18ns() as $relObj) { + if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves + $copyObj->addBrandImageI18n($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\BrandImage 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 ChildBrand object. + * + * @param ChildBrand $v + * @return \Thelia\Model\BrandImage The current object (for fluent API support) + * @throws PropelException + */ + public function setBrandRelatedByBrandId(ChildBrand $v = null) + { + if ($v === null) { + $this->setBrandId(NULL); + } else { + $this->setBrandId($v->getId()); + } + + $this->aBrandRelatedByBrandId = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildBrand object, it will not be re-added. + if ($v !== null) { + $v->addBrandImageRelatedByBrandId($this); + } + + + return $this; + } + + + /** + * Get the associated ChildBrand object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildBrand The associated ChildBrand object. + * @throws PropelException + */ + public function getBrandRelatedByBrandId(ConnectionInterface $con = null) + { + if ($this->aBrandRelatedByBrandId === null && ($this->brand_id !== null)) { + $this->aBrandRelatedByBrandId = ChildBrandQuery::create()->findPk($this->brand_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->aBrandRelatedByBrandId->addBrandImagesRelatedByBrandId($this); + */ + } + + return $this->aBrandRelatedByBrandId; + } + + + /** + * 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 ('BrandRelatedByLogoImageId' == $relationName) { + return $this->initBrandsRelatedByLogoImageId(); + } + if ('BrandImageI18n' == $relationName) { + return $this->initBrandImageI18ns(); + } + } + + /** + * Clears out the collBrandsRelatedByLogoImageId 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 addBrandsRelatedByLogoImageId() + */ + public function clearBrandsRelatedByLogoImageId() + { + $this->collBrandsRelatedByLogoImageId = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collBrandsRelatedByLogoImageId collection loaded partially. + */ + public function resetPartialBrandsRelatedByLogoImageId($v = true) + { + $this->collBrandsRelatedByLogoImageIdPartial = $v; + } + + /** + * Initializes the collBrandsRelatedByLogoImageId collection. + * + * By default this just sets the collBrandsRelatedByLogoImageId collection to an empty array (like clearcollBrandsRelatedByLogoImageId()); + * 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 initBrandsRelatedByLogoImageId($overrideExisting = true) + { + if (null !== $this->collBrandsRelatedByLogoImageId && !$overrideExisting) { + return; + } + $this->collBrandsRelatedByLogoImageId = new ObjectCollection(); + $this->collBrandsRelatedByLogoImageId->setModel('\Thelia\Model\Brand'); + } + + /** + * Gets an array of ChildBrand 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 ChildBrandImage 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|ChildBrand[] List of ChildBrand objects + * @throws PropelException + */ + public function getBrandsRelatedByLogoImageId($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collBrandsRelatedByLogoImageIdPartial && !$this->isNew(); + if (null === $this->collBrandsRelatedByLogoImageId || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collBrandsRelatedByLogoImageId) { + // return empty collection + $this->initBrandsRelatedByLogoImageId(); + } else { + $collBrandsRelatedByLogoImageId = ChildBrandQuery::create(null, $criteria) + ->filterByBrandImageRelatedByLogoImageId($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collBrandsRelatedByLogoImageIdPartial && count($collBrandsRelatedByLogoImageId)) { + $this->initBrandsRelatedByLogoImageId(false); + + foreach ($collBrandsRelatedByLogoImageId as $obj) { + if (false == $this->collBrandsRelatedByLogoImageId->contains($obj)) { + $this->collBrandsRelatedByLogoImageId->append($obj); + } + } + + $this->collBrandsRelatedByLogoImageIdPartial = true; + } + + reset($collBrandsRelatedByLogoImageId); + + return $collBrandsRelatedByLogoImageId; + } + + if ($partial && $this->collBrandsRelatedByLogoImageId) { + foreach ($this->collBrandsRelatedByLogoImageId as $obj) { + if ($obj->isNew()) { + $collBrandsRelatedByLogoImageId[] = $obj; + } + } + } + + $this->collBrandsRelatedByLogoImageId = $collBrandsRelatedByLogoImageId; + $this->collBrandsRelatedByLogoImageIdPartial = false; + } + } + + return $this->collBrandsRelatedByLogoImageId; + } + + /** + * Sets a collection of BrandRelatedByLogoImageId 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 $brandsRelatedByLogoImageId A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildBrandImage The current object (for fluent API support) + */ + public function setBrandsRelatedByLogoImageId(Collection $brandsRelatedByLogoImageId, ConnectionInterface $con = null) + { + $brandsRelatedByLogoImageIdToDelete = $this->getBrandsRelatedByLogoImageId(new Criteria(), $con)->diff($brandsRelatedByLogoImageId); + + + $this->brandsRelatedByLogoImageIdScheduledForDeletion = $brandsRelatedByLogoImageIdToDelete; + + foreach ($brandsRelatedByLogoImageIdToDelete as $brandRelatedByLogoImageIdRemoved) { + $brandRelatedByLogoImageIdRemoved->setBrandImageRelatedByLogoImageId(null); + } + + $this->collBrandsRelatedByLogoImageId = null; + foreach ($brandsRelatedByLogoImageId as $brandRelatedByLogoImageId) { + $this->addBrandRelatedByLogoImageId($brandRelatedByLogoImageId); + } + + $this->collBrandsRelatedByLogoImageId = $brandsRelatedByLogoImageId; + $this->collBrandsRelatedByLogoImageIdPartial = false; + + return $this; + } + + /** + * Returns the number of related Brand objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related Brand objects. + * @throws PropelException + */ + public function countBrandsRelatedByLogoImageId(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collBrandsRelatedByLogoImageIdPartial && !$this->isNew(); + if (null === $this->collBrandsRelatedByLogoImageId || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collBrandsRelatedByLogoImageId) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getBrandsRelatedByLogoImageId()); + } + + $query = ChildBrandQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByBrandImageRelatedByLogoImageId($this) + ->count($con); + } + + return count($this->collBrandsRelatedByLogoImageId); + } + + /** + * Method called to associate a ChildBrand object to this object + * through the ChildBrand foreign key attribute. + * + * @param ChildBrand $l ChildBrand + * @return \Thelia\Model\BrandImage The current object (for fluent API support) + */ + public function addBrandRelatedByLogoImageId(ChildBrand $l) + { + if ($this->collBrandsRelatedByLogoImageId === null) { + $this->initBrandsRelatedByLogoImageId(); + $this->collBrandsRelatedByLogoImageIdPartial = true; + } + + if (!in_array($l, $this->collBrandsRelatedByLogoImageId->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddBrandRelatedByLogoImageId($l); + } + + return $this; + } + + /** + * @param BrandRelatedByLogoImageId $brandRelatedByLogoImageId The brandRelatedByLogoImageId object to add. + */ + protected function doAddBrandRelatedByLogoImageId($brandRelatedByLogoImageId) + { + $this->collBrandsRelatedByLogoImageId[]= $brandRelatedByLogoImageId; + $brandRelatedByLogoImageId->setBrandImageRelatedByLogoImageId($this); + } + + /** + * @param BrandRelatedByLogoImageId $brandRelatedByLogoImageId The brandRelatedByLogoImageId object to remove. + * @return ChildBrandImage The current object (for fluent API support) + */ + public function removeBrandRelatedByLogoImageId($brandRelatedByLogoImageId) + { + if ($this->getBrandsRelatedByLogoImageId()->contains($brandRelatedByLogoImageId)) { + $this->collBrandsRelatedByLogoImageId->remove($this->collBrandsRelatedByLogoImageId->search($brandRelatedByLogoImageId)); + if (null === $this->brandsRelatedByLogoImageIdScheduledForDeletion) { + $this->brandsRelatedByLogoImageIdScheduledForDeletion = clone $this->collBrandsRelatedByLogoImageId; + $this->brandsRelatedByLogoImageIdScheduledForDeletion->clear(); + } + $this->brandsRelatedByLogoImageIdScheduledForDeletion[]= $brandRelatedByLogoImageId; + $brandRelatedByLogoImageId->setBrandImageRelatedByLogoImageId(null); + } + + return $this; + } + + /** + * Clears out the collBrandImageI18ns 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 addBrandImageI18ns() + */ + public function clearBrandImageI18ns() + { + $this->collBrandImageI18ns = null; // important to set this to NULL since that means it is uninitialized + } + + /** + * Reset is the collBrandImageI18ns collection loaded partially. + */ + public function resetPartialBrandImageI18ns($v = true) + { + $this->collBrandImageI18nsPartial = $v; + } + + /** + * Initializes the collBrandImageI18ns collection. + * + * By default this just sets the collBrandImageI18ns collection to an empty array (like clearcollBrandImageI18ns()); + * 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 initBrandImageI18ns($overrideExisting = true) + { + if (null !== $this->collBrandImageI18ns && !$overrideExisting) { + return; + } + $this->collBrandImageI18ns = new ObjectCollection(); + $this->collBrandImageI18ns->setModel('\Thelia\Model\BrandImageI18n'); + } + + /** + * Gets an array of ChildBrandImageI18n 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 ChildBrandImage 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|ChildBrandImageI18n[] List of ChildBrandImageI18n objects + * @throws PropelException + */ + public function getBrandImageI18ns($criteria = null, ConnectionInterface $con = null) + { + $partial = $this->collBrandImageI18nsPartial && !$this->isNew(); + if (null === $this->collBrandImageI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collBrandImageI18ns) { + // return empty collection + $this->initBrandImageI18ns(); + } else { + $collBrandImageI18ns = ChildBrandImageI18nQuery::create(null, $criteria) + ->filterByBrandImage($this) + ->find($con); + + if (null !== $criteria) { + if (false !== $this->collBrandImageI18nsPartial && count($collBrandImageI18ns)) { + $this->initBrandImageI18ns(false); + + foreach ($collBrandImageI18ns as $obj) { + if (false == $this->collBrandImageI18ns->contains($obj)) { + $this->collBrandImageI18ns->append($obj); + } + } + + $this->collBrandImageI18nsPartial = true; + } + + reset($collBrandImageI18ns); + + return $collBrandImageI18ns; + } + + if ($partial && $this->collBrandImageI18ns) { + foreach ($this->collBrandImageI18ns as $obj) { + if ($obj->isNew()) { + $collBrandImageI18ns[] = $obj; + } + } + } + + $this->collBrandImageI18ns = $collBrandImageI18ns; + $this->collBrandImageI18nsPartial = false; + } + } + + return $this->collBrandImageI18ns; + } + + /** + * Sets a collection of BrandImageI18n 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 $brandImageI18ns A Propel collection. + * @param ConnectionInterface $con Optional connection object + * @return ChildBrandImage The current object (for fluent API support) + */ + public function setBrandImageI18ns(Collection $brandImageI18ns, ConnectionInterface $con = null) + { + $brandImageI18nsToDelete = $this->getBrandImageI18ns(new Criteria(), $con)->diff($brandImageI18ns); + + + //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->brandImageI18nsScheduledForDeletion = clone $brandImageI18nsToDelete; + + foreach ($brandImageI18nsToDelete as $brandImageI18nRemoved) { + $brandImageI18nRemoved->setBrandImage(null); + } + + $this->collBrandImageI18ns = null; + foreach ($brandImageI18ns as $brandImageI18n) { + $this->addBrandImageI18n($brandImageI18n); + } + + $this->collBrandImageI18ns = $brandImageI18ns; + $this->collBrandImageI18nsPartial = false; + + return $this; + } + + /** + * Returns the number of related BrandImageI18n objects. + * + * @param Criteria $criteria + * @param boolean $distinct + * @param ConnectionInterface $con + * @return int Count of related BrandImageI18n objects. + * @throws PropelException + */ + public function countBrandImageI18ns(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) + { + $partial = $this->collBrandImageI18nsPartial && !$this->isNew(); + if (null === $this->collBrandImageI18ns || null !== $criteria || $partial) { + if ($this->isNew() && null === $this->collBrandImageI18ns) { + return 0; + } + + if ($partial && !$criteria) { + return count($this->getBrandImageI18ns()); + } + + $query = ChildBrandImageI18nQuery::create(null, $criteria); + if ($distinct) { + $query->distinct(); + } + + return $query + ->filterByBrandImage($this) + ->count($con); + } + + return count($this->collBrandImageI18ns); + } + + /** + * Method called to associate a ChildBrandImageI18n object to this object + * through the ChildBrandImageI18n foreign key attribute. + * + * @param ChildBrandImageI18n $l ChildBrandImageI18n + * @return \Thelia\Model\BrandImage The current object (for fluent API support) + */ + public function addBrandImageI18n(ChildBrandImageI18n $l) + { + if ($l && $locale = $l->getLocale()) { + $this->setLocale($locale); + $this->currentTranslations[$locale] = $l; + } + if ($this->collBrandImageI18ns === null) { + $this->initBrandImageI18ns(); + $this->collBrandImageI18nsPartial = true; + } + + if (!in_array($l, $this->collBrandImageI18ns->getArrayCopy(), true)) { // only add it if the **same** object is not already associated + $this->doAddBrandImageI18n($l); + } + + return $this; + } + + /** + * @param BrandImageI18n $brandImageI18n The brandImageI18n object to add. + */ + protected function doAddBrandImageI18n($brandImageI18n) + { + $this->collBrandImageI18ns[]= $brandImageI18n; + $brandImageI18n->setBrandImage($this); + } + + /** + * @param BrandImageI18n $brandImageI18n The brandImageI18n object to remove. + * @return ChildBrandImage The current object (for fluent API support) + */ + public function removeBrandImageI18n($brandImageI18n) + { + if ($this->getBrandImageI18ns()->contains($brandImageI18n)) { + $this->collBrandImageI18ns->remove($this->collBrandImageI18ns->search($brandImageI18n)); + if (null === $this->brandImageI18nsScheduledForDeletion) { + $this->brandImageI18nsScheduledForDeletion = clone $this->collBrandImageI18ns; + $this->brandImageI18nsScheduledForDeletion->clear(); + } + $this->brandImageI18nsScheduledForDeletion[]= clone $brandImageI18n; + $brandImageI18n->setBrandImage(null); + } + + return $this; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->brand_id = null; + $this->file = 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->collBrandsRelatedByLogoImageId) { + foreach ($this->collBrandsRelatedByLogoImageId as $o) { + $o->clearAllReferences($deep); + } + } + if ($this->collBrandImageI18ns) { + foreach ($this->collBrandImageI18ns as $o) { + $o->clearAllReferences($deep); + } + } + } // if ($deep) + + // i18n behavior + $this->currentLocale = 'en_US'; + $this->currentTranslations = null; + + $this->collBrandsRelatedByLogoImageId = null; + $this->collBrandImageI18ns = null; + $this->aBrandRelatedByBrandId = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(BrandImageTableMap::DEFAULT_STRING_FORMAT); + } + + // timestampable behavior + + /** + * Mark the current object so that the update date doesn't get updated during next save + * + * @return ChildBrandImage The current object (for fluent API support) + */ + public function keepUpdateDateUnchanged() + { + $this->modifiedColumns[BrandImageTableMap::UPDATED_AT] = true; + + return $this; + } + + // i18n behavior + + /** + * Sets the locale for translations + * + * @param string $locale Locale to use for the translation, e.g. 'fr_FR' + * + * @return ChildBrandImage 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 ChildBrandImageI18n */ + public function getTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!isset($this->currentTranslations[$locale])) { + if (null !== $this->collBrandImageI18ns) { + foreach ($this->collBrandImageI18ns as $translation) { + if ($translation->getLocale() == $locale) { + $this->currentTranslations[$locale] = $translation; + + return $translation; + } + } + } + if ($this->isNew()) { + $translation = new ChildBrandImageI18n(); + $translation->setLocale($locale); + } else { + $translation = ChildBrandImageI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->findOneOrCreate($con); + $this->currentTranslations[$locale] = $translation; + } + $this->addBrandImageI18n($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 ChildBrandImage The current object (for fluent API support) + */ + public function removeTranslation($locale = 'en_US', ConnectionInterface $con = null) + { + if (!$this->isNew()) { + ChildBrandImageI18nQuery::create() + ->filterByPrimaryKey(array($this->getPrimaryKey(), $locale)) + ->delete($con); + } + if (isset($this->currentTranslations[$locale])) { + unset($this->currentTranslations[$locale]); + } + foreach ($this->collBrandImageI18ns as $key => $translation) { + if ($translation->getLocale() == $locale) { + unset($this->collBrandImageI18ns[$key]); + break; + } + } + + return $this; + } + + /** + * Returns the current translation + * + * @param ConnectionInterface $con an optional connection object + * + * @return ChildBrandImageI18n */ + 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\BrandImageI18n 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\BrandImageI18n The current object (for fluent API support) + */ + public function setDescription($v) + { $this->getCurrentTranslation()->setDescription($v); + + return $this; + } + + + /** + * Get the [chapo] column value. + * + * @return string + */ + public function getChapo() + { + return $this->getCurrentTranslation()->getChapo(); + } + + + /** + * Set the value of [chapo] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandImageI18n The current object (for fluent API support) + */ + public function setChapo($v) + { $this->getCurrentTranslation()->setChapo($v); + + return $this; + } + + + /** + * Get the [postscriptum] column value. + * + * @return string + */ + public function getPostscriptum() + { + return $this->getCurrentTranslation()->getPostscriptum(); + } + + + /** + * Set the value of [postscriptum] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandImageI18n The current object (for fluent API support) + */ + public function setPostscriptum($v) + { $this->getCurrentTranslation()->setPostscriptum($v); + + 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/BrandImageI18n.php b/core/lib/Thelia/Model/Base/BrandImageI18n.php new file mode 100644 index 000000000..a72990f72 --- /dev/null +++ b/core/lib/Thelia/Model/Base/BrandImageI18n.php @@ -0,0 +1,1442 @@ +locale = 'en_US'; + } + + /** + * Initializes internal state of Thelia\Model\Base\BrandImageI18n 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 BrandImageI18n instance. If + * obj is an instance of BrandImageI18n, delegates to + * equals(BrandImageI18n). 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 BrandImageI18n 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 BrandImageI18n 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; + } + + /** + * Get the [chapo] column value. + * + * @return string + */ + public function getChapo() + { + + return $this->chapo; + } + + /** + * Get the [postscriptum] column value. + * + * @return string + */ + public function getPostscriptum() + { + + return $this->postscriptum; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Thelia\Model\BrandImageI18n 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[BrandImageI18nTableMap::ID] = true; + } + + if ($this->aBrandImage !== null && $this->aBrandImage->getId() !== $v) { + $this->aBrandImage = null; + } + + + return $this; + } // setId() + + /** + * Set the value of [locale] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandImageI18n 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[BrandImageI18nTableMap::LOCALE] = true; + } + + + return $this; + } // setLocale() + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandImageI18n 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[BrandImageI18nTableMap::TITLE] = true; + } + + + return $this; + } // setTitle() + + /** + * Set the value of [description] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandImageI18n 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[BrandImageI18nTableMap::DESCRIPTION] = true; + } + + + return $this; + } // setDescription() + + /** + * Set the value of [chapo] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandImageI18n The current object (for fluent API support) + */ + public function setChapo($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->chapo !== $v) { + $this->chapo = $v; + $this->modifiedColumns[BrandImageI18nTableMap::CHAPO] = true; + } + + + return $this; + } // setChapo() + + /** + * Set the value of [postscriptum] column. + * + * @param string $v new value + * @return \Thelia\Model\BrandImageI18n The current object (for fluent API support) + */ + public function setPostscriptum($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->postscriptum !== $v) { + $this->postscriptum = $v; + $this->modifiedColumns[BrandImageI18nTableMap::POSTSCRIPTUM] = true; + } + + + return $this; + } // setPostscriptum() + + /** + * 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 : BrandImageI18nTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : BrandImageI18nTableMap::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)]; + $this->locale = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : BrandImageI18nTableMap::translateFieldName('Title', TableMap::TYPE_PHPNAME, $indexType)]; + $this->title = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : BrandImageI18nTableMap::translateFieldName('Description', TableMap::TYPE_PHPNAME, $indexType)]; + $this->description = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : BrandImageI18nTableMap::translateFieldName('Chapo', TableMap::TYPE_PHPNAME, $indexType)]; + $this->chapo = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : BrandImageI18nTableMap::translateFieldName('Postscriptum', TableMap::TYPE_PHPNAME, $indexType)]; + $this->postscriptum = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 6; // 6 = BrandImageI18nTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Thelia\Model\BrandImageI18n 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->aBrandImage !== null && $this->id !== $this->aBrandImage->getId()) { + $this->aBrandImage = 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(BrandImageI18nTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildBrandImageI18nQuery::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->aBrandImage = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see BrandImageI18n::setDeleted() + * @see BrandImageI18n::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(BrandImageI18nTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildBrandImageI18nQuery::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(BrandImageI18nTableMap::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); + BrandImageI18nTableMap::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->aBrandImage !== null) { + if ($this->aBrandImage->isModified() || $this->aBrandImage->isNew()) { + $affectedRows += $this->aBrandImage->save($con); + } + $this->setBrandImage($this->aBrandImage); + } + + 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(BrandImageI18nTableMap::ID)) { + $modifiedColumns[':p' . $index++] = '`ID`'; + } + if ($this->isColumnModified(BrandImageI18nTableMap::LOCALE)) { + $modifiedColumns[':p' . $index++] = '`LOCALE`'; + } + if ($this->isColumnModified(BrandImageI18nTableMap::TITLE)) { + $modifiedColumns[':p' . $index++] = '`TITLE`'; + } + if ($this->isColumnModified(BrandImageI18nTableMap::DESCRIPTION)) { + $modifiedColumns[':p' . $index++] = '`DESCRIPTION`'; + } + if ($this->isColumnModified(BrandImageI18nTableMap::CHAPO)) { + $modifiedColumns[':p' . $index++] = '`CHAPO`'; + } + if ($this->isColumnModified(BrandImageI18nTableMap::POSTSCRIPTUM)) { + $modifiedColumns[':p' . $index++] = '`POSTSCRIPTUM`'; + } + + $sql = sprintf( + 'INSERT INTO `brand_image_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; + case '`CHAPO`': + $stmt->bindValue($identifier, $this->chapo, PDO::PARAM_STR); + break; + case '`POSTSCRIPTUM`': + $stmt->bindValue($identifier, $this->postscriptum, 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 = BrandImageI18nTableMap::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; + case 4: + return $this->getChapo(); + break; + case 5: + return $this->getPostscriptum(); + 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['BrandImageI18n'][serialize($this->getPrimaryKey())])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['BrandImageI18n'][serialize($this->getPrimaryKey())] = true; + $keys = BrandImageI18nTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getLocale(), + $keys[2] => $this->getTitle(), + $keys[3] => $this->getDescription(), + $keys[4] => $this->getChapo(), + $keys[5] => $this->getPostscriptum(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aBrandImage) { + $result['BrandImage'] = $this->aBrandImage->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 = BrandImageI18nTableMap::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; + case 4: + $this->setChapo($value); + break; + case 5: + $this->setPostscriptum($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 = BrandImageI18nTableMap::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]]); + if (array_key_exists($keys[4], $arr)) $this->setChapo($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setPostscriptum($arr[$keys[5]]); + } + + /** + * 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(BrandImageI18nTableMap::DATABASE_NAME); + + if ($this->isColumnModified(BrandImageI18nTableMap::ID)) $criteria->add(BrandImageI18nTableMap::ID, $this->id); + if ($this->isColumnModified(BrandImageI18nTableMap::LOCALE)) $criteria->add(BrandImageI18nTableMap::LOCALE, $this->locale); + if ($this->isColumnModified(BrandImageI18nTableMap::TITLE)) $criteria->add(BrandImageI18nTableMap::TITLE, $this->title); + if ($this->isColumnModified(BrandImageI18nTableMap::DESCRIPTION)) $criteria->add(BrandImageI18nTableMap::DESCRIPTION, $this->description); + if ($this->isColumnModified(BrandImageI18nTableMap::CHAPO)) $criteria->add(BrandImageI18nTableMap::CHAPO, $this->chapo); + if ($this->isColumnModified(BrandImageI18nTableMap::POSTSCRIPTUM)) $criteria->add(BrandImageI18nTableMap::POSTSCRIPTUM, $this->postscriptum); + + 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(BrandImageI18nTableMap::DATABASE_NAME); + $criteria->add(BrandImageI18nTableMap::ID, $this->id); + $criteria->add(BrandImageI18nTableMap::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\BrandImageI18n (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()); + $copyObj->setChapo($this->getChapo()); + $copyObj->setPostscriptum($this->getPostscriptum()); + 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\BrandImageI18n 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 ChildBrandImage object. + * + * @param ChildBrandImage $v + * @return \Thelia\Model\BrandImageI18n The current object (for fluent API support) + * @throws PropelException + */ + public function setBrandImage(ChildBrandImage $v = null) + { + if ($v === null) { + $this->setId(NULL); + } else { + $this->setId($v->getId()); + } + + $this->aBrandImage = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildBrandImage object, it will not be re-added. + if ($v !== null) { + $v->addBrandImageI18n($this); + } + + + return $this; + } + + + /** + * Get the associated ChildBrandImage object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildBrandImage The associated ChildBrandImage object. + * @throws PropelException + */ + public function getBrandImage(ConnectionInterface $con = null) + { + if ($this->aBrandImage === null && ($this->id !== null)) { + $this->aBrandImage = ChildBrandImageQuery::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->aBrandImage->addBrandImageI18ns($this); + */ + } + + return $this->aBrandImage; + } + + /** + * 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->chapo = null; + $this->postscriptum = 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->aBrandImage = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(BrandImageI18nTableMap::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/BrandImageI18nQuery.php b/core/lib/Thelia/Model/Base/BrandImageI18nQuery.php new file mode 100644 index 000000000..e59af9820 --- /dev/null +++ b/core/lib/Thelia/Model/Base/BrandImageI18nQuery.php @@ -0,0 +1,607 @@ +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 ChildBrandImageI18n|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = BrandImageI18nTableMap::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(BrandImageI18nTableMap::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 ChildBrandImageI18n A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `LOCALE`, `TITLE`, `DESCRIPTION`, `CHAPO`, `POSTSCRIPTUM` FROM `brand_image_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 ChildBrandImageI18n(); + $obj->hydrate($row); + BrandImageI18nTableMap::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 ChildBrandImageI18n|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 ChildBrandImageI18nQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + $this->addUsingAlias(BrandImageI18nTableMap::ID, $key[0], Criteria::EQUAL); + $this->addUsingAlias(BrandImageI18nTableMap::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 ChildBrandImageI18nQuery 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(BrandImageI18nTableMap::ID, $key[0], Criteria::EQUAL); + $cton1 = $this->getNewCriterion(BrandImageI18nTableMap::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 filterByBrandImage() + * + * @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 ChildBrandImageI18nQuery 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(BrandImageI18nTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(BrandImageI18nTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandImageI18nTableMap::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 ChildBrandImageI18nQuery 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(BrandImageI18nTableMap::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 ChildBrandImageI18nQuery 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(BrandImageI18nTableMap::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 ChildBrandImageI18nQuery 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(BrandImageI18nTableMap::DESCRIPTION, $description, $comparison); + } + + /** + * Filter the query on the chapo column + * + * Example usage: + * + * $query->filterByChapo('fooValue'); // WHERE chapo = 'fooValue' + * $query->filterByChapo('%fooValue%'); // WHERE chapo LIKE '%fooValue%' + * + * + * @param string $chapo 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 ChildBrandImageI18nQuery The current query, for fluid interface + */ + public function filterByChapo($chapo = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($chapo)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $chapo)) { + $chapo = str_replace('*', '%', $chapo); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(BrandImageI18nTableMap::CHAPO, $chapo, $comparison); + } + + /** + * Filter the query on the postscriptum column + * + * Example usage: + * + * $query->filterByPostscriptum('fooValue'); // WHERE postscriptum = 'fooValue' + * $query->filterByPostscriptum('%fooValue%'); // WHERE postscriptum LIKE '%fooValue%' + * + * + * @param string $postscriptum 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 ChildBrandImageI18nQuery The current query, for fluid interface + */ + public function filterByPostscriptum($postscriptum = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($postscriptum)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $postscriptum)) { + $postscriptum = str_replace('*', '%', $postscriptum); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(BrandImageI18nTableMap::POSTSCRIPTUM, $postscriptum, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\BrandImage object + * + * @param \Thelia\Model\BrandImage|ObjectCollection $brandImage The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandImageI18nQuery The current query, for fluid interface + */ + public function filterByBrandImage($brandImage, $comparison = null) + { + if ($brandImage instanceof \Thelia\Model\BrandImage) { + return $this + ->addUsingAlias(BrandImageI18nTableMap::ID, $brandImage->getId(), $comparison); + } elseif ($brandImage instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(BrandImageI18nTableMap::ID, $brandImage->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByBrandImage() only accepts arguments of type \Thelia\Model\BrandImage or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the BrandImage relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandImageI18nQuery The current query, for fluid interface + */ + public function joinBrandImage($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('BrandImage'); + + // 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, 'BrandImage'); + } + + return $this; + } + + /** + * Use the BrandImage relation BrandImage 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\BrandImageQuery A secondary query class using the current class as primary query + */ + public function useBrandImageQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinBrandImage($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'BrandImage', '\Thelia\Model\BrandImageQuery'); + } + + /** + * Exclude object from result + * + * @param ChildBrandImageI18n $brandImageI18n Object to remove from the list of results + * + * @return ChildBrandImageI18nQuery The current query, for fluid interface + */ + public function prune($brandImageI18n = null) + { + if ($brandImageI18n) { + $this->addCond('pruneCond0', $this->getAliasedColName(BrandImageI18nTableMap::ID), $brandImageI18n->getId(), Criteria::NOT_EQUAL); + $this->addCond('pruneCond1', $this->getAliasedColName(BrandImageI18nTableMap::LOCALE), $brandImageI18n->getLocale(), Criteria::NOT_EQUAL); + $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR); + } + + return $this; + } + + /** + * Deletes all rows from the brand_image_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(BrandImageI18nTableMap::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). + BrandImageI18nTableMap::clearInstancePool(); + BrandImageI18nTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildBrandImageI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildBrandImageI18n 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(BrandImageI18nTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(BrandImageI18nTableMap::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(); + + + BrandImageI18nTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + BrandImageI18nTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // BrandImageI18nQuery diff --git a/core/lib/Thelia/Model/Base/BrandImageQuery.php b/core/lib/Thelia/Model/Base/BrandImageQuery.php new file mode 100644 index 000000000..c48983b54 --- /dev/null +++ b/core/lib/Thelia/Model/Base/BrandImageQuery.php @@ -0,0 +1,923 @@ +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 ChildBrandImage|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = BrandImageTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(BrandImageTableMap::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 ChildBrandImage A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `BRAND_ID`, `FILE`, `POSITION`, `CREATED_AT`, `UPDATED_AT` FROM `brand_image` 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 ChildBrandImage(); + $obj->hydrate($row); + BrandImageTableMap::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 ChildBrandImage|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 ChildBrandImageQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(BrandImageTableMap::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 ChildBrandImageQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(BrandImageTableMap::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 ChildBrandImageQuery 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(BrandImageTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(BrandImageTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandImageTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the brand_id column + * + * Example usage: + * + * $query->filterByBrandId(1234); // WHERE brand_id = 1234 + * $query->filterByBrandId(array(12, 34)); // WHERE brand_id IN (12, 34) + * $query->filterByBrandId(array('min' => 12)); // WHERE brand_id > 12 + * + * + * @see filterByBrandRelatedByBrandId() + * + * @param mixed $brandId 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 ChildBrandImageQuery The current query, for fluid interface + */ + public function filterByBrandId($brandId = null, $comparison = null) + { + if (is_array($brandId)) { + $useMinMax = false; + if (isset($brandId['min'])) { + $this->addUsingAlias(BrandImageTableMap::BRAND_ID, $brandId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($brandId['max'])) { + $this->addUsingAlias(BrandImageTableMap::BRAND_ID, $brandId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandImageTableMap::BRAND_ID, $brandId, $comparison); + } + + /** + * Filter the query on the file column + * + * Example usage: + * + * $query->filterByFile('fooValue'); // WHERE file = 'fooValue' + * $query->filterByFile('%fooValue%'); // WHERE file LIKE '%fooValue%' + * + * + * @param string $file 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 ChildBrandImageQuery The current query, for fluid interface + */ + public function filterByFile($file = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($file)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $file)) { + $file = str_replace('*', '%', $file); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(BrandImageTableMap::FILE, $file, $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 ChildBrandImageQuery 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(BrandImageTableMap::POSITION, $position['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($position['max'])) { + $this->addUsingAlias(BrandImageTableMap::POSITION, $position['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandImageTableMap::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 ChildBrandImageQuery 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(BrandImageTableMap::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($createdAt['max'])) { + $this->addUsingAlias(BrandImageTableMap::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandImageTableMap::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 ChildBrandImageQuery 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(BrandImageTableMap::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($updatedAt['max'])) { + $this->addUsingAlias(BrandImageTableMap::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandImageTableMap::UPDATED_AT, $updatedAt, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Brand object + * + * @param \Thelia\Model\Brand|ObjectCollection $brand The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function filterByBrandRelatedByBrandId($brand, $comparison = null) + { + if ($brand instanceof \Thelia\Model\Brand) { + return $this + ->addUsingAlias(BrandImageTableMap::BRAND_ID, $brand->getId(), $comparison); + } elseif ($brand instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(BrandImageTableMap::BRAND_ID, $brand->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByBrandRelatedByBrandId() only accepts arguments of type \Thelia\Model\Brand or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the BrandRelatedByBrandId relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function joinBrandRelatedByBrandId($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('BrandRelatedByBrandId'); + + // 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, 'BrandRelatedByBrandId'); + } + + return $this; + } + + /** + * Use the BrandRelatedByBrandId relation Brand 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\BrandQuery A secondary query class using the current class as primary query + */ + public function useBrandRelatedByBrandIdQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinBrandRelatedByBrandId($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'BrandRelatedByBrandId', '\Thelia\Model\BrandQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\Brand object + * + * @param \Thelia\Model\Brand|ObjectCollection $brand the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function filterByBrandRelatedByLogoImageId($brand, $comparison = null) + { + if ($brand instanceof \Thelia\Model\Brand) { + return $this + ->addUsingAlias(BrandImageTableMap::ID, $brand->getLogoImageId(), $comparison); + } elseif ($brand instanceof ObjectCollection) { + return $this + ->useBrandRelatedByLogoImageIdQuery() + ->filterByPrimaryKeys($brand->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByBrandRelatedByLogoImageId() only accepts arguments of type \Thelia\Model\Brand or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the BrandRelatedByLogoImageId relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function joinBrandRelatedByLogoImageId($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('BrandRelatedByLogoImageId'); + + // 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, 'BrandRelatedByLogoImageId'); + } + + return $this; + } + + /** + * Use the BrandRelatedByLogoImageId relation Brand 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\BrandQuery A secondary query class using the current class as primary query + */ + public function useBrandRelatedByLogoImageIdQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinBrandRelatedByLogoImageId($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'BrandRelatedByLogoImageId', '\Thelia\Model\BrandQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\BrandImageI18n object + * + * @param \Thelia\Model\BrandImageI18n|ObjectCollection $brandImageI18n the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function filterByBrandImageI18n($brandImageI18n, $comparison = null) + { + if ($brandImageI18n instanceof \Thelia\Model\BrandImageI18n) { + return $this + ->addUsingAlias(BrandImageTableMap::ID, $brandImageI18n->getId(), $comparison); + } elseif ($brandImageI18n instanceof ObjectCollection) { + return $this + ->useBrandImageI18nQuery() + ->filterByPrimaryKeys($brandImageI18n->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByBrandImageI18n() only accepts arguments of type \Thelia\Model\BrandImageI18n or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the BrandImageI18n relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function joinBrandImageI18n($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('BrandImageI18n'); + + // 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, 'BrandImageI18n'); + } + + return $this; + } + + /** + * Use the BrandImageI18n relation BrandImageI18n 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\BrandImageI18nQuery A secondary query class using the current class as primary query + */ + public function useBrandImageI18nQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinBrandImageI18n($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'BrandImageI18n', '\Thelia\Model\BrandImageI18nQuery'); + } + + /** + * Exclude object from result + * + * @param ChildBrandImage $brandImage Object to remove from the list of results + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function prune($brandImage = null) + { + if ($brandImage) { + $this->addUsingAlias(BrandImageTableMap::ID, $brandImage->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the brand_image 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(BrandImageTableMap::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). + BrandImageTableMap::clearInstancePool(); + BrandImageTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildBrandImage or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildBrandImage 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(BrandImageTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(BrandImageTableMap::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(); + + + BrandImageTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + BrandImageTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + // timestampable behavior + + /** + * Filter by the latest updated + * + * @param int $nbDays Maximum age of the latest update in days + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function recentlyUpdated($nbDays = 7) + { + return $this->addUsingAlias(BrandImageTableMap::UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Filter by the latest created + * + * @param int $nbDays Maximum age of in days + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function recentlyCreated($nbDays = 7) + { + return $this->addUsingAlias(BrandImageTableMap::CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Order by update date desc + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function lastUpdatedFirst() + { + return $this->addDescendingOrderByColumn(BrandImageTableMap::UPDATED_AT); + } + + /** + * Order by update date asc + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function firstUpdatedFirst() + { + return $this->addAscendingOrderByColumn(BrandImageTableMap::UPDATED_AT); + } + + /** + * Order by create date desc + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function lastCreatedFirst() + { + return $this->addDescendingOrderByColumn(BrandImageTableMap::CREATED_AT); + } + + /** + * Order by create date asc + * + * @return ChildBrandImageQuery The current query, for fluid interface + */ + public function firstCreatedFirst() + { + return $this->addAscendingOrderByColumn(BrandImageTableMap::CREATED_AT); + } + + // 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 ChildBrandImageQuery The current query, for fluid interface + */ + public function joinI18n($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $relationName = $relationAlias ? $relationAlias : 'BrandImageI18n'; + + return $this + ->joinBrandImageI18n($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 ChildBrandImageQuery The current query, for fluid interface + */ + public function joinWithI18n($locale = 'en_US', $joinType = Criteria::LEFT_JOIN) + { + $this + ->joinI18n($locale, null, $joinType) + ->with('BrandImageI18n'); + $this->with['BrandImageI18n']->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 ChildBrandImageI18nQuery 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 : 'BrandImageI18n', '\Thelia\Model\BrandImageI18nQuery'); + } + +} // BrandImageQuery diff --git a/core/lib/Thelia/Model/Base/BrandQuery.php b/core/lib/Thelia/Model/Base/BrandQuery.php new file mode 100644 index 000000000..e9eede241 --- /dev/null +++ b/core/lib/Thelia/Model/Base/BrandQuery.php @@ -0,0 +1,1089 @@ +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 ChildBrand|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = BrandTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(BrandTableMap::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 ChildBrand A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT `ID`, `VISIBLE`, `POSITION`, `LOGO_IMAGE_ID`, `CREATED_AT`, `UPDATED_AT` FROM `brand` 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 ChildBrand(); + $obj->hydrate($row); + BrandTableMap::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 ChildBrand|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 ChildBrandQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(BrandTableMap::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 ChildBrandQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(BrandTableMap::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 ChildBrandQuery 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(BrandTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(BrandTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the visible column + * + * Example usage: + * + * $query->filterByVisible(1234); // WHERE visible = 1234 + * $query->filterByVisible(array(12, 34)); // WHERE visible IN (12, 34) + * $query->filterByVisible(array('min' => 12)); // WHERE visible > 12 + * + * + * @param mixed $visible 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 ChildBrandQuery The current query, for fluid interface + */ + public function filterByVisible($visible = null, $comparison = null) + { + if (is_array($visible)) { + $useMinMax = false; + if (isset($visible['min'])) { + $this->addUsingAlias(BrandTableMap::VISIBLE, $visible['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($visible['max'])) { + $this->addUsingAlias(BrandTableMap::VISIBLE, $visible['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandTableMap::VISIBLE, $visible, $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 ChildBrandQuery 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(BrandTableMap::POSITION, $position['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($position['max'])) { + $this->addUsingAlias(BrandTableMap::POSITION, $position['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandTableMap::POSITION, $position, $comparison); + } + + /** + * Filter the query on the logo_image_id column + * + * Example usage: + * + * $query->filterByLogoImageId(1234); // WHERE logo_image_id = 1234 + * $query->filterByLogoImageId(array(12, 34)); // WHERE logo_image_id IN (12, 34) + * $query->filterByLogoImageId(array('min' => 12)); // WHERE logo_image_id > 12 + * + * + * @see filterByBrandImageRelatedByLogoImageId() + * + * @param mixed $logoImageId 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 ChildBrandQuery The current query, for fluid interface + */ + public function filterByLogoImageId($logoImageId = null, $comparison = null) + { + if (is_array($logoImageId)) { + $useMinMax = false; + if (isset($logoImageId['min'])) { + $this->addUsingAlias(BrandTableMap::LOGO_IMAGE_ID, $logoImageId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($logoImageId['max'])) { + $this->addUsingAlias(BrandTableMap::LOGO_IMAGE_ID, $logoImageId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandTableMap::LOGO_IMAGE_ID, $logoImageId, $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 ChildBrandQuery 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(BrandTableMap::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($createdAt['max'])) { + $this->addUsingAlias(BrandTableMap::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandTableMap::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 ChildBrandQuery 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(BrandTableMap::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($updatedAt['max'])) { + $this->addUsingAlias(BrandTableMap::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(BrandTableMap::UPDATED_AT, $updatedAt, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\BrandImage object + * + * @param \Thelia\Model\BrandImage|ObjectCollection $brandImage The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function filterByBrandImageRelatedByLogoImageId($brandImage, $comparison = null) + { + if ($brandImage instanceof \Thelia\Model\BrandImage) { + return $this + ->addUsingAlias(BrandTableMap::LOGO_IMAGE_ID, $brandImage->getId(), $comparison); + } elseif ($brandImage instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(BrandTableMap::LOGO_IMAGE_ID, $brandImage->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByBrandImageRelatedByLogoImageId() only accepts arguments of type \Thelia\Model\BrandImage or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the BrandImageRelatedByLogoImageId relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function joinBrandImageRelatedByLogoImageId($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('BrandImageRelatedByLogoImageId'); + + // 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, 'BrandImageRelatedByLogoImageId'); + } + + return $this; + } + + /** + * Use the BrandImageRelatedByLogoImageId relation BrandImage 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\BrandImageQuery A secondary query class using the current class as primary query + */ + public function useBrandImageRelatedByLogoImageIdQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinBrandImageRelatedByLogoImageId($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'BrandImageRelatedByLogoImageId', '\Thelia\Model\BrandImageQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\Product object + * + * @param \Thelia\Model\Product|ObjectCollection $product the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function filterByProduct($product, $comparison = null) + { + if ($product instanceof \Thelia\Model\Product) { + return $this + ->addUsingAlias(BrandTableMap::ID, $product->getBrandId(), $comparison); + } elseif ($product instanceof ObjectCollection) { + return $this + ->useProductQuery() + ->filterByPrimaryKeys($product->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByProduct() only accepts arguments of type \Thelia\Model\Product or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Product relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function joinProduct($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Product'); + + // 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, 'Product'); + } + + return $this; + } + + /** + * Use the Product relation Product 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\ProductQuery A secondary query class using the current class as primary query + */ + public function useProductQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinProduct($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Product', '\Thelia\Model\ProductQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\BrandDocument object + * + * @param \Thelia\Model\BrandDocument|ObjectCollection $brandDocument the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function filterByBrandDocument($brandDocument, $comparison = null) + { + if ($brandDocument instanceof \Thelia\Model\BrandDocument) { + return $this + ->addUsingAlias(BrandTableMap::ID, $brandDocument->getBrandId(), $comparison); + } elseif ($brandDocument instanceof ObjectCollection) { + return $this + ->useBrandDocumentQuery() + ->filterByPrimaryKeys($brandDocument->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByBrandDocument() only accepts arguments of type \Thelia\Model\BrandDocument or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the BrandDocument relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function joinBrandDocument($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('BrandDocument'); + + // 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, 'BrandDocument'); + } + + return $this; + } + + /** + * Use the BrandDocument relation BrandDocument 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\BrandDocumentQuery A secondary query class using the current class as primary query + */ + public function useBrandDocumentQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinBrandDocument($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'BrandDocument', '\Thelia\Model\BrandDocumentQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\BrandImage object + * + * @param \Thelia\Model\BrandImage|ObjectCollection $brandImage the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function filterByBrandImageRelatedByBrandId($brandImage, $comparison = null) + { + if ($brandImage instanceof \Thelia\Model\BrandImage) { + return $this + ->addUsingAlias(BrandTableMap::ID, $brandImage->getBrandId(), $comparison); + } elseif ($brandImage instanceof ObjectCollection) { + return $this + ->useBrandImageRelatedByBrandIdQuery() + ->filterByPrimaryKeys($brandImage->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByBrandImageRelatedByBrandId() only accepts arguments of type \Thelia\Model\BrandImage or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the BrandImageRelatedByBrandId relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function joinBrandImageRelatedByBrandId($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('BrandImageRelatedByBrandId'); + + // 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, 'BrandImageRelatedByBrandId'); + } + + return $this; + } + + /** + * Use the BrandImageRelatedByBrandId relation BrandImage 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\BrandImageQuery A secondary query class using the current class as primary query + */ + public function useBrandImageRelatedByBrandIdQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinBrandImageRelatedByBrandId($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'BrandImageRelatedByBrandId', '\Thelia\Model\BrandImageQuery'); + } + + /** + * Filter the query by a related \Thelia\Model\BrandI18n object + * + * @param \Thelia\Model\BrandI18n|ObjectCollection $brandI18n the related object to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function filterByBrandI18n($brandI18n, $comparison = null) + { + if ($brandI18n instanceof \Thelia\Model\BrandI18n) { + return $this + ->addUsingAlias(BrandTableMap::ID, $brandI18n->getId(), $comparison); + } elseif ($brandI18n instanceof ObjectCollection) { + return $this + ->useBrandI18nQuery() + ->filterByPrimaryKeys($brandI18n->getPrimaryKeys()) + ->endUse(); + } else { + throw new PropelException('filterByBrandI18n() only accepts arguments of type \Thelia\Model\BrandI18n or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the BrandI18n relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function joinBrandI18n($relationAlias = null, $joinType = 'LEFT JOIN') + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('BrandI18n'); + + // 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, 'BrandI18n'); + } + + return $this; + } + + /** + * Use the BrandI18n relation BrandI18n 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\BrandI18nQuery A secondary query class using the current class as primary query + */ + public function useBrandI18nQuery($relationAlias = null, $joinType = 'LEFT JOIN') + { + return $this + ->joinBrandI18n($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'BrandI18n', '\Thelia\Model\BrandI18nQuery'); + } + + /** + * Exclude object from result + * + * @param ChildBrand $brand Object to remove from the list of results + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function prune($brand = null) + { + if ($brand) { + $this->addUsingAlias(BrandTableMap::ID, $brand->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the brand 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(BrandTableMap::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). + BrandTableMap::clearInstancePool(); + BrandTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildBrand or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildBrand 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(BrandTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(BrandTableMap::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(); + + + BrandTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + BrandTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + // timestampable behavior + + /** + * Filter by the latest updated + * + * @param int $nbDays Maximum age of the latest update in days + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function recentlyUpdated($nbDays = 7) + { + return $this->addUsingAlias(BrandTableMap::UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Filter by the latest created + * + * @param int $nbDays Maximum age of in days + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function recentlyCreated($nbDays = 7) + { + return $this->addUsingAlias(BrandTableMap::CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Order by update date desc + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function lastUpdatedFirst() + { + return $this->addDescendingOrderByColumn(BrandTableMap::UPDATED_AT); + } + + /** + * Order by update date asc + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function firstUpdatedFirst() + { + return $this->addAscendingOrderByColumn(BrandTableMap::UPDATED_AT); + } + + /** + * Order by create date desc + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function lastCreatedFirst() + { + return $this->addDescendingOrderByColumn(BrandTableMap::CREATED_AT); + } + + /** + * Order by create date asc + * + * @return ChildBrandQuery The current query, for fluid interface + */ + public function firstCreatedFirst() + { + return $this->addAscendingOrderByColumn(BrandTableMap::CREATED_AT); + } + + // 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 ChildBrandQuery The current query, for fluid interface + */ + public function joinI18n($locale = 'en_US', $relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $relationName = $relationAlias ? $relationAlias : 'BrandI18n'; + + return $this + ->joinBrandI18n($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 ChildBrandQuery The current query, for fluid interface + */ + public function joinWithI18n($locale = 'en_US', $joinType = Criteria::LEFT_JOIN) + { + $this + ->joinI18n($locale, null, $joinType) + ->with('BrandI18n'); + $this->with['BrandI18n']->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 ChildBrandI18nQuery 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 : 'BrandI18n', '\Thelia\Model\BrandI18nQuery'); + } + +} // BrandQuery diff --git a/core/lib/Thelia/Model/Base/Coupon.php b/core/lib/Thelia/Model/Base/Coupon.php index e66d7d16f..a9351ece2 100644 --- a/core/lib/Thelia/Model/Base/Coupon.php +++ b/core/lib/Thelia/Model/Base/Coupon.php @@ -169,6 +169,18 @@ abstract class Coupon implements ActiveRecordInterface */ protected $version; + /** + * The value for the version_created_at field. + * @var string + */ + protected $version_created_at; + + /** + * The value for the version_created_by field. + * @var string + */ + protected $version_created_by; + /** * @var ObjectCollection|ChildCouponCountry[] Collection to store aggregation of ChildCouponCountry objects. */ @@ -766,6 +778,37 @@ abstract class Coupon implements ActiveRecordInterface return $this->version; } + /** + * Get the [optionally formatted] temporal [version_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 getVersionCreatedAt($format = NULL) + { + if ($format === null) { + return $this->version_created_at; + } else { + return $this->version_created_at instanceof \DateTime ? $this->version_created_at->format($format) : null; + } + } + + /** + * Get the [version_created_by] column value. + * + * @return string + */ + public function getVersionCreatedBy() + { + + return $this->version_created_by; + } + /** * Set the value of [id] column. * @@ -1150,6 +1193,48 @@ abstract class Coupon implements ActiveRecordInterface return $this; } // setVersion() + /** + * Sets the value of [version_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\Coupon The current object (for fluent API support) + */ + public function setVersionCreatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->version_created_at !== null || $dt !== null) { + if ($dt !== $this->version_created_at) { + $this->version_created_at = $dt; + $this->modifiedColumns[CouponTableMap::VERSION_CREATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setVersionCreatedAt() + + /** + * Set the value of [version_created_by] column. + * + * @param string $v new value + * @return \Thelia\Model\Coupon The current object (for fluent API support) + */ + public function setVersionCreatedBy($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->version_created_by !== $v) { + $this->version_created_by = $v; + $this->modifiedColumns[CouponTableMap::VERSION_CREATED_BY] = true; + } + + + return $this; + } // setVersionCreatedBy() + /** * Indicates whether the columns in this object are only set to default values. * @@ -1247,6 +1332,15 @@ abstract class Coupon implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 15 + $startcol : CouponTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; $this->version = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 16 + $startcol : CouponTableMap::translateFieldName('VersionCreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->version_created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 17 + $startcol : CouponTableMap::translateFieldName('VersionCreatedBy', TableMap::TYPE_PHPNAME, $indexType)]; + $this->version_created_by = (null !== $col) ? (string) $col : null; $this->resetModified(); $this->setNew(false); @@ -1255,7 +1349,7 @@ abstract class Coupon implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 16; // 16 = CouponTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 18; // 18 = CouponTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\Coupon object", 0, $e); @@ -1400,6 +1494,9 @@ abstract class Coupon implements ActiveRecordInterface // versionable behavior if ($this->isVersioningNecessary()) { $this->setVersion($this->isNew() ? 1 : $this->getLastVersionNumber($con) + 1); + if (!$this->isColumnModified(CouponTableMap::VERSION_CREATED_AT)) { + $this->setVersionCreatedAt(time()); + } $createVersion = true; // for postSave hook } if ($isInsert) { @@ -1711,6 +1808,12 @@ abstract class Coupon implements ActiveRecordInterface if ($this->isColumnModified(CouponTableMap::VERSION)) { $modifiedColumns[':p' . $index++] = '`VERSION`'; } + if ($this->isColumnModified(CouponTableMap::VERSION_CREATED_AT)) { + $modifiedColumns[':p' . $index++] = '`VERSION_CREATED_AT`'; + } + if ($this->isColumnModified(CouponTableMap::VERSION_CREATED_BY)) { + $modifiedColumns[':p' . $index++] = '`VERSION_CREATED_BY`'; + } $sql = sprintf( 'INSERT INTO `coupon` (%s) VALUES (%s)', @@ -1770,6 +1873,12 @@ abstract class Coupon implements ActiveRecordInterface case '`VERSION`': $stmt->bindValue($identifier, $this->version, PDO::PARAM_INT); break; + case '`VERSION_CREATED_AT`': + $stmt->bindValue($identifier, $this->version_created_at ? $this->version_created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + case '`VERSION_CREATED_BY`': + $stmt->bindValue($identifier, $this->version_created_by, PDO::PARAM_STR); + break; } } $stmt->execute(); @@ -1880,6 +1989,12 @@ abstract class Coupon implements ActiveRecordInterface case 15: return $this->getVersion(); break; + case 16: + return $this->getVersionCreatedAt(); + break; + case 17: + return $this->getVersionCreatedBy(); + break; default: return null; break; @@ -1925,6 +2040,8 @@ abstract class Coupon implements ActiveRecordInterface $keys[13] => $this->getCreatedAt(), $keys[14] => $this->getUpdatedAt(), $keys[15] => $this->getVersion(), + $keys[16] => $this->getVersionCreatedAt(), + $keys[17] => $this->getVersionCreatedBy(), ); $virtualColumns = $this->virtualColumns; foreach ($virtualColumns as $key => $virtualColumn) { @@ -2029,6 +2146,12 @@ abstract class Coupon implements ActiveRecordInterface case 15: $this->setVersion($value); break; + case 16: + $this->setVersionCreatedAt($value); + break; + case 17: + $this->setVersionCreatedBy($value); + break; } // switch() } @@ -2069,6 +2192,8 @@ abstract class Coupon implements ActiveRecordInterface if (array_key_exists($keys[13], $arr)) $this->setCreatedAt($arr[$keys[13]]); if (array_key_exists($keys[14], $arr)) $this->setUpdatedAt($arr[$keys[14]]); if (array_key_exists($keys[15], $arr)) $this->setVersion($arr[$keys[15]]); + if (array_key_exists($keys[16], $arr)) $this->setVersionCreatedAt($arr[$keys[16]]); + if (array_key_exists($keys[17], $arr)) $this->setVersionCreatedBy($arr[$keys[17]]); } /** @@ -2096,6 +2221,8 @@ abstract class Coupon implements ActiveRecordInterface if ($this->isColumnModified(CouponTableMap::CREATED_AT)) $criteria->add(CouponTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(CouponTableMap::UPDATED_AT)) $criteria->add(CouponTableMap::UPDATED_AT, $this->updated_at); if ($this->isColumnModified(CouponTableMap::VERSION)) $criteria->add(CouponTableMap::VERSION, $this->version); + if ($this->isColumnModified(CouponTableMap::VERSION_CREATED_AT)) $criteria->add(CouponTableMap::VERSION_CREATED_AT, $this->version_created_at); + if ($this->isColumnModified(CouponTableMap::VERSION_CREATED_BY)) $criteria->add(CouponTableMap::VERSION_CREATED_BY, $this->version_created_by); return $criteria; } @@ -2174,6 +2301,8 @@ abstract class Coupon implements ActiveRecordInterface $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); $copyObj->setVersion($this->getVersion()); + $copyObj->setVersionCreatedAt($this->getVersionCreatedAt()); + $copyObj->setVersionCreatedBy($this->getVersionCreatedBy()); if ($deepCopy) { // important: temporarily setNew(false) because this affects the behavior of @@ -4019,6 +4148,8 @@ abstract class Coupon implements ActiveRecordInterface $this->created_at = null; $this->updated_at = null; $this->version = null; + $this->version_created_at = null; + $this->version_created_by = null; $this->alreadyInSave = false; $this->clearAllReferences(); $this->applyDefaultValues(); @@ -4354,6 +4485,8 @@ abstract class Coupon implements ActiveRecordInterface $version->setCreatedAt($this->getCreatedAt()); $version->setUpdatedAt($this->getUpdatedAt()); $version->setVersion($this->getVersion()); + $version->setVersionCreatedAt($this->getVersionCreatedAt()); + $version->setVersionCreatedBy($this->getVersionCreatedBy()); $version->setCoupon($this); $version->save($con); @@ -4407,6 +4540,8 @@ abstract class Coupon implements ActiveRecordInterface $this->setCreatedAt($version->getCreatedAt()); $this->setUpdatedAt($version->getUpdatedAt()); $this->setVersion($version->getVersion()); + $this->setVersionCreatedAt($version->getVersionCreatedAt()); + $this->setVersionCreatedBy($version->getVersionCreatedBy()); return $this; } @@ -4548,6 +4683,8 @@ abstract class Coupon implements ActiveRecordInterface $toVersionNumber = $toVersion['Version']; $ignoredColumns = array_merge(array( 'Version', + 'VersionCreatedAt', + 'VersionCreatedBy', ), $ignoredColumns); $diff = array(); foreach ($fromVersion as $key => $value) { diff --git a/core/lib/Thelia/Model/Base/CouponQuery.php b/core/lib/Thelia/Model/Base/CouponQuery.php index 9e2a4a8a7..54a6466de 100644 --- a/core/lib/Thelia/Model/Base/CouponQuery.php +++ b/core/lib/Thelia/Model/Base/CouponQuery.php @@ -38,6 +38,8 @@ use Thelia\Model\Map\CouponTableMap; * @method ChildCouponQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildCouponQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @method ChildCouponQuery orderByVersion($order = Criteria::ASC) Order by the version column + * @method ChildCouponQuery orderByVersionCreatedAt($order = Criteria::ASC) Order by the version_created_at column + * @method ChildCouponQuery orderByVersionCreatedBy($order = Criteria::ASC) Order by the version_created_by column * * @method ChildCouponQuery groupById() Group by the id column * @method ChildCouponQuery groupByCode() Group by the code column @@ -55,6 +57,8 @@ use Thelia\Model\Map\CouponTableMap; * @method ChildCouponQuery groupByCreatedAt() Group by the created_at column * @method ChildCouponQuery groupByUpdatedAt() Group by the updated_at column * @method ChildCouponQuery groupByVersion() Group by the version column + * @method ChildCouponQuery groupByVersionCreatedAt() Group by the version_created_at column + * @method ChildCouponQuery groupByVersionCreatedBy() Group by the version_created_by column * * @method ChildCouponQuery leftJoin($relation) Adds a LEFT JOIN clause to the query * @method ChildCouponQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query @@ -99,6 +103,8 @@ use Thelia\Model\Map\CouponTableMap; * @method ChildCoupon findOneByCreatedAt(string $created_at) Return the first ChildCoupon filtered by the created_at column * @method ChildCoupon findOneByUpdatedAt(string $updated_at) Return the first ChildCoupon filtered by the updated_at column * @method ChildCoupon findOneByVersion(int $version) Return the first ChildCoupon filtered by the version column + * @method ChildCoupon findOneByVersionCreatedAt(string $version_created_at) Return the first ChildCoupon filtered by the version_created_at column + * @method ChildCoupon findOneByVersionCreatedBy(string $version_created_by) Return the first ChildCoupon filtered by the version_created_by column * * @method array findById(int $id) Return ChildCoupon objects filtered by the id column * @method array findByCode(string $code) Return ChildCoupon objects filtered by the code column @@ -116,6 +122,8 @@ use Thelia\Model\Map\CouponTableMap; * @method array findByCreatedAt(string $created_at) Return ChildCoupon objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildCoupon objects filtered by the updated_at column * @method array findByVersion(int $version) Return ChildCoupon objects filtered by the version column + * @method array findByVersionCreatedAt(string $version_created_at) Return ChildCoupon objects filtered by the version_created_at column + * @method array findByVersionCreatedBy(string $version_created_by) Return ChildCoupon objects filtered by the version_created_by column * */ abstract class CouponQuery extends ModelCriteria @@ -211,7 +219,7 @@ abstract class CouponQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT `ID`, `CODE`, `TYPE`, `SERIALIZED_EFFECTS`, `IS_ENABLED`, `EXPIRATION_DATE`, `MAX_USAGE`, `IS_CUMULATIVE`, `IS_REMOVING_POSTAGE`, `IS_AVAILABLE_ON_SPECIAL_OFFERS`, `IS_USED`, `SERIALIZED_CONDITIONS`, `PER_CUSTOMER_USAGE_COUNT`, `CREATED_AT`, `UPDATED_AT`, `VERSION` FROM `coupon` WHERE `ID` = :p0'; + $sql = 'SELECT `ID`, `CODE`, `TYPE`, `SERIALIZED_EFFECTS`, `IS_ENABLED`, `EXPIRATION_DATE`, `MAX_USAGE`, `IS_CUMULATIVE`, `IS_REMOVING_POSTAGE`, `IS_AVAILABLE_ON_SPECIAL_OFFERS`, `IS_USED`, `SERIALIZED_CONDITIONS`, `PER_CUSTOMER_USAGE_COUNT`, `CREATED_AT`, `UPDATED_AT`, `VERSION`, `VERSION_CREATED_AT`, `VERSION_CREATED_BY` FROM `coupon` WHERE `ID` = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -830,6 +838,78 @@ abstract class CouponQuery extends ModelCriteria return $this->addUsingAlias(CouponTableMap::VERSION, $version, $comparison); } + /** + * Filter the query on the version_created_at column + * + * Example usage: + * + * $query->filterByVersionCreatedAt('2011-03-14'); // WHERE version_created_at = '2011-03-14' + * $query->filterByVersionCreatedAt('now'); // WHERE version_created_at = '2011-03-14' + * $query->filterByVersionCreatedAt(array('max' => 'yesterday')); // WHERE version_created_at > '2011-03-13' + * + * + * @param mixed $versionCreatedAt 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 ChildCouponQuery The current query, for fluid interface + */ + public function filterByVersionCreatedAt($versionCreatedAt = null, $comparison = null) + { + if (is_array($versionCreatedAt)) { + $useMinMax = false; + if (isset($versionCreatedAt['min'])) { + $this->addUsingAlias(CouponTableMap::VERSION_CREATED_AT, $versionCreatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($versionCreatedAt['max'])) { + $this->addUsingAlias(CouponTableMap::VERSION_CREATED_AT, $versionCreatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CouponTableMap::VERSION_CREATED_AT, $versionCreatedAt, $comparison); + } + + /** + * Filter the query on the version_created_by column + * + * Example usage: + * + * $query->filterByVersionCreatedBy('fooValue'); // WHERE version_created_by = 'fooValue' + * $query->filterByVersionCreatedBy('%fooValue%'); // WHERE version_created_by LIKE '%fooValue%' + * + * + * @param string $versionCreatedBy 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 ChildCouponQuery The current query, for fluid interface + */ + public function filterByVersionCreatedBy($versionCreatedBy = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($versionCreatedBy)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $versionCreatedBy)) { + $versionCreatedBy = str_replace('*', '%', $versionCreatedBy); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(CouponTableMap::VERSION_CREATED_BY, $versionCreatedBy, $comparison); + } + /** * Filter the query by a related \Thelia\Model\CouponCountry object * diff --git a/core/lib/Thelia/Model/Base/CouponVersion.php b/core/lib/Thelia/Model/Base/CouponVersion.php index 7b26f06ba..cb98a50f8 100644 --- a/core/lib/Thelia/Model/Base/CouponVersion.php +++ b/core/lib/Thelia/Model/Base/CouponVersion.php @@ -152,6 +152,18 @@ abstract class CouponVersion implements ActiveRecordInterface */ protected $version; + /** + * The value for the version_created_at field. + * @var string + */ + protected $version_created_at; + + /** + * The value for the version_created_by field. + * @var string + */ + protected $version_created_by; + /** * @var Coupon */ @@ -639,6 +651,37 @@ abstract class CouponVersion implements ActiveRecordInterface return $this->version; } + /** + * Get the [optionally formatted] temporal [version_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 getVersionCreatedAt($format = NULL) + { + if ($format === null) { + return $this->version_created_at; + } else { + return $this->version_created_at instanceof \DateTime ? $this->version_created_at->format($format) : null; + } + } + + /** + * Get the [version_created_by] column value. + * + * @return string + */ + public function getVersionCreatedBy() + { + + return $this->version_created_by; + } + /** * Set the value of [id] column. * @@ -1027,6 +1070,48 @@ abstract class CouponVersion implements ActiveRecordInterface return $this; } // setVersion() + /** + * Sets the value of [version_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\CouponVersion The current object (for fluent API support) + */ + public function setVersionCreatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->version_created_at !== null || $dt !== null) { + if ($dt !== $this->version_created_at) { + $this->version_created_at = $dt; + $this->modifiedColumns[CouponVersionTableMap::VERSION_CREATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setVersionCreatedAt() + + /** + * Set the value of [version_created_by] column. + * + * @param string $v new value + * @return \Thelia\Model\CouponVersion The current object (for fluent API support) + */ + public function setVersionCreatedBy($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->version_created_by !== $v) { + $this->version_created_by = $v; + $this->modifiedColumns[CouponVersionTableMap::VERSION_CREATED_BY] = true; + } + + + return $this; + } // setVersionCreatedBy() + /** * Indicates whether the columns in this object are only set to default values. * @@ -1124,6 +1209,15 @@ abstract class CouponVersion implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 15 + $startcol : CouponVersionTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; $this->version = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 16 + $startcol : CouponVersionTableMap::translateFieldName('VersionCreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->version_created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 17 + $startcol : CouponVersionTableMap::translateFieldName('VersionCreatedBy', TableMap::TYPE_PHPNAME, $indexType)]; + $this->version_created_by = (null !== $col) ? (string) $col : null; $this->resetModified(); $this->setNew(false); @@ -1132,7 +1226,7 @@ abstract class CouponVersion implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 16; // 16 = CouponVersionTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 18; // 18 = CouponVersionTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\CouponVersion object", 0, $e); @@ -1401,6 +1495,12 @@ abstract class CouponVersion implements ActiveRecordInterface if ($this->isColumnModified(CouponVersionTableMap::VERSION)) { $modifiedColumns[':p' . $index++] = '`VERSION`'; } + if ($this->isColumnModified(CouponVersionTableMap::VERSION_CREATED_AT)) { + $modifiedColumns[':p' . $index++] = '`VERSION_CREATED_AT`'; + } + if ($this->isColumnModified(CouponVersionTableMap::VERSION_CREATED_BY)) { + $modifiedColumns[':p' . $index++] = '`VERSION_CREATED_BY`'; + } $sql = sprintf( 'INSERT INTO `coupon_version` (%s) VALUES (%s)', @@ -1460,6 +1560,12 @@ abstract class CouponVersion implements ActiveRecordInterface case '`VERSION`': $stmt->bindValue($identifier, $this->version, PDO::PARAM_INT); break; + case '`VERSION_CREATED_AT`': + $stmt->bindValue($identifier, $this->version_created_at ? $this->version_created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + case '`VERSION_CREATED_BY`': + $stmt->bindValue($identifier, $this->version_created_by, PDO::PARAM_STR); + break; } } $stmt->execute(); @@ -1563,6 +1669,12 @@ abstract class CouponVersion implements ActiveRecordInterface case 15: return $this->getVersion(); break; + case 16: + return $this->getVersionCreatedAt(); + break; + case 17: + return $this->getVersionCreatedBy(); + break; default: return null; break; @@ -1608,6 +1720,8 @@ abstract class CouponVersion implements ActiveRecordInterface $keys[13] => $this->getCreatedAt(), $keys[14] => $this->getUpdatedAt(), $keys[15] => $this->getVersion(), + $keys[16] => $this->getVersionCreatedAt(), + $keys[17] => $this->getVersionCreatedBy(), ); $virtualColumns = $this->virtualColumns; foreach ($virtualColumns as $key => $virtualColumn) { @@ -1700,6 +1814,12 @@ abstract class CouponVersion implements ActiveRecordInterface case 15: $this->setVersion($value); break; + case 16: + $this->setVersionCreatedAt($value); + break; + case 17: + $this->setVersionCreatedBy($value); + break; } // switch() } @@ -1740,6 +1860,8 @@ abstract class CouponVersion implements ActiveRecordInterface if (array_key_exists($keys[13], $arr)) $this->setCreatedAt($arr[$keys[13]]); if (array_key_exists($keys[14], $arr)) $this->setUpdatedAt($arr[$keys[14]]); if (array_key_exists($keys[15], $arr)) $this->setVersion($arr[$keys[15]]); + if (array_key_exists($keys[16], $arr)) $this->setVersionCreatedAt($arr[$keys[16]]); + if (array_key_exists($keys[17], $arr)) $this->setVersionCreatedBy($arr[$keys[17]]); } /** @@ -1767,6 +1889,8 @@ abstract class CouponVersion implements ActiveRecordInterface if ($this->isColumnModified(CouponVersionTableMap::CREATED_AT)) $criteria->add(CouponVersionTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(CouponVersionTableMap::UPDATED_AT)) $criteria->add(CouponVersionTableMap::UPDATED_AT, $this->updated_at); if ($this->isColumnModified(CouponVersionTableMap::VERSION)) $criteria->add(CouponVersionTableMap::VERSION, $this->version); + if ($this->isColumnModified(CouponVersionTableMap::VERSION_CREATED_AT)) $criteria->add(CouponVersionTableMap::VERSION_CREATED_AT, $this->version_created_at); + if ($this->isColumnModified(CouponVersionTableMap::VERSION_CREATED_BY)) $criteria->add(CouponVersionTableMap::VERSION_CREATED_BY, $this->version_created_by); return $criteria; } @@ -1853,6 +1977,8 @@ abstract class CouponVersion implements ActiveRecordInterface $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); $copyObj->setVersion($this->getVersion()); + $copyObj->setVersionCreatedAt($this->getVersionCreatedAt()); + $copyObj->setVersionCreatedBy($this->getVersionCreatedBy()); if ($makeNew) { $copyObj->setNew(true); } @@ -1952,6 +2078,8 @@ abstract class CouponVersion implements ActiveRecordInterface $this->created_at = null; $this->updated_at = null; $this->version = null; + $this->version_created_at = null; + $this->version_created_by = null; $this->alreadyInSave = false; $this->clearAllReferences(); $this->applyDefaultValues(); diff --git a/core/lib/Thelia/Model/Base/CouponVersionQuery.php b/core/lib/Thelia/Model/Base/CouponVersionQuery.php index 081b8f04a..3dba632aa 100644 --- a/core/lib/Thelia/Model/Base/CouponVersionQuery.php +++ b/core/lib/Thelia/Model/Base/CouponVersionQuery.php @@ -37,6 +37,8 @@ use Thelia\Model\Map\CouponVersionTableMap; * @method ChildCouponVersionQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildCouponVersionQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @method ChildCouponVersionQuery orderByVersion($order = Criteria::ASC) Order by the version column + * @method ChildCouponVersionQuery orderByVersionCreatedAt($order = Criteria::ASC) Order by the version_created_at column + * @method ChildCouponVersionQuery orderByVersionCreatedBy($order = Criteria::ASC) Order by the version_created_by column * * @method ChildCouponVersionQuery groupById() Group by the id column * @method ChildCouponVersionQuery groupByCode() Group by the code column @@ -54,6 +56,8 @@ use Thelia\Model\Map\CouponVersionTableMap; * @method ChildCouponVersionQuery groupByCreatedAt() Group by the created_at column * @method ChildCouponVersionQuery groupByUpdatedAt() Group by the updated_at column * @method ChildCouponVersionQuery groupByVersion() Group by the version column + * @method ChildCouponVersionQuery groupByVersionCreatedAt() Group by the version_created_at column + * @method ChildCouponVersionQuery groupByVersionCreatedBy() Group by the version_created_by column * * @method ChildCouponVersionQuery leftJoin($relation) Adds a LEFT JOIN clause to the query * @method ChildCouponVersionQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query @@ -82,6 +86,8 @@ use Thelia\Model\Map\CouponVersionTableMap; * @method ChildCouponVersion findOneByCreatedAt(string $created_at) Return the first ChildCouponVersion filtered by the created_at column * @method ChildCouponVersion findOneByUpdatedAt(string $updated_at) Return the first ChildCouponVersion filtered by the updated_at column * @method ChildCouponVersion findOneByVersion(int $version) Return the first ChildCouponVersion filtered by the version column + * @method ChildCouponVersion findOneByVersionCreatedAt(string $version_created_at) Return the first ChildCouponVersion filtered by the version_created_at column + * @method ChildCouponVersion findOneByVersionCreatedBy(string $version_created_by) Return the first ChildCouponVersion filtered by the version_created_by column * * @method array findById(int $id) Return ChildCouponVersion objects filtered by the id column * @method array findByCode(string $code) Return ChildCouponVersion objects filtered by the code column @@ -99,6 +105,8 @@ use Thelia\Model\Map\CouponVersionTableMap; * @method array findByCreatedAt(string $created_at) Return ChildCouponVersion objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildCouponVersion objects filtered by the updated_at column * @method array findByVersion(int $version) Return ChildCouponVersion objects filtered by the version column + * @method array findByVersionCreatedAt(string $version_created_at) Return ChildCouponVersion objects filtered by the version_created_at column + * @method array findByVersionCreatedBy(string $version_created_by) Return ChildCouponVersion objects filtered by the version_created_by column * */ abstract class CouponVersionQuery extends ModelCriteria @@ -187,7 +195,7 @@ abstract class CouponVersionQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT `ID`, `CODE`, `TYPE`, `SERIALIZED_EFFECTS`, `IS_ENABLED`, `EXPIRATION_DATE`, `MAX_USAGE`, `IS_CUMULATIVE`, `IS_REMOVING_POSTAGE`, `IS_AVAILABLE_ON_SPECIAL_OFFERS`, `IS_USED`, `SERIALIZED_CONDITIONS`, `PER_CUSTOMER_USAGE_COUNT`, `CREATED_AT`, `UPDATED_AT`, `VERSION` FROM `coupon_version` WHERE `ID` = :p0 AND `VERSION` = :p1'; + $sql = 'SELECT `ID`, `CODE`, `TYPE`, `SERIALIZED_EFFECTS`, `IS_ENABLED`, `EXPIRATION_DATE`, `MAX_USAGE`, `IS_CUMULATIVE`, `IS_REMOVING_POSTAGE`, `IS_AVAILABLE_ON_SPECIAL_OFFERS`, `IS_USED`, `SERIALIZED_CONDITIONS`, `PER_CUSTOMER_USAGE_COUNT`, `CREATED_AT`, `UPDATED_AT`, `VERSION`, `VERSION_CREATED_AT`, `VERSION_CREATED_BY` FROM `coupon_version` WHERE `ID` = :p0 AND `VERSION` = :p1'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); @@ -820,6 +828,78 @@ abstract class CouponVersionQuery extends ModelCriteria return $this->addUsingAlias(CouponVersionTableMap::VERSION, $version, $comparison); } + /** + * Filter the query on the version_created_at column + * + * Example usage: + * + * $query->filterByVersionCreatedAt('2011-03-14'); // WHERE version_created_at = '2011-03-14' + * $query->filterByVersionCreatedAt('now'); // WHERE version_created_at = '2011-03-14' + * $query->filterByVersionCreatedAt(array('max' => 'yesterday')); // WHERE version_created_at > '2011-03-13' + * + * + * @param mixed $versionCreatedAt 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 ChildCouponVersionQuery The current query, for fluid interface + */ + public function filterByVersionCreatedAt($versionCreatedAt = null, $comparison = null) + { + if (is_array($versionCreatedAt)) { + $useMinMax = false; + if (isset($versionCreatedAt['min'])) { + $this->addUsingAlias(CouponVersionTableMap::VERSION_CREATED_AT, $versionCreatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($versionCreatedAt['max'])) { + $this->addUsingAlias(CouponVersionTableMap::VERSION_CREATED_AT, $versionCreatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CouponVersionTableMap::VERSION_CREATED_AT, $versionCreatedAt, $comparison); + } + + /** + * Filter the query on the version_created_by column + * + * Example usage: + * + * $query->filterByVersionCreatedBy('fooValue'); // WHERE version_created_by = 'fooValue' + * $query->filterByVersionCreatedBy('%fooValue%'); // WHERE version_created_by LIKE '%fooValue%' + * + * + * @param string $versionCreatedBy 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 ChildCouponVersionQuery The current query, for fluid interface + */ + public function filterByVersionCreatedBy($versionCreatedBy = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($versionCreatedBy)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $versionCreatedBy)) { + $versionCreatedBy = str_replace('*', '%', $versionCreatedBy); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(CouponVersionTableMap::VERSION_CREATED_BY, $versionCreatedBy, $comparison); + } + /** * Filter the query by a related \Thelia\Model\Coupon object * diff --git a/core/lib/Thelia/Model/Base/Product.php b/core/lib/Thelia/Model/Base/Product.php index 9f93f3f3b..c6efc04b0 100644 --- a/core/lib/Thelia/Model/Base/Product.php +++ b/core/lib/Thelia/Model/Base/Product.php @@ -19,6 +19,8 @@ use Propel\Runtime\Parser\AbstractParser; use Propel\Runtime\Util\PropelDateTime; use Thelia\Model\Accessory as ChildAccessory; use Thelia\Model\AccessoryQuery as ChildAccessoryQuery; +use Thelia\Model\Brand as ChildBrand; +use Thelia\Model\BrandQuery as ChildBrandQuery; use Thelia\Model\CartItem as ChildCartItem; use Thelia\Model\CartItemQuery as ChildCartItemQuery; use Thelia\Model\Category as ChildCategory; @@ -120,6 +122,12 @@ abstract class Product implements ActiveRecordInterface */ protected $template_id; + /** + * The value for the brand_id field. + * @var int + */ + protected $brand_id; + /** * The value for the created_at field. * @var string @@ -161,6 +169,11 @@ abstract class Product implements ActiveRecordInterface */ protected $aTemplate; + /** + * @var Brand + */ + protected $aBrand; + /** * @var ObjectCollection|ChildProductCategory[] Collection to store aggregation of ChildProductCategory objects. */ @@ -695,6 +708,17 @@ abstract class Product implements ActiveRecordInterface return $this->template_id; } + /** + * Get the [brand_id] column value. + * + * @return int + */ + public function getBrandId() + { + + return $this->brand_id; + } + /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -911,6 +935,31 @@ abstract class Product implements ActiveRecordInterface return $this; } // setTemplateId() + /** + * Set the value of [brand_id] column. + * + * @param int $v new value + * @return \Thelia\Model\Product The current object (for fluent API support) + */ + public function setBrandId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->brand_id !== $v) { + $this->brand_id = $v; + $this->modifiedColumns[ProductTableMap::BRAND_ID] = true; + } + + if ($this->aBrand !== null && $this->aBrand->getId() !== $v) { + $this->aBrand = null; + } + + + return $this; + } // setBrandId() + /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -1083,28 +1132,31 @@ abstract class Product implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ProductTableMap::translateFieldName('TemplateId', TableMap::TYPE_PHPNAME, $indexType)]; $this->template_id = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : ProductTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : ProductTableMap::translateFieldName('BrandId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->brand_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : ProductTableMap::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 ? 7 + $startcol : ProductTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : ProductTableMap::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; - $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : ProductTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : ProductTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; $this->version = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : ProductTableMap::translateFieldName('VersionCreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 10 + $startcol : ProductTableMap::translateFieldName('VersionCreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } $this->version_created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 10 + $startcol : ProductTableMap::translateFieldName('VersionCreatedBy', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 11 + $startcol : ProductTableMap::translateFieldName('VersionCreatedBy', TableMap::TYPE_PHPNAME, $indexType)]; $this->version_created_by = (null !== $col) ? (string) $col : null; $this->resetModified(); @@ -1114,7 +1166,7 @@ abstract class Product implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 11; // 11 = ProductTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 12; // 12 = ProductTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\Product object", 0, $e); @@ -1142,6 +1194,9 @@ abstract class Product implements ActiveRecordInterface if ($this->aTemplate !== null && $this->template_id !== $this->aTemplate->getId()) { $this->aTemplate = null; } + if ($this->aBrand !== null && $this->brand_id !== $this->aBrand->getId()) { + $this->aBrand = null; + } } // ensureConsistency /** @@ -1183,6 +1238,7 @@ abstract class Product implements ActiveRecordInterface $this->aTaxRule = null; $this->aTemplate = null; + $this->aBrand = null; $this->collProductCategories = null; $this->collFeatureProducts = null; @@ -1361,6 +1417,13 @@ abstract class Product implements ActiveRecordInterface $this->setTemplate($this->aTemplate); } + if ($this->aBrand !== null) { + if ($this->aBrand->isModified() || $this->aBrand->isNew()) { + $affectedRows += $this->aBrand->save($con); + } + $this->setBrand($this->aBrand); + } + if ($this->isNew() || $this->isModified()) { // persist changes if ($this->isNew()) { @@ -1684,6 +1747,9 @@ abstract class Product implements ActiveRecordInterface if ($this->isColumnModified(ProductTableMap::TEMPLATE_ID)) { $modifiedColumns[':p' . $index++] = '`TEMPLATE_ID`'; } + if ($this->isColumnModified(ProductTableMap::BRAND_ID)) { + $modifiedColumns[':p' . $index++] = '`BRAND_ID`'; + } if ($this->isColumnModified(ProductTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = '`CREATED_AT`'; } @@ -1728,6 +1794,9 @@ abstract class Product implements ActiveRecordInterface case '`TEMPLATE_ID`': $stmt->bindValue($identifier, $this->template_id, PDO::PARAM_INT); break; + case '`BRAND_ID`': + $stmt->bindValue($identifier, $this->brand_id, 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; @@ -1824,18 +1893,21 @@ abstract class Product implements ActiveRecordInterface return $this->getTemplateId(); break; case 6: - return $this->getCreatedAt(); + return $this->getBrandId(); break; case 7: - return $this->getUpdatedAt(); + return $this->getCreatedAt(); break; case 8: - return $this->getVersion(); + return $this->getUpdatedAt(); break; case 9: - return $this->getVersionCreatedAt(); + return $this->getVersion(); break; case 10: + return $this->getVersionCreatedAt(); + break; + case 11: return $this->getVersionCreatedBy(); break; default: @@ -1873,11 +1945,12 @@ abstract class Product implements ActiveRecordInterface $keys[3] => $this->getVisible(), $keys[4] => $this->getPosition(), $keys[5] => $this->getTemplateId(), - $keys[6] => $this->getCreatedAt(), - $keys[7] => $this->getUpdatedAt(), - $keys[8] => $this->getVersion(), - $keys[9] => $this->getVersionCreatedAt(), - $keys[10] => $this->getVersionCreatedBy(), + $keys[6] => $this->getBrandId(), + $keys[7] => $this->getCreatedAt(), + $keys[8] => $this->getUpdatedAt(), + $keys[9] => $this->getVersion(), + $keys[10] => $this->getVersionCreatedAt(), + $keys[11] => $this->getVersionCreatedBy(), ); $virtualColumns = $this->virtualColumns; foreach ($virtualColumns as $key => $virtualColumn) { @@ -1891,6 +1964,9 @@ abstract class Product implements ActiveRecordInterface if (null !== $this->aTemplate) { $result['Template'] = $this->aTemplate->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); } + if (null !== $this->aBrand) { + $result['Brand'] = $this->aBrand->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } if (null !== $this->collProductCategories) { $result['ProductCategories'] = $this->collProductCategories->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects); } @@ -1977,18 +2053,21 @@ abstract class Product implements ActiveRecordInterface $this->setTemplateId($value); break; case 6: - $this->setCreatedAt($value); + $this->setBrandId($value); break; case 7: - $this->setUpdatedAt($value); + $this->setCreatedAt($value); break; case 8: - $this->setVersion($value); + $this->setUpdatedAt($value); break; case 9: - $this->setVersionCreatedAt($value); + $this->setVersion($value); break; case 10: + $this->setVersionCreatedAt($value); + break; + case 11: $this->setVersionCreatedBy($value); break; } // switch() @@ -2021,11 +2100,12 @@ abstract class Product implements ActiveRecordInterface if (array_key_exists($keys[3], $arr)) $this->setVisible($arr[$keys[3]]); if (array_key_exists($keys[4], $arr)) $this->setPosition($arr[$keys[4]]); if (array_key_exists($keys[5], $arr)) $this->setTemplateId($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setCreatedAt($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setUpdatedAt($arr[$keys[7]]); - if (array_key_exists($keys[8], $arr)) $this->setVersion($arr[$keys[8]]); - if (array_key_exists($keys[9], $arr)) $this->setVersionCreatedAt($arr[$keys[9]]); - if (array_key_exists($keys[10], $arr)) $this->setVersionCreatedBy($arr[$keys[10]]); + if (array_key_exists($keys[6], $arr)) $this->setBrandId($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setCreatedAt($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setUpdatedAt($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setVersion($arr[$keys[9]]); + if (array_key_exists($keys[10], $arr)) $this->setVersionCreatedAt($arr[$keys[10]]); + if (array_key_exists($keys[11], $arr)) $this->setVersionCreatedBy($arr[$keys[11]]); } /** @@ -2043,6 +2123,7 @@ abstract class Product implements ActiveRecordInterface if ($this->isColumnModified(ProductTableMap::VISIBLE)) $criteria->add(ProductTableMap::VISIBLE, $this->visible); if ($this->isColumnModified(ProductTableMap::POSITION)) $criteria->add(ProductTableMap::POSITION, $this->position); if ($this->isColumnModified(ProductTableMap::TEMPLATE_ID)) $criteria->add(ProductTableMap::TEMPLATE_ID, $this->template_id); + if ($this->isColumnModified(ProductTableMap::BRAND_ID)) $criteria->add(ProductTableMap::BRAND_ID, $this->brand_id); if ($this->isColumnModified(ProductTableMap::CREATED_AT)) $criteria->add(ProductTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(ProductTableMap::UPDATED_AT)) $criteria->add(ProductTableMap::UPDATED_AT, $this->updated_at); if ($this->isColumnModified(ProductTableMap::VERSION)) $criteria->add(ProductTableMap::VERSION, $this->version); @@ -2116,6 +2197,7 @@ abstract class Product implements ActiveRecordInterface $copyObj->setVisible($this->getVisible()); $copyObj->setPosition($this->getPosition()); $copyObj->setTemplateId($this->getTemplateId()); + $copyObj->setBrandId($this->getBrandId()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); $copyObj->setVersion($this->getVersion()); @@ -2325,6 +2407,57 @@ abstract class Product implements ActiveRecordInterface return $this->aTemplate; } + /** + * Declares an association between this object and a ChildBrand object. + * + * @param ChildBrand $v + * @return \Thelia\Model\Product The current object (for fluent API support) + * @throws PropelException + */ + public function setBrand(ChildBrand $v = null) + { + if ($v === null) { + $this->setBrandId(NULL); + } else { + $this->setBrandId($v->getId()); + } + + $this->aBrand = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildBrand object, it will not be re-added. + if ($v !== null) { + $v->addProduct($this); + } + + + return $this; + } + + + /** + * Get the associated ChildBrand object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildBrand The associated ChildBrand object. + * @throws PropelException + */ + public function getBrand(ConnectionInterface $con = null) + { + if ($this->aBrand === null && ($this->brand_id !== null)) { + $this->aBrand = ChildBrandQuery::create()->findPk($this->brand_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->aBrand->addProducts($this); + */ + } + + return $this->aBrand; + } + /** * Initializes a collection based on the name of a relation. @@ -5492,6 +5625,7 @@ abstract class Product implements ActiveRecordInterface $this->visible = null; $this->position = null; $this->template_id = null; + $this->brand_id = null; $this->created_at = null; $this->updated_at = null; $this->version = null; @@ -5609,6 +5743,7 @@ abstract class Product implements ActiveRecordInterface $this->collProductsRelatedByProductId = null; $this->aTaxRule = null; $this->aTemplate = null; + $this->aBrand = null; } /** @@ -5956,6 +6091,7 @@ abstract class Product implements ActiveRecordInterface $version->setVisible($this->getVisible()); $version->setPosition($this->getPosition()); $version->setTemplateId($this->getTemplateId()); + $version->setBrandId($this->getBrandId()); $version->setCreatedAt($this->getCreatedAt()); $version->setUpdatedAt($this->getUpdatedAt()); $version->setVersion($this->getVersion()); @@ -6004,6 +6140,7 @@ abstract class Product implements ActiveRecordInterface $this->setVisible($version->getVisible()); $this->setPosition($version->getPosition()); $this->setTemplateId($version->getTemplateId()); + $this->setBrandId($version->getBrandId()); $this->setCreatedAt($version->getCreatedAt()); $this->setUpdatedAt($version->getUpdatedAt()); $this->setVersion($version->getVersion()); diff --git a/core/lib/Thelia/Model/Base/ProductQuery.php b/core/lib/Thelia/Model/Base/ProductQuery.php index 352b5cc68..0c9a195e1 100644 --- a/core/lib/Thelia/Model/Base/ProductQuery.php +++ b/core/lib/Thelia/Model/Base/ProductQuery.php @@ -28,6 +28,7 @@ use Thelia\Model\Map\ProductTableMap; * @method ChildProductQuery orderByVisible($order = Criteria::ASC) Order by the visible column * @method ChildProductQuery orderByPosition($order = Criteria::ASC) Order by the position column * @method ChildProductQuery orderByTemplateId($order = Criteria::ASC) Order by the template_id column + * @method ChildProductQuery orderByBrandId($order = Criteria::ASC) Order by the brand_id column * @method ChildProductQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildProductQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @method ChildProductQuery orderByVersion($order = Criteria::ASC) Order by the version column @@ -40,6 +41,7 @@ use Thelia\Model\Map\ProductTableMap; * @method ChildProductQuery groupByVisible() Group by the visible column * @method ChildProductQuery groupByPosition() Group by the position column * @method ChildProductQuery groupByTemplateId() Group by the template_id column + * @method ChildProductQuery groupByBrandId() Group by the brand_id column * @method ChildProductQuery groupByCreatedAt() Group by the created_at column * @method ChildProductQuery groupByUpdatedAt() Group by the updated_at column * @method ChildProductQuery groupByVersion() Group by the version column @@ -58,6 +60,10 @@ use Thelia\Model\Map\ProductTableMap; * @method ChildProductQuery rightJoinTemplate($relationAlias = null) Adds a RIGHT JOIN clause to the query using the Template relation * @method ChildProductQuery innerJoinTemplate($relationAlias = null) Adds a INNER JOIN clause to the query using the Template relation * + * @method ChildProductQuery leftJoinBrand($relationAlias = null) Adds a LEFT JOIN clause to the query using the Brand relation + * @method ChildProductQuery rightJoinBrand($relationAlias = null) Adds a RIGHT JOIN clause to the query using the Brand relation + * @method ChildProductQuery innerJoinBrand($relationAlias = null) Adds a INNER JOIN clause to the query using the Brand relation + * * @method ChildProductQuery leftJoinProductCategory($relationAlias = null) Adds a LEFT JOIN clause to the query using the ProductCategory relation * @method ChildProductQuery rightJoinProductCategory($relationAlias = null) Adds a RIGHT JOIN clause to the query using the ProductCategory relation * @method ChildProductQuery innerJoinProductCategory($relationAlias = null) Adds a INNER JOIN clause to the query using the ProductCategory relation @@ -111,6 +117,7 @@ use Thelia\Model\Map\ProductTableMap; * @method ChildProduct findOneByVisible(int $visible) Return the first ChildProduct filtered by the visible column * @method ChildProduct findOneByPosition(int $position) Return the first ChildProduct filtered by the position column * @method ChildProduct findOneByTemplateId(int $template_id) Return the first ChildProduct filtered by the template_id column + * @method ChildProduct findOneByBrandId(int $brand_id) Return the first ChildProduct filtered by the brand_id column * @method ChildProduct findOneByCreatedAt(string $created_at) Return the first ChildProduct filtered by the created_at column * @method ChildProduct findOneByUpdatedAt(string $updated_at) Return the first ChildProduct filtered by the updated_at column * @method ChildProduct findOneByVersion(int $version) Return the first ChildProduct filtered by the version column @@ -123,6 +130,7 @@ use Thelia\Model\Map\ProductTableMap; * @method array findByVisible(int $visible) Return ChildProduct objects filtered by the visible column * @method array findByPosition(int $position) Return ChildProduct objects filtered by the position column * @method array findByTemplateId(int $template_id) Return ChildProduct objects filtered by the template_id column + * @method array findByBrandId(int $brand_id) Return ChildProduct objects filtered by the brand_id column * @method array findByCreatedAt(string $created_at) Return ChildProduct objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildProduct objects filtered by the updated_at column * @method array findByVersion(int $version) Return ChildProduct objects filtered by the version column @@ -223,7 +231,7 @@ abstract class ProductQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT `ID`, `TAX_RULE_ID`, `REF`, `VISIBLE`, `POSITION`, `TEMPLATE_ID`, `CREATED_AT`, `UPDATED_AT`, `VERSION`, `VERSION_CREATED_AT`, `VERSION_CREATED_BY` FROM `product` WHERE `ID` = :p0'; + $sql = 'SELECT `ID`, `TAX_RULE_ID`, `REF`, `VISIBLE`, `POSITION`, `TEMPLATE_ID`, `BRAND_ID`, `CREATED_AT`, `UPDATED_AT`, `VERSION`, `VERSION_CREATED_AT`, `VERSION_CREATED_BY` FROM `product` WHERE `ID` = :p0'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key, PDO::PARAM_INT); @@ -550,6 +558,49 @@ abstract class ProductQuery extends ModelCriteria return $this->addUsingAlias(ProductTableMap::TEMPLATE_ID, $templateId, $comparison); } + /** + * Filter the query on the brand_id column + * + * Example usage: + * + * $query->filterByBrandId(1234); // WHERE brand_id = 1234 + * $query->filterByBrandId(array(12, 34)); // WHERE brand_id IN (12, 34) + * $query->filterByBrandId(array('min' => 12)); // WHERE brand_id > 12 + * + * + * @see filterByBrand() + * + * @param mixed $brandId 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 ChildProductQuery The current query, for fluid interface + */ + public function filterByBrandId($brandId = null, $comparison = null) + { + if (is_array($brandId)) { + $useMinMax = false; + if (isset($brandId['min'])) { + $this->addUsingAlias(ProductTableMap::BRAND_ID, $brandId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($brandId['max'])) { + $this->addUsingAlias(ProductTableMap::BRAND_ID, $brandId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ProductTableMap::BRAND_ID, $brandId, $comparison); + } + /** * Filter the query on the created_at column * @@ -899,6 +950,81 @@ abstract class ProductQuery extends ModelCriteria ->useQuery($relationAlias ? $relationAlias : 'Template', '\Thelia\Model\TemplateQuery'); } + /** + * Filter the query by a related \Thelia\Model\Brand object + * + * @param \Thelia\Model\Brand|ObjectCollection $brand The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildProductQuery The current query, for fluid interface + */ + public function filterByBrand($brand, $comparison = null) + { + if ($brand instanceof \Thelia\Model\Brand) { + return $this + ->addUsingAlias(ProductTableMap::BRAND_ID, $brand->getId(), $comparison); + } elseif ($brand instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ProductTableMap::BRAND_ID, $brand->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByBrand() only accepts arguments of type \Thelia\Model\Brand or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Brand relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildProductQuery The current query, for fluid interface + */ + public function joinBrand($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Brand'); + + // 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, 'Brand'); + } + + return $this; + } + + /** + * Use the Brand relation Brand 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\BrandQuery A secondary query class using the current class as primary query + */ + public function useBrandQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinBrand($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Brand', '\Thelia\Model\BrandQuery'); + } + /** * Filter the query by a related \Thelia\Model\ProductCategory object * diff --git a/core/lib/Thelia/Model/Base/ProductVersion.php b/core/lib/Thelia/Model/Base/ProductVersion.php index cf5ea8af9..95ac86eab 100644 --- a/core/lib/Thelia/Model/Base/ProductVersion.php +++ b/core/lib/Thelia/Model/Base/ProductVersion.php @@ -93,6 +93,12 @@ abstract class ProductVersion implements ActiveRecordInterface */ protected $template_id; + /** + * The value for the brand_id field. + * @var int + */ + protected $brand_id; + /** * The value for the created_at field. * @var string @@ -476,6 +482,17 @@ abstract class ProductVersion implements ActiveRecordInterface return $this->template_id; } + /** + * Get the [brand_id] column value. + * + * @return int + */ + public function getBrandId() + { + + return $this->brand_id; + } + /** * Get the [optionally formatted] temporal [created_at] column value. * @@ -688,6 +705,27 @@ abstract class ProductVersion implements ActiveRecordInterface return $this; } // setTemplateId() + /** + * Set the value of [brand_id] column. + * + * @param int $v new value + * @return \Thelia\Model\ProductVersion The current object (for fluent API support) + */ + public function setBrandId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->brand_id !== $v) { + $this->brand_id = $v; + $this->modifiedColumns[ProductVersionTableMap::BRAND_ID] = true; + } + + + return $this; + } // setBrandId() + /** * Sets the value of [created_at] column to a normalized version of the date/time value specified. * @@ -860,28 +898,31 @@ abstract class ProductVersion implements ActiveRecordInterface $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ProductVersionTableMap::translateFieldName('TemplateId', TableMap::TYPE_PHPNAME, $indexType)]; $this->template_id = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : ProductVersionTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : ProductVersionTableMap::translateFieldName('BrandId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->brand_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : ProductVersionTableMap::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 ? 7 + $startcol : ProductVersionTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : ProductVersionTableMap::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; - $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : ProductVersionTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : ProductVersionTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]; $this->version = (null !== $col) ? (int) $col : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : ProductVersionTableMap::translateFieldName('VersionCreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 10 + $startcol : ProductVersionTableMap::translateFieldName('VersionCreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; if ($col === '0000-00-00 00:00:00') { $col = null; } $this->version_created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; - $col = $row[TableMap::TYPE_NUM == $indexType ? 10 + $startcol : ProductVersionTableMap::translateFieldName('VersionCreatedBy', TableMap::TYPE_PHPNAME, $indexType)]; + $col = $row[TableMap::TYPE_NUM == $indexType ? 11 + $startcol : ProductVersionTableMap::translateFieldName('VersionCreatedBy', TableMap::TYPE_PHPNAME, $indexType)]; $this->version_created_by = (null !== $col) ? (string) $col : null; $this->resetModified(); @@ -891,7 +932,7 @@ abstract class ProductVersion implements ActiveRecordInterface $this->ensureConsistency(); } - return $startcol + 11; // 11 = ProductVersionTableMap::NUM_HYDRATE_COLUMNS. + return $startcol + 12; // 12 = ProductVersionTableMap::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating \Thelia\Model\ProductVersion object", 0, $e); @@ -1130,6 +1171,9 @@ abstract class ProductVersion implements ActiveRecordInterface if ($this->isColumnModified(ProductVersionTableMap::TEMPLATE_ID)) { $modifiedColumns[':p' . $index++] = '`TEMPLATE_ID`'; } + if ($this->isColumnModified(ProductVersionTableMap::BRAND_ID)) { + $modifiedColumns[':p' . $index++] = '`BRAND_ID`'; + } if ($this->isColumnModified(ProductVersionTableMap::CREATED_AT)) { $modifiedColumns[':p' . $index++] = '`CREATED_AT`'; } @@ -1174,6 +1218,9 @@ abstract class ProductVersion implements ActiveRecordInterface case '`TEMPLATE_ID`': $stmt->bindValue($identifier, $this->template_id, PDO::PARAM_INT); break; + case '`BRAND_ID`': + $stmt->bindValue($identifier, $this->brand_id, 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; @@ -1263,18 +1310,21 @@ abstract class ProductVersion implements ActiveRecordInterface return $this->getTemplateId(); break; case 6: - return $this->getCreatedAt(); + return $this->getBrandId(); break; case 7: - return $this->getUpdatedAt(); + return $this->getCreatedAt(); break; case 8: - return $this->getVersion(); + return $this->getUpdatedAt(); break; case 9: - return $this->getVersionCreatedAt(); + return $this->getVersion(); break; case 10: + return $this->getVersionCreatedAt(); + break; + case 11: return $this->getVersionCreatedBy(); break; default: @@ -1312,11 +1362,12 @@ abstract class ProductVersion implements ActiveRecordInterface $keys[3] => $this->getVisible(), $keys[4] => $this->getPosition(), $keys[5] => $this->getTemplateId(), - $keys[6] => $this->getCreatedAt(), - $keys[7] => $this->getUpdatedAt(), - $keys[8] => $this->getVersion(), - $keys[9] => $this->getVersionCreatedAt(), - $keys[10] => $this->getVersionCreatedBy(), + $keys[6] => $this->getBrandId(), + $keys[7] => $this->getCreatedAt(), + $keys[8] => $this->getUpdatedAt(), + $keys[9] => $this->getVersion(), + $keys[10] => $this->getVersionCreatedAt(), + $keys[11] => $this->getVersionCreatedBy(), ); $virtualColumns = $this->virtualColumns; foreach ($virtualColumns as $key => $virtualColumn) { @@ -1380,18 +1431,21 @@ abstract class ProductVersion implements ActiveRecordInterface $this->setTemplateId($value); break; case 6: - $this->setCreatedAt($value); + $this->setBrandId($value); break; case 7: - $this->setUpdatedAt($value); + $this->setCreatedAt($value); break; case 8: - $this->setVersion($value); + $this->setUpdatedAt($value); break; case 9: - $this->setVersionCreatedAt($value); + $this->setVersion($value); break; case 10: + $this->setVersionCreatedAt($value); + break; + case 11: $this->setVersionCreatedBy($value); break; } // switch() @@ -1424,11 +1478,12 @@ abstract class ProductVersion implements ActiveRecordInterface if (array_key_exists($keys[3], $arr)) $this->setVisible($arr[$keys[3]]); if (array_key_exists($keys[4], $arr)) $this->setPosition($arr[$keys[4]]); if (array_key_exists($keys[5], $arr)) $this->setTemplateId($arr[$keys[5]]); - if (array_key_exists($keys[6], $arr)) $this->setCreatedAt($arr[$keys[6]]); - if (array_key_exists($keys[7], $arr)) $this->setUpdatedAt($arr[$keys[7]]); - if (array_key_exists($keys[8], $arr)) $this->setVersion($arr[$keys[8]]); - if (array_key_exists($keys[9], $arr)) $this->setVersionCreatedAt($arr[$keys[9]]); - if (array_key_exists($keys[10], $arr)) $this->setVersionCreatedBy($arr[$keys[10]]); + if (array_key_exists($keys[6], $arr)) $this->setBrandId($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setCreatedAt($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setUpdatedAt($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setVersion($arr[$keys[9]]); + if (array_key_exists($keys[10], $arr)) $this->setVersionCreatedAt($arr[$keys[10]]); + if (array_key_exists($keys[11], $arr)) $this->setVersionCreatedBy($arr[$keys[11]]); } /** @@ -1446,6 +1501,7 @@ abstract class ProductVersion implements ActiveRecordInterface if ($this->isColumnModified(ProductVersionTableMap::VISIBLE)) $criteria->add(ProductVersionTableMap::VISIBLE, $this->visible); if ($this->isColumnModified(ProductVersionTableMap::POSITION)) $criteria->add(ProductVersionTableMap::POSITION, $this->position); if ($this->isColumnModified(ProductVersionTableMap::TEMPLATE_ID)) $criteria->add(ProductVersionTableMap::TEMPLATE_ID, $this->template_id); + if ($this->isColumnModified(ProductVersionTableMap::BRAND_ID)) $criteria->add(ProductVersionTableMap::BRAND_ID, $this->brand_id); if ($this->isColumnModified(ProductVersionTableMap::CREATED_AT)) $criteria->add(ProductVersionTableMap::CREATED_AT, $this->created_at); if ($this->isColumnModified(ProductVersionTableMap::UPDATED_AT)) $criteria->add(ProductVersionTableMap::UPDATED_AT, $this->updated_at); if ($this->isColumnModified(ProductVersionTableMap::VERSION)) $criteria->add(ProductVersionTableMap::VERSION, $this->version); @@ -1527,6 +1583,7 @@ abstract class ProductVersion implements ActiveRecordInterface $copyObj->setVisible($this->getVisible()); $copyObj->setPosition($this->getPosition()); $copyObj->setTemplateId($this->getTemplateId()); + $copyObj->setBrandId($this->getBrandId()); $copyObj->setCreatedAt($this->getCreatedAt()); $copyObj->setUpdatedAt($this->getUpdatedAt()); $copyObj->setVersion($this->getVersion()); @@ -1621,6 +1678,7 @@ abstract class ProductVersion implements ActiveRecordInterface $this->visible = null; $this->position = null; $this->template_id = null; + $this->brand_id = null; $this->created_at = null; $this->updated_at = null; $this->version = null; diff --git a/core/lib/Thelia/Model/Base/ProductVersionQuery.php b/core/lib/Thelia/Model/Base/ProductVersionQuery.php index cf017b048..d56f1055c 100644 --- a/core/lib/Thelia/Model/Base/ProductVersionQuery.php +++ b/core/lib/Thelia/Model/Base/ProductVersionQuery.php @@ -27,6 +27,7 @@ use Thelia\Model\Map\ProductVersionTableMap; * @method ChildProductVersionQuery orderByVisible($order = Criteria::ASC) Order by the visible column * @method ChildProductVersionQuery orderByPosition($order = Criteria::ASC) Order by the position column * @method ChildProductVersionQuery orderByTemplateId($order = Criteria::ASC) Order by the template_id column + * @method ChildProductVersionQuery orderByBrandId($order = Criteria::ASC) Order by the brand_id column * @method ChildProductVersionQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column * @method ChildProductVersionQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column * @method ChildProductVersionQuery orderByVersion($order = Criteria::ASC) Order by the version column @@ -39,6 +40,7 @@ use Thelia\Model\Map\ProductVersionTableMap; * @method ChildProductVersionQuery groupByVisible() Group by the visible column * @method ChildProductVersionQuery groupByPosition() Group by the position column * @method ChildProductVersionQuery groupByTemplateId() Group by the template_id column + * @method ChildProductVersionQuery groupByBrandId() Group by the brand_id column * @method ChildProductVersionQuery groupByCreatedAt() Group by the created_at column * @method ChildProductVersionQuery groupByUpdatedAt() Group by the updated_at column * @method ChildProductVersionQuery groupByVersion() Group by the version column @@ -62,6 +64,7 @@ use Thelia\Model\Map\ProductVersionTableMap; * @method ChildProductVersion findOneByVisible(int $visible) Return the first ChildProductVersion filtered by the visible column * @method ChildProductVersion findOneByPosition(int $position) Return the first ChildProductVersion filtered by the position column * @method ChildProductVersion findOneByTemplateId(int $template_id) Return the first ChildProductVersion filtered by the template_id column + * @method ChildProductVersion findOneByBrandId(int $brand_id) Return the first ChildProductVersion filtered by the brand_id column * @method ChildProductVersion findOneByCreatedAt(string $created_at) Return the first ChildProductVersion filtered by the created_at column * @method ChildProductVersion findOneByUpdatedAt(string $updated_at) Return the first ChildProductVersion filtered by the updated_at column * @method ChildProductVersion findOneByVersion(int $version) Return the first ChildProductVersion filtered by the version column @@ -74,6 +77,7 @@ use Thelia\Model\Map\ProductVersionTableMap; * @method array findByVisible(int $visible) Return ChildProductVersion objects filtered by the visible column * @method array findByPosition(int $position) Return ChildProductVersion objects filtered by the position column * @method array findByTemplateId(int $template_id) Return ChildProductVersion objects filtered by the template_id column + * @method array findByBrandId(int $brand_id) Return ChildProductVersion objects filtered by the brand_id column * @method array findByCreatedAt(string $created_at) Return ChildProductVersion objects filtered by the created_at column * @method array findByUpdatedAt(string $updated_at) Return ChildProductVersion objects filtered by the updated_at column * @method array findByVersion(int $version) Return ChildProductVersion objects filtered by the version column @@ -167,7 +171,7 @@ abstract class ProductVersionQuery extends ModelCriteria */ protected function findPkSimple($key, $con) { - $sql = 'SELECT `ID`, `TAX_RULE_ID`, `REF`, `VISIBLE`, `POSITION`, `TEMPLATE_ID`, `CREATED_AT`, `UPDATED_AT`, `VERSION`, `VERSION_CREATED_AT`, `VERSION_CREATED_BY` FROM `product_version` WHERE `ID` = :p0 AND `VERSION` = :p1'; + $sql = 'SELECT `ID`, `TAX_RULE_ID`, `REF`, `VISIBLE`, `POSITION`, `TEMPLATE_ID`, `BRAND_ID`, `CREATED_AT`, `UPDATED_AT`, `VERSION`, `VERSION_CREATED_AT`, `VERSION_CREATED_BY` FROM `product_version` WHERE `ID` = :p0 AND `VERSION` = :p1'; try { $stmt = $con->prepare($sql); $stmt->bindValue(':p0', $key[0], PDO::PARAM_INT); @@ -504,6 +508,47 @@ abstract class ProductVersionQuery extends ModelCriteria return $this->addUsingAlias(ProductVersionTableMap::TEMPLATE_ID, $templateId, $comparison); } + /** + * Filter the query on the brand_id column + * + * Example usage: + * + * $query->filterByBrandId(1234); // WHERE brand_id = 1234 + * $query->filterByBrandId(array(12, 34)); // WHERE brand_id IN (12, 34) + * $query->filterByBrandId(array('min' => 12)); // WHERE brand_id > 12 + * + * + * @param mixed $brandId 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 ChildProductVersionQuery The current query, for fluid interface + */ + public function filterByBrandId($brandId = null, $comparison = null) + { + if (is_array($brandId)) { + $useMinMax = false; + if (isset($brandId['min'])) { + $this->addUsingAlias(ProductVersionTableMap::BRAND_ID, $brandId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($brandId['max'])) { + $this->addUsingAlias(ProductVersionTableMap::BRAND_ID, $brandId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ProductVersionTableMap::BRAND_ID, $brandId, $comparison); + } + /** * Filter the query on the created_at column * diff --git a/core/lib/Thelia/Model/Base/TaxRule.php b/core/lib/Thelia/Model/Base/TaxRule.php index 971a8192f..1f837cd33 100644 --- a/core/lib/Thelia/Model/Base/TaxRule.php +++ b/core/lib/Thelia/Model/Base/TaxRule.php @@ -1545,6 +1545,31 @@ abstract class TaxRule implements ActiveRecordInterface return $this->getProducts($query, $con); } + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this TaxRule is new, it will return + * an empty collection; or if this TaxRule has previously + * been saved, it will retrieve related Products from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in TaxRule. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildProduct[] List of ChildProduct objects + */ + public function getProductsJoinBrand($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildProductQuery::create(null, $criteria); + $query->joinWith('Brand', $joinBehavior); + + return $this->getProducts($query, $con); + } + /** * Clears out the collTaxRuleCountries collection * diff --git a/core/lib/Thelia/Model/Base/Template.php b/core/lib/Thelia/Model/Base/Template.php index 88b44a7a2..c5f8ccbb7 100644 --- a/core/lib/Thelia/Model/Base/Template.php +++ b/core/lib/Thelia/Model/Base/Template.php @@ -1589,6 +1589,31 @@ abstract class Template implements ActiveRecordInterface return $this->getProducts($query, $con); } + + /** + * If this collection has already been initialized with + * an identical criteria, it returns the collection. + * Otherwise if this Template is new, it will return + * an empty collection; or if this Template has previously + * been saved, it will retrieve related Products from storage. + * + * This method is protected by default in order to keep the public + * api reasonable. You can provide public methods for those you + * actually need in Template. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param ConnectionInterface $con optional connection object + * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) + * @return Collection|ChildProduct[] List of ChildProduct objects + */ + public function getProductsJoinBrand($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) + { + $query = ChildProductQuery::create(null, $criteria); + $query->joinWith('Brand', $joinBehavior); + + return $this->getProducts($query, $con); + } + /** * Clears out the collFeatureTemplates collection * diff --git a/core/lib/Thelia/Model/Brand.php b/core/lib/Thelia/Model/Brand.php new file mode 100644 index 000000000..a153e1bc7 --- /dev/null +++ b/core/lib/Thelia/Model/Brand.php @@ -0,0 +1,88 @@ +dispatchEvent(TheliaEvents::BEFORE_CREATEBRAND, new BrandEvent($this)); + + // Set the current position for the new object + $this->setPosition($this->getNextPosition()); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postInsert(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_CREATEBRAND, new BrandEvent($this)); + } + + /** + * {@inheritDoc} + */ + public function preUpdate(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_UPDATEBRAND, new BrandEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postUpdate(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::AFTER_UPDATEBRAND, new BrandEvent($this)); + } + + /** + * {@inheritDoc} + */ + public function preDelete(ConnectionInterface $con = null) + { + $this->dispatchEvent(TheliaEvents::BEFORE_DELETEBRAND, new BrandEvent($this)); + + return true; + } + + /** + * {@inheritDoc} + */ + public function postDelete(ConnectionInterface $con = null) + { + $this->markRewritenUrlObsolete(); + + $this->dispatchEvent(TheliaEvents::AFTER_DELETEBRAND, new BrandEvent($this)); + } +} diff --git a/core/lib/Thelia/Model/BrandDocument.php b/core/lib/Thelia/Model/BrandDocument.php new file mode 100644 index 000000000..432ad69f3 --- /dev/null +++ b/core/lib/Thelia/Model/BrandDocument.php @@ -0,0 +1,130 @@ +filterByBrandId($this->getBrandId()); + } + + /** + * @inheritDoc + */ + public function preInsert(ConnectionInterface $con = null) + { + $this->setPosition($this->getNextPosition()); + + return true; + } + + public function preDelete(ConnectionInterface $con = null) + { + $this->reorderBeforeDelete( + array( + "brand_id" => $this->getBrandId(), + ) + ); + + return true; + } + + /** + * @inheritDoc + */ + public function setParentId($parentId) + { + $this->setBrandId($parentId); + + return $this; + } + + /** + * @inheritDoc + */ + public function getParentId() + { + return $this->getBrandId(); + } + + /** + * @return FileModelParentInterface the parent file model + */ + public function getParentFileModel() + { + return new Brand(); + } + + /** + * Get the ID of the form used to change this object information + * + * @return BaseForm the form + */ + public function getUpdateFormId() + { + return 'thelia.admin.brand.document.modification'; + } + + /** + * Get the form instance used to change this object information + * + * @param \Thelia\Core\HttpFoundation\Request $request + * + * @return BaseForm the form + */ + public function getUpdateFormInstance(Request $request) + { + return new BrandDocumentModification($request); + } + + /** + * @return string the path to the upload directory where files are stored, without final slash + */ + public function getUploadDir() + { + return THELIA_LOCAL_DIR . 'media'.DS.'documents'.DS.'brand'; + } + + /** + * @param int $objectId the ID of the object + * + * @return string the URL to redirect to after update from the back-office + */ + public function getRedirectionUrl($objectId) + { + return '/admin/brand/update/' . $objectId . '?current_tab=document'; + } + + /** + * Get the Query instance for this object + * + * @return ModelCriteria + */ + public function getQueryInstance() + { + return BrandDocumentQuery::create(); + } +} diff --git a/core/lib/Thelia/Model/BrandDocumentI18n.php b/core/lib/Thelia/Model/BrandDocumentI18n.php new file mode 100644 index 000000000..a7bfe0599 --- /dev/null +++ b/core/lib/Thelia/Model/BrandDocumentI18n.php @@ -0,0 +1,10 @@ +getBrand(); + + $content->generateRewrittenUrl($this->getLocale()); + } +} diff --git a/core/lib/Thelia/Model/BrandI18nQuery.php b/core/lib/Thelia/Model/BrandI18nQuery.php new file mode 100644 index 000000000..ea172aaa0 --- /dev/null +++ b/core/lib/Thelia/Model/BrandI18nQuery.php @@ -0,0 +1,20 @@ +filterByBrandId($this->getBrandId()); + } + + /** + * {@inheritDoc} + */ + public function preInsert(ConnectionInterface $con = null) + { + $this->setPosition($this->getNextPosition()); + + return true; + } + + public function preDelete(ConnectionInterface $con = null) + { + $this->reorderBeforeDelete( + array( + "brand_id" => $this->getBrandId(), + ) + ); + + return true; + } + + /** + * @inheritdoc + */ + public function setParentId($parentId) + { + $this->setBrandId($parentId); + + return $this; + } + + /** + * @inheritdoc + */ + public function getParentId() + { + return $this->getBrandId(); + } + + /** + * @return FileModelParentInterface the parent file model + */ + public function getParentFileModel() + { + return new Brand(); + } + + /** + * Get the ID of the form used to change this object information + * + * @return BaseForm the form + */ + public function getUpdateFormId() + { + return 'thelia.admin.brand.image.modification'; + } + + /** + * Get the form instance used to change this object information + * + * @param \Thelia\Core\HttpFoundation\Request $request + * + * @return BaseForm the form + */ + public function getUpdateFormInstance(Request $request) + { + return new BrandImageModification($request); + } + + /** + * @return string the path to the upload directory where files are stored, without final slash + */ + public function getUploadDir() + { + return THELIA_LOCAL_DIR . 'media'.DS.'images'.DS.'brand'; + } + + /** + * @param int $objectId the ID of the object + * + * @return string the URL to redirect to after update from the back-office + */ + public function getRedirectionUrl($objectId) + { + return '/admin/brand/update/' . $objectId . '?current_tab=image'; + } + + /** + * Get the Query instance for this object + * + * @return ModelCriteria + */ + public function getQueryInstance() + { + return BrandImageQuery::create(); + } +} diff --git a/core/lib/Thelia/Model/BrandImageI18n.php b/core/lib/Thelia/Model/BrandImageI18n.php new file mode 100644 index 000000000..647129768 --- /dev/null +++ b/core/lib/Thelia/Model/BrandImageI18n.php @@ -0,0 +1,10 @@ +trans('Home') => $router->generate('admin.home.view', [], Router::ABSOLUTE_URL), + Translator::getInstance()->trans('Brand') => $router->generate('admin.brand.default', [], Router::ABSOLUTE_URL) + ]; + + if (null !== $brand = BrandQuery::create()->findPk($this->getBrandId())) { + + $breadcrumb[$brand->setLocale($locale)->getTitle()] = sprintf( + "%s?current_tab=%s", + $router->generate('admin.brand.update', ['brand_id' => $brand->getId()], Router::ABSOLUTE_URL), + $tab + ); + } + + return $breadcrumb; + } +} \ No newline at end of file diff --git a/core/lib/Thelia/Model/Breadcrumb/BreadcrumbInterface.php b/core/lib/Thelia/Model/Breadcrumb/BreadcrumbInterface.php index dcb928c78..c78193682 100644 --- a/core/lib/Thelia/Model/Breadcrumb/BreadcrumbInterface.php +++ b/core/lib/Thelia/Model/Breadcrumb/BreadcrumbInterface.php @@ -19,10 +19,14 @@ interface BreadcrumbInterface { /** + * Create a breadcrumb from the current object, that will be displayed to the file management UI * - * return the complete breadcrumb for a given resource. + * @param Router $router the router where to find routes + * @param ContainerInterface $container the container + * @param string $tab the tab to return to (probably 'image' or 'document') + * @param string $locale the current locale * - * @return array + * @return array an array of (label => URL) */ - public function getBreadcrumb(Router $router, ContainerInterface $container, $tab); + public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale); } \ No newline at end of file diff --git a/core/lib/Thelia/Model/Breadcrumb/CatalogBreadcrumbTrait.php b/core/lib/Thelia/Model/Breadcrumb/CatalogBreadcrumbTrait.php index 6c9bbb328..f5d2a2cae 100644 --- a/core/lib/Thelia/Model/Breadcrumb/CatalogBreadcrumbTrait.php +++ b/core/lib/Thelia/Model/Breadcrumb/CatalogBreadcrumbTrait.php @@ -17,17 +17,19 @@ use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Router; use Thelia\Core\Template\Loop\CategoryPath; use Thelia\Core\Translation\Translator; +use Thelia\Model\Category; +use Thelia\Model\Product; trait CatalogBreadcrumbTrait { - public function getBaseBreadcrumb(Router $router, ContainerInterface $container, $categoryId, &$locale) + public function getBaseBreadcrumb(Router $router, ContainerInterface $container, $categoryId) { $translator = Translator::getInstance(); $catalogUrl = $router->generate('admin.catalog', [], Router::ABSOLUTE_URL); $breadcrumb = [ - $translator->trans('Home', [], 'bo.default') => $router->generate('admin.home.view', [], Router::ABSOLUTE_URL), - $translator->trans('Catalog', [], 'bo.default') => $catalogUrl, + $translator->trans('Home') => $router->generate('admin.home.view', [], Router::ABSOLUTE_URL), + $translator->trans('Catalog') => $catalogUrl, ]; $categoryPath = new CategoryPath($container); @@ -42,15 +44,13 @@ trait CatalogBreadcrumbTrait $breadcrumb[$result['TITLE']] = sprintf("%s?category_id=%d",$catalogUrl, $result['ID']); } - $locale = $result['LOCALE']; - return $breadcrumb; } - public function getProductBreadcrumb(Router $router, ContainerInterface $container, $tab) + public function getProductBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale) { + /** @var Product $product */ $product = $this->getProduct(); - $locale = null; $breadcrumb = $this->getBaseBreadcrumb($router, $container, $product->getDefaultCategoryId(), $locale); @@ -65,11 +65,11 @@ trait CatalogBreadcrumbTrait return $breadcrumb; } - public function getCategoryBreadcrumb(Router $router, ContainerInterface $container, $tab) + public function getCategoryBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale) { - $locale = null; + /** @var Category $category */ $category = $this->getCategory(); - $breadcrumb = $this->getBaseBreadcrumb($router, $container, $this->getParentId(), $locale); + $breadcrumb = $this->getBaseBreadcrumb($router, $container, $this->getParentId()); $category->setLocale($locale); diff --git a/core/lib/Thelia/Model/Breadcrumb/FolderBreadcrumbTrait.php b/core/lib/Thelia/Model/Breadcrumb/FolderBreadcrumbTrait.php index 3711002c3..78c0dffe9 100644 --- a/core/lib/Thelia/Model/Breadcrumb/FolderBreadcrumbTrait.php +++ b/core/lib/Thelia/Model/Breadcrumb/FolderBreadcrumbTrait.php @@ -17,17 +17,19 @@ use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Router; use Thelia\Core\Template\Loop\FolderPath; use Thelia\Core\Translation\Translator; +use Thelia\Model\Content; +use Thelia\Model\Folder; trait FolderBreadcrumbTrait { - public function getBaseBreadcrumb(Router $router, ContainerInterface $container, $folderId, &$locale) + public function getBaseBreadcrumb(Router $router, ContainerInterface $container, $folderId) { $translator = Translator::getInstance(); $catalogUrl = $router->generate('admin.catalog', [], Router::ABSOLUTE_URL); $breadcrumb = [ - $translator->trans('Home', [], 'bo.default') => $router->generate('admin.home.view', [], Router::ABSOLUTE_URL), - $translator->trans('Folder', [], 'bo.default') => $catalogUrl, + $translator->trans('Home') => $router->generate('admin.home.view', [], Router::ABSOLUTE_URL), + $translator->trans('Folder') => $catalogUrl, ]; $folderPath = new FolderPath($container); @@ -45,16 +47,14 @@ trait FolderBreadcrumbTrait ); } - $locale = $result['LOCALE']; - return $breadcrumb; } - public function getFolderBreadcrumb($router, $container, $tab) + public function getFolderBreadcrumb(Router $router, $container, $tab, $locale) { - $locale = null; + /** @var Folder $folder */ $folder = $this->getFolder(); - $breadcrumb = $this->getBaseBreadcrumb($router, $container, $this->getParentId(), $locale); + $breadcrumb = $this->getBaseBreadcrumb($router, $container, $this->getParentId()); $folder->setLocale($locale); @@ -66,12 +66,12 @@ trait FolderBreadcrumbTrait return $breadcrumb; } - public function getContentBreadcrumb(Router $router, ContainerInterface $container, $tab) + public function getContentBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale) { + /** @var Content $content */ $content = $this->getContent(); - $locale = null; - $breadcrumb = $this->getBaseBreadcrumb($router, $container, $content->getDefaultFolderId(), $locale); + $breadcrumb = $this->getBaseBreadcrumb($router, $container, $content->getDefaultFolderId()); $content->setLocale($locale); diff --git a/core/lib/Thelia/Model/Map/BrandDocumentI18nTableMap.php b/core/lib/Thelia/Model/Map/BrandDocumentI18nTableMap.php new file mode 100644 index 000000000..fae8621cb --- /dev/null +++ b/core/lib/Thelia/Model/Map/BrandDocumentI18nTableMap.php @@ -0,0 +1,498 @@ + array('Id', 'Locale', 'Title', 'Description', 'Chapo', 'Postscriptum', ), + self::TYPE_STUDLYPHPNAME => array('id', 'locale', 'title', 'description', 'chapo', 'postscriptum', ), + self::TYPE_COLNAME => array(BrandDocumentI18nTableMap::ID, BrandDocumentI18nTableMap::LOCALE, BrandDocumentI18nTableMap::TITLE, BrandDocumentI18nTableMap::DESCRIPTION, BrandDocumentI18nTableMap::CHAPO, BrandDocumentI18nTableMap::POSTSCRIPTUM, ), + self::TYPE_RAW_COLNAME => array('ID', 'LOCALE', 'TITLE', 'DESCRIPTION', 'CHAPO', 'POSTSCRIPTUM', ), + self::TYPE_FIELDNAME => array('id', 'locale', 'title', 'description', 'chapo', 'postscriptum', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + ); + + /** + * 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, 'Chapo' => 4, 'Postscriptum' => 5, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'locale' => 1, 'title' => 2, 'description' => 3, 'chapo' => 4, 'postscriptum' => 5, ), + self::TYPE_COLNAME => array(BrandDocumentI18nTableMap::ID => 0, BrandDocumentI18nTableMap::LOCALE => 1, BrandDocumentI18nTableMap::TITLE => 2, BrandDocumentI18nTableMap::DESCRIPTION => 3, BrandDocumentI18nTableMap::CHAPO => 4, BrandDocumentI18nTableMap::POSTSCRIPTUM => 5, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'LOCALE' => 1, 'TITLE' => 2, 'DESCRIPTION' => 3, 'CHAPO' => 4, 'POSTSCRIPTUM' => 5, ), + self::TYPE_FIELDNAME => array('id' => 0, 'locale' => 1, 'title' => 2, 'description' => 3, 'chapo' => 4, 'postscriptum' => 5, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + ); + + /** + * 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('brand_document_i18n'); + $this->setPhpName('BrandDocumentI18n'); + $this->setClassName('\\Thelia\\Model\\BrandDocumentI18n'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addForeignPrimaryKey('ID', 'Id', 'INTEGER' , 'brand_document', 'ID', true, null, null); + $this->addPrimaryKey('LOCALE', 'Locale', 'VARCHAR', true, 5, 'en_US'); + $this->addColumn('TITLE', 'Title', 'VARCHAR', false, 255, null); + $this->addColumn('DESCRIPTION', 'Description', 'CLOB', false, null, null); + $this->addColumn('CHAPO', 'Chapo', 'LONGVARCHAR', false, null, null); + $this->addColumn('POSTSCRIPTUM', 'Postscriptum', 'LONGVARCHAR', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('BrandDocument', '\\Thelia\\Model\\BrandDocument', 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\BrandDocumentI18n $obj A \Thelia\Model\BrandDocumentI18n 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\BrandDocumentI18n object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\BrandDocumentI18n) { + $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\BrandDocumentI18n 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 ? BrandDocumentI18nTableMap::CLASS_DEFAULT : BrandDocumentI18nTableMap::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 (BrandDocumentI18n object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = BrandDocumentI18nTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = BrandDocumentI18nTableMap::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 + BrandDocumentI18nTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = BrandDocumentI18nTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + BrandDocumentI18nTableMap::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 = BrandDocumentI18nTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = BrandDocumentI18nTableMap::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; + BrandDocumentI18nTableMap::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(BrandDocumentI18nTableMap::ID); + $criteria->addSelectColumn(BrandDocumentI18nTableMap::LOCALE); + $criteria->addSelectColumn(BrandDocumentI18nTableMap::TITLE); + $criteria->addSelectColumn(BrandDocumentI18nTableMap::DESCRIPTION); + $criteria->addSelectColumn(BrandDocumentI18nTableMap::CHAPO); + $criteria->addSelectColumn(BrandDocumentI18nTableMap::POSTSCRIPTUM); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.LOCALE'); + $criteria->addSelectColumn($alias . '.TITLE'); + $criteria->addSelectColumn($alias . '.DESCRIPTION'); + $criteria->addSelectColumn($alias . '.CHAPO'); + $criteria->addSelectColumn($alias . '.POSTSCRIPTUM'); + } + } + + /** + * 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(BrandDocumentI18nTableMap::DATABASE_NAME)->getTable(BrandDocumentI18nTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(BrandDocumentI18nTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(BrandDocumentI18nTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new BrandDocumentI18nTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a BrandDocumentI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or BrandDocumentI18n 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(BrandDocumentI18nTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\BrandDocumentI18n) { // 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(BrandDocumentI18nTableMap::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(BrandDocumentI18nTableMap::ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(BrandDocumentI18nTableMap::LOCALE, $value[1])); + $criteria->addOr($criterion); + } + } + + $query = BrandDocumentI18nQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { BrandDocumentI18nTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { BrandDocumentI18nTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the brand_document_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 BrandDocumentI18nQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a BrandDocumentI18n or Criteria object. + * + * @param mixed $criteria Criteria or BrandDocumentI18n 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(BrandDocumentI18nTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from BrandDocumentI18n object + } + + + // Set the correct dbName + $query = BrandDocumentI18nQuery::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; + } + +} // BrandDocumentI18nTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +BrandDocumentI18nTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/BrandDocumentTableMap.php b/core/lib/Thelia/Model/Map/BrandDocumentTableMap.php new file mode 100644 index 000000000..18eb5d29f --- /dev/null +++ b/core/lib/Thelia/Model/Map/BrandDocumentTableMap.php @@ -0,0 +1,476 @@ + array('Id', 'BrandId', 'File', 'Position', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'brandId', 'file', 'position', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(BrandDocumentTableMap::ID, BrandDocumentTableMap::BRAND_ID, BrandDocumentTableMap::FILE, BrandDocumentTableMap::POSITION, BrandDocumentTableMap::CREATED_AT, BrandDocumentTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'BRAND_ID', 'FILE', 'POSITION', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'brand_id', 'file', 'position', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + ); + + /** + * 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, 'BrandId' => 1, 'File' => 2, 'Position' => 3, 'CreatedAt' => 4, 'UpdatedAt' => 5, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'brandId' => 1, 'file' => 2, 'position' => 3, 'createdAt' => 4, 'updatedAt' => 5, ), + self::TYPE_COLNAME => array(BrandDocumentTableMap::ID => 0, BrandDocumentTableMap::BRAND_ID => 1, BrandDocumentTableMap::FILE => 2, BrandDocumentTableMap::POSITION => 3, BrandDocumentTableMap::CREATED_AT => 4, BrandDocumentTableMap::UPDATED_AT => 5, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'BRAND_ID' => 1, 'FILE' => 2, 'POSITION' => 3, 'CREATED_AT' => 4, 'UPDATED_AT' => 5, ), + self::TYPE_FIELDNAME => array('id' => 0, 'brand_id' => 1, 'file' => 2, 'position' => 3, 'created_at' => 4, 'updated_at' => 5, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + ); + + /** + * 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('brand_document'); + $this->setPhpName('BrandDocument'); + $this->setClassName('\\Thelia\\Model\\BrandDocument'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addForeignKey('BRAND_ID', 'BrandId', 'INTEGER', 'brand', 'ID', true, null, null); + $this->addColumn('FILE', 'File', 'VARCHAR', true, 255, null); + $this->addColumn('POSITION', 'Position', 'INTEGER', false, 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('Brand', '\\Thelia\\Model\\Brand', RelationMap::MANY_TO_ONE, array('brand_id' => 'id', ), 'CASCADE', 'RESTRICT'); + $this->addRelation('BrandDocumentI18n', '\\Thelia\\Model\\BrandDocumentI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'BrandDocumentI18ns'); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), + 'i18n' => array('i18n_table' => '%TABLE%_i18n', 'i18n_phpname' => '%PHPNAME%I18n', 'i18n_columns' => 'title, description, chapo, postscriptum', 'locale_column' => 'locale', 'locale_length' => '5', 'default_locale' => '', 'locale_alias' => '', ), + ); + } // getBehaviors() + /** + * Method to invalidate the instance pool of all tables related to brand_document * 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. + BrandDocumentI18nTableMap::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 ? BrandDocumentTableMap::CLASS_DEFAULT : BrandDocumentTableMap::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 (BrandDocument object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = BrandDocumentTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = BrandDocumentTableMap::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 + BrandDocumentTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = BrandDocumentTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + BrandDocumentTableMap::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 = BrandDocumentTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = BrandDocumentTableMap::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; + BrandDocumentTableMap::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(BrandDocumentTableMap::ID); + $criteria->addSelectColumn(BrandDocumentTableMap::BRAND_ID); + $criteria->addSelectColumn(BrandDocumentTableMap::FILE); + $criteria->addSelectColumn(BrandDocumentTableMap::POSITION); + $criteria->addSelectColumn(BrandDocumentTableMap::CREATED_AT); + $criteria->addSelectColumn(BrandDocumentTableMap::UPDATED_AT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.BRAND_ID'); + $criteria->addSelectColumn($alias . '.FILE'); + $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(BrandDocumentTableMap::DATABASE_NAME)->getTable(BrandDocumentTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(BrandDocumentTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(BrandDocumentTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new BrandDocumentTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a BrandDocument or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or BrandDocument 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(BrandDocumentTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\BrandDocument) { // 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(BrandDocumentTableMap::DATABASE_NAME); + $criteria->add(BrandDocumentTableMap::ID, (array) $values, Criteria::IN); + } + + $query = BrandDocumentQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { BrandDocumentTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { BrandDocumentTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the brand_document 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 BrandDocumentQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a BrandDocument or Criteria object. + * + * @param mixed $criteria Criteria or BrandDocument 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(BrandDocumentTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from BrandDocument object + } + + if ($criteria->containsKey(BrandDocumentTableMap::ID) && $criteria->keyContainsValue(BrandDocumentTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.BrandDocumentTableMap::ID.')'); + } + + + // Set the correct dbName + $query = BrandDocumentQuery::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; + } + +} // BrandDocumentTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +BrandDocumentTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/BrandI18nTableMap.php b/core/lib/Thelia/Model/Map/BrandI18nTableMap.php new file mode 100644 index 000000000..965445812 --- /dev/null +++ b/core/lib/Thelia/Model/Map/BrandI18nTableMap.php @@ -0,0 +1,522 @@ + array('Id', 'Locale', 'Title', 'Description', 'Chapo', 'Postscriptum', 'MetaTitle', 'MetaDescription', 'MetaKeywords', ), + self::TYPE_STUDLYPHPNAME => array('id', 'locale', 'title', 'description', 'chapo', 'postscriptum', 'metaTitle', 'metaDescription', 'metaKeywords', ), + self::TYPE_COLNAME => array(BrandI18nTableMap::ID, BrandI18nTableMap::LOCALE, BrandI18nTableMap::TITLE, BrandI18nTableMap::DESCRIPTION, BrandI18nTableMap::CHAPO, BrandI18nTableMap::POSTSCRIPTUM, BrandI18nTableMap::META_TITLE, BrandI18nTableMap::META_DESCRIPTION, BrandI18nTableMap::META_KEYWORDS, ), + self::TYPE_RAW_COLNAME => array('ID', 'LOCALE', 'TITLE', 'DESCRIPTION', 'CHAPO', 'POSTSCRIPTUM', 'META_TITLE', 'META_DESCRIPTION', 'META_KEYWORDS', ), + self::TYPE_FIELDNAME => array('id', 'locale', 'title', 'description', 'chapo', 'postscriptum', 'meta_title', 'meta_description', 'meta_keywords', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, ) + ); + + /** + * 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, 'Chapo' => 4, 'Postscriptum' => 5, 'MetaTitle' => 6, 'MetaDescription' => 7, 'MetaKeywords' => 8, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'locale' => 1, 'title' => 2, 'description' => 3, 'chapo' => 4, 'postscriptum' => 5, 'metaTitle' => 6, 'metaDescription' => 7, 'metaKeywords' => 8, ), + self::TYPE_COLNAME => array(BrandI18nTableMap::ID => 0, BrandI18nTableMap::LOCALE => 1, BrandI18nTableMap::TITLE => 2, BrandI18nTableMap::DESCRIPTION => 3, BrandI18nTableMap::CHAPO => 4, BrandI18nTableMap::POSTSCRIPTUM => 5, BrandI18nTableMap::META_TITLE => 6, BrandI18nTableMap::META_DESCRIPTION => 7, BrandI18nTableMap::META_KEYWORDS => 8, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'LOCALE' => 1, 'TITLE' => 2, 'DESCRIPTION' => 3, 'CHAPO' => 4, 'POSTSCRIPTUM' => 5, 'META_TITLE' => 6, 'META_DESCRIPTION' => 7, 'META_KEYWORDS' => 8, ), + self::TYPE_FIELDNAME => array('id' => 0, 'locale' => 1, 'title' => 2, 'description' => 3, 'chapo' => 4, 'postscriptum' => 5, 'meta_title' => 6, 'meta_description' => 7, 'meta_keywords' => 8, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, ) + ); + + /** + * 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('brand_i18n'); + $this->setPhpName('BrandI18n'); + $this->setClassName('\\Thelia\\Model\\BrandI18n'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addForeignPrimaryKey('ID', 'Id', 'INTEGER' , 'brand', 'ID', true, null, null); + $this->addPrimaryKey('LOCALE', 'Locale', 'VARCHAR', true, 5, 'en_US'); + $this->addColumn('TITLE', 'Title', 'VARCHAR', false, 255, null); + $this->addColumn('DESCRIPTION', 'Description', 'CLOB', false, null, null); + $this->addColumn('CHAPO', 'Chapo', 'LONGVARCHAR', false, null, null); + $this->addColumn('POSTSCRIPTUM', 'Postscriptum', 'LONGVARCHAR', false, null, null); + $this->addColumn('META_TITLE', 'MetaTitle', 'VARCHAR', false, 255, null); + $this->addColumn('META_DESCRIPTION', 'MetaDescription', 'LONGVARCHAR', false, null, null); + $this->addColumn('META_KEYWORDS', 'MetaKeywords', 'LONGVARCHAR', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Brand', '\\Thelia\\Model\\Brand', 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\BrandI18n $obj A \Thelia\Model\BrandI18n 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\BrandI18n object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\BrandI18n) { + $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\BrandI18n 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 ? BrandI18nTableMap::CLASS_DEFAULT : BrandI18nTableMap::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 (BrandI18n object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = BrandI18nTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = BrandI18nTableMap::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 + BrandI18nTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = BrandI18nTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + BrandI18nTableMap::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 = BrandI18nTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = BrandI18nTableMap::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; + BrandI18nTableMap::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(BrandI18nTableMap::ID); + $criteria->addSelectColumn(BrandI18nTableMap::LOCALE); + $criteria->addSelectColumn(BrandI18nTableMap::TITLE); + $criteria->addSelectColumn(BrandI18nTableMap::DESCRIPTION); + $criteria->addSelectColumn(BrandI18nTableMap::CHAPO); + $criteria->addSelectColumn(BrandI18nTableMap::POSTSCRIPTUM); + $criteria->addSelectColumn(BrandI18nTableMap::META_TITLE); + $criteria->addSelectColumn(BrandI18nTableMap::META_DESCRIPTION); + $criteria->addSelectColumn(BrandI18nTableMap::META_KEYWORDS); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.LOCALE'); + $criteria->addSelectColumn($alias . '.TITLE'); + $criteria->addSelectColumn($alias . '.DESCRIPTION'); + $criteria->addSelectColumn($alias . '.CHAPO'); + $criteria->addSelectColumn($alias . '.POSTSCRIPTUM'); + $criteria->addSelectColumn($alias . '.META_TITLE'); + $criteria->addSelectColumn($alias . '.META_DESCRIPTION'); + $criteria->addSelectColumn($alias . '.META_KEYWORDS'); + } + } + + /** + * 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(BrandI18nTableMap::DATABASE_NAME)->getTable(BrandI18nTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(BrandI18nTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(BrandI18nTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new BrandI18nTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a BrandI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or BrandI18n 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(BrandI18nTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\BrandI18n) { // 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(BrandI18nTableMap::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(BrandI18nTableMap::ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(BrandI18nTableMap::LOCALE, $value[1])); + $criteria->addOr($criterion); + } + } + + $query = BrandI18nQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { BrandI18nTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { BrandI18nTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the brand_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 BrandI18nQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a BrandI18n or Criteria object. + * + * @param mixed $criteria Criteria or BrandI18n 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(BrandI18nTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from BrandI18n object + } + + + // Set the correct dbName + $query = BrandI18nQuery::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; + } + +} // BrandI18nTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +BrandI18nTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/BrandImageI18nTableMap.php b/core/lib/Thelia/Model/Map/BrandImageI18nTableMap.php new file mode 100644 index 000000000..a561e352d --- /dev/null +++ b/core/lib/Thelia/Model/Map/BrandImageI18nTableMap.php @@ -0,0 +1,498 @@ + array('Id', 'Locale', 'Title', 'Description', 'Chapo', 'Postscriptum', ), + self::TYPE_STUDLYPHPNAME => array('id', 'locale', 'title', 'description', 'chapo', 'postscriptum', ), + self::TYPE_COLNAME => array(BrandImageI18nTableMap::ID, BrandImageI18nTableMap::LOCALE, BrandImageI18nTableMap::TITLE, BrandImageI18nTableMap::DESCRIPTION, BrandImageI18nTableMap::CHAPO, BrandImageI18nTableMap::POSTSCRIPTUM, ), + self::TYPE_RAW_COLNAME => array('ID', 'LOCALE', 'TITLE', 'DESCRIPTION', 'CHAPO', 'POSTSCRIPTUM', ), + self::TYPE_FIELDNAME => array('id', 'locale', 'title', 'description', 'chapo', 'postscriptum', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + ); + + /** + * 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, 'Chapo' => 4, 'Postscriptum' => 5, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'locale' => 1, 'title' => 2, 'description' => 3, 'chapo' => 4, 'postscriptum' => 5, ), + self::TYPE_COLNAME => array(BrandImageI18nTableMap::ID => 0, BrandImageI18nTableMap::LOCALE => 1, BrandImageI18nTableMap::TITLE => 2, BrandImageI18nTableMap::DESCRIPTION => 3, BrandImageI18nTableMap::CHAPO => 4, BrandImageI18nTableMap::POSTSCRIPTUM => 5, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'LOCALE' => 1, 'TITLE' => 2, 'DESCRIPTION' => 3, 'CHAPO' => 4, 'POSTSCRIPTUM' => 5, ), + self::TYPE_FIELDNAME => array('id' => 0, 'locale' => 1, 'title' => 2, 'description' => 3, 'chapo' => 4, 'postscriptum' => 5, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + ); + + /** + * 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('brand_image_i18n'); + $this->setPhpName('BrandImageI18n'); + $this->setClassName('\\Thelia\\Model\\BrandImageI18n'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addForeignPrimaryKey('ID', 'Id', 'INTEGER' , 'brand_image', 'ID', true, null, null); + $this->addPrimaryKey('LOCALE', 'Locale', 'VARCHAR', true, 5, 'en_US'); + $this->addColumn('TITLE', 'Title', 'VARCHAR', false, 255, null); + $this->addColumn('DESCRIPTION', 'Description', 'CLOB', false, null, null); + $this->addColumn('CHAPO', 'Chapo', 'LONGVARCHAR', false, null, null); + $this->addColumn('POSTSCRIPTUM', 'Postscriptum', 'LONGVARCHAR', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('BrandImage', '\\Thelia\\Model\\BrandImage', 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\BrandImageI18n $obj A \Thelia\Model\BrandImageI18n 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\BrandImageI18n object or a primary key value. + */ + public static function removeInstanceFromPool($value) + { + if (Propel::isInstancePoolingEnabled() && null !== $value) { + if (is_object($value) && $value instanceof \Thelia\Model\BrandImageI18n) { + $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\BrandImageI18n 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 ? BrandImageI18nTableMap::CLASS_DEFAULT : BrandImageI18nTableMap::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 (BrandImageI18n object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = BrandImageI18nTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = BrandImageI18nTableMap::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 + BrandImageI18nTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = BrandImageI18nTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + BrandImageI18nTableMap::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 = BrandImageI18nTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = BrandImageI18nTableMap::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; + BrandImageI18nTableMap::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(BrandImageI18nTableMap::ID); + $criteria->addSelectColumn(BrandImageI18nTableMap::LOCALE); + $criteria->addSelectColumn(BrandImageI18nTableMap::TITLE); + $criteria->addSelectColumn(BrandImageI18nTableMap::DESCRIPTION); + $criteria->addSelectColumn(BrandImageI18nTableMap::CHAPO); + $criteria->addSelectColumn(BrandImageI18nTableMap::POSTSCRIPTUM); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.LOCALE'); + $criteria->addSelectColumn($alias . '.TITLE'); + $criteria->addSelectColumn($alias . '.DESCRIPTION'); + $criteria->addSelectColumn($alias . '.CHAPO'); + $criteria->addSelectColumn($alias . '.POSTSCRIPTUM'); + } + } + + /** + * 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(BrandImageI18nTableMap::DATABASE_NAME)->getTable(BrandImageI18nTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(BrandImageI18nTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(BrandImageI18nTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new BrandImageI18nTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a BrandImageI18n or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or BrandImageI18n 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(BrandImageI18nTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\BrandImageI18n) { // 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(BrandImageI18nTableMap::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(BrandImageI18nTableMap::ID, $value[0]); + $criterion->addAnd($criteria->getNewCriterion(BrandImageI18nTableMap::LOCALE, $value[1])); + $criteria->addOr($criterion); + } + } + + $query = BrandImageI18nQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { BrandImageI18nTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { BrandImageI18nTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the brand_image_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 BrandImageI18nQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a BrandImageI18n or Criteria object. + * + * @param mixed $criteria Criteria or BrandImageI18n 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(BrandImageI18nTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from BrandImageI18n object + } + + + // Set the correct dbName + $query = BrandImageI18nQuery::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; + } + +} // BrandImageI18nTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +BrandImageI18nTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/BrandImageTableMap.php b/core/lib/Thelia/Model/Map/BrandImageTableMap.php new file mode 100644 index 000000000..9fee0b2df --- /dev/null +++ b/core/lib/Thelia/Model/Map/BrandImageTableMap.php @@ -0,0 +1,478 @@ + array('Id', 'BrandId', 'File', 'Position', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'brandId', 'file', 'position', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(BrandImageTableMap::ID, BrandImageTableMap::BRAND_ID, BrandImageTableMap::FILE, BrandImageTableMap::POSITION, BrandImageTableMap::CREATED_AT, BrandImageTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'BRAND_ID', 'FILE', 'POSITION', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'brand_id', 'file', 'position', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + ); + + /** + * 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, 'BrandId' => 1, 'File' => 2, 'Position' => 3, 'CreatedAt' => 4, 'UpdatedAt' => 5, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'brandId' => 1, 'file' => 2, 'position' => 3, 'createdAt' => 4, 'updatedAt' => 5, ), + self::TYPE_COLNAME => array(BrandImageTableMap::ID => 0, BrandImageTableMap::BRAND_ID => 1, BrandImageTableMap::FILE => 2, BrandImageTableMap::POSITION => 3, BrandImageTableMap::CREATED_AT => 4, BrandImageTableMap::UPDATED_AT => 5, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'BRAND_ID' => 1, 'FILE' => 2, 'POSITION' => 3, 'CREATED_AT' => 4, 'UPDATED_AT' => 5, ), + self::TYPE_FIELDNAME => array('id' => 0, 'brand_id' => 1, 'file' => 2, 'position' => 3, 'created_at' => 4, 'updated_at' => 5, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + ); + + /** + * 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('brand_image'); + $this->setPhpName('BrandImage'); + $this->setClassName('\\Thelia\\Model\\BrandImage'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addForeignKey('BRAND_ID', 'BrandId', 'INTEGER', 'brand', 'ID', true, null, null); + $this->addColumn('FILE', 'File', 'VARCHAR', true, 255, null); + $this->addColumn('POSITION', 'Position', 'INTEGER', false, 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('BrandRelatedByBrandId', '\\Thelia\\Model\\Brand', RelationMap::MANY_TO_ONE, array('brand_id' => 'id', ), 'CASCADE', 'RESTRICT'); + $this->addRelation('BrandRelatedByLogoImageId', '\\Thelia\\Model\\Brand', RelationMap::ONE_TO_MANY, array('id' => 'logo_image_id', ), 'SET NULL', 'RESTRICT', 'BrandsRelatedByLogoImageId'); + $this->addRelation('BrandImageI18n', '\\Thelia\\Model\\BrandImageI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'BrandImageI18ns'); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), + 'i18n' => array('i18n_table' => '%TABLE%_i18n', 'i18n_phpname' => '%PHPNAME%I18n', 'i18n_columns' => 'title, description, chapo, postscriptum', 'locale_column' => 'locale', 'locale_length' => '5', 'default_locale' => '', 'locale_alias' => '', ), + ); + } // getBehaviors() + /** + * Method to invalidate the instance pool of all tables related to brand_image * 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. + BrandTableMap::clearInstancePool(); + BrandImageI18nTableMap::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 ? BrandImageTableMap::CLASS_DEFAULT : BrandImageTableMap::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 (BrandImage object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = BrandImageTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = BrandImageTableMap::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 + BrandImageTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = BrandImageTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + BrandImageTableMap::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 = BrandImageTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = BrandImageTableMap::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; + BrandImageTableMap::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(BrandImageTableMap::ID); + $criteria->addSelectColumn(BrandImageTableMap::BRAND_ID); + $criteria->addSelectColumn(BrandImageTableMap::FILE); + $criteria->addSelectColumn(BrandImageTableMap::POSITION); + $criteria->addSelectColumn(BrandImageTableMap::CREATED_AT); + $criteria->addSelectColumn(BrandImageTableMap::UPDATED_AT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.BRAND_ID'); + $criteria->addSelectColumn($alias . '.FILE'); + $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(BrandImageTableMap::DATABASE_NAME)->getTable(BrandImageTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(BrandImageTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(BrandImageTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new BrandImageTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a BrandImage or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or BrandImage 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(BrandImageTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\BrandImage) { // 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(BrandImageTableMap::DATABASE_NAME); + $criteria->add(BrandImageTableMap::ID, (array) $values, Criteria::IN); + } + + $query = BrandImageQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { BrandImageTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { BrandImageTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the brand_image 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 BrandImageQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a BrandImage or Criteria object. + * + * @param mixed $criteria Criteria or BrandImage 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(BrandImageTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from BrandImage object + } + + if ($criteria->containsKey(BrandImageTableMap::ID) && $criteria->keyContainsValue(BrandImageTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.BrandImageTableMap::ID.')'); + } + + + // Set the correct dbName + $query = BrandImageQuery::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; + } + +} // BrandImageTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +BrandImageTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/BrandTableMap.php b/core/lib/Thelia/Model/Map/BrandTableMap.php new file mode 100644 index 000000000..b069e9bbf --- /dev/null +++ b/core/lib/Thelia/Model/Map/BrandTableMap.php @@ -0,0 +1,482 @@ + array('Id', 'Visible', 'Position', 'LogoImageId', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'visible', 'position', 'logoImageId', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(BrandTableMap::ID, BrandTableMap::VISIBLE, BrandTableMap::POSITION, BrandTableMap::LOGO_IMAGE_ID, BrandTableMap::CREATED_AT, BrandTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'VISIBLE', 'POSITION', 'LOGO_IMAGE_ID', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'visible', 'position', 'logo_image_id', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + ); + + /** + * 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, 'Visible' => 1, 'Position' => 2, 'LogoImageId' => 3, 'CreatedAt' => 4, 'UpdatedAt' => 5, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'visible' => 1, 'position' => 2, 'logoImageId' => 3, 'createdAt' => 4, 'updatedAt' => 5, ), + self::TYPE_COLNAME => array(BrandTableMap::ID => 0, BrandTableMap::VISIBLE => 1, BrandTableMap::POSITION => 2, BrandTableMap::LOGO_IMAGE_ID => 3, BrandTableMap::CREATED_AT => 4, BrandTableMap::UPDATED_AT => 5, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'VISIBLE' => 1, 'POSITION' => 2, 'LOGO_IMAGE_ID' => 3, 'CREATED_AT' => 4, 'UPDATED_AT' => 5, ), + self::TYPE_FIELDNAME => array('id' => 0, 'visible' => 1, 'position' => 2, 'logo_image_id' => 3, 'created_at' => 4, 'updated_at' => 5, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + ); + + /** + * 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('brand'); + $this->setPhpName('Brand'); + $this->setClassName('\\Thelia\\Model\\Brand'); + $this->setPackage('Thelia.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addColumn('VISIBLE', 'Visible', 'TINYINT', false, null, null); + $this->addColumn('POSITION', 'Position', 'INTEGER', false, null, null); + $this->addForeignKey('LOGO_IMAGE_ID', 'LogoImageId', 'INTEGER', 'brand_image', 'ID', false, 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('BrandImageRelatedByLogoImageId', '\\Thelia\\Model\\BrandImage', RelationMap::MANY_TO_ONE, array('logo_image_id' => 'id', ), 'SET NULL', 'RESTRICT'); + $this->addRelation('Product', '\\Thelia\\Model\\Product', RelationMap::ONE_TO_MANY, array('id' => 'brand_id', ), 'SET NULL', null, 'Products'); + $this->addRelation('BrandDocument', '\\Thelia\\Model\\BrandDocument', RelationMap::ONE_TO_MANY, array('id' => 'brand_id', ), 'CASCADE', 'RESTRICT', 'BrandDocuments'); + $this->addRelation('BrandImageRelatedByBrandId', '\\Thelia\\Model\\BrandImage', RelationMap::ONE_TO_MANY, array('id' => 'brand_id', ), 'CASCADE', 'RESTRICT', 'BrandImagesRelatedByBrandId'); + $this->addRelation('BrandI18n', '\\Thelia\\Model\\BrandI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'BrandI18ns'); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), + 'i18n' => array('i18n_table' => '%TABLE%_i18n', 'i18n_phpname' => '%PHPNAME%I18n', 'i18n_columns' => 'title, description, chapo, postscriptum, meta_title, meta_description, meta_keywords', 'locale_column' => 'locale', 'locale_length' => '5', 'default_locale' => '', 'locale_alias' => '', ), + ); + } // getBehaviors() + /** + * Method to invalidate the instance pool of all tables related to brand * 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. + ProductTableMap::clearInstancePool(); + BrandDocumentTableMap::clearInstancePool(); + BrandImageTableMap::clearInstancePool(); + BrandI18nTableMap::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 ? BrandTableMap::CLASS_DEFAULT : BrandTableMap::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 (Brand object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = BrandTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = BrandTableMap::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 + BrandTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = BrandTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + BrandTableMap::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 = BrandTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = BrandTableMap::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; + BrandTableMap::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(BrandTableMap::ID); + $criteria->addSelectColumn(BrandTableMap::VISIBLE); + $criteria->addSelectColumn(BrandTableMap::POSITION); + $criteria->addSelectColumn(BrandTableMap::LOGO_IMAGE_ID); + $criteria->addSelectColumn(BrandTableMap::CREATED_AT); + $criteria->addSelectColumn(BrandTableMap::UPDATED_AT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.VISIBLE'); + $criteria->addSelectColumn($alias . '.POSITION'); + $criteria->addSelectColumn($alias . '.LOGO_IMAGE_ID'); + $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(BrandTableMap::DATABASE_NAME)->getTable(BrandTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(BrandTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(BrandTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new BrandTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a Brand or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or Brand 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(BrandTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Thelia\Model\Brand) { // 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(BrandTableMap::DATABASE_NAME); + $criteria->add(BrandTableMap::ID, (array) $values, Criteria::IN); + } + + $query = BrandQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { BrandTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { BrandTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the brand 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 BrandQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a Brand or Criteria object. + * + * @param mixed $criteria Criteria or Brand 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(BrandTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from Brand object + } + + if ($criteria->containsKey(BrandTableMap::ID) && $criteria->keyContainsValue(BrandTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.BrandTableMap::ID.')'); + } + + + // Set the correct dbName + $query = BrandQuery::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; + } + +} // BrandTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +BrandTableMap::buildTableMap(); diff --git a/core/lib/Thelia/Model/Map/CouponCustomerCountTableMap.php b/core/lib/Thelia/Model/Map/CouponCustomerCountTableMap.php index cbed11f68..380852cff 100644 --- a/core/lib/Thelia/Model/Map/CouponCustomerCountTableMap.php +++ b/core/lib/Thelia/Model/Map/CouponCustomerCountTableMap.php @@ -147,8 +147,8 @@ class CouponCustomerCountTableMap extends TableMap */ public function buildRelations() { - $this->addRelation('Customer', '\\Thelia\\Model\\Customer', RelationMap::MANY_TO_ONE, array('customer_id' => 'id', ), 'CASCADE', null); - $this->addRelation('Coupon', '\\Thelia\\Model\\Coupon', RelationMap::MANY_TO_ONE, array('coupon_id' => 'id', ), 'CASCADE', null); + $this->addRelation('Customer', '\\Thelia\\Model\\Customer', RelationMap::MANY_TO_ONE, array('customer_id' => 'id', ), 'CASCADE', 'RESTRICT'); + $this->addRelation('Coupon', '\\Thelia\\Model\\Coupon', RelationMap::MANY_TO_ONE, array('coupon_id' => 'id', ), 'CASCADE', 'RESTRICT'); } // buildRelations() /** diff --git a/core/lib/Thelia/Model/Map/CouponTableMap.php b/core/lib/Thelia/Model/Map/CouponTableMap.php index 72c03b526..3a32501d9 100644 --- a/core/lib/Thelia/Model/Map/CouponTableMap.php +++ b/core/lib/Thelia/Model/Map/CouponTableMap.php @@ -58,7 +58,7 @@ class CouponTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 16; + const NUM_COLUMNS = 18; /** * The number of lazy-loaded columns @@ -68,7 +68,7 @@ class CouponTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 16; + const NUM_HYDRATE_COLUMNS = 18; /** * the column name for the ID field @@ -150,6 +150,16 @@ class CouponTableMap extends TableMap */ const VERSION = 'coupon.VERSION'; + /** + * the column name for the VERSION_CREATED_AT field + */ + const VERSION_CREATED_AT = 'coupon.VERSION_CREATED_AT'; + + /** + * the column name for the VERSION_CREATED_BY field + */ + const VERSION_CREATED_BY = 'coupon.VERSION_CREATED_BY'; + /** * The default string format for model objects of the related table */ @@ -171,12 +181,12 @@ class CouponTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'Code', 'Type', 'SerializedEffects', 'IsEnabled', 'ExpirationDate', 'MaxUsage', 'IsCumulative', 'IsRemovingPostage', 'IsAvailableOnSpecialOffers', 'IsUsed', 'SerializedConditions', 'PerCustomerUsageCount', 'CreatedAt', 'UpdatedAt', 'Version', ), - self::TYPE_STUDLYPHPNAME => array('id', 'code', 'type', 'serializedEffects', 'isEnabled', 'expirationDate', 'maxUsage', 'isCumulative', 'isRemovingPostage', 'isAvailableOnSpecialOffers', 'isUsed', 'serializedConditions', 'perCustomerUsageCount', 'createdAt', 'updatedAt', 'version', ), - self::TYPE_COLNAME => array(CouponTableMap::ID, CouponTableMap::CODE, CouponTableMap::TYPE, CouponTableMap::SERIALIZED_EFFECTS, CouponTableMap::IS_ENABLED, CouponTableMap::EXPIRATION_DATE, CouponTableMap::MAX_USAGE, CouponTableMap::IS_CUMULATIVE, CouponTableMap::IS_REMOVING_POSTAGE, CouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, CouponTableMap::IS_USED, CouponTableMap::SERIALIZED_CONDITIONS, CouponTableMap::PER_CUSTOMER_USAGE_COUNT, CouponTableMap::CREATED_AT, CouponTableMap::UPDATED_AT, CouponTableMap::VERSION, ), - self::TYPE_RAW_COLNAME => array('ID', 'CODE', 'TYPE', 'SERIALIZED_EFFECTS', 'IS_ENABLED', 'EXPIRATION_DATE', 'MAX_USAGE', 'IS_CUMULATIVE', 'IS_REMOVING_POSTAGE', 'IS_AVAILABLE_ON_SPECIAL_OFFERS', 'IS_USED', 'SERIALIZED_CONDITIONS', 'PER_CUSTOMER_USAGE_COUNT', 'CREATED_AT', 'UPDATED_AT', 'VERSION', ), - self::TYPE_FIELDNAME => array('id', 'code', 'type', 'serialized_effects', 'is_enabled', 'expiration_date', 'max_usage', 'is_cumulative', 'is_removing_postage', 'is_available_on_special_offers', 'is_used', 'serialized_conditions', 'per_customer_usage_count', 'created_at', 'updated_at', 'version', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) + self::TYPE_PHPNAME => array('Id', 'Code', 'Type', 'SerializedEffects', 'IsEnabled', 'ExpirationDate', 'MaxUsage', 'IsCumulative', 'IsRemovingPostage', 'IsAvailableOnSpecialOffers', 'IsUsed', 'SerializedConditions', 'PerCustomerUsageCount', 'CreatedAt', 'UpdatedAt', 'Version', 'VersionCreatedAt', 'VersionCreatedBy', ), + self::TYPE_STUDLYPHPNAME => array('id', 'code', 'type', 'serializedEffects', 'isEnabled', 'expirationDate', 'maxUsage', 'isCumulative', 'isRemovingPostage', 'isAvailableOnSpecialOffers', 'isUsed', 'serializedConditions', 'perCustomerUsageCount', 'createdAt', 'updatedAt', 'version', 'versionCreatedAt', 'versionCreatedBy', ), + self::TYPE_COLNAME => array(CouponTableMap::ID, CouponTableMap::CODE, CouponTableMap::TYPE, CouponTableMap::SERIALIZED_EFFECTS, CouponTableMap::IS_ENABLED, CouponTableMap::EXPIRATION_DATE, CouponTableMap::MAX_USAGE, CouponTableMap::IS_CUMULATIVE, CouponTableMap::IS_REMOVING_POSTAGE, CouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, CouponTableMap::IS_USED, CouponTableMap::SERIALIZED_CONDITIONS, CouponTableMap::PER_CUSTOMER_USAGE_COUNT, CouponTableMap::CREATED_AT, CouponTableMap::UPDATED_AT, CouponTableMap::VERSION, CouponTableMap::VERSION_CREATED_AT, CouponTableMap::VERSION_CREATED_BY, ), + self::TYPE_RAW_COLNAME => array('ID', 'CODE', 'TYPE', 'SERIALIZED_EFFECTS', 'IS_ENABLED', 'EXPIRATION_DATE', 'MAX_USAGE', 'IS_CUMULATIVE', 'IS_REMOVING_POSTAGE', 'IS_AVAILABLE_ON_SPECIAL_OFFERS', 'IS_USED', 'SERIALIZED_CONDITIONS', 'PER_CUSTOMER_USAGE_COUNT', 'CREATED_AT', 'UPDATED_AT', 'VERSION', 'VERSION_CREATED_AT', 'VERSION_CREATED_BY', ), + self::TYPE_FIELDNAME => array('id', 'code', 'type', 'serialized_effects', 'is_enabled', 'expiration_date', 'max_usage', 'is_cumulative', 'is_removing_postage', 'is_available_on_special_offers', 'is_used', 'serialized_conditions', 'per_customer_usage_count', 'created_at', 'updated_at', 'version', 'version_created_at', 'version_created_by', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, ) ); /** @@ -186,12 +196,12 @@ class CouponTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'Code' => 1, 'Type' => 2, 'SerializedEffects' => 3, 'IsEnabled' => 4, 'ExpirationDate' => 5, 'MaxUsage' => 6, 'IsCumulative' => 7, 'IsRemovingPostage' => 8, 'IsAvailableOnSpecialOffers' => 9, 'IsUsed' => 10, 'SerializedConditions' => 11, 'PerCustomerUsageCount' => 12, 'CreatedAt' => 13, 'UpdatedAt' => 14, 'Version' => 15, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serializedEffects' => 3, 'isEnabled' => 4, 'expirationDate' => 5, 'maxUsage' => 6, 'isCumulative' => 7, 'isRemovingPostage' => 8, 'isAvailableOnSpecialOffers' => 9, 'isUsed' => 10, 'serializedConditions' => 11, 'perCustomerUsageCount' => 12, 'createdAt' => 13, 'updatedAt' => 14, 'version' => 15, ), - self::TYPE_COLNAME => array(CouponTableMap::ID => 0, CouponTableMap::CODE => 1, CouponTableMap::TYPE => 2, CouponTableMap::SERIALIZED_EFFECTS => 3, CouponTableMap::IS_ENABLED => 4, CouponTableMap::EXPIRATION_DATE => 5, CouponTableMap::MAX_USAGE => 6, CouponTableMap::IS_CUMULATIVE => 7, CouponTableMap::IS_REMOVING_POSTAGE => 8, CouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS => 9, CouponTableMap::IS_USED => 10, CouponTableMap::SERIALIZED_CONDITIONS => 11, CouponTableMap::PER_CUSTOMER_USAGE_COUNT => 12, CouponTableMap::CREATED_AT => 13, CouponTableMap::UPDATED_AT => 14, CouponTableMap::VERSION => 15, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'CODE' => 1, 'TYPE' => 2, 'SERIALIZED_EFFECTS' => 3, 'IS_ENABLED' => 4, 'EXPIRATION_DATE' => 5, 'MAX_USAGE' => 6, 'IS_CUMULATIVE' => 7, 'IS_REMOVING_POSTAGE' => 8, 'IS_AVAILABLE_ON_SPECIAL_OFFERS' => 9, 'IS_USED' => 10, 'SERIALIZED_CONDITIONS' => 11, 'PER_CUSTOMER_USAGE_COUNT' => 12, 'CREATED_AT' => 13, 'UPDATED_AT' => 14, 'VERSION' => 15, ), - self::TYPE_FIELDNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serialized_effects' => 3, 'is_enabled' => 4, 'expiration_date' => 5, 'max_usage' => 6, 'is_cumulative' => 7, 'is_removing_postage' => 8, 'is_available_on_special_offers' => 9, 'is_used' => 10, 'serialized_conditions' => 11, 'per_customer_usage_count' => 12, 'created_at' => 13, 'updated_at' => 14, 'version' => 15, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) + self::TYPE_PHPNAME => array('Id' => 0, 'Code' => 1, 'Type' => 2, 'SerializedEffects' => 3, 'IsEnabled' => 4, 'ExpirationDate' => 5, 'MaxUsage' => 6, 'IsCumulative' => 7, 'IsRemovingPostage' => 8, 'IsAvailableOnSpecialOffers' => 9, 'IsUsed' => 10, 'SerializedConditions' => 11, 'PerCustomerUsageCount' => 12, 'CreatedAt' => 13, 'UpdatedAt' => 14, 'Version' => 15, 'VersionCreatedAt' => 16, 'VersionCreatedBy' => 17, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serializedEffects' => 3, 'isEnabled' => 4, 'expirationDate' => 5, 'maxUsage' => 6, 'isCumulative' => 7, 'isRemovingPostage' => 8, 'isAvailableOnSpecialOffers' => 9, 'isUsed' => 10, 'serializedConditions' => 11, 'perCustomerUsageCount' => 12, 'createdAt' => 13, 'updatedAt' => 14, 'version' => 15, 'versionCreatedAt' => 16, 'versionCreatedBy' => 17, ), + self::TYPE_COLNAME => array(CouponTableMap::ID => 0, CouponTableMap::CODE => 1, CouponTableMap::TYPE => 2, CouponTableMap::SERIALIZED_EFFECTS => 3, CouponTableMap::IS_ENABLED => 4, CouponTableMap::EXPIRATION_DATE => 5, CouponTableMap::MAX_USAGE => 6, CouponTableMap::IS_CUMULATIVE => 7, CouponTableMap::IS_REMOVING_POSTAGE => 8, CouponTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS => 9, CouponTableMap::IS_USED => 10, CouponTableMap::SERIALIZED_CONDITIONS => 11, CouponTableMap::PER_CUSTOMER_USAGE_COUNT => 12, CouponTableMap::CREATED_AT => 13, CouponTableMap::UPDATED_AT => 14, CouponTableMap::VERSION => 15, CouponTableMap::VERSION_CREATED_AT => 16, CouponTableMap::VERSION_CREATED_BY => 17, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'CODE' => 1, 'TYPE' => 2, 'SERIALIZED_EFFECTS' => 3, 'IS_ENABLED' => 4, 'EXPIRATION_DATE' => 5, 'MAX_USAGE' => 6, 'IS_CUMULATIVE' => 7, 'IS_REMOVING_POSTAGE' => 8, 'IS_AVAILABLE_ON_SPECIAL_OFFERS' => 9, 'IS_USED' => 10, 'SERIALIZED_CONDITIONS' => 11, 'PER_CUSTOMER_USAGE_COUNT' => 12, 'CREATED_AT' => 13, 'UPDATED_AT' => 14, 'VERSION' => 15, 'VERSION_CREATED_AT' => 16, 'VERSION_CREATED_BY' => 17, ), + self::TYPE_FIELDNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serialized_effects' => 3, 'is_enabled' => 4, 'expiration_date' => 5, 'max_usage' => 6, 'is_cumulative' => 7, 'is_removing_postage' => 8, 'is_available_on_special_offers' => 9, 'is_used' => 10, 'serialized_conditions' => 11, 'per_customer_usage_count' => 12, 'created_at' => 13, 'updated_at' => 14, 'version' => 15, 'version_created_at' => 16, 'version_created_by' => 17, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, ) ); /** @@ -226,6 +236,8 @@ class CouponTableMap extends TableMap $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('VERSION', 'Version', 'INTEGER', false, null, 0); + $this->addColumn('VERSION_CREATED_AT', 'VersionCreatedAt', 'TIMESTAMP', false, null, null); + $this->addColumn('VERSION_CREATED_BY', 'VersionCreatedBy', 'VARCHAR', false, 100, null); } // initialize() /** @@ -235,12 +247,12 @@ class CouponTableMap extends TableMap { $this->addRelation('CouponCountry', '\\Thelia\\Model\\CouponCountry', RelationMap::ONE_TO_MANY, array('id' => 'coupon_id', ), 'CASCADE', null, 'CouponCountries'); $this->addRelation('CouponModule', '\\Thelia\\Model\\CouponModule', RelationMap::ONE_TO_MANY, array('id' => 'coupon_id', ), 'CASCADE', null, 'CouponModules'); - $this->addRelation('CouponCustomerCount', '\\Thelia\\Model\\CouponCustomerCount', RelationMap::ONE_TO_MANY, array('id' => 'coupon_id', ), 'CASCADE', null, 'CouponCustomerCounts'); + $this->addRelation('CouponCustomerCount', '\\Thelia\\Model\\CouponCustomerCount', RelationMap::ONE_TO_MANY, array('id' => 'coupon_id', ), 'CASCADE', 'RESTRICT', 'CouponCustomerCounts'); $this->addRelation('CouponI18n', '\\Thelia\\Model\\CouponI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'CouponI18ns'); $this->addRelation('CouponVersion', '\\Thelia\\Model\\CouponVersion', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'CouponVersions'); $this->addRelation('Country', '\\Thelia\\Model\\Country', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Countries'); $this->addRelation('Module', '\\Thelia\\Model\\Module', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Modules'); - $this->addRelation('Customer', '\\Thelia\\Model\\Customer', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Customers'); + $this->addRelation('Customer', '\\Thelia\\Model\\Customer', RelationMap::MANY_TO_MANY, array(), 'CASCADE', 'RESTRICT', 'Customers'); } // buildRelations() /** @@ -254,7 +266,7 @@ class CouponTableMap extends TableMap return array( 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), 'i18n' => array('i18n_table' => '%TABLE%_i18n', 'i18n_phpname' => '%PHPNAME%I18n', 'i18n_columns' => 'title, short_description, description', 'locale_column' => 'locale', 'locale_length' => '5', 'default_locale' => '', 'locale_alias' => '', ), - 'versionable' => array('version_column' => 'version', 'version_table' => '', 'log_created_at' => 'false', 'log_created_by' => 'false', 'log_comment' => 'false', 'version_created_at_column' => 'version_created_at', 'version_created_by_column' => 'version_created_by', 'version_comment_column' => 'version_comment', ), + 'versionable' => array('version_column' => 'version', 'version_table' => '', 'log_created_at' => 'true', 'log_created_by' => 'true', 'log_comment' => 'false', 'version_created_at_column' => 'version_created_at', 'version_created_by_column' => 'version_created_by', 'version_comment_column' => 'version_comment', ), ); } // getBehaviors() /** @@ -425,6 +437,8 @@ class CouponTableMap extends TableMap $criteria->addSelectColumn(CouponTableMap::CREATED_AT); $criteria->addSelectColumn(CouponTableMap::UPDATED_AT); $criteria->addSelectColumn(CouponTableMap::VERSION); + $criteria->addSelectColumn(CouponTableMap::VERSION_CREATED_AT); + $criteria->addSelectColumn(CouponTableMap::VERSION_CREATED_BY); } else { $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.CODE'); @@ -442,6 +456,8 @@ class CouponTableMap extends TableMap $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); $criteria->addSelectColumn($alias . '.VERSION'); + $criteria->addSelectColumn($alias . '.VERSION_CREATED_AT'); + $criteria->addSelectColumn($alias . '.VERSION_CREATED_BY'); } } diff --git a/core/lib/Thelia/Model/Map/CouponVersionTableMap.php b/core/lib/Thelia/Model/Map/CouponVersionTableMap.php index fccda1064..9b4e8994e 100644 --- a/core/lib/Thelia/Model/Map/CouponVersionTableMap.php +++ b/core/lib/Thelia/Model/Map/CouponVersionTableMap.php @@ -58,7 +58,7 @@ class CouponVersionTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 16; + const NUM_COLUMNS = 18; /** * The number of lazy-loaded columns @@ -68,7 +68,7 @@ class CouponVersionTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 16; + const NUM_HYDRATE_COLUMNS = 18; /** * the column name for the ID field @@ -150,6 +150,16 @@ class CouponVersionTableMap extends TableMap */ const VERSION = 'coupon_version.VERSION'; + /** + * the column name for the VERSION_CREATED_AT field + */ + const VERSION_CREATED_AT = 'coupon_version.VERSION_CREATED_AT'; + + /** + * the column name for the VERSION_CREATED_BY field + */ + const VERSION_CREATED_BY = 'coupon_version.VERSION_CREATED_BY'; + /** * The default string format for model objects of the related table */ @@ -162,12 +172,12 @@ class CouponVersionTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'Code', 'Type', 'SerializedEffects', 'IsEnabled', 'ExpirationDate', 'MaxUsage', 'IsCumulative', 'IsRemovingPostage', 'IsAvailableOnSpecialOffers', 'IsUsed', 'SerializedConditions', 'PerCustomerUsageCount', 'CreatedAt', 'UpdatedAt', 'Version', ), - self::TYPE_STUDLYPHPNAME => array('id', 'code', 'type', 'serializedEffects', 'isEnabled', 'expirationDate', 'maxUsage', 'isCumulative', 'isRemovingPostage', 'isAvailableOnSpecialOffers', 'isUsed', 'serializedConditions', 'perCustomerUsageCount', 'createdAt', 'updatedAt', 'version', ), - self::TYPE_COLNAME => array(CouponVersionTableMap::ID, CouponVersionTableMap::CODE, CouponVersionTableMap::TYPE, CouponVersionTableMap::SERIALIZED_EFFECTS, CouponVersionTableMap::IS_ENABLED, CouponVersionTableMap::EXPIRATION_DATE, CouponVersionTableMap::MAX_USAGE, CouponVersionTableMap::IS_CUMULATIVE, CouponVersionTableMap::IS_REMOVING_POSTAGE, CouponVersionTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, CouponVersionTableMap::IS_USED, CouponVersionTableMap::SERIALIZED_CONDITIONS, CouponVersionTableMap::PER_CUSTOMER_USAGE_COUNT, CouponVersionTableMap::CREATED_AT, CouponVersionTableMap::UPDATED_AT, CouponVersionTableMap::VERSION, ), - self::TYPE_RAW_COLNAME => array('ID', 'CODE', 'TYPE', 'SERIALIZED_EFFECTS', 'IS_ENABLED', 'EXPIRATION_DATE', 'MAX_USAGE', 'IS_CUMULATIVE', 'IS_REMOVING_POSTAGE', 'IS_AVAILABLE_ON_SPECIAL_OFFERS', 'IS_USED', 'SERIALIZED_CONDITIONS', 'PER_CUSTOMER_USAGE_COUNT', 'CREATED_AT', 'UPDATED_AT', 'VERSION', ), - self::TYPE_FIELDNAME => array('id', 'code', 'type', 'serialized_effects', 'is_enabled', 'expiration_date', 'max_usage', 'is_cumulative', 'is_removing_postage', 'is_available_on_special_offers', 'is_used', 'serialized_conditions', 'per_customer_usage_count', 'created_at', 'updated_at', 'version', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) + self::TYPE_PHPNAME => array('Id', 'Code', 'Type', 'SerializedEffects', 'IsEnabled', 'ExpirationDate', 'MaxUsage', 'IsCumulative', 'IsRemovingPostage', 'IsAvailableOnSpecialOffers', 'IsUsed', 'SerializedConditions', 'PerCustomerUsageCount', 'CreatedAt', 'UpdatedAt', 'Version', 'VersionCreatedAt', 'VersionCreatedBy', ), + self::TYPE_STUDLYPHPNAME => array('id', 'code', 'type', 'serializedEffects', 'isEnabled', 'expirationDate', 'maxUsage', 'isCumulative', 'isRemovingPostage', 'isAvailableOnSpecialOffers', 'isUsed', 'serializedConditions', 'perCustomerUsageCount', 'createdAt', 'updatedAt', 'version', 'versionCreatedAt', 'versionCreatedBy', ), + self::TYPE_COLNAME => array(CouponVersionTableMap::ID, CouponVersionTableMap::CODE, CouponVersionTableMap::TYPE, CouponVersionTableMap::SERIALIZED_EFFECTS, CouponVersionTableMap::IS_ENABLED, CouponVersionTableMap::EXPIRATION_DATE, CouponVersionTableMap::MAX_USAGE, CouponVersionTableMap::IS_CUMULATIVE, CouponVersionTableMap::IS_REMOVING_POSTAGE, CouponVersionTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS, CouponVersionTableMap::IS_USED, CouponVersionTableMap::SERIALIZED_CONDITIONS, CouponVersionTableMap::PER_CUSTOMER_USAGE_COUNT, CouponVersionTableMap::CREATED_AT, CouponVersionTableMap::UPDATED_AT, CouponVersionTableMap::VERSION, CouponVersionTableMap::VERSION_CREATED_AT, CouponVersionTableMap::VERSION_CREATED_BY, ), + self::TYPE_RAW_COLNAME => array('ID', 'CODE', 'TYPE', 'SERIALIZED_EFFECTS', 'IS_ENABLED', 'EXPIRATION_DATE', 'MAX_USAGE', 'IS_CUMULATIVE', 'IS_REMOVING_POSTAGE', 'IS_AVAILABLE_ON_SPECIAL_OFFERS', 'IS_USED', 'SERIALIZED_CONDITIONS', 'PER_CUSTOMER_USAGE_COUNT', 'CREATED_AT', 'UPDATED_AT', 'VERSION', 'VERSION_CREATED_AT', 'VERSION_CREATED_BY', ), + self::TYPE_FIELDNAME => array('id', 'code', 'type', 'serialized_effects', 'is_enabled', 'expiration_date', 'max_usage', 'is_cumulative', 'is_removing_postage', 'is_available_on_special_offers', 'is_used', 'serialized_conditions', 'per_customer_usage_count', 'created_at', 'updated_at', 'version', 'version_created_at', 'version_created_by', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, ) ); /** @@ -177,12 +187,12 @@ class CouponVersionTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'Code' => 1, 'Type' => 2, 'SerializedEffects' => 3, 'IsEnabled' => 4, 'ExpirationDate' => 5, 'MaxUsage' => 6, 'IsCumulative' => 7, 'IsRemovingPostage' => 8, 'IsAvailableOnSpecialOffers' => 9, 'IsUsed' => 10, 'SerializedConditions' => 11, 'PerCustomerUsageCount' => 12, 'CreatedAt' => 13, 'UpdatedAt' => 14, 'Version' => 15, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serializedEffects' => 3, 'isEnabled' => 4, 'expirationDate' => 5, 'maxUsage' => 6, 'isCumulative' => 7, 'isRemovingPostage' => 8, 'isAvailableOnSpecialOffers' => 9, 'isUsed' => 10, 'serializedConditions' => 11, 'perCustomerUsageCount' => 12, 'createdAt' => 13, 'updatedAt' => 14, 'version' => 15, ), - self::TYPE_COLNAME => array(CouponVersionTableMap::ID => 0, CouponVersionTableMap::CODE => 1, CouponVersionTableMap::TYPE => 2, CouponVersionTableMap::SERIALIZED_EFFECTS => 3, CouponVersionTableMap::IS_ENABLED => 4, CouponVersionTableMap::EXPIRATION_DATE => 5, CouponVersionTableMap::MAX_USAGE => 6, CouponVersionTableMap::IS_CUMULATIVE => 7, CouponVersionTableMap::IS_REMOVING_POSTAGE => 8, CouponVersionTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS => 9, CouponVersionTableMap::IS_USED => 10, CouponVersionTableMap::SERIALIZED_CONDITIONS => 11, CouponVersionTableMap::PER_CUSTOMER_USAGE_COUNT => 12, CouponVersionTableMap::CREATED_AT => 13, CouponVersionTableMap::UPDATED_AT => 14, CouponVersionTableMap::VERSION => 15, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'CODE' => 1, 'TYPE' => 2, 'SERIALIZED_EFFECTS' => 3, 'IS_ENABLED' => 4, 'EXPIRATION_DATE' => 5, 'MAX_USAGE' => 6, 'IS_CUMULATIVE' => 7, 'IS_REMOVING_POSTAGE' => 8, 'IS_AVAILABLE_ON_SPECIAL_OFFERS' => 9, 'IS_USED' => 10, 'SERIALIZED_CONDITIONS' => 11, 'PER_CUSTOMER_USAGE_COUNT' => 12, 'CREATED_AT' => 13, 'UPDATED_AT' => 14, 'VERSION' => 15, ), - self::TYPE_FIELDNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serialized_effects' => 3, 'is_enabled' => 4, 'expiration_date' => 5, 'max_usage' => 6, 'is_cumulative' => 7, 'is_removing_postage' => 8, 'is_available_on_special_offers' => 9, 'is_used' => 10, 'serialized_conditions' => 11, 'per_customer_usage_count' => 12, 'created_at' => 13, 'updated_at' => 14, 'version' => 15, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ) + self::TYPE_PHPNAME => array('Id' => 0, 'Code' => 1, 'Type' => 2, 'SerializedEffects' => 3, 'IsEnabled' => 4, 'ExpirationDate' => 5, 'MaxUsage' => 6, 'IsCumulative' => 7, 'IsRemovingPostage' => 8, 'IsAvailableOnSpecialOffers' => 9, 'IsUsed' => 10, 'SerializedConditions' => 11, 'PerCustomerUsageCount' => 12, 'CreatedAt' => 13, 'UpdatedAt' => 14, 'Version' => 15, 'VersionCreatedAt' => 16, 'VersionCreatedBy' => 17, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serializedEffects' => 3, 'isEnabled' => 4, 'expirationDate' => 5, 'maxUsage' => 6, 'isCumulative' => 7, 'isRemovingPostage' => 8, 'isAvailableOnSpecialOffers' => 9, 'isUsed' => 10, 'serializedConditions' => 11, 'perCustomerUsageCount' => 12, 'createdAt' => 13, 'updatedAt' => 14, 'version' => 15, 'versionCreatedAt' => 16, 'versionCreatedBy' => 17, ), + self::TYPE_COLNAME => array(CouponVersionTableMap::ID => 0, CouponVersionTableMap::CODE => 1, CouponVersionTableMap::TYPE => 2, CouponVersionTableMap::SERIALIZED_EFFECTS => 3, CouponVersionTableMap::IS_ENABLED => 4, CouponVersionTableMap::EXPIRATION_DATE => 5, CouponVersionTableMap::MAX_USAGE => 6, CouponVersionTableMap::IS_CUMULATIVE => 7, CouponVersionTableMap::IS_REMOVING_POSTAGE => 8, CouponVersionTableMap::IS_AVAILABLE_ON_SPECIAL_OFFERS => 9, CouponVersionTableMap::IS_USED => 10, CouponVersionTableMap::SERIALIZED_CONDITIONS => 11, CouponVersionTableMap::PER_CUSTOMER_USAGE_COUNT => 12, CouponVersionTableMap::CREATED_AT => 13, CouponVersionTableMap::UPDATED_AT => 14, CouponVersionTableMap::VERSION => 15, CouponVersionTableMap::VERSION_CREATED_AT => 16, CouponVersionTableMap::VERSION_CREATED_BY => 17, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'CODE' => 1, 'TYPE' => 2, 'SERIALIZED_EFFECTS' => 3, 'IS_ENABLED' => 4, 'EXPIRATION_DATE' => 5, 'MAX_USAGE' => 6, 'IS_CUMULATIVE' => 7, 'IS_REMOVING_POSTAGE' => 8, 'IS_AVAILABLE_ON_SPECIAL_OFFERS' => 9, 'IS_USED' => 10, 'SERIALIZED_CONDITIONS' => 11, 'PER_CUSTOMER_USAGE_COUNT' => 12, 'CREATED_AT' => 13, 'UPDATED_AT' => 14, 'VERSION' => 15, 'VERSION_CREATED_AT' => 16, 'VERSION_CREATED_BY' => 17, ), + self::TYPE_FIELDNAME => array('id' => 0, 'code' => 1, 'type' => 2, 'serialized_effects' => 3, 'is_enabled' => 4, 'expiration_date' => 5, 'max_usage' => 6, 'is_cumulative' => 7, 'is_removing_postage' => 8, 'is_available_on_special_offers' => 9, 'is_used' => 10, 'serialized_conditions' => 11, 'per_customer_usage_count' => 12, 'created_at' => 13, 'updated_at' => 14, 'version' => 15, 'version_created_at' => 16, 'version_created_by' => 17, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, ) ); /** @@ -217,6 +227,8 @@ class CouponVersionTableMap extends TableMap $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); $this->addPrimaryKey('VERSION', 'Version', 'INTEGER', true, null, 0); + $this->addColumn('VERSION_CREATED_AT', 'VersionCreatedAt', 'TIMESTAMP', false, null, null); + $this->addColumn('VERSION_CREATED_BY', 'VersionCreatedBy', 'VARCHAR', false, 100, null); } // initialize() /** @@ -430,6 +442,8 @@ class CouponVersionTableMap extends TableMap $criteria->addSelectColumn(CouponVersionTableMap::CREATED_AT); $criteria->addSelectColumn(CouponVersionTableMap::UPDATED_AT); $criteria->addSelectColumn(CouponVersionTableMap::VERSION); + $criteria->addSelectColumn(CouponVersionTableMap::VERSION_CREATED_AT); + $criteria->addSelectColumn(CouponVersionTableMap::VERSION_CREATED_BY); } else { $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.CODE'); @@ -447,6 +461,8 @@ class CouponVersionTableMap extends TableMap $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); $criteria->addSelectColumn($alias . '.VERSION'); + $criteria->addSelectColumn($alias . '.VERSION_CREATED_AT'); + $criteria->addSelectColumn($alias . '.VERSION_CREATED_BY'); } } diff --git a/core/lib/Thelia/Model/Map/CustomerTableMap.php b/core/lib/Thelia/Model/Map/CustomerTableMap.php index 794de006f..ca96ddaca 100644 --- a/core/lib/Thelia/Model/Map/CustomerTableMap.php +++ b/core/lib/Thelia/Model/Map/CustomerTableMap.php @@ -228,8 +228,8 @@ class CustomerTableMap extends TableMap $this->addRelation('Address', '\\Thelia\\Model\\Address', RelationMap::ONE_TO_MANY, array('id' => 'customer_id', ), 'CASCADE', 'RESTRICT', 'Addresses'); $this->addRelation('Order', '\\Thelia\\Model\\Order', RelationMap::ONE_TO_MANY, array('id' => 'customer_id', ), 'RESTRICT', 'RESTRICT', 'Orders'); $this->addRelation('Cart', '\\Thelia\\Model\\Cart', RelationMap::ONE_TO_MANY, array('id' => 'customer_id', ), 'CASCADE', 'RESTRICT', 'Carts'); - $this->addRelation('CouponCustomerCount', '\\Thelia\\Model\\CouponCustomerCount', RelationMap::ONE_TO_MANY, array('id' => 'customer_id', ), 'CASCADE', null, 'CouponCustomerCounts'); - $this->addRelation('Coupon', '\\Thelia\\Model\\Coupon', RelationMap::MANY_TO_MANY, array(), 'CASCADE', null, 'Coupons'); + $this->addRelation('CouponCustomerCount', '\\Thelia\\Model\\CouponCustomerCount', RelationMap::ONE_TO_MANY, array('id' => 'customer_id', ), 'CASCADE', 'RESTRICT', 'CouponCustomerCounts'); + $this->addRelation('Coupon', '\\Thelia\\Model\\Coupon', RelationMap::MANY_TO_MANY, array(), 'CASCADE', 'RESTRICT', 'Coupons'); } // buildRelations() /** diff --git a/core/lib/Thelia/Model/Map/ProductTableMap.php b/core/lib/Thelia/Model/Map/ProductTableMap.php index daba44213..3675ab7e0 100644 --- a/core/lib/Thelia/Model/Map/ProductTableMap.php +++ b/core/lib/Thelia/Model/Map/ProductTableMap.php @@ -58,7 +58,7 @@ class ProductTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 11; + const NUM_COLUMNS = 12; /** * The number of lazy-loaded columns @@ -68,7 +68,7 @@ class ProductTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 11; + const NUM_HYDRATE_COLUMNS = 12; /** * the column name for the ID field @@ -100,6 +100,11 @@ class ProductTableMap extends TableMap */ const TEMPLATE_ID = 'product.TEMPLATE_ID'; + /** + * the column name for the BRAND_ID field + */ + const BRAND_ID = 'product.BRAND_ID'; + /** * the column name for the CREATED_AT field */ @@ -146,12 +151,12 @@ class ProductTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'TaxRuleId', 'Ref', 'Visible', 'Position', 'TemplateId', 'CreatedAt', 'UpdatedAt', 'Version', 'VersionCreatedAt', 'VersionCreatedBy', ), - self::TYPE_STUDLYPHPNAME => array('id', 'taxRuleId', 'ref', 'visible', 'position', 'templateId', 'createdAt', 'updatedAt', 'version', 'versionCreatedAt', 'versionCreatedBy', ), - self::TYPE_COLNAME => array(ProductTableMap::ID, ProductTableMap::TAX_RULE_ID, ProductTableMap::REF, ProductTableMap::VISIBLE, ProductTableMap::POSITION, ProductTableMap::TEMPLATE_ID, ProductTableMap::CREATED_AT, ProductTableMap::UPDATED_AT, ProductTableMap::VERSION, ProductTableMap::VERSION_CREATED_AT, ProductTableMap::VERSION_CREATED_BY, ), - self::TYPE_RAW_COLNAME => array('ID', 'TAX_RULE_ID', 'REF', 'VISIBLE', 'POSITION', 'TEMPLATE_ID', 'CREATED_AT', 'UPDATED_AT', 'VERSION', 'VERSION_CREATED_AT', 'VERSION_CREATED_BY', ), - self::TYPE_FIELDNAME => array('id', 'tax_rule_id', 'ref', 'visible', 'position', 'template_id', 'created_at', 'updated_at', 'version', 'version_created_at', 'version_created_by', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ) + self::TYPE_PHPNAME => array('Id', 'TaxRuleId', 'Ref', 'Visible', 'Position', 'TemplateId', 'BrandId', 'CreatedAt', 'UpdatedAt', 'Version', 'VersionCreatedAt', 'VersionCreatedBy', ), + self::TYPE_STUDLYPHPNAME => array('id', 'taxRuleId', 'ref', 'visible', 'position', 'templateId', 'brandId', 'createdAt', 'updatedAt', 'version', 'versionCreatedAt', 'versionCreatedBy', ), + self::TYPE_COLNAME => array(ProductTableMap::ID, ProductTableMap::TAX_RULE_ID, ProductTableMap::REF, ProductTableMap::VISIBLE, ProductTableMap::POSITION, ProductTableMap::TEMPLATE_ID, ProductTableMap::BRAND_ID, ProductTableMap::CREATED_AT, ProductTableMap::UPDATED_AT, ProductTableMap::VERSION, ProductTableMap::VERSION_CREATED_AT, ProductTableMap::VERSION_CREATED_BY, ), + self::TYPE_RAW_COLNAME => array('ID', 'TAX_RULE_ID', 'REF', 'VISIBLE', 'POSITION', 'TEMPLATE_ID', 'BRAND_ID', 'CREATED_AT', 'UPDATED_AT', 'VERSION', 'VERSION_CREATED_AT', 'VERSION_CREATED_BY', ), + self::TYPE_FIELDNAME => array('id', 'tax_rule_id', 'ref', 'visible', 'position', 'template_id', 'brand_id', 'created_at', 'updated_at', 'version', 'version_created_at', 'version_created_by', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) ); /** @@ -161,12 +166,12 @@ class ProductTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'TaxRuleId' => 1, 'Ref' => 2, 'Visible' => 3, 'Position' => 4, 'TemplateId' => 5, 'CreatedAt' => 6, 'UpdatedAt' => 7, 'Version' => 8, 'VersionCreatedAt' => 9, 'VersionCreatedBy' => 10, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'taxRuleId' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'templateId' => 5, 'createdAt' => 6, 'updatedAt' => 7, 'version' => 8, 'versionCreatedAt' => 9, 'versionCreatedBy' => 10, ), - self::TYPE_COLNAME => array(ProductTableMap::ID => 0, ProductTableMap::TAX_RULE_ID => 1, ProductTableMap::REF => 2, ProductTableMap::VISIBLE => 3, ProductTableMap::POSITION => 4, ProductTableMap::TEMPLATE_ID => 5, ProductTableMap::CREATED_AT => 6, ProductTableMap::UPDATED_AT => 7, ProductTableMap::VERSION => 8, ProductTableMap::VERSION_CREATED_AT => 9, ProductTableMap::VERSION_CREATED_BY => 10, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'TAX_RULE_ID' => 1, 'REF' => 2, 'VISIBLE' => 3, 'POSITION' => 4, 'TEMPLATE_ID' => 5, 'CREATED_AT' => 6, 'UPDATED_AT' => 7, 'VERSION' => 8, 'VERSION_CREATED_AT' => 9, 'VERSION_CREATED_BY' => 10, ), - self::TYPE_FIELDNAME => array('id' => 0, 'tax_rule_id' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'template_id' => 5, 'created_at' => 6, 'updated_at' => 7, 'version' => 8, 'version_created_at' => 9, 'version_created_by' => 10, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ) + self::TYPE_PHPNAME => array('Id' => 0, 'TaxRuleId' => 1, 'Ref' => 2, 'Visible' => 3, 'Position' => 4, 'TemplateId' => 5, 'BrandId' => 6, 'CreatedAt' => 7, 'UpdatedAt' => 8, 'Version' => 9, 'VersionCreatedAt' => 10, 'VersionCreatedBy' => 11, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'taxRuleId' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'templateId' => 5, 'brandId' => 6, 'createdAt' => 7, 'updatedAt' => 8, 'version' => 9, 'versionCreatedAt' => 10, 'versionCreatedBy' => 11, ), + self::TYPE_COLNAME => array(ProductTableMap::ID => 0, ProductTableMap::TAX_RULE_ID => 1, ProductTableMap::REF => 2, ProductTableMap::VISIBLE => 3, ProductTableMap::POSITION => 4, ProductTableMap::TEMPLATE_ID => 5, ProductTableMap::BRAND_ID => 6, ProductTableMap::CREATED_AT => 7, ProductTableMap::UPDATED_AT => 8, ProductTableMap::VERSION => 9, ProductTableMap::VERSION_CREATED_AT => 10, ProductTableMap::VERSION_CREATED_BY => 11, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'TAX_RULE_ID' => 1, 'REF' => 2, 'VISIBLE' => 3, 'POSITION' => 4, 'TEMPLATE_ID' => 5, 'BRAND_ID' => 6, 'CREATED_AT' => 7, 'UPDATED_AT' => 8, 'VERSION' => 9, 'VERSION_CREATED_AT' => 10, 'VERSION_CREATED_BY' => 11, ), + self::TYPE_FIELDNAME => array('id' => 0, 'tax_rule_id' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'template_id' => 5, 'brand_id' => 6, 'created_at' => 7, 'updated_at' => 8, 'version' => 9, 'version_created_at' => 10, 'version_created_by' => 11, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) ); /** @@ -191,6 +196,7 @@ class ProductTableMap extends TableMap $this->addColumn('VISIBLE', 'Visible', 'TINYINT', true, null, 0); $this->addColumn('POSITION', 'Position', 'INTEGER', true, null, 0); $this->addForeignKey('TEMPLATE_ID', 'TemplateId', 'INTEGER', 'template', 'ID', false, null, null); + $this->addForeignKey('BRAND_ID', 'BrandId', 'INTEGER', 'brand', 'ID', false, null, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('VERSION', 'Version', 'INTEGER', false, null, 0); @@ -205,6 +211,7 @@ class ProductTableMap extends TableMap { $this->addRelation('TaxRule', '\\Thelia\\Model\\TaxRule', RelationMap::MANY_TO_ONE, array('tax_rule_id' => 'id', ), 'RESTRICT', 'RESTRICT'); $this->addRelation('Template', '\\Thelia\\Model\\Template', RelationMap::MANY_TO_ONE, array('template_id' => 'id', ), null, null); + $this->addRelation('Brand', '\\Thelia\\Model\\Brand', RelationMap::MANY_TO_ONE, array('brand_id' => 'id', ), 'SET NULL', null); $this->addRelation('ProductCategory', '\\Thelia\\Model\\ProductCategory', RelationMap::ONE_TO_MANY, array('id' => 'product_id', ), 'CASCADE', 'RESTRICT', 'ProductCategories'); $this->addRelation('FeatureProduct', '\\Thelia\\Model\\FeatureProduct', RelationMap::ONE_TO_MANY, array('id' => 'product_id', ), 'CASCADE', 'RESTRICT', 'FeatureProducts'); $this->addRelation('ProductSaleElements', '\\Thelia\\Model\\ProductSaleElements', RelationMap::ONE_TO_MANY, array('id' => 'product_id', ), 'CASCADE', 'RESTRICT', 'ProductSaleElementss'); @@ -398,6 +405,7 @@ class ProductTableMap extends TableMap $criteria->addSelectColumn(ProductTableMap::VISIBLE); $criteria->addSelectColumn(ProductTableMap::POSITION); $criteria->addSelectColumn(ProductTableMap::TEMPLATE_ID); + $criteria->addSelectColumn(ProductTableMap::BRAND_ID); $criteria->addSelectColumn(ProductTableMap::CREATED_AT); $criteria->addSelectColumn(ProductTableMap::UPDATED_AT); $criteria->addSelectColumn(ProductTableMap::VERSION); @@ -410,6 +418,7 @@ class ProductTableMap extends TableMap $criteria->addSelectColumn($alias . '.VISIBLE'); $criteria->addSelectColumn($alias . '.POSITION'); $criteria->addSelectColumn($alias . '.TEMPLATE_ID'); + $criteria->addSelectColumn($alias . '.BRAND_ID'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); $criteria->addSelectColumn($alias . '.VERSION'); diff --git a/core/lib/Thelia/Model/Map/ProductVersionTableMap.php b/core/lib/Thelia/Model/Map/ProductVersionTableMap.php index e3e36c8be..d8d22c2b7 100644 --- a/core/lib/Thelia/Model/Map/ProductVersionTableMap.php +++ b/core/lib/Thelia/Model/Map/ProductVersionTableMap.php @@ -58,7 +58,7 @@ class ProductVersionTableMap extends TableMap /** * The total number of columns */ - const NUM_COLUMNS = 11; + const NUM_COLUMNS = 12; /** * The number of lazy-loaded columns @@ -68,7 +68,7 @@ class ProductVersionTableMap extends TableMap /** * The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */ - const NUM_HYDRATE_COLUMNS = 11; + const NUM_HYDRATE_COLUMNS = 12; /** * the column name for the ID field @@ -100,6 +100,11 @@ class ProductVersionTableMap extends TableMap */ const TEMPLATE_ID = 'product_version.TEMPLATE_ID'; + /** + * the column name for the BRAND_ID field + */ + const BRAND_ID = 'product_version.BRAND_ID'; + /** * the column name for the CREATED_AT field */ @@ -137,12 +142,12 @@ class ProductVersionTableMap extends TableMap * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ protected static $fieldNames = array ( - self::TYPE_PHPNAME => array('Id', 'TaxRuleId', 'Ref', 'Visible', 'Position', 'TemplateId', 'CreatedAt', 'UpdatedAt', 'Version', 'VersionCreatedAt', 'VersionCreatedBy', ), - self::TYPE_STUDLYPHPNAME => array('id', 'taxRuleId', 'ref', 'visible', 'position', 'templateId', 'createdAt', 'updatedAt', 'version', 'versionCreatedAt', 'versionCreatedBy', ), - self::TYPE_COLNAME => array(ProductVersionTableMap::ID, ProductVersionTableMap::TAX_RULE_ID, ProductVersionTableMap::REF, ProductVersionTableMap::VISIBLE, ProductVersionTableMap::POSITION, ProductVersionTableMap::TEMPLATE_ID, ProductVersionTableMap::CREATED_AT, ProductVersionTableMap::UPDATED_AT, ProductVersionTableMap::VERSION, ProductVersionTableMap::VERSION_CREATED_AT, ProductVersionTableMap::VERSION_CREATED_BY, ), - self::TYPE_RAW_COLNAME => array('ID', 'TAX_RULE_ID', 'REF', 'VISIBLE', 'POSITION', 'TEMPLATE_ID', 'CREATED_AT', 'UPDATED_AT', 'VERSION', 'VERSION_CREATED_AT', 'VERSION_CREATED_BY', ), - self::TYPE_FIELDNAME => array('id', 'tax_rule_id', 'ref', 'visible', 'position', 'template_id', 'created_at', 'updated_at', 'version', 'version_created_at', 'version_created_by', ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ) + self::TYPE_PHPNAME => array('Id', 'TaxRuleId', 'Ref', 'Visible', 'Position', 'TemplateId', 'BrandId', 'CreatedAt', 'UpdatedAt', 'Version', 'VersionCreatedAt', 'VersionCreatedBy', ), + self::TYPE_STUDLYPHPNAME => array('id', 'taxRuleId', 'ref', 'visible', 'position', 'templateId', 'brandId', 'createdAt', 'updatedAt', 'version', 'versionCreatedAt', 'versionCreatedBy', ), + self::TYPE_COLNAME => array(ProductVersionTableMap::ID, ProductVersionTableMap::TAX_RULE_ID, ProductVersionTableMap::REF, ProductVersionTableMap::VISIBLE, ProductVersionTableMap::POSITION, ProductVersionTableMap::TEMPLATE_ID, ProductVersionTableMap::BRAND_ID, ProductVersionTableMap::CREATED_AT, ProductVersionTableMap::UPDATED_AT, ProductVersionTableMap::VERSION, ProductVersionTableMap::VERSION_CREATED_AT, ProductVersionTableMap::VERSION_CREATED_BY, ), + self::TYPE_RAW_COLNAME => array('ID', 'TAX_RULE_ID', 'REF', 'VISIBLE', 'POSITION', 'TEMPLATE_ID', 'BRAND_ID', 'CREATED_AT', 'UPDATED_AT', 'VERSION', 'VERSION_CREATED_AT', 'VERSION_CREATED_BY', ), + self::TYPE_FIELDNAME => array('id', 'tax_rule_id', 'ref', 'visible', 'position', 'template_id', 'brand_id', 'created_at', 'updated_at', 'version', 'version_created_at', 'version_created_by', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) ); /** @@ -152,12 +157,12 @@ class ProductVersionTableMap extends TableMap * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 */ protected static $fieldKeys = array ( - self::TYPE_PHPNAME => array('Id' => 0, 'TaxRuleId' => 1, 'Ref' => 2, 'Visible' => 3, 'Position' => 4, 'TemplateId' => 5, 'CreatedAt' => 6, 'UpdatedAt' => 7, 'Version' => 8, 'VersionCreatedAt' => 9, 'VersionCreatedBy' => 10, ), - self::TYPE_STUDLYPHPNAME => array('id' => 0, 'taxRuleId' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'templateId' => 5, 'createdAt' => 6, 'updatedAt' => 7, 'version' => 8, 'versionCreatedAt' => 9, 'versionCreatedBy' => 10, ), - self::TYPE_COLNAME => array(ProductVersionTableMap::ID => 0, ProductVersionTableMap::TAX_RULE_ID => 1, ProductVersionTableMap::REF => 2, ProductVersionTableMap::VISIBLE => 3, ProductVersionTableMap::POSITION => 4, ProductVersionTableMap::TEMPLATE_ID => 5, ProductVersionTableMap::CREATED_AT => 6, ProductVersionTableMap::UPDATED_AT => 7, ProductVersionTableMap::VERSION => 8, ProductVersionTableMap::VERSION_CREATED_AT => 9, ProductVersionTableMap::VERSION_CREATED_BY => 10, ), - self::TYPE_RAW_COLNAME => array('ID' => 0, 'TAX_RULE_ID' => 1, 'REF' => 2, 'VISIBLE' => 3, 'POSITION' => 4, 'TEMPLATE_ID' => 5, 'CREATED_AT' => 6, 'UPDATED_AT' => 7, 'VERSION' => 8, 'VERSION_CREATED_AT' => 9, 'VERSION_CREATED_BY' => 10, ), - self::TYPE_FIELDNAME => array('id' => 0, 'tax_rule_id' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'template_id' => 5, 'created_at' => 6, 'updated_at' => 7, 'version' => 8, 'version_created_at' => 9, 'version_created_by' => 10, ), - self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ) + self::TYPE_PHPNAME => array('Id' => 0, 'TaxRuleId' => 1, 'Ref' => 2, 'Visible' => 3, 'Position' => 4, 'TemplateId' => 5, 'BrandId' => 6, 'CreatedAt' => 7, 'UpdatedAt' => 8, 'Version' => 9, 'VersionCreatedAt' => 10, 'VersionCreatedBy' => 11, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'taxRuleId' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'templateId' => 5, 'brandId' => 6, 'createdAt' => 7, 'updatedAt' => 8, 'version' => 9, 'versionCreatedAt' => 10, 'versionCreatedBy' => 11, ), + self::TYPE_COLNAME => array(ProductVersionTableMap::ID => 0, ProductVersionTableMap::TAX_RULE_ID => 1, ProductVersionTableMap::REF => 2, ProductVersionTableMap::VISIBLE => 3, ProductVersionTableMap::POSITION => 4, ProductVersionTableMap::TEMPLATE_ID => 5, ProductVersionTableMap::BRAND_ID => 6, ProductVersionTableMap::CREATED_AT => 7, ProductVersionTableMap::UPDATED_AT => 8, ProductVersionTableMap::VERSION => 9, ProductVersionTableMap::VERSION_CREATED_AT => 10, ProductVersionTableMap::VERSION_CREATED_BY => 11, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'TAX_RULE_ID' => 1, 'REF' => 2, 'VISIBLE' => 3, 'POSITION' => 4, 'TEMPLATE_ID' => 5, 'BRAND_ID' => 6, 'CREATED_AT' => 7, 'UPDATED_AT' => 8, 'VERSION' => 9, 'VERSION_CREATED_AT' => 10, 'VERSION_CREATED_BY' => 11, ), + self::TYPE_FIELDNAME => array('id' => 0, 'tax_rule_id' => 1, 'ref' => 2, 'visible' => 3, 'position' => 4, 'template_id' => 5, 'brand_id' => 6, 'created_at' => 7, 'updated_at' => 8, 'version' => 9, 'version_created_at' => 10, 'version_created_by' => 11, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) ); /** @@ -182,6 +187,7 @@ class ProductVersionTableMap extends TableMap $this->addColumn('VISIBLE', 'Visible', 'TINYINT', true, null, 0); $this->addColumn('POSITION', 'Position', 'INTEGER', true, null, 0); $this->addColumn('TEMPLATE_ID', 'TemplateId', 'INTEGER', false, null, null); + $this->addColumn('BRAND_ID', 'BrandId', 'INTEGER', false, null, null); $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); $this->addPrimaryKey('VERSION', 'Version', 'INTEGER', true, null, 0); @@ -264,11 +270,11 @@ class ProductVersionTableMap extends TableMap 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 ? 8 + $offset : static::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)] === null) { + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 9 + $offset : static::translateFieldName('Version', 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 ? 8 + $offset : static::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)])); + return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 9 + $offset : static::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)])); } /** @@ -390,6 +396,7 @@ class ProductVersionTableMap extends TableMap $criteria->addSelectColumn(ProductVersionTableMap::VISIBLE); $criteria->addSelectColumn(ProductVersionTableMap::POSITION); $criteria->addSelectColumn(ProductVersionTableMap::TEMPLATE_ID); + $criteria->addSelectColumn(ProductVersionTableMap::BRAND_ID); $criteria->addSelectColumn(ProductVersionTableMap::CREATED_AT); $criteria->addSelectColumn(ProductVersionTableMap::UPDATED_AT); $criteria->addSelectColumn(ProductVersionTableMap::VERSION); @@ -402,6 +409,7 @@ class ProductVersionTableMap extends TableMap $criteria->addSelectColumn($alias . '.VISIBLE'); $criteria->addSelectColumn($alias . '.POSITION'); $criteria->addSelectColumn($alias . '.TEMPLATE_ID'); + $criteria->addSelectColumn($alias . '.BRAND_ID'); $criteria->addSelectColumn($alias . '.CREATED_AT'); $criteria->addSelectColumn($alias . '.UPDATED_AT'); $criteria->addSelectColumn($alias . '.VERSION'); diff --git a/local/config/schema.xml b/local/config/schema.xml index 9539cca25..11b653378 100644 --- a/local/config/schema.xml +++ b/local/config/schema.xml @@ -33,12 +33,13 @@ - + + @@ -48,6 +49,9 @@ + + + @@ -57,6 +61,9 @@ + + + @@ -105,6 +112,9 @@ + + + @@ -154,6 +164,11 @@ + + + + + @@ -213,6 +228,11 @@ + + + + +
@@ -232,6 +252,10 @@ + + + +
@@ -308,6 +332,11 @@ + + + + +
@@ -349,7 +378,7 @@
- + @@ -365,12 +394,12 @@ - - - + + +
@@ -435,6 +464,9 @@ + + +
@@ -493,6 +525,10 @@ + + + + @@ -520,7 +556,7 @@
- + @@ -601,6 +637,12 @@ + + + + + + @@ -696,6 +738,9 @@ + + + @@ -877,6 +922,7 @@ + @@ -1047,6 +1093,10 @@ + + + + @@ -1067,6 +1117,10 @@ + + + + @@ -1087,6 +1141,10 @@ + + + + @@ -1203,9 +1261,6 @@ - - - @@ -1246,6 +1301,10 @@ + + + + @@ -1291,6 +1350,7 @@ + @@ -1299,4 +1359,136 @@
+ + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
diff --git a/local/modules/Tinymce/AdminIncludes/brand-edit-js.html b/local/modules/Tinymce/AdminIncludes/brand-edit-js.html new file mode 100644 index 000000000..8e2952d56 --- /dev/null +++ b/local/modules/Tinymce/AdminIncludes/brand-edit-js.html @@ -0,0 +1 @@ +{include file="includes/tinymce_init.tpl"} \ No newline at end of file diff --git a/setup/insert.sql b/setup/insert.sql index d5ae99111..f7217a52f 100644 --- a/setup/insert.sql +++ b/setup/insert.sql @@ -1289,7 +1289,8 @@ INSERT INTO resource (`id`, `code`, `created_at`, `updated_at`) VALUES (31, 'admin.configuration.advanced', NOW(), NOW()), (32, 'admin.configuration.translations', NOW(), NOW()), (33, 'admin.export', NOW(), NOW()), -(34, 'admin.tools', NOW(), NOW()); +(34, 'admin.tools', NOW(), NOW()), +(35, 'admin.brand', NOW(), NOW()); /** generated with command : php Thelia thelia:generate-resources --output sql-i18n diff --git a/setup/thelia.sql b/setup/thelia.sql index 97c3b75c3..2c7809d99 100644 --- a/setup/thelia.sql +++ b/setup/thelia.sql @@ -23,7 +23,7 @@ CREATE TABLE `category` PRIMARY KEY (`id`), INDEX `idx_parent` (`parent`), INDEX `idx_parent_position` (`parent`, `position`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- product @@ -39,6 +39,7 @@ CREATE TABLE `product` `visible` TINYINT DEFAULT 0 NOT NULL, `position` INTEGER DEFAULT 0 NOT NULL, `template_id` INTEGER, + `brand_id` INTEGER, `created_at` DATETIME, `updated_at` DATETIME, `version` INTEGER DEFAULT 0, @@ -48,6 +49,7 @@ CREATE TABLE `product` UNIQUE INDEX `ref_UNIQUE` (`ref`), INDEX `idx_product_tax_rule_id` (`tax_rule_id`), INDEX `fk_product_template_id` (`template_id`), + INDEX `fk_product_brand1_idx` (`brand_id`), CONSTRAINT `fk_product_tax_rule_id` FOREIGN KEY (`tax_rule_id`) REFERENCES `tax_rule` (`id`) @@ -55,8 +57,12 @@ CREATE TABLE `product` ON DELETE RESTRICT, CONSTRAINT `fk_product_template` FOREIGN KEY (`template_id`) - REFERENCES `template` (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; + REFERENCES `template` (`id`), + CONSTRAINT `fk_product_brand` + FOREIGN KEY (`brand_id`) + REFERENCES `brand` (`id`) + ON DELETE SET NULL +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- product_category @@ -85,7 +91,7 @@ CREATE TABLE `product_category` REFERENCES `category` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- country @@ -112,7 +118,7 @@ CREATE TABLE `country` REFERENCES `area` (`id`) ON UPDATE RESTRICT ON DELETE SET NULL -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- tax @@ -128,7 +134,7 @@ CREATE TABLE `tax` `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- tax_rule @@ -143,7 +149,7 @@ CREATE TABLE `tax_rule` `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- tax_rule_country @@ -179,7 +185,7 @@ CREATE TABLE `tax_rule_country` REFERENCES `country` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- feature @@ -195,7 +201,7 @@ CREATE TABLE `feature` `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- feature_av @@ -217,7 +223,7 @@ CREATE TABLE `feature_av` REFERENCES `feature` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- feature_product @@ -255,7 +261,7 @@ CREATE TABLE `feature_product` REFERENCES `feature_av` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- feature_template @@ -283,7 +289,7 @@ CREATE TABLE `feature_template` CONSTRAINT `fk_feature_template` FOREIGN KEY (`template_id`) REFERENCES `template` (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- attribute @@ -298,7 +304,7 @@ CREATE TABLE `attribute` `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- attribute_av @@ -320,7 +326,7 @@ CREATE TABLE `attribute_av` REFERENCES `attribute` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- attribute_combination @@ -354,7 +360,7 @@ CREATE TABLE `attribute_combination` REFERENCES `product_sale_elements` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- product_sale_elements @@ -384,7 +390,7 @@ CREATE TABLE `product_sale_elements` REFERENCES `product` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- attribute_template @@ -411,7 +417,7 @@ CREATE TABLE `attribute_template` CONSTRAINT `fk_attribute_template` FOREIGN KEY (`template_id`) REFERENCES `template` (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- config @@ -430,7 +436,7 @@ CREATE TABLE `config` `updated_at` DATETIME, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- customer @@ -464,7 +470,7 @@ CREATE TABLE `customer` REFERENCES `customer_title` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- address @@ -511,7 +517,7 @@ CREATE TABLE `address` REFERENCES `country` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- customer_title @@ -527,7 +533,7 @@ CREATE TABLE `customer_title` `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- lang @@ -554,7 +560,7 @@ CREATE TABLE `lang` `updated_at` DATETIME, PRIMARY KEY (`id`), INDEX `idx_lang_by_default` (`by_default`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- folder @@ -574,7 +580,7 @@ CREATE TABLE `folder` `version_created_at` DATETIME, `version_created_by` VARCHAR(100), PRIMARY KEY (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- content @@ -593,7 +599,7 @@ CREATE TABLE `content` `version_created_at` DATETIME, `version_created_by` VARCHAR(100), PRIMARY KEY (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- product_image @@ -617,7 +623,7 @@ CREATE TABLE `product_image` REFERENCES `product` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- product_document @@ -640,7 +646,7 @@ CREATE TABLE `product_document` REFERENCES `product` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- order @@ -722,7 +728,7 @@ CREATE TABLE `order` REFERENCES `lang` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- currency @@ -743,7 +749,7 @@ CREATE TABLE `currency` PRIMARY KEY (`id`), INDEX `idx_currency_by_default` (`by_default`), INDEX `idx_currency_code` (`code`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- order_address @@ -768,7 +774,7 @@ CREATE TABLE `order_address` `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- order_product @@ -805,7 +811,7 @@ CREATE TABLE `order_product` REFERENCES `order` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- order_status @@ -821,7 +827,7 @@ CREATE TABLE `order_status` `updated_at` DATETIME, PRIMARY KEY (`id`), UNIQUE INDEX `code_UNIQUE` (`code`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- order_product_attribute_combination @@ -850,7 +856,7 @@ CREATE TABLE `order_product_attribute_combination` REFERENCES `order_product` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- module @@ -871,7 +877,7 @@ CREATE TABLE `module` PRIMARY KEY (`id`), UNIQUE INDEX `code_UNIQUE` (`code`), INDEX `idx_module_activate` (`activate`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- accessory @@ -900,7 +906,7 @@ CREATE TABLE `accessory` REFERENCES `product` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- area @@ -916,7 +922,7 @@ CREATE TABLE `area` `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- area_delivery_module @@ -945,7 +951,7 @@ CREATE TABLE `area_delivery_module` REFERENCES `module` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- profile @@ -961,7 +967,7 @@ CREATE TABLE `profile` `updated_at` DATETIME, PRIMARY KEY (`id`), UNIQUE INDEX `code_UNIQUE` (`code`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- resource @@ -977,7 +983,7 @@ CREATE TABLE `resource` `updated_at` DATETIME, PRIMARY KEY (`id`), UNIQUE INDEX `code_UNIQUE` (`code`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- admin @@ -1008,7 +1014,7 @@ CREATE TABLE `admin` REFERENCES `profile` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- profile_resource @@ -1036,7 +1042,7 @@ CREATE TABLE `profile_resource` REFERENCES `resource` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- profile_module @@ -1064,7 +1070,7 @@ CREATE TABLE `profile_module` REFERENCES `module` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- message @@ -1088,7 +1094,7 @@ CREATE TABLE `message` `version_created_by` VARCHAR(100), PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- coupon @@ -1114,6 +1120,8 @@ CREATE TABLE `coupon` `created_at` DATETIME, `updated_at` DATETIME, `version` INTEGER DEFAULT 0, + `version_created_at` DATETIME, + `version_created_by` VARCHAR(100), PRIMARY KEY (`id`), UNIQUE INDEX `code_UNIQUE` (`code`), INDEX `idx_is_enabled` (`is_enabled`), @@ -1124,7 +1132,7 @@ CREATE TABLE `coupon` INDEX `idx_is_removing_postage` (`is_removing_postage`), INDEX `idx_max_usage` (`max_usage`), INDEX `idx_is_available_on_special_offers` (`is_available_on_special_offers`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- admin_log @@ -1145,7 +1153,7 @@ CREATE TABLE `admin_log` `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- content_folder @@ -1174,7 +1182,7 @@ CREATE TABLE `content_folder` REFERENCES `folder` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- cart @@ -1219,7 +1227,7 @@ CREATE TABLE `cart` REFERENCES `currency` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- cart_item @@ -1259,7 +1267,7 @@ CREATE TABLE `cart_item` REFERENCES `product_sale_elements` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- product_price @@ -1287,7 +1295,7 @@ CREATE TABLE `product_price` FOREIGN KEY (`currency_id`) REFERENCES `currency` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- category_image @@ -1311,7 +1319,7 @@ CREATE TABLE `category_image` REFERENCES `category` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- folder_image @@ -1335,7 +1343,7 @@ CREATE TABLE `folder_image` REFERENCES `folder` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- content_image @@ -1359,7 +1367,7 @@ CREATE TABLE `content_image` REFERENCES `content` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- category_document @@ -1382,7 +1390,7 @@ CREATE TABLE `category_document` REFERENCES `category` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- content_document @@ -1405,7 +1413,7 @@ CREATE TABLE `content_document` REFERENCES `content` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- folder_document @@ -1428,7 +1436,7 @@ CREATE TABLE `folder_document` REFERENCES `folder` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- product_associated_content @@ -1457,7 +1465,7 @@ CREATE TABLE `product_associated_content` REFERENCES `content` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- category_associated_content @@ -1486,7 +1494,7 @@ CREATE TABLE `category_associated_content` REFERENCES `content` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- rewriting_url @@ -1512,7 +1520,7 @@ CREATE TABLE `rewriting_url` REFERENCES `rewriting_url` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- rewriting_argument @@ -1534,7 +1542,7 @@ CREATE TABLE `rewriting_argument` REFERENCES `rewriting_url` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- template @@ -1548,7 +1556,7 @@ CREATE TABLE `template` `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- module_image @@ -1572,7 +1580,7 @@ CREATE TABLE `module_image` REFERENCES `module` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- order_product_tax @@ -1597,7 +1605,7 @@ CREATE TABLE `order_product_tax` REFERENCES `order_product` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- newsletter @@ -1616,7 +1624,7 @@ CREATE TABLE `newsletter` `updated_at` DATETIME, PRIMARY KEY (`id`), UNIQUE INDEX `email_UNIQUE` (`email`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- order_coupon @@ -1649,7 +1657,7 @@ CREATE TABLE `order_coupon` REFERENCES `order` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- coupon_country @@ -1671,7 +1679,7 @@ CREATE TABLE `coupon_country` FOREIGN KEY (`coupon_id`) REFERENCES `coupon` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- coupon_module @@ -1693,7 +1701,7 @@ CREATE TABLE `coupon_module` FOREIGN KEY (`module_id`) REFERENCES `module` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- order_coupon_country @@ -1714,7 +1722,7 @@ CREATE TABLE `order_coupon_country` CONSTRAINT `fk_order_coupon_country_coupon_id` FOREIGN KEY (`coupon_id`) REFERENCES `order_coupon` (`id`) -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- order_coupon_module @@ -1736,7 +1744,7 @@ CREATE TABLE `order_coupon_module` FOREIGN KEY (`module_id`) REFERENCES `module` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- coupon_customer_count @@ -1754,12 +1762,83 @@ CREATE TABLE `coupon_customer_count` CONSTRAINT `fk_coupon_customer_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`) + ON UPDATE RESTRICT ON DELETE CASCADE, CONSTRAINT `fk_coupon_customer_coupon_id` FOREIGN KEY (`coupon_id`) REFERENCES `coupon` (`id`) + ON UPDATE RESTRICT ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- brand +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `brand`; + +CREATE TABLE `brand` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `visible` TINYINT, + `position` INTEGER, + `logo_image_id` INTEGER, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + INDEX `fk_brand_brand_image_idx` (`logo_image_id`), + CONSTRAINT `fk_logo_image_id_brand_image` + FOREIGN KEY (`logo_image_id`) + REFERENCES `brand_image` (`id`) + ON UPDATE RESTRICT + ON DELETE SET NULL +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- brand_document +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `brand_document`; + +CREATE TABLE `brand_document` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `brand_id` INTEGER NOT NULL, + `file` VARCHAR(255) NOT NULL, + `position` INTEGER, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + INDEX `idx_brand_document_brand_id` (`brand_id`), + CONSTRAINT `fk_brand_document_brand_id` + FOREIGN KEY (`brand_id`) + REFERENCES `brand` (`id`) + ON UPDATE RESTRICT + ON DELETE CASCADE +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- brand_image +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `brand_image`; + +CREATE TABLE `brand_image` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `brand_id` INTEGER NOT NULL, + `file` VARCHAR(255) NOT NULL, + `position` INTEGER, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + INDEX `idx_brand_image_brand_id` (`brand_id`), + CONSTRAINT `fk_brand_image_brand_id` + FOREIGN KEY (`brand_id`) + REFERENCES `brand` (`id`) + ON UPDATE RESTRICT + ON DELETE CASCADE +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- category_i18n @@ -1783,7 +1862,7 @@ CREATE TABLE `category_i18n` FOREIGN KEY (`id`) REFERENCES `category` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- product_i18n @@ -1807,7 +1886,7 @@ CREATE TABLE `product_i18n` FOREIGN KEY (`id`) REFERENCES `product` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- country_i18n @@ -1828,7 +1907,7 @@ CREATE TABLE `country_i18n` FOREIGN KEY (`id`) REFERENCES `country` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- tax_i18n @@ -1847,7 +1926,7 @@ CREATE TABLE `tax_i18n` FOREIGN KEY (`id`) REFERENCES `tax` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- tax_rule_i18n @@ -1866,7 +1945,7 @@ CREATE TABLE `tax_rule_i18n` FOREIGN KEY (`id`) REFERENCES `tax_rule` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- feature_i18n @@ -1887,7 +1966,7 @@ CREATE TABLE `feature_i18n` FOREIGN KEY (`id`) REFERENCES `feature` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- feature_av_i18n @@ -1908,7 +1987,7 @@ CREATE TABLE `feature_av_i18n` FOREIGN KEY (`id`) REFERENCES `feature_av` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- attribute_i18n @@ -1929,7 +2008,7 @@ CREATE TABLE `attribute_i18n` FOREIGN KEY (`id`) REFERENCES `attribute` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- attribute_av_i18n @@ -1950,7 +2029,7 @@ CREATE TABLE `attribute_av_i18n` FOREIGN KEY (`id`) REFERENCES `attribute_av` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- config_i18n @@ -1971,7 +2050,7 @@ CREATE TABLE `config_i18n` FOREIGN KEY (`id`) REFERENCES `config` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- customer_title_i18n @@ -1990,7 +2069,7 @@ CREATE TABLE `customer_title_i18n` FOREIGN KEY (`id`) REFERENCES `customer_title` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- folder_i18n @@ -2014,7 +2093,7 @@ CREATE TABLE `folder_i18n` FOREIGN KEY (`id`) REFERENCES `folder` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- content_i18n @@ -2038,7 +2117,7 @@ CREATE TABLE `content_i18n` FOREIGN KEY (`id`) REFERENCES `content` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- product_image_i18n @@ -2059,7 +2138,7 @@ CREATE TABLE `product_image_i18n` FOREIGN KEY (`id`) REFERENCES `product_image` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- product_document_i18n @@ -2080,7 +2159,7 @@ CREATE TABLE `product_document_i18n` FOREIGN KEY (`id`) REFERENCES `product_document` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- currency_i18n @@ -2098,7 +2177,7 @@ CREATE TABLE `currency_i18n` FOREIGN KEY (`id`) REFERENCES `currency` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- order_status_i18n @@ -2119,7 +2198,7 @@ CREATE TABLE `order_status_i18n` FOREIGN KEY (`id`) REFERENCES `order_status` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- module_i18n @@ -2140,7 +2219,7 @@ CREATE TABLE `module_i18n` FOREIGN KEY (`id`) REFERENCES `module` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- profile_i18n @@ -2161,7 +2240,7 @@ CREATE TABLE `profile_i18n` FOREIGN KEY (`id`) REFERENCES `profile` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- resource_i18n @@ -2182,7 +2261,7 @@ CREATE TABLE `resource_i18n` FOREIGN KEY (`id`) REFERENCES `resource` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- message_i18n @@ -2203,7 +2282,7 @@ CREATE TABLE `message_i18n` FOREIGN KEY (`id`) REFERENCES `message` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- coupon_i18n @@ -2223,7 +2302,7 @@ CREATE TABLE `coupon_i18n` FOREIGN KEY (`id`) REFERENCES `coupon` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- category_image_i18n @@ -2244,7 +2323,7 @@ CREATE TABLE `category_image_i18n` FOREIGN KEY (`id`) REFERENCES `category_image` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- folder_image_i18n @@ -2265,7 +2344,7 @@ CREATE TABLE `folder_image_i18n` FOREIGN KEY (`id`) REFERENCES `folder_image` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- content_image_i18n @@ -2286,7 +2365,7 @@ CREATE TABLE `content_image_i18n` FOREIGN KEY (`id`) REFERENCES `content_image` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- category_document_i18n @@ -2307,7 +2386,7 @@ CREATE TABLE `category_document_i18n` FOREIGN KEY (`id`) REFERENCES `category_document` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- content_document_i18n @@ -2328,7 +2407,7 @@ CREATE TABLE `content_document_i18n` FOREIGN KEY (`id`) REFERENCES `content_document` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- folder_document_i18n @@ -2349,7 +2428,7 @@ CREATE TABLE `folder_document_i18n` FOREIGN KEY (`id`) REFERENCES `folder_document` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- template_i18n @@ -2367,7 +2446,7 @@ CREATE TABLE `template_i18n` FOREIGN KEY (`id`) REFERENCES `template` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- module_image_i18n @@ -2388,7 +2467,73 @@ CREATE TABLE `module_image_i18n` FOREIGN KEY (`id`) REFERENCES `module_image` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- brand_i18n +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `brand_i18n`; + +CREATE TABLE `brand_i18n` +( + `id` INTEGER NOT NULL, + `locale` VARCHAR(5) DEFAULT 'en_US' NOT NULL, + `title` VARCHAR(255), + `description` LONGTEXT, + `chapo` TEXT, + `postscriptum` TEXT, + `meta_title` VARCHAR(255), + `meta_description` TEXT, + `meta_keywords` TEXT, + PRIMARY KEY (`id`,`locale`), + CONSTRAINT `brand_i18n_FK_1` + FOREIGN KEY (`id`) + REFERENCES `brand` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- brand_document_i18n +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `brand_document_i18n`; + +CREATE TABLE `brand_document_i18n` +( + `id` INTEGER NOT NULL, + `locale` VARCHAR(5) DEFAULT 'en_US' NOT NULL, + `title` VARCHAR(255), + `description` LONGTEXT, + `chapo` TEXT, + `postscriptum` TEXT, + PRIMARY KEY (`id`,`locale`), + CONSTRAINT `brand_document_i18n_FK_1` + FOREIGN KEY (`id`) + REFERENCES `brand_document` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- brand_image_i18n +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `brand_image_i18n`; + +CREATE TABLE `brand_image_i18n` +( + `id` INTEGER NOT NULL, + `locale` VARCHAR(5) DEFAULT 'en_US' NOT NULL, + `title` VARCHAR(255), + `description` LONGTEXT, + `chapo` TEXT, + `postscriptum` TEXT, + PRIMARY KEY (`id`,`locale`), + CONSTRAINT `brand_image_i18n_FK_1` + FOREIGN KEY (`id`) + REFERENCES `brand_image` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- category_version @@ -2412,7 +2557,7 @@ CREATE TABLE `category_version` FOREIGN KEY (`id`) REFERENCES `category` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- product_version @@ -2428,6 +2573,7 @@ CREATE TABLE `product_version` `visible` TINYINT DEFAULT 0 NOT NULL, `position` INTEGER DEFAULT 0 NOT NULL, `template_id` INTEGER, + `brand_id` INTEGER, `created_at` DATETIME, `updated_at` DATETIME, `version` INTEGER DEFAULT 0 NOT NULL, @@ -2438,7 +2584,7 @@ CREATE TABLE `product_version` FOREIGN KEY (`id`) REFERENCES `product` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- folder_version @@ -2462,7 +2608,7 @@ CREATE TABLE `folder_version` FOREIGN KEY (`id`) REFERENCES `folder` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- content_version @@ -2485,7 +2631,7 @@ CREATE TABLE `content_version` FOREIGN KEY (`id`) REFERENCES `content` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- order_version @@ -2522,7 +2668,7 @@ CREATE TABLE `order_version` FOREIGN KEY (`id`) REFERENCES `order` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- message_version @@ -2549,7 +2695,7 @@ CREATE TABLE `message_version` FOREIGN KEY (`id`) REFERENCES `message` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- coupon_version @@ -2575,12 +2721,14 @@ CREATE TABLE `coupon_version` `created_at` DATETIME, `updated_at` DATETIME, `version` INTEGER DEFAULT 0 NOT NULL, + `version_created_at` DATETIME, + `version_created_by` VARCHAR(100), PRIMARY KEY (`id`,`version`), CONSTRAINT `coupon_version_FK_1` FOREIGN KEY (`id`) REFERENCES `coupon` (`id`) ON DELETE CASCADE -) ENGINE=InnoDB CHARACTER SET='utf8'; +) ENGINE=InnoDB; # This restores the fkey checks, after having unset them earlier SET FOREIGN_KEY_CHECKS = 1; diff --git a/setup/update/2.0.3.sql b/setup/update/2.0.3.sql index cde550b0e..230c3e1cf 100644 --- a/setup/update/2.0.3.sql +++ b/setup/update/2.0.3.sql @@ -46,7 +46,104 @@ CREATE TABLE `order_version` ) ENGINE=InnoDB CHARACTER SET='utf8'; # Add missing columns to coupon (version_created_at, version_created_by) -ALTER TABLE `order` ADD `version_created_at` DATE AFTER `version`; -ALTER TABLE `order` ADD `version_created_by` VARCHAR(100) AFTER `version_created_at`; +ALTER TABLE `coupon` ADD `version_created_at` DATE AFTER `version`; +ALTER TABLE `coupon` ADD `version_created_by` VARCHAR(100) AFTER `version_created_at`; + +# Add the "brand" resource +INSERT INTO resource (`code`, `created_at`, `updated_at`) VALUES ('admin.brand', NOW(), NOW()); + +# Add Brand tables + +-- --------------------------------------------------------------------- +-- brand +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `brand`; + +CREATE TABLE `brand` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `visible` TINYINT, + `title` VARCHAR(255), + `description` LONGTEXT, + `chapo` TEXT, + `postscriptum` TEXT, + `meta_title` VARCHAR(255), + `meta_description` TEXT, + `meta_keywords` TEXT, + `logo_image_id` INTEGER, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + INDEX `fk_brand_brand_image1_idx` (`logo_image_id`), + CONSTRAINT `fk_logo_image_id_brand_image` + FOREIGN KEY (`logo_image_id`) + REFERENCES `brand_image` (`id`) + ON UPDATE RESTRICT + ON DELETE SET NULL +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- brand_document +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `brand_document`; + +CREATE TABLE `brand_document` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `brand_id` INTEGER NOT NULL, + `file` VARCHAR(255) NOT NULL, + `position` INTEGER, + `title` VARCHAR(255), + `description` LONGTEXT, + `chapo` TEXT, + `postscriptum` TEXT, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + INDEX `idx_brand_document_brand_id` (`brand_id`), + CONSTRAINT `fk_brand_document_brand_id` + FOREIGN KEY (`brand_id`) + REFERENCES `brand` (`id`) + ON UPDATE RESTRICT + ON DELETE CASCADE +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- brand_image +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `brand_image`; + +CREATE TABLE `brand_image` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `brand_id` INTEGER NOT NULL, + `file` VARCHAR(255) NOT NULL, + `position` INTEGER, + `title` VARCHAR(255), + `description` LONGTEXT, + `chapo` TEXT, + `postscriptum` TEXT, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + INDEX `idx_brand_image_brand_id` (`brand_id`), + INDEX `idx_brand_image_brand_id_is_brand_logo` (`brand_id`), + CONSTRAINT `fk_brand_image_brand_id` + FOREIGN KEY (`brand_id`) + REFERENCES `brand` (`id`) + ON UPDATE RESTRICT + ON DELETE CASCADE +) ENGINE=InnoDB; + + +-- --------------------------------------------------------- +-- Add brand field to product table, and related constraint. +-- --------------------------------------------------------- + +ALTER TABLE `product` ADD `brand_id` INTEGER DEFAULT 0 AFTER `template_id`; +ALTER TABLE `product` ADD CONSTRAINT `fk_product_brand` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`) ON DELETE SET NULL; SET FOREIGN_KEY_CHECKS = 1; \ No newline at end of file diff --git a/templates/backOffice/default/brand-edit.html b/templates/backOffice/default/brand-edit.html new file mode 100644 index 000000000..30c930a0c --- /dev/null +++ b/templates/backOffice/default/brand-edit.html @@ -0,0 +1,178 @@ +{extends file="admin-layout.tpl"} + +{block name="no-return-functions"} + {$admin_current_location = 'tools'} +{/block} + +{block name="check-resource"}admin.brand{/block} +{block name="check-access"}view{/block} + +{block name="page-title"}{intl l='Edit brand'}{/block} + +{block name="main-content"} +
+
+ {loop name="brand_edit" type="brand" visible="*" id="{$brand_id}" backend_context="1" lang="$edit_language_id"} + + + +
+
+
+
+ {intl l='Edit brand %title' title={$TITLE}} +
+
+ +
+
+ + + +
+ +
+ +
+ + {form name="thelia.admin.brand.modification"} + + + + {include file="includes/inner-form-toolbar.html" close_url={url path='/admin/brand'}} + + + + {* Be sure to get the currency ID, even if the form could not be validated *} + + + {form_hidden_fields form=$form} + + {admin_form_field form=$form name="success_url" value={url path="/admin/brand/update/{$ID}"}} + {admin_form_field form=$form name="locale" value={$edit_language_locale}} + + {if $form_error} +
{$form_error_message}
+ {/if} + +
+
+ {include file="includes/standard-description-form-fields.html"} +
+ +
+ {admin_form_field form=$form name="visible"} +
+
+ + {include + file="includes/inner-form-toolbar.html" + hide_submit_buttons = false + hide_flags = true + + close_url={url path="/admin/brand"} + } + + {intl l='Brand created on %date_create. Last modification: %date_change' date_create={format_date date=$CREATE_DATE} date_change={format_date date=$UPDATE_DATE} } + + {/form} +
+
+ +
+ {form name="thelia.admin.seo"} + {include + file = "includes/seo-tab.html" + form = $form + formAction = {url path='/admin/brand/seo/save'} + closeUrl = {url path='/admin/brand'} + current_id = $brand_id + } + {/form} +
+ +
+ {include file='includes/image-upload-form.html' imageType='brand' parentId=$brand_id} +
+ +
+ {include file='includes/document-upload-form.html' documentType='brand' parentId=$brand_id} +
+ +
+
+ {include + file = "includes/inner-form-toolbar.html" + hide_submit_buttons = true + page_url = {$pageUrl} + close_url = {$closeUrl} + current_tab = "modules" + } +
+ + {include file="includes/module-tab-content.html" location="brand-edit"} +
+
+
+
+
+
+ {/loop} +
+
+ {/block} + + + +{block name="javascript-initialization"} + {javascripts file='assets/js/dropzone.js'} + + {/javascripts} + {javascripts file='assets/js/image-upload.js'} + + {/javascripts} + {javascripts file='assets/js/document-upload.js'} + + {/javascripts} + {javascripts file='assets/js/jquery-ui-1.10.3.custom.min.js'} + + {/javascripts} + +{/block} + +{block name="javascript-last-call"} + {module_include location='brand-edit-js'} +{/block} \ No newline at end of file diff --git a/templates/backOffice/default/brands.html b/templates/backOffice/default/brands.html new file mode 100644 index 000000000..361033606 --- /dev/null +++ b/templates/backOffice/default/brands.html @@ -0,0 +1,304 @@ +{extends file="admin-layout.tpl"} + +{block name="no-return-functions"} + {$admin_current_location = 'tools'} +{/block} + +{block name="page-title"}{intl l='Brands'}{/block} + +{block name="check-resource"}admin.brand{/block} +{block name="check-access"}view{/block} + +{block name="main-content"} +
+ +
+ + + + {module_include location='brands_top'} + +
+
+ +
+
+ + + + + + + + + + + + + + + + {module_include location='brands_table_header'} + + + + + + + {loop name="brands" type="brand" visible="*" backend_context="1" lang=$lang_id order=$order} + + + + + + + + + + + + {module_include location='brands_table_row'} + + + + {/loop} + {elseloop rel="brands"} + + + + {/elseloop} + +
+ {intl l='Brands'} + {loop type="auth" name="can_create" role="ADMIN" resource="admin.brand" access="CREATE"} + + + + + + {/loop} +
+ {admin_sortable_header + current_order=$order + order='id' + reverse_order='id-reverse' + path='/admin/brands' + label="{intl l='ID'}" + } +   + {admin_sortable_header + current_order=$order + order='alpha' + reverse_order='alpha-reverse' + path='/admin/brand' + label="{intl l='Name'}" + } + + {admin_sortable_header + current_order=$order + order='manual' + reverse_order='manual-reverse' + path='/admin/brand' + label="{intl l="Position"}" + } + + {admin_sortable_header + current_order=$content_order + order='visible' + reverse_order='visible-reverse' + path={url path='/admin/brand'} + label="{intl l='Online'}" + } + {intl l='Actions'}
{$ID} + {loop type="image" name="folder_image" source="brand" source_id="$ID" limit="1" width="50" height="50" resize_mode="crop" backend_context="1"} + + {$TITLE} + + {/loop} + + {loop type="auth" name="can_change" role="ADMIN" resource="admin.brand" access="UPDATE"} + {$TITLE} + {/loop} + {elseloop rel="can_change"} + {$TITLE} + {/elseloop} + + {admin_position_block + resource="admin.brand" + access="UPDATE" + path="/admin/brand/update-position" + url_parameter="brand_id" + in_place_edit_class="brandPositionChange" + position="$POSITION" + id="$ID" + } + + {loop type="auth" name="can_change" role="ADMIN" resource="admin.brand" access="UPDATE"} +
+ +
+ {/loop} + + {elseloop rel="can_change"} +
+ +
+ {/elseloop} +
+
+ {loop type="auth" name="can_change" role="ADMIN" resource="admin.brand" access="UPDATE"} + + + + {/loop} + + {loop type="auth" name="can_delete" role="ADMIN" resource="admin.brand" access="DELETE"} + + + + {/loop} +
+
+
+ {intl l="No brand has been created yet. Click the + button to create one."} +
+
+
+
+
+
+ + {module_include location='brands_bottom'} + +
+
+ + + {* Adding a new brand *} + + {form name="thelia.admin.brand.creation"} + + {* Capture the dialog body, to pass it to the generic dialog *} + {capture "creation_dialog"} + {form_hidden_fields form=$form} + + {loop type="lang" name="default-lang" default_only="1"} + {* Switch edition to the current locale *} + + + {admin_form_field form=$form name="locale" value=$LOCALE} + {/loop} + + {admin_form_field form=$form name="success_url" value={url path='/admin/brand/update/_ID_'}} + {admin_form_field form=$form name="title"} + {admin_form_field form=$form name="visible"} + + {module_include location='brand_create_form'} + + {/capture} + + {include + file = "includes/generic-create-dialog.html" + + dialog_id = "creation_dialog" + dialog_title = {intl l="Create a new brand"} + dialog_body = {$smarty.capture.creation_dialog nofilter} + + dialog_ok_label = {intl l="Create this brand"} + + form_action = {url path='/admin/brand/create'} + form_enctype = {form_enctype form=$form} + form_error_message = $form_error_message + } + {/form} + + + {* Delete confirmation dialog *} + + {capture "delete_dialog"} + + + {module_include location='brand_delete_form'} + + {/capture} + + {include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_dialog" + dialog_title = {intl l="Delete brand"} + dialog_message = {intl l="Do you really want to delete this brand ?"} + + form_action = {url path='/admin/brand/delete'} + form_content = {$smarty.capture.delete_dialog nofilter} + } +{/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='brands-js'} +{/block} \ No newline at end of file diff --git a/templates/backOffice/default/tools.html b/templates/backOffice/default/tools.html index b97263508..7562df9af 100644 --- a/templates/backOffice/default/tools.html +++ b/templates/backOffice/default/tools.html @@ -40,6 +40,13 @@ {/loop} + {loop name="auth-export" type="auth" role="ADMIN" resource="admin.brand" access="VIEW"} + + {intl l="Brands"} + + + {/loop} + {loop name="auth-export" type="auth" role="ADMIN" resource="admin.export" access="VIEW"} {intl l="Export"} From 401276181537ed89b6d60174d60afeead34f03c7 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 26 Jun 2014 11:25:50 +0200 Subject: [PATCH 09/64] testFormatDateWithLocale always fails on Windows --- .../Thelia/Tests/Core/Template/Smarty/Plugins/FormatTest.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/lib/Thelia/Tests/Core/Template/Smarty/Plugins/FormatTest.php b/core/lib/Thelia/Tests/Core/Template/Smarty/Plugins/FormatTest.php index b1643d7f9..625539e6a 100644 --- a/core/lib/Thelia/Tests/Core/Template/Smarty/Plugins/FormatTest.php +++ b/core/lib/Thelia/Tests/Core/Template/Smarty/Plugins/FormatTest.php @@ -160,6 +160,9 @@ class FormatTest extends \PHPUnit_Framework_TestCase public function testFormatDateWithLocale() { + // Fails on Windows + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') return; + $dateTime = new \DateTime(); // 2014-06-17 $dateTime->setTimestamp(1402987842); From 9b455e6c871fa2686ffb35110bb09c99c2ba92f7 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 26 Jun 2014 11:26:49 +0200 Subject: [PATCH 10/64] Fixed unit tests --- core/lib/Thelia/Files/FileManager.php | 2 +- core/lib/Thelia/Model/CategoryImage.php | 1 - core/lib/Thelia/Model/ContentDocument.php | 11 ++-- core/lib/Thelia/Tests/Action/DocumentTest.php | 58 ++++++++++++++++--- core/lib/Thelia/Tests/Action/ImageTest.php | 53 ++++++++++++----- .../Thelia/Tests/Files/FileManagerTest.php | 1 - 6 files changed, 95 insertions(+), 31 deletions(-) diff --git a/core/lib/Thelia/Files/FileManager.php b/core/lib/Thelia/Files/FileManager.php index 19fa7adf8..9478a6498 100644 --- a/core/lib/Thelia/Files/FileManager.php +++ b/core/lib/Thelia/Files/FileManager.php @@ -208,7 +208,7 @@ class FileManager * * @param FileModelInterface $model File being deleted */ - public function c($model) + public function deleteFile($model) { $url = $model->getUploadDir() . DS . $model->getFile(); diff --git a/core/lib/Thelia/Model/CategoryImage.php b/core/lib/Thelia/Model/CategoryImage.php index 4f95e026b..75c66f967 100644 --- a/core/lib/Thelia/Model/CategoryImage.php +++ b/core/lib/Thelia/Model/CategoryImage.php @@ -11,7 +11,6 @@ use Thelia\Form\BaseForm; use Thelia\Form\CategoryImageModification; use Thelia\Model\Base\CategoryImage as BaseCategoryImage; use Propel\Runtime\Connection\ConnectionInterface; -use Thelia\Model\Base\CategoryImageQuery; use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait; use Thelia\Files\FileModelInterface; diff --git a/core/lib/Thelia/Model/ContentDocument.php b/core/lib/Thelia/Model/ContentDocument.php index f766eed22..c2fb09ada 100644 --- a/core/lib/Thelia/Model/ContentDocument.php +++ b/core/lib/Thelia/Model/ContentDocument.php @@ -3,23 +3,24 @@ namespace Thelia\Model; use Propel\Runtime\ActiveQuery\ModelCriteria; +use Propel\Runtime\Connection\ConnectionInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Routing\Router; use Thelia\Core\HttpFoundation\Request; +use Thelia\Files\FileModelInterface; use Thelia\Files\FileModelParentInterface; use Thelia\Form\BaseForm; use Thelia\Form\ContentDocumentModification; use Thelia\Model\Base\ContentDocument as BaseContentDocument; -use Propel\Runtime\Connection\ConnectionInterface; -use Thelia\Model\Base\ContentDocumentQuery; use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait; -use Thelia\Files\FileModelInterface; +use Thelia\Model\Tools\ModelEventDispatcherTrait; +use Thelia\Model\Tools\PositionManagementTrait; class ContentDocument extends BaseContentDocument implements BreadcrumbInterface, FileModelInterface { - use \Thelia\Model\Tools\ModelEventDispatcherTrait; - use \Thelia\Model\Tools\PositionManagementTrait; + use ModelEventDispatcherTrait; + use PositionManagementTrait; use FolderBreadcrumbTrait; /** diff --git a/core/lib/Thelia/Tests/Action/DocumentTest.php b/core/lib/Thelia/Tests/Action/DocumentTest.php index b3c546165..947dd66fa 100644 --- a/core/lib/Thelia/Tests/Action/DocumentTest.php +++ b/core/lib/Thelia/Tests/Action/DocumentTest.php @@ -18,6 +18,7 @@ use Thelia\Core\HttpFoundation\Session\Session; use Thelia\Action\Document; use Thelia\Core\Event\Document\DocumentEvent; +use Thelia\Files\FileManager; use Thelia\Model\ConfigQuery; /** @@ -39,6 +40,25 @@ class DocumentTest extends \Thelia\Tests\TestCaseWithURLToolSetup $container->set("event_dispatcher", $dispatcher); + $fileManager = new FileManager([ + "document.product" => "Thelia\\Model\\ProductDocument", + "image.product" => "Thelia\\Model\\ProductImage", + + "document.category" => "Thelia\\Model\\CategoryDocument", + "image.category" => "Thelia\\Model\\CategoryImage", + + "document.content" => "Thelia\\Model\\ContentDocument", + "image.content" => "Thelia\\Model\\ContentImage", + + "document.folder" => "Thelia\\Model\\FolderDocument", + "image.folder" => "Thelia\\Model\\FolderImage", + + "document.brand" => "Thelia\\Model\\BrandDocument", + "image.brand" => "Thelia\\Model\\BrandImage", + ]); + + $container->set("thelia.file_manager", $this->getFileManager()); + $request = new Request(); $request->setSession($this->session); @@ -47,6 +67,28 @@ class DocumentTest extends \Thelia\Tests\TestCaseWithURLToolSetup return $container; } + public function getFileManager() + { + $fileManager = new FileManager([ + "document.product" => "Thelia\\Model\\ProductDocument", + "image.product" => "Thelia\\Model\\ProductImage", + + "document.category" => "Thelia\\Model\\CategoryDocument", + "image.category" => "Thelia\\Model\\CategoryImage", + + "document.content" => "Thelia\\Model\\ContentDocument", + "image.content" => "Thelia\\Model\\ContentImage", + + "document.folder" => "Thelia\\Model\\FolderDocument", + "image.folder" => "Thelia\\Model\\FolderImage", + + "document.brand" => "Thelia\\Model\\BrandDocument", + "image.brand" => "Thelia\\Model\\BrandImage", + ]); + + return $fileManager; + } + public function setUp() { $this->session = new Session(new MockArraySessionStorage()); @@ -100,7 +142,7 @@ class DocumentTest extends \Thelia\Tests\TestCaseWithURLToolSetup { $event = new DocumentEvent($this->request); - $document = new Document($this->getContainer()); + $document = new Document($this->getFileManager()); $document->processDocument($event); } @@ -115,7 +157,7 @@ class DocumentTest extends \Thelia\Tests\TestCaseWithURLToolSetup { $event = new DocumentEvent($this->request); - $document = new Document($this->getContainer()); + $document = new Document($this->getFileManager()); $event->setCacheFilepath("blablabla.txt"); $event->setCacheSubdirectory("tests"); @@ -133,7 +175,7 @@ class DocumentTest extends \Thelia\Tests\TestCaseWithURLToolSetup { $event = new DocumentEvent($this->request); - $document = new Document($this->getContainer()); + $document = new Document($this->getFileManager()); $event->setCacheFilepath("blablabla.pdf"); $event->setCacheSubdirectory("../../../"); @@ -151,7 +193,7 @@ class DocumentTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setSourceFilepath(__DIR__."/assets/documents/sources/test-document-1.txt"); $event->setCacheSubdirectory("tests"); - $document = new Document($this->getContainer()); + $document = new Document($this->getFileManager()); // mock cache configuration. $config = ConfigQuery::create()->filterByName('original_document_delivery_mode')->findOne(); @@ -180,7 +222,7 @@ class DocumentTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setSourceFilepath(__DIR__."/assets/documents/sources/test-document-2.txt"); $event->setCacheSubdirectory("tests"); - $document = new Document($this->getContainer()); + $document = new Document($this->getFileManager()); // mock cache configuration. $config = ConfigQuery::create()->filterByName('original_document_delivery_mode')->findOne(); @@ -205,7 +247,7 @@ class DocumentTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setCacheSubdirectory('tests'); - $document = new Document($this->getContainer()); + $document = new Document($this->getFileManager()); $document->clearCache($event); } @@ -214,7 +256,7 @@ class DocumentTest extends \Thelia\Tests\TestCaseWithURLToolSetup { $event = new DocumentEvent($this->request); - $document = new Document($this->getContainer()); + $document = new Document($this->getFileManager()); $document->clearCache($event); } @@ -230,7 +272,7 @@ class DocumentTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setCacheSubdirectory('../../../..'); - $document = new Document($this->getContainer()); + $document = new Document($this->getFileManager()); $document->clearCache($event); } diff --git a/core/lib/Thelia/Tests/Action/ImageTest.php b/core/lib/Thelia/Tests/Action/ImageTest.php index 00d08123c..462d3b624 100755 --- a/core/lib/Thelia/Tests/Action/ImageTest.php +++ b/core/lib/Thelia/Tests/Action/ImageTest.php @@ -18,6 +18,7 @@ use Thelia\Core\HttpFoundation\Session\Session; use Thelia\Action\Image; use Thelia\Core\Event\Image\ImageEvent; +use Thelia\Files\FileManager; use Thelia\Model\ConfigQuery; /** @@ -47,6 +48,28 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup return $container; } + public function getFileManager() + { + $fileManager = new FileManager([ + "document.product" => "Thelia\\Model\\ProductDocument", + "image.product" => "Thelia\\Model\\ProductImage", + + "document.category" => "Thelia\\Model\\CategoryDocument", + "image.category" => "Thelia\\Model\\CategoryImage", + + "document.content" => "Thelia\\Model\\ContentDocument", + "image.content" => "Thelia\\Model\\ContentImage", + + "document.folder" => "Thelia\\Model\\FolderDocument", + "image.folder" => "Thelia\\Model\\FolderImage", + + "document.brand" => "Thelia\\Model\\BrandDocument", + "image.brand" => "Thelia\\Model\\BrandImage", + ]); + + return $fileManager; + } + public function setUp() { $this->session = new Session(new MockArraySessionStorage()); @@ -100,7 +123,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup { $event = new ImageEvent($this->request); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $image->processImage($event); } @@ -115,7 +138,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup { $event = new ImageEvent($this->request); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $event->setCacheFilepath("blablabla.png"); $event->setCacheSubdirectory("tests"); @@ -133,7 +156,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup { $event = new ImageEvent($this->request); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $event->setCacheFilepath("blablabla.png"); $event->setCacheSubdirectory("../../../"); @@ -151,7 +174,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-1.png"); $event->setCacheSubdirectory("tests"); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); // mock cache configuration. $config = ConfigQuery::create()->filterByName('original_image_delivery_mode')->findOne(); @@ -180,7 +203,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-9.png"); $event->setCacheSubdirectory("tests"); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); // mock cache configuration. $config = ConfigQuery::create()->filterByName('original_image_delivery_mode')->findOne(); @@ -214,7 +237,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setHeight(100); $event->setResizeMode(Image::EXACT_RATIO_WITH_BORDERS); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $image->processImage($event); } @@ -234,7 +257,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setHeight(100); $event->setResizeMode(Image::EXACT_RATIO_WITH_BORDERS); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $image->processImage($event); } @@ -251,7 +274,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setEffects(array("grayscale", "vertical_flip", "horizontal_flip", 'colorize:#00ff00', 'gamma: 0.2')); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $image->processImage($event); } @@ -271,7 +294,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setHeight(100); $event->setResizeMode(Image::EXACT_RATIO_WITH_CROP); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $image->processImage($event); } @@ -291,7 +314,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setHeight(150); $event->setResizeMode(Image::EXACT_RATIO_WITH_CROP); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $image->processImage($event); } @@ -309,7 +332,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setWidth(100); $event->setHeight(100); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $image->processImage($event); } @@ -327,7 +350,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setWidth(100); $event->setHeight(100); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $image->processImage($event); } @@ -338,7 +361,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setCacheSubdirectory('tests'); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $image->clearCache($event); } @@ -347,7 +370,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup { $event = new ImageEvent($this->request); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $image->clearCache($event); } @@ -363,7 +386,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup $event->setCacheSubdirectory('../../../..'); - $image = new Image($this->getContainer()); + $image = new Image($this->getFileManager()); $image->clearCache($event); } diff --git a/core/lib/Thelia/Tests/Files/FileManagerTest.php b/core/lib/Thelia/Tests/Files/FileManagerTest.php index 78ad73aee..01197860c 100644 --- a/core/lib/Thelia/Tests/Files/FileManagerTest.php +++ b/core/lib/Thelia/Tests/Files/FileManagerTest.php @@ -394,5 +394,4 @@ class FileManagerTest extends \PHPUnit_Framework_TestCase 'images', 'brand' ); } - } \ No newline at end of file From 13e57e332afa8c5dc02e82b7334d6edb4a166911 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 26 Jun 2014 15:49:46 +0200 Subject: [PATCH 11/64] Added brand creation --- setup/faker.php | 43 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/setup/faker.php b/setup/faker.php index 95080f40b..e42abbd4c 100644 --- a/setup/faker.php +++ b/setup/faker.php @@ -139,15 +139,25 @@ try { ->find(); $productPrice->delete(); + $brand = Thelia\Model\BrandQuery::create() + ->find(); + $brand->delete(); + + $brand = Thelia\Model\BrandI18nQuery::create() + ->find(); + $brand->delete(); + \Thelia\Model\ProductImageQuery::create()->find()->delete(); \Thelia\Model\CategoryImageQuery::create()->find()->delete(); \Thelia\Model\FolderImageQuery::create()->find()->delete(); \Thelia\Model\ContentImageQuery::create()->find()->delete(); + \Thelia\Model\BrandImageQuery::create()->find()->delete(); \Thelia\Model\ProductDocumentQuery::create()->find()->delete(); \Thelia\Model\CategoryDocumentQuery::create()->find()->delete(); \Thelia\Model\FolderDocumentQuery::create()->find()->delete(); \Thelia\Model\ContentDocumentQuery::create()->find()->delete(); + \Thelia\Model\BrandDocumentQuery::create()->find()->delete(); \Thelia\Model\CouponQuery::create()->find()->delete(); \Thelia\Model\OrderQuery::create()->find()->delete(); @@ -384,6 +394,30 @@ try { } } + echo "Creating brands\n"; + + $brandIdList = []; + + for ($k=0; $k<4; $k++) { + $brand = new Thelia\Model\Brand(); + + $brand->setVisible(1); + $brand->setPosition($k+1); + setI18n($faker, $brand); + + $brand->save(); + $brandId = $brand->getId(); + $brandIdList[] = $brandId; + + $image = new \Thelia\Model\BrandImage(); + $image->setBrandId($brandId); + generate_image($image, 'brand', $brandId); + + $document = new \Thelia\Model\BrandDocument(); + $document->setBrandId($brandId); + generate_document($document, 'brand', $brandId); + } + echo "Creating categories and products\n"; //categories and products @@ -396,12 +430,12 @@ try { $subcategory = createCategory($faker, $category->getId(), $j, $categoryIdList, $contentIdList); for ($k=0; $kgetMessage()."\n"; + echo "Cause: ".$e->getPrevious()->getMessage()."\n"; echo $e->getTraceAsString(); + $con->rollBack(); } -function createProduct($faker, Thelia\Model\Category $category, $position, $template, &$productIdList) +function createProduct($faker, Thelia\Model\Category $category, $position, $template, $brandIdList, &$productIdList) { $product = new Thelia\Model\Product(); $product->setRef($category->getId() . '_' . $position . '_' . $faker->randomNumber(8)); @@ -628,6 +664,7 @@ function createProduct($faker, Thelia\Model\Category $category, $position, $temp $product->setPosition($position); $product->setTaxRuleId(1); $product->setTemplate($template); + $product->setBrandId($brandIdList[array_rand($brandIdList, 1)]); setI18n($faker, $product); From 65dd2fb129455666732e7d76f2e9834c47bf1a9c Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 26 Jun 2014 15:50:00 +0200 Subject: [PATCH 12/64] Changed product_brand fk --- core/lib/Thelia/Model/Map/BrandTableMap.php | 3 +-- core/lib/Thelia/Model/Map/ProductTableMap.php | 4 ++-- core/lib/Thelia/Model/Map/TemplateTableMap.php | 3 ++- local/config/schema.xml | 4 ++-- setup/thelia.sql | 6 ++++-- 5 files changed, 11 insertions(+), 9 deletions(-) diff --git a/core/lib/Thelia/Model/Map/BrandTableMap.php b/core/lib/Thelia/Model/Map/BrandTableMap.php index b069e9bbf..55e41bfa5 100644 --- a/core/lib/Thelia/Model/Map/BrandTableMap.php +++ b/core/lib/Thelia/Model/Map/BrandTableMap.php @@ -174,7 +174,7 @@ class BrandTableMap extends TableMap public function buildRelations() { $this->addRelation('BrandImageRelatedByLogoImageId', '\\Thelia\\Model\\BrandImage', RelationMap::MANY_TO_ONE, array('logo_image_id' => 'id', ), 'SET NULL', 'RESTRICT'); - $this->addRelation('Product', '\\Thelia\\Model\\Product', RelationMap::ONE_TO_MANY, array('id' => 'brand_id', ), 'SET NULL', null, 'Products'); + $this->addRelation('Product', '\\Thelia\\Model\\Product', RelationMap::ONE_TO_MANY, array('id' => 'brand_id', ), 'RESTRICT', 'RESTRICT', 'Products'); $this->addRelation('BrandDocument', '\\Thelia\\Model\\BrandDocument', RelationMap::ONE_TO_MANY, array('id' => 'brand_id', ), 'CASCADE', 'RESTRICT', 'BrandDocuments'); $this->addRelation('BrandImageRelatedByBrandId', '\\Thelia\\Model\\BrandImage', RelationMap::ONE_TO_MANY, array('id' => 'brand_id', ), 'CASCADE', 'RESTRICT', 'BrandImagesRelatedByBrandId'); $this->addRelation('BrandI18n', '\\Thelia\\Model\\BrandI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'BrandI18ns'); @@ -200,7 +200,6 @@ class BrandTableMap extends TableMap { // Invalidate objects in ".$this->getClassNameFromBuilder($joinedTableTableMapBuilder)." instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. - ProductTableMap::clearInstancePool(); BrandDocumentTableMap::clearInstancePool(); BrandImageTableMap::clearInstancePool(); BrandI18nTableMap::clearInstancePool(); diff --git a/core/lib/Thelia/Model/Map/ProductTableMap.php b/core/lib/Thelia/Model/Map/ProductTableMap.php index 3675ab7e0..64d176029 100644 --- a/core/lib/Thelia/Model/Map/ProductTableMap.php +++ b/core/lib/Thelia/Model/Map/ProductTableMap.php @@ -210,8 +210,8 @@ class ProductTableMap extends TableMap public function buildRelations() { $this->addRelation('TaxRule', '\\Thelia\\Model\\TaxRule', RelationMap::MANY_TO_ONE, array('tax_rule_id' => 'id', ), 'RESTRICT', 'RESTRICT'); - $this->addRelation('Template', '\\Thelia\\Model\\Template', RelationMap::MANY_TO_ONE, array('template_id' => 'id', ), null, null); - $this->addRelation('Brand', '\\Thelia\\Model\\Brand', RelationMap::MANY_TO_ONE, array('brand_id' => 'id', ), 'SET NULL', null); + $this->addRelation('Template', '\\Thelia\\Model\\Template', RelationMap::MANY_TO_ONE, array('template_id' => 'id', ), 'SET NULL', null); + $this->addRelation('Brand', '\\Thelia\\Model\\Brand', RelationMap::MANY_TO_ONE, array('brand_id' => 'id', ), 'RESTRICT', 'RESTRICT'); $this->addRelation('ProductCategory', '\\Thelia\\Model\\ProductCategory', RelationMap::ONE_TO_MANY, array('id' => 'product_id', ), 'CASCADE', 'RESTRICT', 'ProductCategories'); $this->addRelation('FeatureProduct', '\\Thelia\\Model\\FeatureProduct', RelationMap::ONE_TO_MANY, array('id' => 'product_id', ), 'CASCADE', 'RESTRICT', 'FeatureProducts'); $this->addRelation('ProductSaleElements', '\\Thelia\\Model\\ProductSaleElements', RelationMap::ONE_TO_MANY, array('id' => 'product_id', ), 'CASCADE', 'RESTRICT', 'ProductSaleElementss'); diff --git a/core/lib/Thelia/Model/Map/TemplateTableMap.php b/core/lib/Thelia/Model/Map/TemplateTableMap.php index 901007c03..efcd161bb 100644 --- a/core/lib/Thelia/Model/Map/TemplateTableMap.php +++ b/core/lib/Thelia/Model/Map/TemplateTableMap.php @@ -155,7 +155,7 @@ class TemplateTableMap extends TableMap */ public function buildRelations() { - $this->addRelation('Product', '\\Thelia\\Model\\Product', RelationMap::ONE_TO_MANY, array('id' => 'template_id', ), null, null, 'Products'); + $this->addRelation('Product', '\\Thelia\\Model\\Product', RelationMap::ONE_TO_MANY, array('id' => 'template_id', ), 'SET NULL', null, 'Products'); $this->addRelation('FeatureTemplate', '\\Thelia\\Model\\FeatureTemplate', RelationMap::ONE_TO_MANY, array('id' => 'template_id', ), null, null, 'FeatureTemplates'); $this->addRelation('AttributeTemplate', '\\Thelia\\Model\\AttributeTemplate', RelationMap::ONE_TO_MANY, array('id' => 'template_id', ), null, null, 'AttributeTemplates'); $this->addRelation('TemplateI18n', '\\Thelia\\Model\\TemplateI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'TemplateI18ns'); @@ -183,6 +183,7 @@ class TemplateTableMap extends TableMap { // Invalidate objects in ".$this->getClassNameFromBuilder($joinedTableTableMapBuilder)." instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + ProductTableMap::clearInstancePool(); TemplateI18nTableMap::clearInstancePool(); } diff --git a/local/config/schema.xml b/local/config/schema.xml index 11b653378..de1f058ef 100644 --- a/local/config/schema.xml +++ b/local/config/schema.xml @@ -46,10 +46,10 @@ - + - + diff --git a/setup/thelia.sql b/setup/thelia.sql index 2c7809d99..100e8fd3b 100644 --- a/setup/thelia.sql +++ b/setup/thelia.sql @@ -57,11 +57,13 @@ CREATE TABLE `product` ON DELETE RESTRICT, CONSTRAINT `fk_product_template` FOREIGN KEY (`template_id`) - REFERENCES `template` (`id`), + REFERENCES `template` (`id`) + ON DELETE SET NULL, CONSTRAINT `fk_product_brand` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`) - ON DELETE SET NULL + ON UPDATE RESTRICT + ON DELETE RESTRICT ) ENGINE=InnoDB; -- --------------------------------------------------------------------- From 2c9accf58eb4f1258208a0fefc354e1337d405eb Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 26 Jun 2014 19:52:28 +0200 Subject: [PATCH 13/64] Added pre and post processing event disatching --- core/lib/Thelia/Action/Image.php | 97 ++++--------------- .../Thelia/Core/Event/Image/ImageEvent.php | 23 +++++ core/lib/Thelia/Core/Event/TheliaEvents.php | 10 ++ 3 files changed, 53 insertions(+), 77 deletions(-) diff --git a/core/lib/Thelia/Action/Image.php b/core/lib/Thelia/Action/Image.php index 2f38775bc..eb338e219 100644 --- a/core/lib/Thelia/Action/Image.php +++ b/core/lib/Thelia/Action/Image.php @@ -18,6 +18,7 @@ use Imagine\Image\ImageInterface; use Imagine\Image\ImagineInterface; use Imagine\Image\Point; use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Thelia\Core\Event\File\FileCreateOrUpdateEvent; use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent; use Thelia\Core\Event\Image\ImageDeleteEvent; use Thelia\Core\Event\Image\ImageEvent; @@ -85,8 +86,10 @@ class Image extends BaseCachedFile implements EventSubscriberInterface * * This method updates the cache_file_path and file_url attributes of the event * - * @param \Thelia\Core\Event\Image\ImageEvent $event - * @throws \InvalidArgumentException, ImageException + * @param ImageEvent $event + * + * @throws \Thelia\Exception\ImageException + * @throws \InvalidArgumentException */ public function processImage(ImageEvent $event) { @@ -136,6 +139,11 @@ class Image extends BaseCachedFile implements EventSubscriberInterface if ($image) { + // Allow image pre-processing (watermarging, or other stuff...) + $event->setImageObject($image); + $event->getDispatcher()->dispatch(TheliaEvents::IMAGE_PREPROCESSING, $event); + $image = $event->getImageObject(); + $background_color = $event->getBackgroundColor(); if ($background_color != null) { @@ -205,6 +213,11 @@ class Image extends BaseCachedFile implements EventSubscriberInterface if (is_null($quality)) $quality = ConfigQuery::read('default_image_quality_percent', 75); + // Allow image post-processing (watermarging, or other stuff...) + $event->setImageObject($image); + $event->getDispatcher()->dispatch(TheliaEvents::IMAGE_POSTPROCESSING, $event); + $image = $event->getImageObject(); + $image->save( $cacheFilePath, array('quality' => $quality) @@ -229,78 +242,6 @@ class Image extends BaseCachedFile implements EventSubscriberInterface $event->setOriginalFileUrl(URL::getInstance()->absoluteUrl($original_image_url, null, URL::PATH_TO_FILE)); } - /** - * Take care of saving image in the database and file storage - * - * @param \Thelia\Core\Event\Image\ImageCreateOrUpdateEvent $event Image event - * - * @throws \Thelia\Exception\ImageException - * @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action - */ - public function saveImage(ImageCreateOrUpdateEvent $event) - { - $model = $event->getModelImage(); - - $nbModifiedLines = $model->save(); - $event->setModelImage($model); - - if (!$nbModifiedLines) { - throw new ImageException( - sprintf( - 'Image "%s" with parent id %s failed to be saved', - $event->getParentName(), - $event->getParentId() - ) - ); - } - - $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelImage(), $event->getUploadedFile()); - $event->setUploadedFile($newUploadedFile); - } - - /** - * Take care of updating image in the database and file storage - * - * @param ImageCreateOrUpdateEvent $event Image event - * - * @throws \Thelia\Exception\ImageException - * @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action - */ - public function updateImage(ImageCreateOrUpdateEvent $event) - { - // Copy and save file - if ($event->getUploadedFile()) { - // Remove old picture file from file storage - $url = $event->getModelImage()->getUploadDir() . '/' . $event->getOldModelImage()->getFile(); - unlink(str_replace('..', '', $url)); - - $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelImage(), $event->getUploadedFile()); - $event->setUploadedFile($newUploadedFile); - } - - // Update image modifications - $event->getModelImage()->save(); - $event->setModelImage($event->getModelImage()); - } - - public function updatePosition(UpdateFilePositionEvent $event) - { - $this->genericUpdatePosition($event->getQuery(), $event); - } - - /** - * Take care of deleting image in the database and file storage - * - * @param ImageDeleteEvent $event Image event - * - * @throws \Exception - * @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action - */ - public function deleteImage(ImageDeleteEvent $event) - { - $this->fileManager->deleteFile($event->getImageToDelete()); - } - /** * Process image resizing, with borders or cropping. If $dest_width and $dest_height * are both null, no resize is performed. @@ -420,10 +361,12 @@ class Image extends BaseCachedFile implements EventSubscriberInterface { return array( TheliaEvents::IMAGE_PROCESS => array("processImage", 128), + + // Implemented in parent class BaseCachedFile TheliaEvents::IMAGE_CLEAR_CACHE => array("clearCache", 128), - TheliaEvents::IMAGE_DELETE => array("deleteImage", 128), - TheliaEvents::IMAGE_SAVE => array("saveImage", 128), - TheliaEvents::IMAGE_UPDATE => array("updateImage", 128), + TheliaEvents::IMAGE_DELETE => array("deleteFile", 128), + TheliaEvents::IMAGE_SAVE => array("saveFile", 128), + TheliaEvents::IMAGE_UPDATE => array("updateFile", 128), TheliaEvents::IMAGE_UPDATE_POSITION => array("updatePosition", 128), ); } diff --git a/core/lib/Thelia/Core/Event/Image/ImageEvent.php b/core/lib/Thelia/Core/Event/Image/ImageEvent.php index e6f152708..318265c26 100644 --- a/core/lib/Thelia/Core/Event/Image/ImageEvent.php +++ b/core/lib/Thelia/Core/Event/Image/ImageEvent.php @@ -12,6 +12,7 @@ namespace Thelia\Core\Event\Image; +use Imagine\Image\ImageInterface; use Thelia\Core\Event\CachedFileEvent; class ImageEvent extends CachedFileEvent @@ -71,6 +72,11 @@ class ImageEvent extends CachedFileEvent */ protected $quality = null; + /** + * @var ImageInterface + */ + protected $imageObject; + /** * @return boolean true if the required image is the original image (resize_mode and background_color are not significant) */ @@ -209,4 +215,21 @@ class ImageEvent extends CachedFileEvent return $this; } + + /** + * @param ImageInterface $imageObject + * @return $this + */ + public function setImageObject($imageObject) + { + $this->imageObject = $imageObject; + return $this; + } + + /** + * @return ImageInterface + */ + public function getImageObject() { + return $this->imageObject; + } } diff --git a/core/lib/Thelia/Core/Event/TheliaEvents.php b/core/lib/Thelia/Core/Event/TheliaEvents.php index 82cac917a..9c2962801 100644 --- a/core/lib/Thelia/Core/Event/TheliaEvents.php +++ b/core/lib/Thelia/Core/Event/TheliaEvents.php @@ -382,6 +382,16 @@ final class TheliaEvents */ const IMAGE_PROCESS = "action.processImage"; + /** + * Sent just after creating the image object from the image file + */ + const IMAGE_PREPROCESSING = "action.preProcessImage"; + + /** + * Sent just before saving the processed image object on disk + */ + const IMAGE_POSTPROCESSING = "action.postProcessImage"; + /** * Sent on document processing */ From fcceaa630d8f21ce13f55bd8c02b3453b35dbc60 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 26 Jun 2014 20:17:24 +0200 Subject: [PATCH 14/64] Deleted test images after tests --- core/lib/Thelia/Tests/Action/LangTest.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/core/lib/Thelia/Tests/Action/LangTest.php b/core/lib/Thelia/Tests/Action/LangTest.php index e4fc50e71..a4cea6212 100644 --- a/core/lib/Thelia/Tests/Action/LangTest.php +++ b/core/lib/Thelia/Tests/Action/LangTest.php @@ -172,4 +172,11 @@ class LangTest extends \PHPUnit_Framework_TestCase ->update(array('ByDefault' => true)); } + protected function tearDown() + { + @unlink(THELIA_TEMPLATE_DIR . "/backOffice/default/assets/img/flags/TEST.png"); + @unlink(THELIA_TEMPLATE_DIR . "/backOffice/default/assets/img/flags/TES.png"); + } + + } From d969f84ae07d62ab662cc752a46887e7c886e2cb Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 26 Jun 2014 20:18:06 +0200 Subject: [PATCH 15/64] Restoired file events compatibility, factorised code --- core/lib/Thelia/Action/BaseCachedFile.php | 77 ++ core/lib/Thelia/Action/Document.php | 87 +- .../Controller/Admin/FileController.php | 860 ++++++------------ .../Document/DocumentCreateOrUpdateEvent.php | 140 +-- .../Event/Document/DocumentDeleteEvent.php | 60 +- .../Event/File/FileCreateOrUpdateEvent.php | 168 ++++ .../Core/Event/File/FileDeleteEvent.php | 62 ++ .../Event/Image/ImageCreateOrUpdateEvent.php | 128 +-- .../Core/Event/Image/ImageDeleteEvent.php | 61 +- core/lib/Thelia/Files/FileModelInterface.php | 46 +- core/lib/Thelia/Tests/Action/ImageTest.php | 22 +- 11 files changed, 846 insertions(+), 865 deletions(-) create mode 100644 core/lib/Thelia/Core/Event/File/FileCreateOrUpdateEvent.php create mode 100644 core/lib/Thelia/Core/Event/File/FileDeleteEvent.php diff --git a/core/lib/Thelia/Action/BaseCachedFile.php b/core/lib/Thelia/Action/BaseCachedFile.php index 505615c97..42e67f5c8 100644 --- a/core/lib/Thelia/Action/BaseCachedFile.php +++ b/core/lib/Thelia/Action/BaseCachedFile.php @@ -12,6 +12,10 @@ namespace Thelia\Action; use Thelia\Core\Event\CachedFileEvent; +use Thelia\Core\Event\File\FileCreateOrUpdateEvent; +use Thelia\Core\Event\Image\FileDeleteEvent; +use Thelia\Core\Event\UpdateFilePositionEvent; +use Thelia\Exception\FileException; use Thelia\Files\FileManager; use Thelia\Tools\URL; @@ -176,4 +180,77 @@ abstract class BaseCachedFile extends BaseAction return $path; } + + + /** + * Take care of saving a file in the database and file storage + * + * @param FileCreateOrUpdateEvent $event Image event + * + * @throws \Thelia\Exception\FileException + * + */ + public function saveFile(FileCreateOrUpdateEvent $event) + { + $model = $event->getModel(); + + $nbModifiedLines = $model->save(); + $event->setModel($model); + + if (!$nbModifiedLines) { + throw new FileException( + sprintf( + 'File "%s" (type %s) with parent id %s failed to be saved', + $event->getParentName(), + get_class($model), + $event->getParentId() + ) + ); + } + + $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModel(), $event->getUploadedFile()); + + $event->setUploadedFile($newUploadedFile); + } + + + /** + * Take care of updating file in the database and file storage + * + * @param FileCreateOrUpdateEvent $event Image event + * + * @throws \Thelia\Exception\FileException + */ + public function updateFile(FileCreateOrUpdateEvent $event) + { + // Copy and save file + if ($event->getUploadedFile()) { + // Remove old picture file from file storage + $url = $event->getModel()->getUploadDir() . '/' . $event->getOldModel()->getFile(); + unlink(str_replace('..', '', $url)); + + $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModel(), $event->getUploadedFile()); + $event->setUploadedFile($newUploadedFile); + } + + // Update image modifications + $event->getModel()->save(); + $event->setModel($event->getModel()); + } + + /** + * Deleting file in the database and in storage + * + * @param FileDeleteEvent $event Image event + */ + public function deleteImage(FileDeleteEvent $event) + { + $this->fileManager->deleteFile($event->getFileToDelete()); + } + + public function updatePosition(UpdateFilePositionEvent $event) + { + $this->genericUpdatePosition($event->getQuery(), $event); + } + } diff --git a/core/lib/Thelia/Action/Document.php b/core/lib/Thelia/Action/Document.php index ef3f17bf2..8499fd087 100644 --- a/core/lib/Thelia/Action/Document.php +++ b/core/lib/Thelia/Action/Document.php @@ -105,93 +105,16 @@ class Document extends BaseCachedFile implements EventSubscriberInterface $event->setDocumentUrl(URL::getInstance()->absoluteUrl($documentUrl, null, URL::PATH_TO_FILE)); } - /** - * Take care of saving document in the database and file storage - * - * @param \Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent $event Document event - * - * @throws \Thelia\Exception\ImageException - * @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action - */ - public function saveDocument(DocumentCreateOrUpdateEvent $event) - { - $model = $event->getModelDocument(); - - $nbModifiedLines = $model->save(); - - $event->setModelDocument($model); - - if (!$nbModifiedLines) { - throw new ImageException( - sprintf( - 'Document "%s" with parent id %s failed to be saved', - $event->getParentName(), - $event->getParentId() - ) - ); - } - - $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelDocument(), $event->getUploadedFile()); - - $event->setUploadedFile($newUploadedFile); - } - - /** - * Take care of updating document in the database and file storage - * - * @param \Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent $event Document event - * - * @throws \Thelia\Exception\ImageException - * @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action - */ - public function updateDocument(DocumentCreateOrUpdateEvent $event) - { - if (null !== $event->getUploadedFile()) { - $event->getModelDocument()->setTitle($event->getUploadedFile()->getClientOriginalName()); - } - - // Copy and save file - if ($event->getUploadedFile()) { - // Remove old picture file from file storage - $url = $event->getModelDocument()->getUploadDir() . '/' . $event->getOldModelDocument()->getFile(); - - unlink(str_replace('..', '', $url)); - - $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelDocument(), $event->getUploadedFile()); - - $event->setUploadedFile($newUploadedFile); - } - - // Update document modifications - $event->getModelDocument()->save(); - $event->setModelDocument($event->getModelDocument()); - } - - public function updatePosition(UpdateFilePositionEvent $event) - { - $this->genericUpdatePosition($event->getQuery(), $event); - } - - /** - * Take care of deleting document in the database and file storage - * - * @param \Thelia\Core\Event\Document\DocumentDeleteEvent $event Image event - * - * @throws \Exception - */ - public function deleteDocument(DocumentDeleteEvent $event) - { - $this->fileManager->deleteFile($event->getDocumentToDelete()); - } - public static function getSubscribedEvents() { return array( TheliaEvents::DOCUMENT_PROCESS => array("processDocument", 128), + + // Implemented in parent class BaseCachedFile TheliaEvents::DOCUMENT_CLEAR_CACHE => array("clearCache", 128), - TheliaEvents::DOCUMENT_DELETE => array("deleteDocument", 128), - TheliaEvents::DOCUMENT_SAVE => array("saveDocument", 128), - TheliaEvents::DOCUMENT_UPDATE => array("updateDocument", 128), + TheliaEvents::DOCUMENT_DELETE => array("deleteFile", 128), + TheliaEvents::DOCUMENT_SAVE => array("saveFile", 128), + TheliaEvents::DOCUMENT_UPDATE => array("updateFile", 128), TheliaEvents::DOCUMENT_UPDATE_POSITION => array("updatePosition", 128), ); } diff --git a/core/lib/Thelia/Controller/Admin/FileController.php b/core/lib/Thelia/Controller/Admin/FileController.php index eb493aa13..a89234350 100644 --- a/core/lib/Thelia/Controller/Admin/FileController.php +++ b/core/lib/Thelia/Controller/Admin/FileController.php @@ -14,10 +14,8 @@ namespace Thelia\Controller\Admin; use Propel\Runtime\Exception\PropelException; use Symfony\Component\HttpFoundation\File\UploadedFile; -use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent; -use Thelia\Core\Event\Document\DocumentDeleteEvent; -use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent; -use Thelia\Core\Event\Image\ImageDeleteEvent; +use Thelia\Core\Event\File\FileCreateOrUpdateEvent; +use Thelia\Core\Event\Image\FileDeleteEvent; use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\UpdateFilePositionEvent; use Thelia\Core\HttpFoundation\Response; @@ -56,107 +54,16 @@ class FileController extends BaseAdminController } /** - * Manage how a image collection has to be saved + * Manage how a file collection has to be saved * - * @param int $parentId Parent id owning images being saved - * @param string $parentType Parent Type owning images being saved + * @param int $parentId Parent id owning files being saved + * @param string $parentType Parent Type owning files being saved (product, category, content, etc.) + * @param string $objectType Object type, e.g. image or document + * @param array $validMimeTypes an array of valid mime types. If empty, any mime type is allowed. * * @return Response */ - public function saveImageAjaxAction($parentId, $parentType) - { - $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); - $this->checkXmlHttpRequest(); - - if ($this->getRequest()->isMethod('POST')) { - - /** @var UploadedFile $fileBeingUploaded */ - $fileBeingUploaded = $this->getRequest()->files->get('file'); - - $fileManager = $this->getFileManager(); - - // Validate if file is too big - if ($fileBeingUploaded->getError() == 1) { - $message = $this->getTranslator() - ->trans( - 'File is too heavy, please retry with a file having a size less than %size%.', - array('%size%' => ini_get('upload_max_filesize')), - 'core' - ); - - return new ResponseRest($message, 'text', 403); - } - // Validate if it is a image or file - if (!$fileManager->isImage($fileBeingUploaded->getMimeType())) { - $message = $this->getTranslator() - ->trans( - 'You can only upload images (.png, .jpg, .jpeg, .gif)', - array(), - 'image' - ); - - return new ResponseRest($message, 'text', 415); - } - - $imageModel = $fileManager->getModelInstance('image', $parentType); - - $parentModel = $imageModel->getParentFileModel(); - - if ($parentModel === null || $imageModel === null || $fileBeingUploaded === null) { - return new Response('', 404); - } - - $defaultTitle = $parentModel->getTitle(); - - if (empty($defaultTitle)) { - $defaultTitle = $fileBeingUploaded->getClientOriginalName(); - } - - $imageModel - ->setParentId($parentId) - ->setLocale(Lang::getDefaultLanguage()->getLocale()) - ->setTitle($defaultTitle) - ; - - $imageCreateOrUpdateEvent = new ImageCreateOrUpdateEvent($parentId); - $imageCreateOrUpdateEvent->setModelImage($imageModel); - $imageCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded); - $imageCreateOrUpdateEvent->setParentName($parentModel->getTitle()); - - // Dispatch Event to the Action - $this->dispatch( - TheliaEvents::IMAGE_SAVE, - $imageCreateOrUpdateEvent - ); - - $this->adminLogAppend( - AdminResources::retrieve($parentType), - AccessManager::UPDATE, - $this->container->get('thelia.translator')->trans( - 'Saving images for %parentName% parent id %parentId%', - array( - '%parentName%' => $imageCreateOrUpdateEvent->getParentName(), - '%parentId%' => $imageCreateOrUpdateEvent->getParentId() - ), - 'image' - ) - ); - - return new ResponseRest(array('status' => true, 'message' => '')); - } - - return new Response('', 404); - } - - /** - * Manage how a document collection has to be saved - * - * @param int $parentId Parent id owning documents being saved - * @param string $parentType Parent Type owning documents being saved - * - * @return Response - */ - public function saveDocumentAjaxAction($parentId, $parentType) + public function saveFileAjaxAction($parentId, $parentType, $objectType, $validMimeTypes = array()) { $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkXmlHttpRequest(); @@ -173,46 +80,76 @@ class FileController extends BaseAdminController $message = $this->getTranslator() ->trans( 'File is too large, please retry with a file having a size less than %size%.', - array('%size%' => ini_get('post_max_size')), - 'document' + array('%size%' => ini_get('upload_max_filesize')), + 'core' ); return new ResponseRest($message, 'text', 403); } - $documentModel = $fileManager->getModelInstance('document', $parentType); - $parentModel = $documentModel->getParentFileModel($parentType, $parentId); + if (! empty($validMimeTypes)) { - if ($parentModel === null || $documentModel === null || $fileBeingUploaded === null) { + // Check if we have the proper file type + $isValid = false; + + $mimeType = $fileBeingUploaded->getMimeType(); + + if (in_array($mimeType, $validMimeTypes)) { + $isValid = true; + } + + if (! $isValid) { + $message = $this->getTranslator() + ->trans( + 'Only files having the following mime type are allowed: %types%', + [ '%types%' => implode(', ', $validMimeTypes)] + ); + + return new ResponseRest($message, 'text', 415); + } + } + + $fileModel = $fileManager->getModelInstance($objectType, $parentType); + + $parentModel = $fileModel->getParentFileModel(); + + if ($parentModel === null || $fileModel === null || $fileBeingUploaded === null) { return new Response('', 404); } - $documentModel->setParentId($parentId); - $documentModel->setLocale(Lang::getDefaultLanguage()->getLocale()); - $documentModel->setTitle($fileBeingUploaded->getClientOriginalName()); + $defaultTitle = $parentModel->getTitle(); - $documentCreateOrUpdateEvent = new DocumentCreateOrUpdateEvent($parentId); + if (empty($defaultTitle)) { + $defaultTitle = $fileBeingUploaded->getClientOriginalName(); + } - $documentCreateOrUpdateEvent->setModelDocument($documentModel); - $documentCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded); - $documentCreateOrUpdateEvent->setParentName($parentModel->getTitle()); + $fileModel + ->setParentId($parentId) + ->setLocale(Lang::getDefaultLanguage()->getLocale()) + ->setTitle($defaultTitle) + ; + + $fileCreateOrUpdateEvent = new FileCreateOrUpdateEvent($parentId); + $fileCreateOrUpdateEvent->setModel($fileModel); + $fileCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded); + $fileCreateOrUpdateEvent->setParentName($parentModel->getTitle()); // Dispatch Event to the Action $this->dispatch( - TheliaEvents::DOCUMENT_SAVE, - $documentCreateOrUpdateEvent + TheliaEvents::IMAGE_SAVE, + $fileCreateOrUpdateEvent ); $this->adminLogAppend( AdminResources::retrieve($parentType), AccessManager::UPDATE, - $this->container->get('thelia.translator')->trans( - 'Saving document for %parentName% parent id %parentId%', + $this->getTranslator()->trans( + 'Saving %obj% for %parentName% parent id %parentId%', array( - '%parentName%' => $documentCreateOrUpdateEvent->getParentName(), - '%parentId%' => $documentCreateOrUpdateEvent->getParentId() - ), - 'document' + '%parentName%' => $fileCreateOrUpdateEvent->getParentName(), + '%parentId%' => $fileCreateOrUpdateEvent->getParentId(), + '%obj%' => $objectType + ) ) ); @@ -222,6 +159,32 @@ class FileController extends BaseAdminController return new Response('', 404); } + /** + * Manage how a image collection has to be saved + * + * @param int $parentId Parent id owning images being saved + * @param string $parentType Parent Type owning images being saved + * + * @return Response + */ + public function saveImageAjaxAction($parentId, $parentType) + { + return $this->saveFileAjaxAction($parentId, $parentType, 'image', ['image/jpeg' , 'image/png' ,'image/gif']); + } + + /** + * Manage how a document collection has to be saved + * + * @param int $parentId Parent id owning documents being saved + * @param string $parentType Parent Type owning documents being saved + * + * @return Response + */ + public function saveDocumentAjaxAction($parentId, $parentType) + { + return $this->saveFileAjaxAction($parentId, $parentType, 'document'); + } + /** * Manage how a image list will be displayed in AJAX * @@ -359,6 +322,106 @@ class FileController extends BaseAdminController )); } + + /** + * Manage how a file is updated + * + * @param int $fileId File identifier + * @param string $parentType Parent Type owning file being saved + * @param string $objectType the type of the file, image or document + * @param string $eventName the event type. + * + * @return FileModelInterface + */ + public function updateFileAction($fileId, $parentType, $objectType, $eventName) + { + $message = false; + + $fileManager = $this->getFileManager(); + + $fileModelInstance = $fileManager->getModelInstance($objectType, $parentType); + + $fileUpdateForm = $fileModelInstance->getUpdateFormInstance($this->getRequest()); + + /** @var FileModelInterface $file */ + $file = $fileModelInstance->getQueryInstance()->findPk($fileId); + + try { + $oldFile = clone $file; + + if (null === $file) { + throw new \InvalidArgumentException(sprintf('%d %s id does not exist', $fileId, $objectType)); + } + + $data = $this->validateForm($fileUpdateForm)->getData(); + + $event = new FileCreateOrUpdateEvent(null); + + $file->setLocale($data['locale']); + + if (isset($data['title'])) { + $file->setTitle($data['title']); + } + if (isset($data['chapo'])) { + $file->setChapo($data['chapo']); + } + if (isset($data['description'])) { + $file->setDescription($data['description']); + } + if (isset($data['file'])) { + $file->setFile($data['file']); + } + if (isset($data['postscriptum'])) { + $file->setPostscriptum($data['postscriptum']); + } + + $event->setModel($file); + $event->setOldModel($oldFile); + + $files = $this->getRequest()->files; + + $fileForm = $files->get($fileUpdateForm->getName()); + + if (isset($fileForm['file'])) { + $event->setUploadedFile($fileForm['file']); + } + + $this->dispatch($eventName, $event); + + $fileUpdated = $event->getModel(); + + $this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE, + sprintf('%s with Ref %s (ID %d) modified', ucfirst($objectType), $fileUpdated->getTitle(), $fileUpdated->getId()) + ); + + if ($this->getRequest()->get('save_mode') == 'close') { + $this->redirect(URL::getInstance()->absoluteUrl($fileModelInstance->getRedirectionUrl($fileId))); + } else { + $this->redirectSuccess($fileUpdateForm); + } + + } catch (FormValidationException $e) { + $message = sprintf('Please check your input: %s', $e->getMessage()); + } catch (PropelException $e) { + $message = $e->getMessage(); + } catch (\Exception $e) { + $message = sprintf('Sorry, an error occurred: %s', $e->getMessage().' '.$e->getFile()); + } + + if ($message !== false) { + Tlog::getInstance()->error(sprintf('Error during %s editing : %s.', $objectType, $message)); + + $fileUpdateForm->setErrorMessage($message); + + $this->getParserContext() + ->addForm($fileUpdateForm) + ->setGeneralError($message); + } + + return $fileModelInstance; + } + + /** * Manage how an image is updated * @@ -373,72 +436,13 @@ class FileController extends BaseAdminController return $response; } - $message = false; - - $fileManager = $this->getFileManager(); - - $modelInstance = $fileManager->getModelInstance('image', $parentType); - - $imageModification = $modelInstance->getUpdateFormInstance($this->getRequest()); - - /** @var FileModelInterface $image */ - $image = $modelInstance->getQueryInstance()->findPk($imageId); - - try { - $oldImage = clone $image; - - if (null === $image) { - throw new \InvalidArgumentException(sprintf('%d image id does not exist', $imageId)); - } - - $form = $this->validateForm($imageModification); - - $event = $this->createImageEventInstance($parentType, $image, $form->getData()); - $event->setOldModelImage($oldImage); - - $files = $this->getRequest()->files; - $fileForm = $files->get($imageModification->getName()); - if (isset($fileForm['file'])) { - $event->setUploadedFile($fileForm['file']); - } - - $this->dispatch(TheliaEvents::IMAGE_UPDATE, $event); - - $imageUpdated = $event->getModelImage(); - - $this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE, sprintf('Image with Ref %s (ID %d) modified', $imageUpdated->getTitle(), $imageUpdated->getId())); - - if ($this->getRequest()->get('save_mode') == 'close') { - $this->redirect(URL::getInstance()->absoluteUrl($modelInstance->getRedirectionUrl($imageId))); - } else { - $this->redirectSuccess($imageModification); - } - - } catch (FormValidationException $e) { - $message = sprintf('Please check your input: %s', $e->getMessage()); - } catch (PropelException $e) { - $message = $e->getMessage(); - } catch (\Exception $e) { - $message = sprintf('Sorry, an error occurred: %s', $e->getMessage().' '.$e->getFile()); - } - - if ($message !== false) { - Tlog::getInstance()->error(sprintf('Error during image editing : %s.', $message)); - - $imageModification->setErrorMessage($message); - - $this->getParserContext() - ->addForm($imageModification) - ->setGeneralError($message); - } - - $redirectUrl = $modelInstance->getRedirectionUrl($imageId); + $imageInstance = $this->updateFileAction($imageId, $parentType, 'image', TheliaEvents::IMAGE_UPDATE); return $this->render('image-edit', array( 'imageId' => $imageId, 'imageType' => $parentType, - 'redirectUrl' => $redirectUrl, - 'formId' => $modelInstance->getUpdateFormId() + 'redirectUrl' => $imageInstance, + 'formId' => $imageInstance->getUpdateFormId() )); } @@ -452,79 +456,97 @@ class FileController extends BaseAdminController */ public function updateDocumentAction($documentId, $parentType) { + if (null !== $response = $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE)) { return $response; } - $message = false; - - $fileManager = $this->getFileManager(); - - $modelInstance = $fileManager->getModelInstance('document', $parentType); - - $documentModification = $modelInstance->getUpdateFormInstance($this->getRequest()); - - /** @var FileModelInterface $document */ - $document = $modelInstance->getQueryInstance()->findPk($documentId); - - try { - $oldDocument = clone $document; - - if (null === $document) { - throw new \InvalidArgumentException(sprintf('%d document id does not exist', $documentId)); - } - - $form = $this->validateForm($documentModification); - - $event = $this->createDocumentEventInstance($parentType, $document, $form->getData()); - $event->setOldModelDocument($oldDocument); - - $files = $this->getRequest()->files; - $fileForm = $files->get($documentModification->getName()); - if (isset($fileForm['file'])) { - $event->setUploadedFile($fileForm['file']); - } - - $this->dispatch(TheliaEvents::DOCUMENT_UPDATE, $event); - - $documentUpdated = $event->getModelDocument(); - - $this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE, sprintf('Document with Ref %s (ID %d) modified', $documentUpdated->getTitle(), $documentUpdated->getId())); - - if ($this->getRequest()->get('save_mode') == 'close') { - $this->redirect(URL::getInstance()->absoluteUrl($modelInstance->getRedirectionUrl($documentId))); - } else { - $this->redirectSuccess($documentModification); - } - - } catch (FormValidationException $e) { - $message = sprintf('Please check your input: %s', $e->getMessage()); - } catch (PropelException $e) { - $message = $e->getMessage(); - } catch (\Exception $e) { - $message = sprintf('Sorry, an error occurred: %s', $e->getMessage().' '.$e->getFile()); - } - - if ($message !== false) { - Tlog::getInstance()->error(sprintf('Error during document editing : %s.', $message)); - - $documentModification->setErrorMessage($message); - - $this->getParserContext() - ->addForm($documentModification) - ->setGeneralError($message); - } - - $redirectUrl = $modelInstance->getRedirectionUrl($documentId); + $documentInstance = $this->updateFileAction($documentId, $parentType, 'document', TheliaEvents::DOCUMENT_UPDATE); return $this->render('document-edit', array( 'documentId' => $documentId, 'documentType' => $parentType, - 'redirectUrl' => $redirectUrl, - 'formId' => $modelInstance->getUpdateFormId() + 'redirectUrl' => $documentInstance->getRedirectionUrl($documentId), + 'formId' => $documentInstance->getUpdateFormId() )); } + + /** + * Manage how a image has to be deleted (AJAX) + * + * @param int $fileId Parent id owning image being deleted + * @param string $parentType Parent Type owning image being deleted + * @param string $objectType the type of the file, image or document + * @param string $eventName the event type. + * + * @return Response + */ + public function deleteFileAction($fileId, $parentType, $objectType, $eventName) + { + $message = null; + + $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); + $this->checkXmlHttpRequest(); + + $fileManager = $this->getFileManager(); + $modelInstance = $fileManager->getModelInstance($objectType, $parentType); + + $model = $modelInstance->getQueryInstance()->findPk($fileId); + + if ($model == null) { + return $this->pageNotFound(); + } + + // Feed event + $fileDeleteEvent = new FileDeleteEvent($model); + + // Dispatch Event to the Action + try { + $this->dispatch($eventName, $fileDeleteEvent); + + $this->adminLogAppend( + AdminResources::retrieve($parentType), + AccessManager::UPDATE, + $this->getTranslator()->trans( + 'Deleting %obj% for %id% with parent id %parentId%', + array( + '%obj%' => $objectType, + '%id%' => $fileDeleteEvent->getFileToDelete()->getId(), + '%parentId%' => $fileDeleteEvent->getFileToDelete()->getParentId(), + ) + ) + ); + } catch (\Exception $e) { + $message = $this->getTranslator()->trans( + 'Fail to delete %obj% for %id% with parent id %parentId% (Exception : %e%)', + array( + '%obj%' => $objectType, + '%id%' => $fileDeleteEvent->getFileToDelete()->getId(), + '%parentId%' => $fileDeleteEvent->getFileToDelete()->getParentId(), + '%e%' => $e->getMessage() + ) + ); + + $this->adminLogAppend( + AdminResources::retrieve($parentType), + AccessManager::UPDATE, + $message + ); + } + + if (null === $message) { + $message = $this->getTranslator()->trans( + '%obj%s deleted successfully', + ['%obj%' => ucfirst($objectType)], + 'image' + ); + } + + return new Response($message); + } + + /** * Manage how a image has to be deleted (AJAX) * @@ -535,189 +557,7 @@ class FileController extends BaseAdminController */ public function deleteImageAction($imageId, $parentType) { - $message = null; - - $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); - $this->checkXmlHttpRequest(); - - $fileManager = $this->getFileManager(); - $modelInstance = $fileManager->getModelInstance('image', $parentType); - - $model = $modelInstance->getQueryInstance()->findPk($imageId); - - if ($model == null) { - return $this->pageNotFound(); - } - - // Feed event - $imageDeleteEvent = new ImageDeleteEvent( - $model, - $parentType - ); - - // Dispatch Event to the Action - try { - $this->dispatch( - TheliaEvents::IMAGE_DELETE, - $imageDeleteEvent - ); - - $this->adminLogAppend( - AdminResources::retrieve($parentType), - AccessManager::UPDATE, - $this->container->get('thelia.translator')->trans( - 'Deleting image for %id% with parent id %parentId%', - array( - '%id%' => $imageDeleteEvent->getImageToDelete()->getId(), - '%parentId%' => $imageDeleteEvent->getImageToDelete()->getParentId(), - ), - 'image' - ) - ); - } catch (\Exception $e) { - $this->adminLogAppend( - AdminResources::retrieve($parentType), - AccessManager::UPDATE, - $this->container->get('thelia.translator')->trans( - 'Fail to delete image for %id% with parent id %parentId% (Exception : %e%)', - array( - '%id%' => $imageDeleteEvent->getImageToDelete()->getId(), - '%parentId%' => $imageDeleteEvent->getImageToDelete()->getParentId(), - '%e%' => $e->getMessage() - ), - 'image' - ) - ); - $message = $this->getTranslator() - ->trans( - 'Fail to delete image for %id% with parent id %parentId% (Exception : %e%)', - array( - '%id%' => $imageDeleteEvent->getImageToDelete()->getId(), - '%parentId%' => $imageDeleteEvent->getImageToDelete()->getParentId(), - '%e%' => $e->getMessage() - ), - 'image' - ); - } - - if (null === $message) { - $message = $this->getTranslator() - ->trans( - 'Images deleted successfully', - array(), - 'image' - ); - } - - return new Response($message); - } - - public function updateImagePositionAction($parentType, /** @noinspection PhpUnusedParameterInspection */ $parentId) - { - $message = null; - - $imageId = $this->getRequest()->request->get('image_id'); - $position = $this->getRequest()->request->get('position'); - - $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); - $this->checkXmlHttpRequest(); - - $fileManager = $this->getFileManager(); - $modelInstance = $fileManager->getModelInstance('image', $parentType); - $model = $modelInstance->getQueryInstance()->findPk($imageId); - - if ($model === null || $position === null) { - return $this->pageNotFound(); - } - - // Feed event - $imageUpdateImagePositionEvent = new UpdateFilePositionEvent( - $modelInstance->getQueryInstance($parentType), - $imageId, - UpdateFilePositionEvent::POSITION_ABSOLUTE, - $position - ); - - // Dispatch Event to the Action - try { - $this->dispatch( - TheliaEvents::IMAGE_UPDATE_POSITION, - $imageUpdateImagePositionEvent - ); - } catch (\Exception $e) { - - $message = $this->getTranslator() - ->trans( - 'Fail to update image position', - array(), - 'image' - ) . $e->getMessage(); - } - - if (null === $message) { - $message = $this->getTranslator() - ->trans( - 'Image position updated', - array(), - 'image' - ); - } - - return new Response($message); - } - - public function updateDocumentPositionAction($parentType, /** @noinspection PhpUnusedParameterInspection */ $parentId) - { - $message = null; - - $documentId = $this->getRequest()->request->get('document_id'); - $position = $this->getRequest()->request->get('position'); - - $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); - $this->checkXmlHttpRequest(); - - $fileManager = $this->getFileManager(); - $modelInstance = $fileManager->getModelInstance('document', $parentType); - $model = $modelInstance->getQueryInstance()->findPk($documentId); - - if ($model === null || $position === null) { - return $this->pageNotFound(); - } - - // Feed event - $documentUpdateDocumentPositionEvent = new UpdateFilePositionEvent( - $modelInstance->getQueryInstance(), - $documentId, - UpdateFilePositionEvent::POSITION_ABSOLUTE, - $position - ); - - // Dispatch Event to the Action - try { - $this->dispatch( - TheliaEvents::DOCUMENT_UPDATE_POSITION, - $documentUpdateDocumentPositionEvent - ); - } catch (\Exception $e) { - - $message = $this->getTranslator() - ->trans( - 'Fail to update document position', - array(), - 'document' - ) . $e->getMessage(); - } - - if (null === $message) { - $message = $this->getTranslator() - ->trans( - 'Document position updated', - array(), - 'document' - ); - } - - return new Response($message); + return $this->deleteFileAction($imageId, $parentType, 'image', TheliaEvents::IMAGE_DELETE); } /** @@ -730,160 +570,66 @@ class FileController extends BaseAdminController */ public function deleteDocumentAction($documentId, $parentType) { + return $this->deleteFileAction($documentId, $parentType, 'document', TheliaEvents::DOCUMENT_DELETE); + } + + public function updateFilePositionAction($parentType, $parentId, $objectType, $eventName) + { + $message = null; + + $position = $this->getRequest()->request->get('position'); + $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkXmlHttpRequest(); $fileManager = $this->getFileManager(); - $modelInstance = $fileManager->getModelInstance('document', $parentType); - $model = $modelInstance->getQueryInstance()->findPk($documentId); + $modelInstance = $fileManager->getModelInstance($objectType, $parentType); + $model = $modelInstance->getQueryInstance()->findPk($parentId); - if ($model == null) { + if ($model === null || $position === null) { return $this->pageNotFound(); } // Feed event - $documentDeleteEvent = new DocumentDeleteEvent( - $model, - $parentType + $event = new UpdateFilePositionEvent( + $modelInstance->getQueryInstance($parentType), + $parentId, + UpdateFilePositionEvent::POSITION_ABSOLUTE, + $position ); // Dispatch Event to the Action try { - $this->dispatch( - TheliaEvents::DOCUMENT_DELETE, - $documentDeleteEvent - ); - - $this->adminLogAppend( - AdminResources::retrieve($parentType), - AccessManager::UPDATE, - $this->container->get('thelia.translator')->trans( - 'Deleting document for %id% with parent id %parentId%', - array( - '%id%' => $documentDeleteEvent->getDocumentToDelete()->getId(), - '%parentId%' => $documentDeleteEvent->getDocumentToDelete()->getParentId(), - ), - 'document' - ) - ); + $this->dispatch($eventName,$event); } catch (\Exception $e) { - $this->adminLogAppend( - AdminResources::retrieve($parentType), - AccessManager::UPDATE, - $this->container->get('thelia.translator')->trans( - 'Fail to delete document for %id% with parent id %parentId% (Exception : %e%)', - array( - '%id%' => $documentDeleteEvent->getDocumentToDelete()->getId(), - '%parentId%' => $documentDeleteEvent->getDocumentToDelete()->getParentId(), - '%e%' => $e->getMessage() - ), - 'document' - ) - ); + + $message = $this->getTranslator()->trans( + 'Fail to update %type% position: %err%', + [ '%type%' => $objectType, '%err%' => $e->getMessage() ] + ); } - $message = $this->getTranslator() - ->trans( - 'Document deleted successfully', - array(), - 'document' + if (null === $message) { + $message = $this->getTranslator()->trans( + '%type% position updated', + [ '%type%' => ucfirst($objectType) ] ); + } return new Response($message); } - /** - * Log error message - * - * @param string $parentType Parent type - * @param string $action Creation|Update|Delete - * @param string $message Message to log - * @param \Exception $e Exception to log - * - * @return $this - */ - protected function logError($parentType, $action, $message, $e) + public function updateImagePositionAction($parentType, /** @noinspection PhpUnusedParameterInspection */ $parentId) { - Tlog::getInstance()->error( - sprintf( - 'Error during ' . $parentType . ' ' . $action . ' process : %s. Exception was %s', - $message, - $e->getMessage() - ) - ); + $imageId = $this->getRequest()->request->get('image_id'); - return $this; + return $this->updateFilePositionAction($parentType, $imageId, 'image', TheliaEvents::IMAGE_UPDATE_POSITION); } - /** - * Create Image Event instance - * - * @param string $parentType Parent Type owning images being saved - * @param FileModelInterface $model the model - * @param array $data Post data - * - * @return ImageCreateOrUpdateEvent - */ - protected function createImageEventInstance($parentType, $model, $data) + public function updateDocumentPositionAction($parentType, /** @noinspection PhpUnusedParameterInspection */ $parentId) { - $imageCreateEvent = new ImageCreateOrUpdateEvent(null); + $documentId = $this->getRequest()->request->get('document_id'); - $model->setLocale($data['locale']); - - if (isset($data['title'])) { - $model->setTitle($data['title']); - } - if (isset($data['chapo'])) { - $model->setChapo($data['chapo']); - } - if (isset($data['description'])) { - $model->setDescription($data['description']); - } - if (isset($data['file'])) { - $model->setFile($data['file']); - } - if (isset($data['postscriptum'])) { - $model->setPostscriptum($data['postscriptum']); - } - - $imageCreateEvent->setModelImage($model); - - return $imageCreateEvent; + return $this->updateFilePositionAction($parentType, $documentId, 'document', TheliaEvents::DOCUMENT_UPDATE_POSITION); } - - /** - * Create Document Event instance - * - * @param string $parentType Parent Type owning documents being saved - * @param FileModelInterface $model the model - * @param array $data Post data - * - * @return DocumentCreateOrUpdateEvent - */ - protected function createDocumentEventInstance($parentType, $model, $data) - { - $documentCreateEvent = new DocumentCreateOrUpdateEvent(null); - - $model->setLocale($data['locale']); - if (isset($data['title'])) { - $model->setTitle($data['title']); - } - if (isset($data['chapo'])) { - $model->setChapo($data['chapo']); - } - if (isset($data['description'])) { - $model->setDescription($data['description']); - } - if (isset($data['file'])) { - $model->setFile($data['file']); - } - if (isset($data['postscriptum'])) { - $model->setPostscriptum($data['postscriptum']); - } - - $documentCreateEvent->setModelDocument($model); - - return $documentCreateEvent; - } - -} +} \ No newline at end of file diff --git a/core/lib/Thelia/Core/Event/Document/DocumentCreateOrUpdateEvent.php b/core/lib/Thelia/Core/Event/Document/DocumentCreateOrUpdateEvent.php index 422f4a889..b0c603e8d 100644 --- a/core/lib/Thelia/Core/Event/Document/DocumentCreateOrUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/Document/DocumentCreateOrUpdateEvent.php @@ -11,167 +11,121 @@ /*************************************************************************************/ namespace Thelia\Core\Event\Document; -use Symfony\Component\HttpFoundation\File\UploadedFile; -use Thelia\Core\Event\ActionEvent; + +use Thelia\Core\Event\File\FileCreateOrUpdateEvent; use Thelia\Files\FileModelInterface; -use Thelia\Model\CategoryDocument; -use Thelia\Model\ContentDocument; -use Thelia\Model\FolderDocument; -use Thelia\Model\ProductDocument; /** * Created by JetBrains PhpStorm. * Date: 9/18/13 * Time: 3:56 PM * - * Occurring when a Document is saved + * Occurring when an Document is saved * * @package Document * @author Guillaume MOREL - * + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ -class DocumentCreateOrUpdateEvent extends ActionEvent +class DocumentCreateOrUpdateEvent extends FileCreateOrUpdateEvent { - - /** @var CategoryDocument|ProductDocument|ContentDocument|FolderDocument model to save */ - protected $modelDocument = array(); - - /** @var CategoryDocument|ProductDocument|ContentDocument|FolderDocument model to save */ - protected $oldModelDocument = array(); - - /** @var UploadedFile Document file to save */ - protected $uploadedFile = null; - - /** @var int Document parent id */ - protected $parentId = null; - - /** @var string Parent name */ - protected $parentName = null; - /** * Constructor * - * @param int $parentId Document parent id + * @param string $documentType Document type + * ex : FileManager::TYPE_CATEGORY + * @param int $parentId Document parent id + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ - public function __construct($parentId) + public function __construct($documentType, $parentId) { - $this->parentId = $parentId; + parent::__construct($parentId); + } + + /** + * @param mixed $locale + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead + */ + public function setLocale($locale) + { + return $this; + } + + /** + * @return mixed + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead + */ + public function getLocale() + { + throw new \RuntimeException("getLocale() is deprecated and no longer supported"); } /** * Set Document to save * - * @param FileModelInterface $document Document to save + * @param $document FileModelInterface * * @return $this + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ public function setModelDocument($document) { - $this->modelDocument = $document; - - return $this; + parent::setModel($document); } /** * Get Document being saved * * @return FileModelInterface + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ public function getModelDocument() { - return $this->modelDocument; + return parent::getModel(); } /** - * Set Document parent id + * Set picture type * - * @param int $parentId Document parent id + * @param string $documentType Document type * * @return $this + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ - public function setParentId($parentId) + public function setDocumentType($documentType) { - $this->parentId = $parentId; - return $this; } /** - * Get Document parent id - * - * @return int - */ - public function getParentId() - { - return $this->parentId; - } - - /** - * Set uploaded file - * - * @param UploadedFile $uploadedFile File being uploaded - * - * @return $this - */ - public function setUploadedFile($uploadedFile) - { - $this->uploadedFile = $uploadedFile; - - return $this; - } - - /** - * Get uploaded file - * - * @return UploadedFile - */ - public function getUploadedFile() - { - return $this->uploadedFile; - } - - /** - * Set parent name - * - * @param string $parentName Parent name - * - * @return $this - */ - public function setParentName($parentName) - { - $this->parentName = $parentName; - - return $this; - } - - /** - * Get parent name + * Get picture type * * @return string + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ - public function getParentName() + public function getDocumentType() { - return $this->parentName; + throw new \RuntimeException("getDocumentType() is deprecated and no longer supported"); } /** * Set old model value * * @param FileModelInterface $oldModelDocument + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ public function setOldModelDocument($oldModelDocument) { - $this->oldModelDocument = $oldModelDocument; + parent::setOldModel($oldModelDocument); } /** * Get old model value * * @return FileModelInterface + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ public function getOldModelDocument() { - return $this->oldModelDocument; + return parent::getOldModel(); } - -} +} \ No newline at end of file diff --git a/core/lib/Thelia/Core/Event/Document/DocumentDeleteEvent.php b/core/lib/Thelia/Core/Event/Document/DocumentDeleteEvent.php index d97ddcd23..a258eb0b1 100644 --- a/core/lib/Thelia/Core/Event/Document/DocumentDeleteEvent.php +++ b/core/lib/Thelia/Core/Event/Document/DocumentDeleteEvent.php @@ -12,8 +12,11 @@ namespace Thelia\Core\Event\Document; -use Thelia\Core\Event\ActionEvent; -use Thelia\Files\FileModelInterface; +use Thelia\Core\Event\Image\FileDeleteEvent; +use Thelia\Model\CategoryDocument; +use Thelia\Model\ContentDocument; +use Thelia\Model\FolderDocument; +use Thelia\Model\ProductDocument; /** * Created by JetBrains PhpStorm. @@ -24,34 +27,58 @@ use Thelia\Files\FileModelInterface; * * @package Document * @author Guillaume MOREL - * + * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead */ -class DocumentDeleteEvent extends ActionEvent +class DocumentDeleteEvent extends FileDeleteEvent { - - /** @var FileModelInterface Document about to be deleted */ - protected $documentToDelete = null; - /** * Constructor * - * @param FileModelInterface $documentToDelete Document about to be deleted + * @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $documentToDelete Document about to be deleted + * @param string $documentType Document type + * ex : FileManager::TYPE_CATEGORY + * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead */ - public function __construct($documentToDelete) + public function __construct($documentToDelete, $documentType) { - $this->documentToDelete = $documentToDelete; + parent::__construct($documentToDelete); + } + + /** + * Set picture type + * + * @param string $documentType Document type + * + * @return $this + * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead + */ + public function setDocumentType($documentType) + { + return $this; + } + + /** + * Get picture type + * + * @return string + * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead + */ + public function getDocumentType() + { + throw new \RuntimeException("getDocumentType() is deprecated and no longer supported"); } /** * Set Document about to be deleted * - * @param FileModelInterface $documentToDelete Document about to be deleted + * @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $documentToDelete Document about to be deleted * * @return $this + * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead */ public function setDocumentToDelete($documentToDelete) { - $this->documentToDelete = $documentToDelete; + parent::setFileToDelete($documentToDelete); return $this; } @@ -59,11 +86,12 @@ class DocumentDeleteEvent extends ActionEvent /** * Get Document about to be deleted * - * @return FileModelInterface + * @return CategoryDocument|ProductDocument|ContentDocument|FolderDocument + * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead */ public function getDocumentToDelete() { - return $this->documentToDelete; + return parent::getFileToDelete(); } -} +} \ No newline at end of file diff --git a/core/lib/Thelia/Core/Event/File/FileCreateOrUpdateEvent.php b/core/lib/Thelia/Core/Event/File/FileCreateOrUpdateEvent.php new file mode 100644 index 000000000..08784f9cd --- /dev/null +++ b/core/lib/Thelia/Core/Event/File/FileCreateOrUpdateEvent.php @@ -0,0 +1,168 @@ + + * + */ +class FileCreateOrUpdateEvent extends ActionEvent +{ + /** @var FileModelInterface model to save */ + protected $model = array(); + + /** @var FileModelInterface model to save */ + protected $oldModel = array(); + + /** @var UploadedFile Document file to save */ + protected $uploadedFile = null; + + /** @var int Document parent id */ + protected $parentId = null; + + /** @var string Parent name */ + protected $parentName = null; + + /** + * Constructor + * + * @param int $parentId file parent id + */ + public function __construct($parentId) + { + $this->parentId = $parentId; + } + + /** + * Set file to save + * + * @param FileModelInterface $model Document to save + * + * @return $this + */ + public function setModel($model) + { + $this->model = $model; + + return $this; + } + + /** + * Get file being saved + * + * @return FileModelInterface + */ + public function getModel() + { + return $this->model; + } + + /** + * Set Document parent id + * + * @param int $parentId Document parent id + * + * @return $this + */ + public function setParentId($parentId) + { + $this->parentId = $parentId; + + return $this; + } + + /** + * Get Document parent id + * + * @return int + */ + public function getParentId() + { + return $this->parentId; + } + + /** + * Set uploaded file + * + * @param UploadedFile $uploadedFile File being uploaded + * + * @return $this + */ + public function setUploadedFile($uploadedFile) + { + $this->uploadedFile = $uploadedFile; + + return $this; + } + + /** + * Get uploaded file + * + * @return UploadedFile + */ + public function getUploadedFile() + { + return $this->uploadedFile; + } + + /** + * Set parent name + * + * @param string $parentName Parent name + * + * @return $this + */ + public function setParentName($parentName) + { + $this->parentName = $parentName; + + return $this; + } + + /** + * Get parent name + * + * @return string + */ + public function getParentName() + { + return $this->parentName; + } + + /** + * Set old model value + * + * @param FileModelInterface $oldModel + */ + public function setOldModel($oldModel) + { + $this->oldModel = $oldModel; + } + + /** + * Get old model value + * + * @return FileModelInterface + */ + public function getOldModel() + { + return $this->oldModel; + } +} diff --git a/core/lib/Thelia/Core/Event/File/FileDeleteEvent.php b/core/lib/Thelia/Core/Event/File/FileDeleteEvent.php new file mode 100644 index 000000000..38fd3203f --- /dev/null +++ b/core/lib/Thelia/Core/Event/File/FileDeleteEvent.php @@ -0,0 +1,62 @@ + + */ +class FileDeleteEvent extends ActionEvent +{ + /** @var FileModelInterface Image about to be deleted */ + protected $fileToDelete = null; + + /** + * Constructor + * + * @param FileModelInterface $fileToDelete Image about to be deleted + */ + public function __construct($fileToDelete) + { + $this->fileToDelete = $fileToDelete; + } + + /** + * Set Image about to be deleted + * + * @param FileModelInterface $fileToDelete Image about to be deleted + * + * @return $this + */ + public function setFileToDelete($fileToDelete) + { + $this->fileToDelete = $fileToDelete; + + return $this; + } + + /** + * Get Image about to be deleted + * + * @return FileModelInterface + */ + public function getFileToDelete() + { + return $this->fileToDelete; + } + +} diff --git a/core/lib/Thelia/Core/Event/Image/ImageCreateOrUpdateEvent.php b/core/lib/Thelia/Core/Event/Image/ImageCreateOrUpdateEvent.php index 562a79609..85826cbd6 100644 --- a/core/lib/Thelia/Core/Event/Image/ImageCreateOrUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/Image/ImageCreateOrUpdateEvent.php @@ -11,8 +11,8 @@ /*************************************************************************************/ namespace Thelia\Core\Event\Image; -use Symfony\Component\HttpFoundation\File\UploadedFile; -use Thelia\Core\Event\ActionEvent; + +use Thelia\Core\Event\File\FileCreateOrUpdateEvent; use Thelia\Files\FileModelInterface; /** @@ -24,170 +24,108 @@ use Thelia\Files\FileModelInterface; * * @package Image * @author Guillaume MOREL - * + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ -class ImageCreateOrUpdateEvent extends ActionEvent +class ImageCreateOrUpdateEvent extends FileCreateOrUpdateEvent { - - /** @var FileModelInterface model to save */ - protected $modelImage = array(); - - /** @var FileModelInterface model to save */ - protected $oldModelImage = array(); - - /** @var UploadedFile Image file to save */ - protected $uploadedFile = null; - - /** @var int Image parent id */ - protected $parentId = null; - - /** @var string Parent name */ - protected $parentName = null; - - protected $locale; - /** * Constructor * - * @param int $parentId Image parent id + * @param string $imageType Image type + * ex : FileManager::TYPE_CATEGORY + * @param int $parentId Image parent id + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ - public function __construct($parentId) + public function __construct($imageType, $parentId) { - $this->parentId = $parentId; + parent::__construct($parentId); } /** - * @param string $locale + * @param mixed $locale + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ public function setLocale($locale) { - $this->locale = $locale; - return $this; } /** * @return mixed + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ public function getLocale() { - return $this->locale; + throw new \RuntimeException("getLocale() is deprecated and no longer supported"); } /** * Set Image to save * - * @param FileModelInterface $image + * @param $image FileModelInterface * * @return $this + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ public function setModelImage($image) { - $this->modelImage = $image; - - return $this; + parent::setModel($image); } /** * Get Image being saved * * @return FileModelInterface + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ public function getModelImage() { - return $this->modelImage; + return parent::getModel(); } /** - * Set Image parent id + * Set picture type * - * @param int $parentId Image parent id + * @param string $imageType Image type * * @return $this + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ - public function setParentId($parentId) + public function setImageType($imageType) { - $this->parentId = $parentId; - return $this; } /** - * Get Image parent id - * - * @return int - */ - public function getParentId() - { - return $this->parentId; - } - - /** - * Set uploaded file - * - * @param UploadedFile $uploadedFile File being uploaded - * - * @return $this - */ - public function setUploadedFile($uploadedFile) - { - $this->uploadedFile = $uploadedFile; - - return $this; - } - - /** - * Get uploaded file - * - * @return UploadedFile - */ - public function getUploadedFile() - { - return $this->uploadedFile; - } - - /** - * Set parent name - * - * @param string $parentName Parent name - * - * @return $this - */ - public function setParentName($parentName) - { - $this->parentName = $parentName; - - return $this; - } - - /** - * Get parent name + * Get picture type * * @return string + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ - public function getParentName() + public function getImageType() { - return $this->parentName; + throw new \RuntimeException("getImageType() is deprecated and no longer supported"); } /** * Set old model value * - * @param \Thelia\Model\CategoryImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage|\Thelia\Model\ProductImage $oldModelImage + * @param FileModelInterface $oldModelImage + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ public function setOldModelImage($oldModelImage) { - $this->oldModelImage = $oldModelImage; + parent::setOldModel($oldModelImage); } /** * Get old model value * - * @return \Thelia\Model\CategoryImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage|\Thelia\Model\ProductImage + * @return FileModelInterface + * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ public function getOldModelImage() { - return $this->oldModelImage; + return parent::getOldModel(); } - } diff --git a/core/lib/Thelia/Core/Event/Image/ImageDeleteEvent.php b/core/lib/Thelia/Core/Event/Image/ImageDeleteEvent.php index 4021a27e9..266875e67 100644 --- a/core/lib/Thelia/Core/Event/Image/ImageDeleteEvent.php +++ b/core/lib/Thelia/Core/Event/Image/ImageDeleteEvent.php @@ -12,8 +12,10 @@ namespace Thelia\Core\Event\Image; -use Thelia\Core\Event\ActionEvent; -use Thelia\Files\FileModelInterface; +use Thelia\Model\CategoryImage; +use Thelia\Model\ContentImage; +use Thelia\Model\FolderImage; +use Thelia\Model\ProductImage; /** * Created by JetBrains PhpStorm. @@ -24,36 +26,58 @@ use Thelia\Files\FileModelInterface; * * @package Image * @author Guillaume MOREL - * + * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead */ -class ImageDeleteEvent extends ActionEvent +class ImageDeleteEvent extends FileDeleteEvent { - /** @var string Image type */ - protected $imageType = null; - - /** @var FileModelInterface Image about to be deleted */ - protected $imageToDelete = null; - /** * Constructor * - * @param FileModelInterface $imageToDelete Image about to be deleted + * @param CategoryImage|ProductImage|ContentImage|FolderImage $imageToDelete Image about to be deleted + * @param string $imageType Image type + * ex : FileManager::TYPE_CATEGORY + * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead */ - public function __construct($imageToDelete) + public function __construct($imageToDelete, $imageType) { - $this->imageToDelete = $imageToDelete; + parent::__construct($imageToDelete); + } + + /** + * Set picture type + * + * @param string $imageType Image type + * + * @return $this + * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead + */ + public function setImageType($imageType) + { + return $this; + } + + /** + * Get picture type + * + * @return string + * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead + */ + public function getImageType() + { + throw new \RuntimeException("getImageType() is deprecated and no longer supported"); } /** * Set Image about to be deleted * - * @param FileModelInterface $imageToDelete Image about to be deleted + * @param CategoryImage|ProductImage|ContentImage|FolderImage $imageToDelete Image about to be deleted * * @return $this + * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead */ public function setImageToDelete($imageToDelete) { - $this->imageToDelete = $imageToDelete; + parent::setFileToDelete($imageToDelete); return $this; } @@ -61,11 +85,12 @@ class ImageDeleteEvent extends ActionEvent /** * Get Image about to be deleted * - * @return FileModelInterface + * @return CategoryImage|ProductImage|ContentImage|FolderImage + * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead */ public function getImageToDelete() { - return $this->imageToDelete; + return parent::getFileToDelete(); } -} +} \ No newline at end of file diff --git a/core/lib/Thelia/Files/FileModelInterface.php b/core/lib/Thelia/Files/FileModelInterface.php index 781070044..589e071ec 100644 --- a/core/lib/Thelia/Files/FileModelInterface.php +++ b/core/lib/Thelia/Files/FileModelInterface.php @@ -84,10 +84,27 @@ interface FileModelInterface */ public function getQueryInstance(); + /** + * Save the model object. + * + * @return mixed + */ public function save(); + + /** + * Delete the model object. + * + * @return mixed + */ public function delete(); + + /** + * Get the model object ID + * + * @return int + */ public function getId(); @@ -95,12 +112,39 @@ interface FileModelInterface * Set the current title * * @param string $title the title in the current locale - * @return FileModelInterface */ public function setTitle($title); + /** + * Get the current title + * + * @param string $title the title in the current locale + * @return FileModelInterface + */ + public function getTitle(); + + /** + * Set the chapo + * + * @param string $chapo the chapo in the current locale + * @return FileModelInterface + */ public function setChapo($chapo); + + /** + * Set the description + * + * @param string $description the description in the current locale + * @return FileModelInterface + */ public function setDescription($description); + + /** + * Set the postscriptum + * + * @param string $postscriptum the postscriptum in the current locale + * @return FileModelInterface + */ public function setPostscriptum($postscriptum); /** diff --git a/core/lib/Thelia/Tests/Action/ImageTest.php b/core/lib/Thelia/Tests/Action/ImageTest.php index 462d3b624..d6746a34c 100755 --- a/core/lib/Thelia/Tests/Action/ImageTest.php +++ b/core/lib/Thelia/Tests/Action/ImageTest.php @@ -32,13 +32,15 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup protected $session; + public function getDispatcher() { + return $this->getMock("Symfony\\Component\\EventDispatcher\\EventDispatcherInterface"); + } + public function getContainer() { $container = new \Symfony\Component\DependencyInjection\ContainerBuilder(); - $dispatcher = $this->getMock("Symfony\Component\EventDispatcher\EventDispatcherInterface"); - - $container->set("event_dispatcher", $dispatcher); + $container->set("event_dispatcher", $this->getDispatcher()); $request = new Request(); $request->setSession($this->session); @@ -137,6 +139,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testProcessNonExistentImage() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $image = new Image($this->getFileManager()); @@ -155,6 +158,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testProcessImageOutsideValidPath() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $image = new Image($this->getFileManager()); @@ -170,6 +174,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testProcessImageWithoutAnyTransformationsCopy() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-1.png"); $event->setCacheSubdirectory("tests"); @@ -199,6 +204,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testProcessImageWithoutAnyTransformationsSymlink() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-9.png"); $event->setCacheSubdirectory("tests"); @@ -228,6 +234,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testProcessImageResizeHorizWithBands() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-2.png"); $event->setCacheSubdirectory("tests"); @@ -248,6 +255,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testProcessImageResizeVertWithBands() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-3.png"); $event->setCacheSubdirectory("tests"); @@ -268,6 +276,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testProcessImageWithTransformations() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-4.png"); $event->setCacheSubdirectory("tests"); @@ -285,6 +294,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testProcessImageResizeHorizWithCrop() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-5.png"); $event->setCacheSubdirectory("tests"); @@ -305,6 +315,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testProcessImageResizeVertWithCrop() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-6.png"); $event->setCacheSubdirectory("tests"); @@ -325,6 +336,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testProcessImageResizeHorizKeepRatio() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-7.png"); $event->setCacheSubdirectory("tests"); @@ -343,6 +355,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testProcessImageResizeVertKeepRatio() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-8.png"); $event->setCacheSubdirectory("tests"); @@ -358,6 +371,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testClearTestsCache() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $event->setCacheSubdirectory('tests'); @@ -369,6 +383,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testClearWholeCache() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $image = new Image($this->getFileManager()); @@ -383,6 +398,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup public function testClearUnallowedPathCache() { $event = new ImageEvent($this->request); + $event->setDispatcher($this->getDispatcher()); $event->setCacheSubdirectory('../../../..'); From 5701d76c1e4596d0eced880ec464ae17358350f2 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Fri, 27 Jun 2014 19:50:20 +0200 Subject: [PATCH 16/64] Removed constraints on the "source" parameter --- core/lib/Thelia/Core/Template/Loop/Document.php | 10 +++------- core/lib/Thelia/Core/Template/Loop/Image.php | 10 +++------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/core/lib/Thelia/Core/Template/Loop/Document.php b/core/lib/Thelia/Core/Template/Loop/Document.php index 586a74ab7..5a129afd6 100644 --- a/core/lib/Thelia/Core/Template/Loop/Document.php +++ b/core/lib/Thelia/Core/Template/Loop/Document.php @@ -39,7 +39,7 @@ class Document extends BaseI18nLoop implements PropelSearchLoopInterface protected $timestampable = true; /** - * @var array Possible document sources + * @var array Possible standard document sources */ protected $possible_sources = array('category', 'product', 'folder', 'content', 'brand'); @@ -66,12 +66,8 @@ class Document extends BaseI18nLoop implements PropelSearchLoopInterface Argument::createIntTypeArgument('folder'), Argument::createIntTypeArgument('content'), - new Argument( - 'source', - new TypeCollection( - new EnumType($this->possible_sources) - ) - ), + Argument::createAnyTypeArgument('source'), + Argument::createIntTypeArgument('source_id'), Argument::createBooleanTypeArgument('force_return', true) ); diff --git a/core/lib/Thelia/Core/Template/Loop/Image.php b/core/lib/Thelia/Core/Template/Loop/Image.php index 234ed26de..b77609201 100644 --- a/core/lib/Thelia/Core/Template/Loop/Image.php +++ b/core/lib/Thelia/Core/Template/Loop/Image.php @@ -39,7 +39,7 @@ class Image extends BaseI18nLoop implements PropelSearchLoopInterface protected $timestampable = true; /** - * @var array Possible image sources + * @var array Possible standard image sources */ protected $possible_sources = array('category', 'product', 'folder', 'content', 'module', 'brand'); @@ -80,12 +80,8 @@ class Image extends BaseI18nLoop implements PropelSearchLoopInterface Argument::createIntTypeArgument('folder'), Argument::createIntTypeArgument('content'), - new Argument( - 'source', - new TypeCollection( - new EnumType($this->possible_sources) - ) - ), + Argument::createAnyTypeArgument('source'), + Argument::createIntTypeArgument('source_id'), Argument::createBooleanTypeArgument('force_return', true) ); From 297b0bd6ceec8949a4ba763ded6cb5440601a9db Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Fri, 27 Jun 2014 19:50:55 +0200 Subject: [PATCH 17/64] Added some missing form variables --- core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php index 9fe5d2581..3bdc715fd 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php @@ -135,12 +135,14 @@ class Form extends AbstractSmartyPlugin $template->assign("checked", isset($fieldVars['checked']) ? $fieldVars['checked'] : false); $template->assign("choices", isset($fieldVars['choices']) ? $fieldVars['choices'] : false); $template->assign("multiple", isset($fieldVars['multiple']) ? $fieldVars['multiple'] : false); + $template->assign("disabled", isset($fieldVars['disabled']) ? $fieldVars['disabled'] : false); + $template->assign("readonly", isset($fieldVars['readonly']) ? $fieldVars['readonly'] : false); + $template->assign("max_length", isset($fieldVars['max_length']) ? $fieldVars['max_length'] : false); + $template->assign('required', isset($fieldVars['required']) ? $fieldVars['required'] : false); $template->assign("label", $fieldVars["label"]); $template->assign("label_attr", $fieldVars["label_attr"]); - $template->assign('required', isset($fieldVars['required']) ? $fieldVars['required'] : false); - $template->assign('total_value_count', $total_value_count); $errors = $fieldVars["errors"]; From 15f60ad22bc7c8ecfb773751f2bce50bd9b959ad Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Fri, 27 Jun 2014 19:51:41 +0200 Subject: [PATCH 18/64] Added product's brand selection in the general tab. --- .../lib/Thelia/Core/Template/Loop/Product.php | 10 ++++++++-- .../Thelia/Form/ProductModificationForm.php | 12 ++++++++++++ .../default/includes/product-general-tab.html | 19 +++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/core/lib/Thelia/Core/Template/Loop/Product.php b/core/lib/Thelia/Core/Template/Loop/Product.php index e90f6b463..fbf5303fa 100644 --- a/core/lib/Thelia/Core/Template/Loop/Product.php +++ b/core/lib/Thelia/Core/Template/Loop/Product.php @@ -460,6 +460,7 @@ class Product extends BaseI18nLoop implements PropelSearchLoopInterface, SearchL /** @var \Thelia\Core\Security\SecurityContext $securityContext */ $securityContext = $this->container->get('thelia.securityContext'); + /** @var \Thelia\Model\Product $product */ foreach ($loopResult->getResultDataCollection() as $product) { $loopResultRow = new LoopResultRow($product); @@ -510,7 +511,6 @@ class Product extends BaseI18nLoop implements PropelSearchLoopInterface, SearchL ->set("TAXED_PROMO_PRICE" , $taxedPromoPrice) ->set("IS_PROMO" , $product->getVirtualColumn('is_promo')) ->set("IS_NEW" , $product->getVirtualColumn('is_new')) - ; @@ -989,6 +989,12 @@ class Product extends BaseI18nLoop implements PropelSearchLoopInterface, SearchL return $loopResult; } + /** + * @param $loopResultRow + * @param \Thelia\Model\Product $product + * @param $default_category_id + * @return mixed + */ private function associateValues($loopResultRow, $product, $default_category_id) { $loopResultRow @@ -1010,7 +1016,7 @@ class Product extends BaseI18nLoop implements PropelSearchLoopInterface, SearchL ->set("TEMPLATE" , $product->getTemplateId()) ->set("DEFAULT_CATEGORY" , $default_category_id) ->set("TAX_RULE_ID" , $product->getTaxRuleId()) - + ->set("BRAND_ID" , $product->getBrandId()) ; diff --git a/core/lib/Thelia/Form/ProductModificationForm.php b/core/lib/Thelia/Form/ProductModificationForm.php index b3b362f8a..18f79c659 100644 --- a/core/lib/Thelia/Form/ProductModificationForm.php +++ b/core/lib/Thelia/Form/ProductModificationForm.php @@ -13,6 +13,7 @@ namespace Thelia\Form; use Symfony\Component\Validator\Constraints\GreaterThan; +use Symfony\Component\Validator\Constraints\NotBlank; use Thelia\Core\Translation\Translator; class ProductModificationForm extends ProductCreationForm @@ -33,6 +34,17 @@ class ProductModificationForm extends ProductCreationForm "label" => Translator::getInstance()->trans("Product template"), "label_attr" => array("for" => "product_template_field") )) + ->add("brand_id", "integer", [ + 'constraints' => [ new NotBlank() ], + 'required' => true, + 'label' => Translator::getInstance()->trans('Brand / Supplier'), + 'label_attr' => [ + 'for' => 'mode', + ], + 'attr' => [ + 'help' => Translator::getInstance()->trans("Select the product brand, or supplier."), + ] + ]) ; // Add standard description fields, excluding title and locale, which a re defined in parent class diff --git a/templates/backOffice/default/includes/product-general-tab.html b/templates/backOffice/default/includes/product-general-tab.html index eab5f1e44..6d26a9ed5 100644 --- a/templates/backOffice/default/includes/product-general-tab.html +++ b/templates/backOffice/default/includes/product-general-tab.html @@ -71,6 +71,25 @@ {/form_field} + {form_field form=$form field='brand_id'} +
+ + {admin_form_field_label form=$form name='brand_id'} + + + + {if ! empty($label_attr.help)} + {$label_attr.help} + {/if} +
+ {/form_field} + {form_field form=$form field='visible'}
From f279131fe699e1caad8ffc6e38c642f093ba9433 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Fri, 27 Jun 2014 20:12:55 +0200 Subject: [PATCH 19/64] Added brand storage in product table --- core/lib/Thelia/Action/Product.php | 1 + .../Controller/Admin/ProductController.php | 8 +++++++- .../Core/Event/Product/ProductUpdateEvent.php | 20 +++++++++++++++++++ core/lib/Thelia/Tests/Action/ProductTest.php | 3 +++ 4 files changed, 31 insertions(+), 1 deletion(-) diff --git a/core/lib/Thelia/Action/Product.php b/core/lib/Thelia/Action/Product.php index 5d827be8e..2ef61a268 100644 --- a/core/lib/Thelia/Action/Product.php +++ b/core/lib/Thelia/Action/Product.php @@ -99,6 +99,7 @@ class Product extends BaseAction implements EventSubscriberInterface ->setChapo($event->getChapo()) ->setPostscriptum($event->getPostscriptum()) ->setVisible($event->getVisible() ? 1 : 0) + ->setBrandId($event->getBrandId() <= 0 ? null : $event->getBrandId()) ->save() ; diff --git a/core/lib/Thelia/Controller/Admin/ProductController.php b/core/lib/Thelia/Controller/Admin/ProductController.php index 4cbfbad42..f3a625807 100644 --- a/core/lib/Thelia/Controller/Admin/ProductController.php +++ b/core/lib/Thelia/Controller/Admin/ProductController.php @@ -164,6 +164,7 @@ class ProductController extends AbstractSeoCrudController ->setPostscriptum($formData['postscriptum']) ->setVisible($formData['visible']) ->setDefaultCategory($formData['default_category']) + ->setBrandId($formData['brand_id']) ; // Create and dispatch the change event @@ -213,6 +214,10 @@ class ProductController extends AbstractSeoCrudController $array[$key][] = $value; } + /** + * @param Product $object + * @return ProductModificationForm + */ protected function hydrateObjectForm($object) { // Find product's sale elements @@ -320,7 +325,8 @@ class ProductController extends AbstractSeoCrudController 'description' => $object->getDescription(), 'postscriptum' => $object->getPostscriptum(), 'visible' => $object->getVisible(), - 'default_category' => $object->getDefaultCategoryId() + 'default_category' => $object->getDefaultCategoryId(), + 'brand_id' => $object->getBrandId() ); // Setup the object form diff --git a/core/lib/Thelia/Core/Event/Product/ProductUpdateEvent.php b/core/lib/Thelia/Core/Event/Product/ProductUpdateEvent.php index 1768f3384..4a20b491c 100644 --- a/core/lib/Thelia/Core/Event/Product/ProductUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/Product/ProductUpdateEvent.php @@ -19,6 +19,8 @@ class ProductUpdateEvent extends ProductCreateEvent protected $chapo; protected $description; protected $postscriptum; + protected $brand_id; + public function __construct($product_id) { @@ -72,4 +74,22 @@ class ProductUpdateEvent extends ProductCreateEvent return $this; } + + /** + * @param int $brand_id + * @return $this + */ + public function setBrandId($brand_id) + { + $this->brand_id = $brand_id; + return $this; + } + + /** + * @return int + */ + public function getBrandId() + { + return $this->brand_id; + } } diff --git a/core/lib/Thelia/Tests/Action/ProductTest.php b/core/lib/Thelia/Tests/Action/ProductTest.php index 89c6d3a17..15a6d7424 100644 --- a/core/lib/Thelia/Tests/Action/ProductTest.php +++ b/core/lib/Thelia/Tests/Action/ProductTest.php @@ -26,6 +26,7 @@ use Thelia\Core\Event\Product\ProductSetTemplateEvent; use Thelia\Core\Event\Product\ProductToggleVisibilityEvent; use Thelia\Core\Event\Product\ProductUpdateEvent; use Thelia\Model\AccessoryQuery; +use Thelia\Model\BrandQuery; use Thelia\Model\CategoryQuery; use Thelia\Model\ContentQuery; use Thelia\Model\CurrencyQuery; @@ -115,6 +116,7 @@ class ProductTest extends TestCaseWithURLToolSetup { $event = new ProductUpdateEvent($product->getId()); $defaultCategory = CategoryQuery::create()->select('id')->addAscendingOrderByColumn('RAND()')->findOne(); + $brandId = BrandQuery::create()->findOne()->getId(); $event ->setLocale('fr_FR') ->setTitle('test MAJ titre en français') @@ -123,6 +125,7 @@ class ProductTest extends TestCaseWithURLToolSetup ->setPostscriptum('test postscriptum fr') ->setVisible(1) ->setDefaultCategory($defaultCategory) + ->setBrandId($brandId) ->setDispatcher($this->getDispatcher()); ; From a0aa0bd1c26a03514603446ef72b1207723c37ef Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Fri, 27 Jun 2014 21:07:51 +0200 Subject: [PATCH 20/64] Added brand logo image selection --- core/lib/Thelia/Action/Brand.php | 1 + .../Controller/Admin/BrandController.php | 18 ++++++----- .../Core/Event/Brand/BrandUpdateEvent.php | 19 ++++++++++++ core/lib/Thelia/Core/Template/Loop/Brand.php | 1 + .../Smarty/Plugins/AdminUtilities.php | 20 +++++++----- .../Form/Brand/BrandModificationForm.php | 9 ++++++ .../Thelia/Form/ProductModificationForm.php | 4 +-- .../assets/js/image-picker/image-picker.css | 29 +++++++++++++++++ .../js/image-picker/image-picker.min.js | 7 +++++ templates/backOffice/default/brand-edit.html | 31 +++++++++++++++++++ 10 files changed, 120 insertions(+), 19 deletions(-) create mode 100644 templates/backOffice/default/assets/js/image-picker/image-picker.css create mode 100644 templates/backOffice/default/assets/js/image-picker/image-picker.min.js diff --git a/core/lib/Thelia/Action/Brand.php b/core/lib/Thelia/Action/Brand.php index b362a0ee3..b289541f2 100644 --- a/core/lib/Thelia/Action/Brand.php +++ b/core/lib/Thelia/Action/Brand.php @@ -58,6 +58,7 @@ class Brand extends BaseAction implements EventSubscriberInterface $brand ->setVisible($event->getVisible()) + ->setLogoImageId(intval($event->getLogoImageId()) == 0 ? null : $event->getLogoImageId()) ->setLocale($event->getLocale()) ->setTitle($event->getTitle()) ->setDescription($event->getDescription()) diff --git a/core/lib/Thelia/Controller/Admin/BrandController.php b/core/lib/Thelia/Controller/Admin/BrandController.php index c41332894..b7229d27e 100644 --- a/core/lib/Thelia/Controller/Admin/BrandController.php +++ b/core/lib/Thelia/Controller/Admin/BrandController.php @@ -80,13 +80,14 @@ class BrandController extends AbstractSeoCrudController // Prepare the data that will hydrate the form $data = [ - 'id' => $object->getId(), - 'locale' => $object->getLocale(), - 'title' => $object->getTitle(), - 'chapo' => $object->getChapo(), - 'description' => $object->getDescription(), - 'postscriptum' => $object->getPostscriptum(), - 'visible' => $object->getVisible() ? true : false + 'id' => $object->getId(), + 'locale' => $object->getLocale(), + 'title' => $object->getTitle(), + 'chapo' => $object->getChapo(), + 'description' => $object->getDescription(), + 'postscriptum' => $object->getPostscriptum(), + 'visible' => $object->getVisible() ? true : false, + 'logo_image_id' => $object->getLogoImageId() ]; // Setup the object form @@ -123,12 +124,13 @@ class BrandController extends AbstractSeoCrudController $brandUpdateEvent = new BrandUpdateEvent($formData['id']); $brandUpdateEvent + ->setLogoImageId($formData['logo_image_id']) + ->setVisible($formData['visible']) ->setLocale($formData['locale']) ->setTitle($formData['title']) ->setChapo($formData['chapo']) ->setDescription($formData['description']) ->setPostscriptum($formData['postscriptum']) - ->setVisible($formData['visible']) ; return $brandUpdateEvent; diff --git a/core/lib/Thelia/Core/Event/Brand/BrandUpdateEvent.php b/core/lib/Thelia/Core/Event/Brand/BrandUpdateEvent.php index ffd2456d8..7b9398622 100644 --- a/core/lib/Thelia/Core/Event/Brand/BrandUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/Brand/BrandUpdateEvent.php @@ -24,6 +24,7 @@ class BrandUpdateEvent extends BrandCreateEvent protected $chapo; protected $description; protected $postscriptum; + protected $logo_image_id; /** * @param int $brandId @@ -112,4 +113,22 @@ class BrandUpdateEvent extends BrandCreateEvent { return $this->postscriptum; } + + /** + * @param int $logo_image_id + * @return $this + */ + public function setLogoImageId($logo_image_id) + { + $this->logo_image_id = $logo_image_id; + return $this; + } + + /** + * @return int + */ + public function getLogoImageId() + { + return $this->logo_image_id; + } } diff --git a/core/lib/Thelia/Core/Template/Loop/Brand.php b/core/lib/Thelia/Core/Template/Loop/Brand.php index 0a9774221..c5fab67af 100644 --- a/core/lib/Thelia/Core/Template/Loop/Brand.php +++ b/core/lib/Thelia/Core/Template/Loop/Brand.php @@ -183,6 +183,7 @@ class Brand extends BaseI18nLoop implements PropelSearchLoopInterface, SearchLoo ->set("META_KEYWORDS" , $brand->getVirtualColumn('i18n_META_KEYWORDS')) ->set("POSITION" , $brand->getPosition()) ->set("VISIBLE" , $brand->getVisible()) + ->set("LOGO_IMAGE_ID" , $brand->getLogoImageId()) ; $loopResult->addRow($loopResultRow); diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php index 0a8fe68e2..ff77aab6e 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php @@ -159,15 +159,19 @@ class AdminUtilities extends AbstractSmartyPlugin public function buildFormFieldLabel($params, &$smarty) { - $form = $this->getParam($params, 'form', false); - $field_name = $this->getParam($params, 'name', false); - $label_attr = $this->getParam($params, 'label_attr', array()); + $form = $this->getParam($params, 'form', false); + $field_name = $this->getParam($params, 'name', false); + $label_attr = $this->getParam($params, 'label_attr', false); - return $this->fetchSnippet($smarty, 'forms'.DS.'form-label', array( - 'form' => $form, - 'field_name' => $field_name, - 'label_attr' => $label_attr - )); + $args = [ + 'form' => $form, + 'field_name' => $field_name, + ]; + + if ($label_attr !== false) + $args['label_attr'] = $label_attr; + + return $this->fetchSnippet($smarty, 'forms'.DS.'form-label', $args); } /** diff --git a/core/lib/Thelia/Form/Brand/BrandModificationForm.php b/core/lib/Thelia/Form/Brand/BrandModificationForm.php index fa0ba3015..d30b8ad0d 100644 --- a/core/lib/Thelia/Form/Brand/BrandModificationForm.php +++ b/core/lib/Thelia/Form/Brand/BrandModificationForm.php @@ -53,6 +53,15 @@ class BrandModificationForm extends BrandCreationForm ] ] ) + ->add("logo_image_id", "integer", [ + 'constraints' => [ ], + 'required' => false, + 'label' => Translator::getInstance()->trans('Select the brand logo'), + 'label_attr' => [ + 'for' => 'mode', + 'help' => Translator::getInstance()->trans("Select the brand logo amongst the brand images") + ] + ]) ; // Add standard description fields, excluding title and locale, which are already defined diff --git a/core/lib/Thelia/Form/ProductModificationForm.php b/core/lib/Thelia/Form/ProductModificationForm.php index 18f79c659..894399d94 100644 --- a/core/lib/Thelia/Form/ProductModificationForm.php +++ b/core/lib/Thelia/Form/ProductModificationForm.php @@ -40,10 +40,8 @@ class ProductModificationForm extends ProductCreationForm 'label' => Translator::getInstance()->trans('Brand / Supplier'), 'label_attr' => [ 'for' => 'mode', - ], - 'attr' => [ 'help' => Translator::getInstance()->trans("Select the product brand, or supplier."), - ] + ], ]) ; diff --git a/templates/backOffice/default/assets/js/image-picker/image-picker.css b/templates/backOffice/default/assets/js/image-picker/image-picker.css new file mode 100644 index 000000000..14a96e398 --- /dev/null +++ b/templates/backOffice/default/assets/js/image-picker/image-picker.css @@ -0,0 +1,29 @@ +ul.thumbnails.image_picker_selector { + overflow: auto; + list-style-image: none; + list-style-position: outside; + list-style-type: none; + padding: 0px; + margin: 0px; } + ul.thumbnails.image_picker_selector ul { + overflow: auto; + list-style-image: none; + list-style-position: outside; + list-style-type: none; + padding: 0px; + margin: 0px; } + ul.thumbnails.image_picker_selector li.group_title { + float: none; } + ul.thumbnails.image_picker_selector li { + margin: 0px 12px 12px 0px; + float: left; } + ul.thumbnails.image_picker_selector li .thumbnail { + padding: 6px; + border: 1px solid #dddddd; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; } + ul.thumbnails.image_picker_selector li .thumbnail img { + -webkit-user-drag: none; } + ul.thumbnails.image_picker_selector li .thumbnail.selected { + background: #f39922; } diff --git a/templates/backOffice/default/assets/js/image-picker/image-picker.min.js b/templates/backOffice/default/assets/js/image-picker/image-picker.min.js new file mode 100644 index 000000000..c0c731d68 --- /dev/null +++ b/templates/backOffice/default/assets/js/image-picker/image-picker.min.js @@ -0,0 +1,7 @@ +// Image Picker +// by Rodrigo Vera +// +// Version 0.2.4 +// Full source at https://github.com/rvera/image-picker +// MIT License, https://github.com/rvera/image-picker/blob/master/LICENSE +(function(){var t,e,i,s,l=function(t,e){return function(){return t.apply(e,arguments)}},n=[].indexOf||function(t){for(var e=0,i=this.length;i>e;e++)if(e in this&&this[e]===t)return e;return-1};jQuery.fn.extend({imagepicker:function(e){return null==e&&(e={}),this.each(function(){var i;return i=jQuery(this),i.data("picker")&&i.data("picker").destroy(),i.data("picker",new t(this,s(e))),null!=e.initialized?e.initialized.call(i.data("picker")):void 0})}}),s=function(t){var e;return e={hide_select:!0,show_label:!1,initialized:void 0,changed:void 0,clicked:void 0,selected:void 0,limit:void 0,limit_reached:void 0},jQuery.extend(e,t)},i=function(t,e){return 0===jQuery(t).not(e).length&&0===jQuery(e).not(t).length},t=function(){function t(t,e){this.opts=null!=e?e:{},this.sync_picker_with_select=l(this.sync_picker_with_select,this),this.select=jQuery(t),this.multiple="multiple"===this.select.attr("multiple"),null!=this.select.data("limit")&&(this.opts.limit=parseInt(this.select.data("limit"))),this.build_and_append_picker()}return t.prototype.destroy=function(){var t,e,i,s;for(s=this.picker_options,e=0,i=s.length;i>e;e++)t=s[e],t.destroy();return this.picker.remove(),this.select.unbind("change"),this.select.removeData("picker"),this.select.show()},t.prototype.build_and_append_picker=function(){var t=this;return this.opts.hide_select&&this.select.hide(),this.select.change(function(){return t.sync_picker_with_select()}),null!=this.picker&&this.picker.remove(),this.create_picker(),this.select.after(this.picker),this.sync_picker_with_select()},t.prototype.sync_picker_with_select=function(){var t,e,i,s,l;for(s=this.picker_options,l=[],e=0,i=s.length;i>e;e++)t=s[e],t.is_selected()?l.push(t.mark_as_selected()):l.push(t.unmark_as_selected());return l},t.prototype.create_picker=function(){return this.picker=jQuery("
    "),this.picker_options=[],this.recursively_parse_option_groups(this.select,this.picker),this.picker},t.prototype.recursively_parse_option_groups=function(t,i){var s,l,n,r,c,o,h,a,p,u;for(a=t.children("optgroup"),r=0,o=a.length;o>r;r++)n=a[r],n=jQuery(n),s=jQuery("
      "),s.append(jQuery("
    • "+n.attr("label")+"
    • ")),i.append(jQuery("
    • ").append(s)),this.recursively_parse_option_groups(n,s);for(p=function(){var i,s,n,r;for(n=t.children("option"),r=[],i=0,s=n.length;s>i;i++)l=n[i],r.push(new e(l,this,this.opts));return r}.call(this),u=[],c=0,h=p.length;h>c;c++)l=p[c],this.picker_options.push(l),l.has_image()&&u.push(i.append(l.node));return u},t.prototype.has_implicit_blanks=function(){var t;return function(){var e,i,s,l;for(s=this.picker_options,l=[],e=0,i=s.length;i>e;e++)t=s[e],t.is_blank()&&!t.has_image()&&l.push(t);return l}.call(this).length>0},t.prototype.selected_values=function(){return this.multiple?this.select.val()||[]:[this.select.val()]},t.prototype.toggle=function(t){var e,s,l;return s=this.selected_values(),l=""+t.value(),this.multiple?n.call(this.selected_values(),l)>=0?(e=this.selected_values(),e.splice(jQuery.inArray(l,s),1),this.select.val([]),this.select.val(e)):null!=this.opts.limit&&this.selected_values().length>=this.opts.limit?null!=this.opts.limit_reached&&this.opts.limit_reached.call(this.select):this.select.val(this.selected_values().concat(l)):this.has_implicit_blanks()&&t.is_selected()?this.select.val(""):this.select.val(l),i(s,this.selected_values())||(this.select.change(),null==this.opts.changed)?void 0:this.opts.changed.call(this.select,s,this.selected_values())},t}(),e=function(){function t(t,e,i){this.picker=e,this.opts=null!=i?i:{},this.clicked=l(this.clicked,this),this.option=jQuery(t),this.create_node()}return t.prototype.destroy=function(){return this.node.find(".thumbnail").unbind()},t.prototype.has_image=function(){return null!=this.option.data("img-src")},t.prototype.is_blank=function(){return!(null!=this.value()&&""!==this.value())},t.prototype.is_selected=function(){var t;return t=this.picker.select.val(),this.picker.multiple?jQuery.inArray(this.value(),t)>=0:this.value()===t},t.prototype.mark_as_selected=function(){return this.node.find(".thumbnail").addClass("selected")},t.prototype.unmark_as_selected=function(){return this.node.find(".thumbnail").removeClass("selected")},t.prototype.value=function(){return this.option.val()},t.prototype.label=function(){return this.option.data("img-label")?this.option.data("img-label"):this.option.text()},t.prototype.clicked=function(){return this.picker.toggle(this),null!=this.opts.clicked&&this.opts.clicked.call(this.picker.select,this),null!=this.opts.selected&&this.is_selected()?this.opts.selected.call(this.picker.select,this):void 0},t.prototype.create_node=function(){var t,e;return this.node=jQuery("
    • "),t=jQuery(""),t.attr("src",this.option.data("img-src")),e=jQuery("
      "),e.click({option:this},function(t){return t.data.option.clicked()}),e.append(t),this.opts.show_label&&e.append(jQuery("

      ").html(this.label())),this.node.append(e),this.node},t}()}).call(this); \ No newline at end of file diff --git a/templates/backOffice/default/brand-edit.html b/templates/backOffice/default/brand-edit.html index 30c930a0c..17a819c1b 100644 --- a/templates/backOffice/default/brand-edit.html +++ b/templates/backOffice/default/brand-edit.html @@ -1,5 +1,11 @@ {extends file="admin-layout.tpl"} +{block name="after-admin-css"} + {stylesheets file='assets/js/image-picker/image-picker.css'} + + {/stylesheets} +{/block} + {block name="no-return-functions"} {$admin_current_location = 'tools'} {/block} @@ -77,6 +83,26 @@

      {admin_form_field form=$form name="visible"} + + {form_field form=$form field='logo_image_id'} +
      + + {admin_form_field_label form=$form name='logo_image_id'} + + + + {if $label_attr.help} + {$label_attr.help} + {/if} +
      + {/form_field} +
      @@ -152,6 +178,9 @@ {javascripts file='assets/js/jquery-ui-1.10.3.custom.min.js'} {/javascripts} + {javascripts file='assets/js/image-picker/image-picker.min.js'} + + {/javascripts} {/block} From 6bc22fd7ef396d2e677545a75a8d3764a6e08705 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 14:49:29 +0200 Subject: [PATCH 21/64] Brand integration --- .../frontOffice/default/includes/single-product.html | 8 +++----- templates/frontOffice/default/index.html | 11 +++++------ templates/frontOffice/default/product.html | 11 +++++------ 3 files changed, 13 insertions(+), 17 deletions(-) diff --git a/templates/frontOffice/default/includes/single-product.html b/templates/frontOffice/default/includes/single-product.html index f49e36e79..7977bddae 100644 --- a/templates/frontOffice/default/includes/single-product.html +++ b/templates/frontOffice/default/includes/single-product.html @@ -6,13 +6,11 @@ {/if}
      - {loop name="brand.feature" type="feature" product=$product_id title="brand"} - {loop name="brand.value" type="feature_value" feature=$ID product=$product_id} + {loop name="brand" type="brand" product=$product_id } {/loop} - {/loop} - {loop name="brand.feature" type="feature" product=$product_id title="isbn"} - {loop name="brand.value" type="feature_value" feature=$ID product=$product_id} + {loop name="isbn.feature" type="feature" product=$product_id title="isbn"} + {loop name="isbn.value" type="feature_value" feature=$ID product=$product_id} {/loop} {/loop} diff --git a/templates/frontOffice/default/index.html b/templates/frontOffice/default/index.html index 8a12a402d..1d5f96d6e 100644 --- a/templates/frontOffice/default/index.html +++ b/templates/frontOffice/default/index.html @@ -48,13 +48,12 @@
      {$product_id=$ID} - {loop name="brand.feature" type="feature" product="{$ID}" title="brand"} - {loop name="brand.value" type="feature_value" feature="{$ID}" product="$product_id"} - - {/loop} + {loop name="brand.feature" type="brand" product="{$ID}"} + {/loop} - {loop name="brand.feature" type="feature" product=$ID title="isbn"} - {loop name="brand.value" type="feature_value" feature=$ID product=$product_id} + + {loop name="isbn.feature" type="feature" product=$ID title="isbn"} + {loop name="isbn.value" type="feature_value" feature=$ID product=$product_id} {/loop} {/loop} diff --git a/templates/frontOffice/default/product.html b/templates/frontOffice/default/product.html index bf31e294f..5301d82f8 100644 --- a/templates/frontOffice/default/product.html +++ b/templates/frontOffice/default/product.html @@ -36,13 +36,12 @@
      - {loop name="brand.feature" type="feature" product="{$ID}" title="brand"} - {loop name="brand.value" type="feature_value" feature="{$ID}" product="{product attr="id"}"} - - {/loop} + {loop name="brand.feature" type="brand" product="{$ID}"} + {/loop} - {loop name="brand.feature" type="feature" product="{$ID}" title="isbn"} - {loop name="brand.value" type="feature_value" feature="{$ID}" product="{product attr="id"}"} + + {loop name="isbn.feature" type="feature" product="{$ID}" title="isbn"} + {loop name="isbn.value" type="feature_value" feature="{$ID}" product="{product attr="id"}"} {/loop} {/loop} From 31182c07fc83b9b1e4819aeb82ceec9597bda061 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 14:49:58 +0200 Subject: [PATCH 22/64] Added product parapter --- core/lib/Thelia/Core/Template/Loop/Brand.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/core/lib/Thelia/Core/Template/Loop/Brand.php b/core/lib/Thelia/Core/Template/Loop/Brand.php index c5fab67af..c177a7297 100644 --- a/core/lib/Thelia/Core/Template/Loop/Brand.php +++ b/core/lib/Thelia/Core/Template/Loop/Brand.php @@ -21,6 +21,7 @@ use Thelia\Core\Template\Element\SearchLoopInterface; use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Model\BrandQuery; +use Thelia\Model\ProductQuery; use Thelia\Type\BooleanOrBothType; use Thelia\Type; use Thelia\Type\TypeCollection; @@ -45,6 +46,7 @@ class Brand extends BaseI18nLoop implements PropelSearchLoopInterface, SearchLoo { return new ArgumentCollection( Argument::createIntListTypeArgument('id'), + Argument::createIntTypeArgument('product'), Argument::createBooleanOrBothTypeArgument('visible', 1), Argument::createAnyTypeArgument('title'), new Argument( @@ -103,6 +105,12 @@ class Brand extends BaseI18nLoop implements PropelSearchLoopInterface, SearchLoo $search->filterById($id, Criteria::IN); } + $product = $this->getProduct(); + + if (!is_null($product) && null !== $productObj = ProductQuery::create()->findPk($product)) { + $search->filterByProduct($productObj); + } + $visible = $this->getVisible(); if ($visible !== BooleanOrBothType::ANY) $search->filterByVisible($visible ? 1 : 0); From 1458d2ff699a340b83a4687e0a656bae3764ffe1 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 14:50:15 +0200 Subject: [PATCH 23/64] Brand related translations --- templates/backOffice/default/I18n/en_US.php | 31 ++++++++++++------- templates/backOffice/default/I18n/fr_FR.php | 31 ++++++++++++------- .../backOffice/default/translations.html | 2 +- 3 files changed, 39 insertions(+), 25 deletions(-) diff --git a/templates/backOffice/default/I18n/en_US.php b/templates/backOffice/default/I18n/en_US.php index 934dad7df..f935107ce 100644 --- a/templates/backOffice/default/I18n/en_US.php +++ b/templates/backOffice/default/I18n/en_US.php @@ -14,8 +14,6 @@ return array( 'Warning, some of your shipping zones are not attached to any delivery module:' => 'Warning, some of your shipping zones are not attached to any delivery module:', 'A content could be attached to more than one folder. Select here the additional folders for this content.' => 'A content could be attached to more than one folder. Select here the additional folders for this content.', 'A product could be attached to more than one category. Select here the additional categories for this product.' => 'A product could be attached to more than one category. Select here the additional categories for this product.', - 'A short description, used when a summary or an introduction is required' => 'A short description, used when a summary or an introduction is required', - 'A short post-description information' => 'A short post-description information', 'Aborted orders' => 'Aborted orders', 'Accessory title' => 'Accessory title', 'Action' => 'Action', @@ -25,6 +23,7 @@ return array( 'Add a condition' => 'Add a condition', 'Add a new Customer' => 'Add a new Customer', 'Add a new address' => 'Add a new address', + 'Add a new brand' => 'Add a new brand', 'Add a new category' => 'Add a new category', 'Add a new combination' => 'Add a new combination', 'Add a new content' => 'Add a new content', @@ -84,6 +83,8 @@ return array( 'Back-office template you want to translate' => 'Back-office template you want to translate', 'Back-office templates' => 'Back-office templates', 'Back-office users' => 'Back-office users', + 'Brand created on %date_create. Last modification: %date_change' => 'Brand created on %date_create. Last modification: %date_change', + 'Brands' => 'Brands', 'Browse files' => 'Browse files', 'Browse this category' => 'Browse this category', 'Browse this folder' => 'Browse this folder', @@ -105,6 +106,7 @@ return array( 'Cellular phone number' => 'Cellular phone number', 'Change this administrator' => 'Change this administrator', 'Change this attribute' => 'Change this attribute', + 'Change this brand' => 'Change this brand', 'Change this condition' => 'Change this condition', 'Change this country' => 'Change this country', 'Change this coupon' => 'Change this coupon', @@ -167,6 +169,7 @@ return array( 'Create a new administrator' => 'Create a new administrator', 'Create a new attribute' => 'Create a new attribute', 'Create a new attribute value' => 'Create a new attribute value', + 'Create a new brand' => 'Create a new brand', 'Create a new category' => 'Create a new category', 'Create a new combination' => 'Create a new combination', 'Create a new content' => 'Create a new content', @@ -190,6 +193,7 @@ return array( 'Create coupon' => 'Create coupon', 'Create this address' => 'Create this address', 'Create this attribute' => 'Create this attribute', + 'Create this brand' => 'Create this brand', 'Create this category' => 'Create this category', 'Create this combination' => 'Create this combination', 'Create this content' => 'Create this content', @@ -239,6 +243,7 @@ return array( 'Delete an order' => 'Delete an order', 'Delete attribute' => 'Delete attribute', 'Delete attribute value' => 'Delete attribute value', + 'Delete brand' => 'Delete brand', 'Delete category' => 'Delete category', 'Delete content' => 'Delete content', 'Delete country' => 'Delete country', @@ -258,6 +263,7 @@ return array( 'Delete this accessory' => 'Delete this accessory', 'Delete this administrator' => 'Delete this administrator', 'Delete this attribute' => 'Delete this attribute', + 'Delete this brand' => 'Delete this brand', 'Delete this category and all its contents' => 'Delete this category and all its contents', 'Delete this combination' => 'Delete this combination', 'Delete this condition' => 'Delete this condition', @@ -299,6 +305,7 @@ return array( 'Do you really want to delete this administrator ?' => 'Do you really want to delete this administrator ?', 'Do you really want to delete this attribute ? It will be removed from all product templates.' => 'Do you really want to delete this attribute ? It will be removed from all product templates.', 'Do you really want to delete this attribute value ?' => 'Do you really want to delete this attribute value ?', + 'Do you really want to delete this brand ?' => 'Do you really want to delete this brand ?', 'Do you really want to delete this category and all its content ?' => 'Do you really want to delete this category and all its content ?', 'Do you really want to delete this combination ?' => 'Do you really want to delete this combination ?', 'Do you really want to delete this condition ?' => 'Do you really want to delete this condition ?', @@ -336,7 +343,6 @@ return array( 'Do you really want to use this address by default ?' => 'Do you really want to use this address by default ?', 'Document informations' => 'Document information', 'Documents' => 'Documents', - 'Don\'t repeat keywords over and over in a row. Rather, put in keyword phrases.' => 'Don\'t repeat keywords over and over in a row. Rather, put in keyword phrases.', 'Download invoice as PDF' => 'Download invoice as PDF', 'Download purchase order as PDF' => 'Download purchase order as PDF', 'Drop files to upload' => 'Drop files to upload', @@ -366,6 +372,8 @@ return array( 'Edit an image' => 'Edit an image', 'Edit an order' => 'Edit an order', 'Edit attribute "%name"' => 'Edit attribute "%name"', + 'Edit brand' => 'Edit brand', + 'Edit brand %title' => 'Edit brand %title', 'Edit category' => 'Edit category', 'Edit category %title' => 'Edit category %title', 'Edit content' => 'Edit content', @@ -398,6 +406,7 @@ return array( 'Edit tax rule taxes' => 'Edit tax rule taxes', 'Edit template "%name"' => 'Edit template "%name"', 'Edit this address' => 'Edit this address', + 'Edit this brand' => 'Edit this brand', 'Edit this category' => 'Edit this category', 'Edit this content' => 'Edit this content', 'Edit this customer' => 'Edit this customer', @@ -411,6 +420,7 @@ return array( 'Editing %fold' => 'Editing %fold', 'Editing %title' => 'Editing %title', 'Editing attribute "%name"' => 'Editing attribute "%name"', + 'Editing brand "%title"' => 'Editing brand "%title"', 'Editing country "%name"' => 'Editing country "%name"', 'Editing coupon "%title"' => 'Editing coupon "%title"', 'Editing currency "%name"' => 'Editing currency "%name"', @@ -457,6 +467,7 @@ return array( 'Enter information in the default language (%title)' => 'Enter information in the default language (%title)', 'Enter new accessory position' => 'Enter new accessory position', 'Enter new attribute position' => 'Enter new attribute position', + 'Enter new brand position' => 'Enter new brand position', 'Enter new category position' => 'Enter new category position', 'Enter new content position' => 'Enter new content position', 'Enter new currency position' => 'Enter new currency position', @@ -545,7 +556,6 @@ return array( 'Invoice informations' => 'Invoice information', 'Invoice reference' => 'Invoice reference', 'Items to translate' => 'Items to translate', - 'Keep the most important part of your description in the first 150-160 characters.' => 'Keep the most important part of your description in the first 150-160 characters.', 'Kg' => 'Kg', 'Label' => 'Label', 'Language name' => 'Language name', @@ -573,8 +583,6 @@ return array( 'Mailing template name' => 'Mailing template name', 'Mailing template purpose' => 'Mailing template purpose', 'Mailing templates' => 'Mailing templates', - 'Make sure it uses keywords found within the page itself.' => 'Make sure it uses keywords found within the page itself.', - 'Make sure that your title is clear, and contains many of the keywords within the page itself.' => 'Make sure that your title is clear, and contains many of the keywords within the page itself.', 'Manage attributes included in this product template' => 'Manage attributes included in this product template', 'Manage features included in this product template' => 'Manage features included in this product template', 'Manage module rights' => 'Manage module rights', @@ -605,10 +613,13 @@ return array( 'No available content in this folder' => 'No available content in this folder', 'No available product in this category' => 'No available product in this category', 'No available value for this attribute' => 'No available value for this attribute', + 'No brand' => 'No brand', + 'No brand has been created yet. Click the + button to create one.' => 'No brand has been created yet. Click the + button to create one.', 'No categories found' => 'No categories found', 'No country has been created yet. Click the + button to create one.' => 'No country has been created yet. Click the + button to create one.', 'No currency has been created yet. Click the + button to create one.' => 'No currency has been created yet. Click the + button to create one.', 'No folders found' => 'No folders found', + 'No logo image' => 'No logo image', 'No mailing template has been created yet. Click the + button to create one.' => 'No mailing template has been created yet. Click the + button to create one.', 'No product attribute has been created yet. Click the + button to create one.' => 'No product attribute has been created yet. Click the + button to create one.', 'No product feature has been created yet. Click the + button to create one.' => 'No product feature has been created yet. Click the + button to create one.', @@ -664,7 +675,6 @@ return array( 'Port' => 'Port', 'Port :' => 'Port :', 'Position' => 'Position', - 'Post Scriptum' => 'Post Scriptum', 'Postage' => 'Postage', 'Postscriptum' => 'Postscriptum', 'Preview' => 'Preview', @@ -731,7 +741,6 @@ return array( 'Resource' => 'Resource', 'Resource access rights' => 'Resource access rights', 'Resources' => 'Resources', - 'Rewritten URL' => 'Rewritten URL', 'Rights' => 'Rights', 'SEO' => 'SEO', 'Sale' => 'Sale', @@ -790,7 +799,6 @@ return array( 'Shipping zones management' => 'Shipping zones management', 'Shop' => 'Shop', 'Shop Informations' => 'Shop Information', - 'Short conclusion' => 'Short conclusion', 'Short description' => 'Short description', 'Short description :' => 'Short description :', 'Show logs' => 'Show logs', @@ -838,7 +846,6 @@ return array( 'Template title' => 'Template title', 'Templates' => 'Templates', 'Text version of this message' => 'Text version of this message', - 'The HTML TITLE element is the most important element on your web page.' => 'The HTML TITLE element is the most important element on your web page.', 'The default pricing is used when no combination is defined.' => 'The default pricing is used when no combination is defined.', 'The destinations processes logs to display, store or send them. You can select and configure zero, one or more destinations below.' => 'The destinations processes logs to display, store or send them. You can select and configure zero, one or more destinations below.', 'The detailed description.' => 'The detailed description.', @@ -936,6 +943,7 @@ return array( 'Unit. price' => 'Unit. price', 'Unlimited' => 'Unlimited', 'Unlimited number of uses' => 'Unlimited number of uses', + 'Unsupported field type \'%type\' in form-field.html' => 'Unsupported field type \'%type\' in form-field.html', 'Update' => 'Update', 'Update an administrator' => 'Update an administrator', 'Update coupon' => 'Update coupon', @@ -947,6 +955,7 @@ return array( 'Use Ctrl+click to select (or deselect) more that one attribute value' => 'Use Ctrl+click to select (or deselect) more that one attribute value', 'Use Ctrl+click to select (or deselect) more that one category' => 'Use Ctrl+click to select (or deselect) more that one category', 'Use Ctrl+click to select (or deselect) more that one country' => 'Utiliser Ctrl+clic pour sélectionner (ou dé-sélectionner) plusieurs pays.', + 'Use Ctrl+click to select (or deselect) more that one item' => 'Use Ctrl+click to select (or deselect) more that one item', 'Use Ctrl+click to select (or deselect) more that one product' => 'Use Ctrl+click to select (or deselect) more that one product', 'Use Ctrl+click to select (or deselect) more that one shipping method' => 'Use Ctrl+click to select (or deselect) more that one shipping method', 'Use Ctrl+click to select more than one value. You can also clear selected values.' => 'Use Ctrl+click to select more than one value. You can also clear selected values.', @@ -954,7 +963,6 @@ return array( 'Use Text message defined below' => 'Use Text message defined below', 'Use address by default' => 'Use address by default', 'Use default layout' => 'Use default layout', - 'Use the keyword phrase in your URL.' => 'Use the keyword phrase in your URL.', 'Use this address by default' => 'Use this address by default', 'Used in your store front' => 'Used in your store front', 'Username' => 'Username', @@ -989,7 +997,6 @@ return array( 'You can change the default folder (%title) in the "General" tab.' => 'You can change the default folder (%title) in the "General" tab.', 'You can\'t delete this administrator' => 'You can\'t delete this administrator', 'You can\'t delete this profile' => 'You can\'t delete this profile', - 'You don\'t need to use commas or other punctuations.' => 'You don\'t need to use commas or other punctuations.', 'You may also quickly create combinations from products attributes using the Combination Builder.' => 'You may also quickly create combinations from products attributes using the Combination Builder.', 'Your current IP address is %ip' => 'Your current IP address is %ip', 'Zip code' => 'Zip code', diff --git a/templates/backOffice/default/I18n/fr_FR.php b/templates/backOffice/default/I18n/fr_FR.php index ee8220a4c..67bfde6b9 100755 --- a/templates/backOffice/default/I18n/fr_FR.php +++ b/templates/backOffice/default/I18n/fr_FR.php @@ -14,8 +14,6 @@ return array( 'Warning, some of your shipping zones are not attached to any delivery module:' => 'Attention, les zones de livraison suivantes ne sont associées à aucun module:', 'A content could be attached to more than one folder. Select here the additional folders for this content.' => 'Un contenu peut être rattaché à plusieurs dossiers. Sélectionnez ici les dossiers dans lesquels ce contenu apparaîtra', 'A product could be attached to more than one category. Select here the additional categories for this product.' => 'Un produit peut être associé à plusieurs rubriques. Sélectionner les rubrique pour lesquels le produit sera associé', - 'A short description, used when a summary or an introduction is required' => 'Une courte description, utilisée lorsqu\'un résumé ou une introduction est requise', - 'A short post-description information' => 'Champs d\'information complémentaire', 'Aborted orders' => 'Paniers abandonnés', 'Accessory title' => 'Titre de l\'accessoire', 'Action' => 'Action', @@ -25,6 +23,7 @@ return array( 'Add a condition' => 'Ajouter une condition', 'Add a new Customer' => 'Ajouter un client', 'Add a new address' => 'Ajouter une nouvelle adresse', + 'Add a new brand' => 'Ajouter une nouvelle marque', 'Add a new category' => 'Ajouter une catégorie', 'Add a new combination' => 'Ajouter une nouvelle combinaison', 'Add a new content' => 'Ajouter un nouveau contenu', @@ -84,6 +83,8 @@ return array( 'Back-office template you want to translate' => 'Template back-office à traduire', 'Back-office templates' => 'Templates Back-office', 'Back-office users' => 'Utilisateur du B.O', + 'Brand created on %date_create. Last modification: %date_change' => 'Marque créée le %date_create. Dernière modification: %date_change', + 'Brands' => 'Marques et Fournisseurs', 'Browse files' => 'Parcourir les fichiers', 'Browse this category' => 'Parcourir cette catégorie', 'Browse this folder' => 'Parcourir ce dossier', @@ -105,6 +106,7 @@ return array( 'Cellular phone number' => 'Numéro de portable', 'Change this administrator' => 'Modifier cet administrateur', 'Change this attribute' => 'Modifier cette déclinaison', + 'Change this brand' => 'Modifiercette marque', 'Change this condition' => 'Modifier cette condition', 'Change this country' => 'Modifier ce pays', 'Change this coupon' => 'Modifier ce code promo', @@ -167,6 +169,7 @@ return array( 'Create a new administrator' => 'Créer un nouvel administrateur', 'Create a new attribute' => 'Créer une nouvelle déclinaison', 'Create a new attribute value' => 'Créer une nouvelle valeur de déclinaison', + 'Create a new brand' => 'Ajouter une nouvelle marque', 'Create a new category' => 'Créer une nouvelle rubrique', 'Create a new combination' => 'Créer une nouvelle combinaison', 'Create a new content' => 'Créer un nouveau contenu', @@ -190,6 +193,7 @@ return array( 'Create coupon' => 'Créer un code promo', 'Create this address' => 'Créer cette adresse', 'Create this attribute' => 'Créer cette déclinaison', + 'Create this brand' => 'Ajouter cette marque', 'Create this category' => 'Créer cette rubrique', 'Create this combination' => 'Créer cette combinaison', 'Create this content' => 'Créer ce contenu', @@ -239,6 +243,7 @@ return array( 'Delete an order' => 'Supprimer une commande', 'Delete attribute' => 'Supprimer cette déclinaison', 'Delete attribute value' => 'Supprimer une valeur de déclinaison', + 'Delete brand' => 'Supprimer cette marque', 'Delete category' => 'Supprimer cette rubrique', 'Delete content' => 'Supprimer le contenu', 'Delete country' => 'Supprimer le pays', @@ -258,6 +263,7 @@ return array( 'Delete this accessory' => 'Supprimer cet accessoire', 'Delete this administrator' => 'Supprimer cet administrateur', 'Delete this attribute' => 'Supprimer cette déclinaison', + 'Delete this brand' => 'Supprimer cette marque', 'Delete this category and all its contents' => 'Supprimer cette rubrique et tout ce qu\'elle contient ?', 'Delete this combination' => 'Supprimer cette combinaison', 'Delete this condition' => 'Supprimer cette condition', @@ -299,6 +305,7 @@ return array( 'Do you really want to delete this administrator ?' => 'Confirmez-vous la suppression de cet administrateur ?', 'Do you really want to delete this attribute ? It will be removed from all product templates.' => 'Voulez-vous vraiment supprimer cette déclinaison ? Elle sera supprimée de tous les gabarits de produit.', 'Do you really want to delete this attribute value ?' => 'Voulez-vous vraiment supprimer cette déclinaison ?', + 'Do you really want to delete this brand ?' => 'Confirmez-vous la suppresison de cette marque ?', 'Do you really want to delete this category and all its content ?' => 'Voulez-vous vraiment supprimer cette rubrique et tout ce qu\'elle contient ?', 'Do you really want to delete this combination ?' => 'Voulez-vous vraiment supprimer cette combinaison ?', 'Do you really want to delete this condition ?' => 'Supprimer cette condition ?', @@ -336,7 +343,6 @@ return array( 'Do you really want to use this address by default ?' => 'Voulez-vous vraiment utiliser cette adresse comme adresse par défaut ?', 'Document informations' => 'Informations du document', 'Documents' => 'Documents', - 'Don\'t repeat keywords over and over in a row. Rather, put in keyword phrases.' => 'Ne répétez pas sans cesse les même mots-clés dans une ligne. Préférez utiliser des expressions de mots-clés', 'Download invoice as PDF' => 'Télécharger la facture au format PDF', 'Download purchase order as PDF' => 'Télécharger le bon de commande au format PDF', 'Drop files to upload' => 'Déposez des fichiers à envoyer', @@ -366,6 +372,8 @@ return array( 'Edit an image' => 'Modifier une image', 'Edit an order' => 'Editer une commande', 'Edit attribute "%name"' => 'Modifier la déclinaison "%name"', + 'Edit brand' => 'Modifier un marque', + 'Edit brand %title' => 'Edition de la marque "%title"', 'Edit category' => 'Editer la rubrique', 'Edit category %title' => 'Modifier la rubrique %title', 'Edit content' => 'Modifier le contenu', @@ -398,6 +406,7 @@ return array( 'Edit tax rule taxes' => 'Modifier les taxes de la règle de taxe', 'Edit template "%name"' => 'Modifier le gabarit "%name"', 'Edit this address' => 'Editer cette adresse', + 'Edit this brand' => 'Modifier cette marque', 'Edit this category' => 'Editer cette rubrique', 'Edit this content' => 'Modifier ce contenu', 'Edit this customer' => 'Modifier ce client', @@ -411,6 +420,7 @@ return array( 'Editing %fold' => 'Modification de %fold', 'Editing %title' => 'En cours de modification de %title', 'Editing attribute "%name"' => 'En cours de modification de la déclinaison "%name"', + 'Editing brand "%title"' => 'Edition de la marque "%title"', 'Editing country "%name"' => 'En cours de modification du pays "%name"', 'Editing coupon "%title"' => 'Edition du code promo "%title" ', 'Editing currency "%name"' => 'En cours de modification de la devise "%name"', @@ -457,6 +467,7 @@ return array( 'Enter information in the default language (%title)' => 'Entrez les informations dans la langue par défaut (%title) ', 'Enter new accessory position' => 'Renseigner la nouvelle position pour cet accessoire', 'Enter new attribute position' => 'Modifier la position de la déclinaison', + 'Enter new brand position' => 'Indiquez la position désirée', 'Enter new category position' => 'Classement de la catégorie', 'Enter new content position' => 'Modifier la position du contenu', 'Enter new currency position' => 'Modifier la position de la devise', @@ -545,7 +556,6 @@ return array( 'Invoice informations' => 'Informations de facturation', 'Invoice reference' => 'Facture ref', 'Items to translate' => 'Elément à traduire', - 'Keep the most important part of your description in the first 150-160 characters.' => 'Votre description ne devrait pas dépasser 150 à 160 caractères', 'Kg' => 'Kg', 'Label' => 'Libellé', 'Language name' => 'Nom de la langue', @@ -573,8 +583,6 @@ return array( 'Mailing template name' => 'Nom du template de mailing', 'Mailing template purpose' => 'Role du template de mailing', 'Mailing templates' => 'Template e-mail', - 'Make sure it uses keywords found within the page itself.' => 'Assurez vous d\'utiliser des mots-clés présents dans la page courante', - 'Make sure that your title is clear, and contains many of the keywords within the page itself.' => 'Assurez-vous d\'avoir un titre clair et qui contient les mots-clés correspondant à la page en cours', 'Manage attributes included in this product template' => 'Gestion des déclinaisons présentes dans ce gabarit de produit', 'Manage features included in this product template' => 'Gestion des caractéristiques présentes dans ce gabarit de produit', 'Manage module rights' => 'Gestion des droits pour les modules', @@ -605,10 +613,13 @@ return array( 'No available content in this folder' => 'Ce dossier n\'a pas de contenu', 'No available product in this category' => 'Aucun produit disponible dans cette rubrique', 'No available value for this attribute' => 'Aucune valeur disponible pour cette déclinaison', + 'No brand' => 'Aucune marque', + 'No brand has been created yet. Click the + button to create one.' => 'Aucune marque n\'a encore été créée. Cliquez le boputon + pour en ajouter une.', 'No categories found' => 'Aucune rubrique trouvée', 'No country has been created yet. Click the + button to create one.' => 'Aucun pays n\'a encore été créé. Cliquez sur le bouton + pour en créer un', 'No currency has been created yet. Click the + button to create one.' => 'Aucune devise n\'a encore été crée. Cliquez sur le bouton + pour en créer une.', 'No folders found' => 'Aucun dossier n\'a été trouvé.', + 'No logo image' => 'Aucun logo', 'No mailing template has been created yet. Click the + button to create one.' => 'Aucun template de mailing n\'a encore été créé. Cliquez sur le bouton + pour en ajouter un.', 'No product attribute has been created yet. Click the + button to create one.' => 'Aucune déclinaison produit n\'a encore été créée. Cliquez sur le bouton + pour en créer une.', 'No product feature has been created yet. Click the + button to create one.' => 'Aucune caractéristique produit n\'a encore été ajoutée. Cliquez sur le bouton + pour en créer une.', @@ -664,7 +675,6 @@ return array( 'Port' => 'Port', 'Port :' => 'Port : ', 'Position' => 'Position', - 'Post Scriptum' => 'Post-scriptum', 'Postage' => 'Frais de livraison', 'Postscriptum' => 'Post-scriptum', 'Preview' => 'Prévisualisation', @@ -731,7 +741,6 @@ return array( 'Resource' => 'Ressource', 'Resource access rights' => 'Droits d\'accès pour les ressources', 'Resources' => 'Ressources', - 'Rewritten URL' => 'URL réécrites', 'Rights' => 'Droits', 'SEO' => 'SEO', 'Sale' => 'En promo', @@ -790,7 +799,6 @@ return array( 'Shipping zones management' => 'Zones de livraison', 'Shop' => 'Boutique', 'Shop Informations' => 'Informations sur la boutique', - 'Short conclusion' => 'Courte conclusion', 'Short description' => 'Description courte', 'Short description :' => 'Description courte : ', 'Show logs' => 'Voir les logs', @@ -838,7 +846,6 @@ return array( 'Template title' => 'Titre du gabarit', 'Templates' => 'Gabarits de produit', 'Text version of this message' => 'Version texte du message', - 'The HTML TITLE element is the most important element on your web page.' => 'L\'élément HTML TITLE est le plus important dans votre page', 'The default pricing is used when no combination is defined.' => 'Le prix pas défaut est utilisez lorsqu\'aucune combinaison n\'est utilisé', 'The destinations processes logs to display, store or send them. You can select and configure zero, one or more destinations below.' => 'Les destinations permettent d\'afficher, stocker ou bien envoyer les logs. Vous pouvez en sélectionner zéro, un ou plusieurs dans la liste ci-dessous', 'The detailed description.' => 'La description détaillée.', @@ -936,6 +943,7 @@ return array( 'Unit. price' => 'Prix unitaire', 'Unlimited' => 'Illimité', 'Unlimited number of uses' => 'Nombre d\'utilisations illimité', + 'Unsupported field type \'%type\' in form-field.html' => 'Le type de champ \'%type\' n\'est pas suppporté par form-field.html ', 'Update' => 'Mettre à jour', 'Update an administrator' => 'Mettre à jour cet administrateur', 'Update coupon' => 'Mettre à jour le code', @@ -947,6 +955,7 @@ return array( 'Use Ctrl+click to select (or deselect) more that one attribute value' => 'Ctrl+clic permet de séléctionner (ou dé-selectionner) plusieurs valeurs de déclinaison.', 'Use Ctrl+click to select (or deselect) more that one category' => 'Ctrl+Clic permet de sélectionner ou dé-sélectionner plus d\'une catégorie', 'Use Ctrl+click to select (or deselect) more that one country' => 'Ctrl+Clic permet de sélectionner ou dé-sélectionner plus d\'un pays', + 'Use Ctrl+click to select (or deselect) more that one item' => 'Utilisez Ctrl+clic pour séléctionner (ou dé-selectionner) plus d\'un élément', 'Use Ctrl+click to select (or deselect) more that one product' => 'Ctrl+Clic permet de sélectionner ou dé-sélectionner plus d\'un produit', 'Use Ctrl+click to select (or deselect) more that one shipping method' => 'Ctrl+Clic permet de sélectionner ou dé-sélectionner plus d\'un mode de transport', 'Use Ctrl+click to select more than one value. You can also clear selected values.' => 'Utilisez Ctrl+clic pour choisir plus d\'une valeur. Vous pouvez aussi tout désélectionner.', @@ -954,7 +963,6 @@ return array( 'Use Text message defined below' => 'Utiliser la version texte définie ci-dessous', 'Use address by default' => 'Utiliser comme adresse par défaut', 'Use default layout' => 'Utiliser le layout par défaut', - 'Use the keyword phrase in your URL.' => 'Utilisez des mots clés dans votre url', 'Use this address by default' => 'Utiliser cette adresse par défaut', 'Used in your store front' => 'Utilisé dans le front de votre boutique', 'Username' => 'Nom d\'utilisateur', @@ -989,7 +997,6 @@ return array( 'You can change the default folder (%title) in the "General" tab.' => 'Vous pouvez modifier le dossier par défaut (%title) dans l\'onglet "Général".', 'You can\'t delete this administrator' => 'Vous ne pouvez pas supprimer cet administrateur', 'You can\'t delete this profile' => 'Vous ne pouvez pas supprimer ce profil', - 'You don\'t need to use commas or other punctuations.' => 'Vous n\'avez pas besoin d\'utiliser de virgules ou d\'autres signes de ponctuation', 'You may also quickly create combinations from products attributes using the Combination Builder.' => 'Vous pouvez aussi créer rapidement une série de combinaisons avec le gestionnaire de combinaisons.', 'Your current IP address is %ip' => 'Votre adresse IP est %ip', 'Zip code' => 'Code postal', diff --git a/templates/backOffice/default/translations.html b/templates/backOffice/default/translations.html index a64861dcf..f523622c9 100644 --- a/templates/backOffice/default/translations.html +++ b/templates/backOffice/default/translations.html @@ -64,7 +64,7 @@ From 7ab306cb6c408e456b935cf2b0d2fbc677fc0837 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 14:51:04 +0200 Subject: [PATCH 24/64] Tra,slations of strings moved from templates to form definitions --- core/lib/Thelia/Config/I18n/en_US.php | 45 ++++++++++++++++++--------- core/lib/Thelia/Config/I18n/fr_FR.php | 45 ++++++++++++++++++--------- 2 files changed, 60 insertions(+), 30 deletions(-) diff --git a/core/lib/Thelia/Config/I18n/en_US.php b/core/lib/Thelia/Config/I18n/en_US.php index 6b92a7fb6..688cbf762 100644 --- a/core/lib/Thelia/Config/I18n/en_US.php +++ b/core/lib/Thelia/Config/I18n/en_US.php @@ -6,11 +6,16 @@ return array( '%obj SEO modification' => '%obj SEO modification', '%obj creation' => '%obj creation', '%obj modification' => '%obj modification', + '%obj%s deleted successfully' => '%obj%s deleted successfully', + '%type% position updated' => '%type% position updated', '\'%type\' loop class should extends Thelia\Core\Template\Element\BaseLoop' => '\'%type\' loop class should extends Thelia\Core\Template\Element\BaseLoop', 'A currency with code "%name" already exists.' => 'A currency with code "%name" already exists.', + 'A descriptive title' => 'A descriptive title', 'A loop named \'%name\' already exists in the current scope.' => 'A loop named \'%name\' already exists in the current scope.', 'A message with name "%name" already exists.' => 'A message with name "%name" already exists.', 'A product with reference %ref already exists. Please choose another reference.' => 'A product with reference %ref already exists. Please choose another reference.', + 'A short description, used when a summary or an introduction is required' => 'A short description, used when a summary or an introduction is required', + 'A short text, used when an additional or supplemental information is required.' => 'A short text, used when an additional or supplemental information is required.', 'A user already exists with this email address. Please login or if you\'ve forgotten your password, go to Reset Your Password.' => 'A user already exists with this email address. Please login or if you\'ve forgotten your password, go to Reset Your Password.', 'A value for attribute "%name" is already present in the combination' => 'A value for attribute "%name" is already present in the combination', 'A variable with name "%name" already exists.' => 'A variable with name "%name" already exists.', @@ -39,6 +44,9 @@ return array( 'Bad tax list JSON' => 'Bad tax list JSON', 'Billing country' => 'Billing country', 'Billing coutry is' => 'Le pays de facturation est', + 'Brand' => 'Brand', + 'Brand / Supplier' => 'Brand / Supplier', + 'Brand name' => 'Brand name', 'Business ID' => 'Business ID', 'Cannot find a default country. Please define one.' => 'Cannot find a default country. Please define one.', 'Cannot find the shop country. Please select a shop country.' => 'Cannot find the shop country. Please select a shop country.', @@ -78,37 +86,34 @@ return array( 'Default folder *' => 'Default folder *', 'Default product category *' => 'Default product category *', 'Default product sale element' => 'Default product sale element', - 'Deleting document for %id% with parent id %parentId%' => 'Deleting document for %id% with parent id %parentId%', - 'Deleting image for %id% with parent id %parentId%' => 'Deleting image for %id% with parent id %parentId%', + 'Deleting %obj% for %id% with parent id %parentId%' => 'Deleting %obj% for %id% with parent id %parentId%', 'Delivery country' => 'Delivery country', 'Delivery coutry is' => 'Le pays de livraison est', 'Delivery module ID not found' => 'Delivery module ID not found', 'Description' => 'Description', 'Detailed description' => 'Detailed description', 'Disabled' => 'Disabled', - 'Document deleted successfully' => 'Document deleted successfully', - 'Document position updated' => 'Document position updated', + 'Don\'t repeat keywords over and over in a row. Rather, put in keyword phrases.' => 'Don\'t repeat keywords over and over in a row. Rather, put in keyword phrases.', 'EAN Code' => 'EAN Code', 'Email Address' => 'Email Address', 'Email address' => 'Email address', 'Emergency' => 'Emergency', 'Enable remote SMTP use' => 'Enable remote SMTP use', 'Encryption' => 'Encryption', + 'Enter here the brand name in the default language (%title%)' => 'Enter here the brand name in the default language (%title%)', 'Equal to' => 'Egal à', 'Error during %action process : %error. Exception was %exc' => 'Error during %action process : %error. Exception was %exc', 'Error occured while processing order ref. %ref, ID %id: %err' => 'Error occured while processing order ref. %ref, ID %id: %err', 'Errors' => 'Errors', - 'Fail to delete document for %id% with parent id %parentId% (Exception : %e%)' => 'Fail to delete document for %id% with parent id %parentId% (Exception : %e%)', - 'Fail to delete image for %id% with parent id %parentId% (Exception : %e%)' => 'Fail to delete image for %id% with parent id %parentId% (Exception : %e%)', - 'Fail to update document position' => 'Fail to update document position', - 'Fail to update image position' => 'Fail to update image position', + 'Fail to delete %obj% for %id% with parent id %parentId% (Exception : %e%)' => 'Fail to delete %obj% for %id% with parent id %parentId% (Exception : %e%)', + 'Fail to update %type% position: %err%' => 'Fail to update %type% position: %err%', 'Failed to create instance of module "%name%" when trying to delete module. Module directory has probably been deleted' => 'Failed to create instance of module "%name%" when trying to delete module. Module directory has probably been deleted', 'Failed to find a payment Module with ID=%mid for order ID=%oid' => 'Failed to find a payment Module with ID=%mid for order ID=%oid', 'Failed to open translation file %file. Please be sure that this file is writable by your Web server' => 'Failed to open translation file %file. Please be sure that this file is writable by your Web server', 'Failed to update language definition: %ex' => 'Failed to update language definition: %ex', 'Fax' => 'Fax', 'Feature value does not match FLOAT format' => 'Feature value does not match FLOAT format', - 'File is too heavy, please retry with a file having a size less than %size%.' => 'File is too Large, please retry with a file having a size less than %size%.', + 'File is too large, please retry with a file having a size less than %size%.' => 'File is too large, please retry with a file having a size less than %size%.', 'First Name' => 'First Name', 'Firstname' => 'Firstname', 'Fixed Amount Discount' => 'Fixed Amount Discount', @@ -132,8 +137,6 @@ return array( 'If a translation is missing or incomplete :' => 'If a translation is missing or incomplete :', 'If cart item count is %operator% %quantity%' => 'If cart item count is %operator% %quantity%', 'If cart total amount is %operator% %amount% %currency%' => 'If cart total amount is %operator% %amount% %currency%', - 'Image position updated' => 'Image position updated', - 'Images deleted successfully' => 'Images deleted successfully', 'Impossible to delete a customer who already have orders' => 'Impossible to delete a customer who already have orders', 'In' => 'In', 'Information' => 'Information', @@ -141,6 +144,7 @@ return array( 'Invalid value "%value" for "%param" parameter in loop type: %type, name: %name' => 'Invalid value "%value" for "%param" parameter in loop type: %type, name: %name', 'Invalid value for walkMode parameter: %value' => 'Invalid value for walkMode parameter: %value', 'Is it the default product sale element ?' => 'Is it the default product sale element ?', + 'Keep the most important part of your description in the first 150-160 characters.' => 'Keep the most important part of your description in the first 150-160 characters.', 'Language name' => 'Language name', 'Last Name' => 'Last Name', 'Lastname' => 'Lastname', @@ -155,6 +159,8 @@ return array( 'Loop must implements \'PropelSearchLoopInterface\' to be versionable' => 'Loop must implements \'PropelSearchLoopInterface\' to be versionable', 'Loop must implements one of the following interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`' => 'Loop must implements one of the following interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`', 'Loop type \'%type\' is not defined.' => 'Loop type \'%type\' is not defined.', + 'Make sure it uses keywords found within the page itself.' => 'Make sure it uses keywords found within the page itself.', + 'Make sure that your title is clear, and contains many of the keywords within the page itself.' => 'Make sure that your title is clear, and contains many of the keywords within the page itself.', 'Make this address as my primary address' => 'Make this address as my primary address', 'Maximum usage count reached for coupon %code' => 'Maximum usage count reached for coupon %code', 'Message subject' => 'Message subject', @@ -182,6 +188,7 @@ return array( 'Not found' => 'Not found', 'Not in' => 'Not in', 'Notices' => 'Notices', + 'Only files having the following mime type are allowed: %types%' => 'Only files having the following mime type are allowed: %types%', 'Only if order billing country is %op% %countries_list%' => 'Le pays de facturation de la commande est %op% %countries_list% ', 'Only if order shipping country is %op% %countries_list%' => 'Le pays de livraison de la commande est %op% %countries_list% ', 'Order address ID not found' => 'Order address ID not found', @@ -255,9 +262,13 @@ return array( 'Rotated Text File' => 'Rotated Text File', 'Sale price excluding taxes' => 'Sale price excluding taxes', 'Sale price including taxes' => 'Sale price including taxes', - 'Saving documents for %parentName% parent id %parentId% (%parentType%)' => 'Saving documents for %parentName% parent id %parentId% (%parentType%)', - 'Saving images for %parentName% parent id %parentId% (%parentType%)' => 'Saving images for %parentName% parent id %parentId% (%parentType%)', + 'Saving %obj% for %parentName% parent id %parentId%' => 'Saving %obj% for %parentName% parent id %parentId%', + 'Select the brand logo' => 'Select the brand logo', + 'Select the brand logo amongst the brand images' => 'Select the brand logo amongst the brand images', + 'Select the product brand, or supplier.' => 'Select the product brand, or supplier.', 'Shipping zone name' => 'Shipping zone name', + 'Short additional text' => 'Short additional text', + 'Short description text' => 'Short description text', 'Show redirections *' => 'Show redirections *', 'Sorry, an error occured: %msg' => 'Sorry, an error occured: %msg', 'Sorry, an error occurred: %err' => 'Sorry, an error occurred: %err', @@ -286,15 +297,19 @@ return array( 'Template file %file cannot be found.' => 'Template file %file cannot be found.', 'Text File' => 'Text File', 'Text Message' => 'Text Message', + 'The HTML TITLE element is the most important element on your web page.' => 'The HTML TITLE element is the most important element on your web page.', 'The TaxEngine should be passed to this form before using it.' => 'The TaxEngine should be passed to this form before using it.', + 'The brand name or title' => 'The brand name or title', 'The cart item count should match the condition' => 'The cart item count should match the condition', 'The coupon applies if the cart contains at least one product of the selected categories' => 'The coupon applies if the cart contains at least one product of the selected categories', 'The coupon applies if the cart contains at least one product of the specified product list' => 'The coupon applies if the cart contains at least one product of the specified product list', 'The coupon applies to some customers only' => 'The coupon applies to some customers only', 'The coupon applies to the selected delivery countries' => 'Ce code promo s\'applique seulement aux pays de facturation sélectionnés', 'The coupon is valid after a given date' => 'Le code promo est valide seulement à partir d\'une certaine date', + 'The detailed description.' => 'The detailed description.', 'The image which replaces an undefined country flag (%file) was not found. Please check unknown-flag-path configuration variable, and check that the image exists.' => 'The image which replaces an undefined country flag (%file) was not found. Please check unknown-flag-path configuration variable, and check that the image exists.', 'The loop name \'%name\' is already defined in %className class' => 'The loop name \'%name\' is already defined in %className class', + 'This brand is online' => 'This brand is online', 'This category is online.' => 'This category is online.', 'This condition is always true' => 'This condition is always true', 'This content is online.' => 'This content is online.', @@ -329,9 +344,9 @@ return array( 'Unconditionnal usage' => 'Unconditionnal usage', 'Undefined loop argument "%name"' => 'Undefined loop argument "%name"', 'Undefined search mode \'%mode\'' => 'Undefined search mode \'%mode\'', - 'Undefined translation type: %item' => 'Undefined translation type: %item', 'Unknown order ID: %id' => 'Unknown order ID: %id', 'Unsupported magic method %name. only getArgname() is supported.' => 'Unsupported magic method %name. only getArgname() is supported.', + 'Use the keyword phrase in your URL.' => 'Use the keyword phrase in your URL.', 'Username' => 'Username', 'Username *' => 'Username *', 'Valid only from %date% to the coupon expiration date' => 'Valide à partir du %date% jusqu\'à la date d\'expiration', @@ -343,7 +358,7 @@ return array( 'Weight' => 'Weight', 'Yes, I have a password :' => 'Yes, I have a password :', 'You are already registered!' => 'You are already registered!', - 'You can only upload images (.png, .jpg, .jpeg, .gif)' => 'You can only upload images (.png, .jpg, .jpeg, .gif)', + 'You don\'t need to use commas or other punctuations.' => 'You don\'t need to use commas or other punctuations.', 'Your Email Address' => 'Your Email Address', 'Your Message' => 'Your Message', 'Your current password does not match.' => 'Your current password does not match.', diff --git a/core/lib/Thelia/Config/I18n/fr_FR.php b/core/lib/Thelia/Config/I18n/fr_FR.php index bd789a0ad..cb9062a1f 100644 --- a/core/lib/Thelia/Config/I18n/fr_FR.php +++ b/core/lib/Thelia/Config/I18n/fr_FR.php @@ -6,11 +6,16 @@ return array( '%obj SEO modification' => 'Modification SEO de %obj', '%obj creation' => 'Création de %obj', '%obj modification' => 'Modification de %obj', + '%obj%s deleted successfully' => '%obj%s ont été supprimé(e)s', + '%type% position updated' => 'Mise à jour de la position de %type%', '\'%type\' loop class should extends Thelia\Core\Template\Element\BaseLoop' => 'La classe de boucle \'%type\' doit hériter de Thelia\Core\Template\Element\BaseLoop ', 'A currency with code "%name" already exists.' => 'Une devise avec la code "%name" existe déjà', + 'A descriptive title' => 'Un titre descriptif', 'A loop named \'%name\' already exists in the current scope.' => 'Une boucle nommée \'%name\' existe déjà dans le scope courant', 'A message with name "%name" already exists.' => 'Un message avec le nom "%name" existe déjà.', 'A product with reference %ref already exists. Please choose another reference.' => 'Un produit portant la référfence %ref existe déja. Merci de choisir une autre référence.', + 'A short description, used when a summary or an introduction is required' => 'Un texte court, utilisée quand un résumé ou une introduction est nécessaire.', + 'A short text, used when an additional or supplemental information is required.' => 'Un texte court, utilisé quand une conclusion ou une information complémentaire est nécessaire.', 'A user already exists with this email address. Please login or if you\'ve forgotten your password, go to Reset Your Password.' => 'Un utilisateur existe déjà avec cette adresse email. Connectez-vous ou demandez une réinitialisation de votre mot de passe.', 'A value for attribute "%name" is already present in the combination' => 'Une valeur pour la déclinaison "%name" est déjà présente dans la combinaison', 'A variable with name "%name" already exists.' => 'Une variable avec le nom "%name" existe déjà.', @@ -39,6 +44,9 @@ return array( 'Bad tax list JSON' => 'Mauvais JSON de la liste des taxes', 'Billing country' => 'Pays de livraison', 'Billing coutry is' => 'Pays de facturation', + 'Brand' => 'Marque', + 'Brand / Supplier' => 'Marque / Fournisseur', + 'Brand name' => 'Nom de la marque', 'Business ID' => 'ID du business', 'Cannot find a default country. Please define one.' => 'Impossible de trouver un pays par défaut. Veuillez en définir un.', 'Cannot find the shop country. Please select a shop country.' => 'Impossible de trouver le pays du magasin. Veuillez en sélectionner un.', @@ -78,37 +86,34 @@ return array( 'Default folder *' => 'Dossier par défaut *', 'Default product category *' => 'Catégorie du produit par défaut *', 'Default product sale element' => 'Product Sale Element par défaut', - 'Deleting document for %id% with parent id %parentId%' => 'Suppression du document %id% avec l\'ID parent %parentId%', - 'Deleting image for %id% with parent id %parentId%' => 'Suppression de l\'image %id% avec l\'ID parent %parentId%', + 'Deleting %obj% for %id% with parent id %parentId%' => 'Suppresion de %obj%, ID %id%, ID parent %parentId%', 'Delivery country' => 'Pays de livraison', 'Delivery coutry is' => 'Le pays de livraison est', 'Delivery module ID not found' => 'Id du module de livraison non trouvé', 'Description' => 'Description', 'Detailed description' => 'Description détaillée', 'Disabled' => 'Désactivé', - 'Document deleted successfully' => 'Le document a été supprimé.', - 'Document position updated' => 'La position du document a été modfiée', + 'Don\'t repeat keywords over and over in a row. Rather, put in keyword phrases.' => 'Ne répétez pas sans cesse les même mots-clés dans une ligne. Préférez utiliser des expressions de mots-clés', 'EAN Code' => 'Code EAN', 'Email Address' => 'Adresse mail', 'Email address' => 'Adresse e-mail', 'Emergency' => 'Urgence', 'Enable remote SMTP use' => 'Activer l\'utilisation d\'un serveur SMTP distant.', 'Encryption' => 'Chiffrement', + 'Enter here the brand name in the default language (%title%)' => 'Indiquez le nom de la marque dans la langue par défaut (%title%)', 'Equal to' => 'Egal à', 'Error during %action process : %error. Exception was %exc' => 'Erreur lors de %action: %error. Exception: %exc ', 'Error occured while processing order ref. %ref, ID %id: %err' => 'Un erreur est survenue paedant le traitement de la commande ref. %ref, ID %id; %err', 'Errors' => 'Erreurs', - 'Fail to delete document for %id% with parent id %parentId% (Exception : %e%)' => 'Echec lors de la suppression du document %id% avec l\'ID parent %parentId% (Exception : %e%)', - 'Fail to delete image for %id% with parent id %parentId% (Exception : %e%)' => 'Echec lors de la suppression de l\'image %id% avec l\'ID parent %parentId% (Exception : %e%)', - 'Fail to update document position' => 'La position du document e n\'a pas pu être modfiée', - 'Fail to update image position' => 'La position de l\'image n\'a pas pu être modfiée', + 'Fail to delete %obj% for %id% with parent id %parentId% (Exception : %e%)' => 'Ne peut supprimer %obj% ID %id% ID parent %parentId% (Exception : %e%)', + 'Fail to update %type% position: %err%' => 'Erreur lors de la mise àç jour de la position de %type%: %err%', 'Failed to create instance of module "%name%" when trying to delete module. Module directory has probably been deleted' => 'Ne peut créer une instance du module "%name%" lors de la suppression du module. Le répertoire du module à sans doute été supprimé manuellement.', 'Failed to find a payment Module with ID=%mid for order ID=%oid' => 'Ne peut trouver le module de paiement ID=%mid pour la commande ID=%oid ', 'Failed to open translation file %file. Please be sure that this file is writable by your Web server' => 'L\'ouverture du fichier %file a échoué. Merci de vérifier que ce fichier est accessible en écriture pour votre serveur Web.', 'Failed to update language definition: %ex' => 'Erreur lors de la mise à jour de la définition de la langue : %ex', 'Fax' => 'Fax', 'Feature value does not match FLOAT format' => 'valeur de caractéristique n\'est pas un FLOAT', - 'File is too heavy, please retry with a file having a size less than %size%.' => 'La taille du fichier est trop importante, et doit être inféreiure à %size%.', + 'File is too large, please retry with a file having a size less than %size%.' => 'La taille de ce fichier est trop importante. Merci d\'envoyer des fichier dont la taille est inférieure à %size%.', 'First Name' => 'Prénom', 'Firstname' => 'Prénom', 'Fixed Amount Discount' => 'Remise d\'un montant fixe', @@ -132,8 +137,6 @@ return array( 'If a translation is missing or incomplete :' => 'Si une traduction est manquante ou incomplète :', 'If cart item count is %operator% %quantity%' => 'Le nombre d\'articles dans le panier est %operator% %quantity% ', 'If cart total amount is %operator% %amount% %currency%' => 'Si le total du panier est %operator% %amount% %currency% ', - 'Image position updated' => 'La position de l\'image a été modfiée', - 'Images deleted successfully' => 'L\'image a été supprimée.', 'Impossible to delete a customer who already have orders' => 'Impossible de supprimer un client si celui-ci a déjà une commande', 'In' => 'Compris dans', 'Information' => 'Information', @@ -141,6 +144,7 @@ return array( 'Invalid value "%value" for "%param" parameter in loop type: %type, name: %name' => 'La valeur "%value" est invalide pour le paramètre "%param" dans la boucle type: %type, nom: %name ', 'Invalid value for walkMode parameter: %value' => 'Valeur incorrecte pour le paramètre walkMode : %value', 'Is it the default product sale element ?' => 'Product Sale Element par défaut ?', + 'Keep the most important part of your description in the first 150-160 characters.' => 'Votre description ne devrait pas dépasser 150 à 160 caractères', 'Language name' => 'Nom de la langue', 'Last Name' => 'Nom', 'Lastname' => 'Nom', @@ -155,6 +159,8 @@ return array( 'Loop must implements \'PropelSearchLoopInterface\' to be versionable' => 'Les classes \'boucle\' doivent implémenter \'PropelSearchLoopInterface\' pour être versonnables', 'Loop must implements one of the following interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`' => 'Une boucle doit implémenter au moins une de ces interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`', 'Loop type \'%type\' is not defined.' => 'La boucle de type \'%type\' n\'existe pas.', + 'Make sure it uses keywords found within the page itself.' => 'Assurez vous d\'utiliser des mots-clés présents dans la page courante', + 'Make sure that your title is clear, and contains many of the keywords within the page itself.' => 'Assurez-vous d\'avoir un titre clair et qui contient les mots-clés correspondant à la page en cours', 'Make this address as my primary address' => 'Choisir cette adresse comme adresse par défaut', 'Maximum usage count reached for coupon %code' => 'Le nombre maximum d\'utilisation pour le coupon %code est dépassé.', 'Message subject' => 'Sujet', @@ -182,6 +188,7 @@ return array( 'Not found' => 'Non trouvé.', 'Not in' => 'Non compris dans', 'Notices' => 'Notices', + 'Only files having the following mime type are allowed: %types%' => 'Seuls les types MIME autorisés sont les suivants: %types%', 'Only if order billing country is %op% %countries_list%' => 'Si le pays de facturation %op% %countries_list% ', 'Only if order shipping country is %op% %countries_list%' => 'Si le pays de livraison %op% %countries_list% ', 'Order address ID not found' => 'ID de l\'adresse de la commande non trouvé', @@ -255,9 +262,13 @@ return array( 'Rotated Text File' => 'Rotation du fichier texte', 'Sale price excluding taxes' => 'Prix de vente Hors Taxes', 'Sale price including taxes' => 'Prix de vente Toutes Taxes Comprises', - 'Saving documents for %parentName% parent id %parentId% (%parentType%)' => 'Enregistrement des documents pour %parentName% ID parent %parentId% (%parentType%)', - 'Saving images for %parentName% parent id %parentId% (%parentType%)' => 'Enregistrement des images pour %parentName% ID parent %parentId% (%parentType%)', + 'Saving %obj% for %parentName% parent id %parentId%' => 'Enregistrement de %obj% pour %parentName% ID parent %parentId%', + 'Select the brand logo' => 'Logo de la marque', + 'Select the brand logo amongst the brand images' => 'Choisissez le logo de la marque parmis les images associées à cette marque', + 'Select the product brand, or supplier.' => 'Choisissez la marque ou le fournisseur du produit.', 'Shipping zone name' => 'Nom de la zone de livraison', + 'Short additional text' => 'Un court texte supplémentaire', + 'Short description text' => 'Un court texte de description', 'Show redirections *' => 'Montrer les redirections *', 'Sorry, an error occured: %msg' => 'Désolé, une erreur est survenue : %msg', 'Sorry, an error occurred: %err' => 'Désolé, une erreur est survenue: %err', @@ -286,15 +297,19 @@ return array( 'Template file %file cannot be found.' => 'Le fichier %file n\'a pas été trouvé dans le template. ', 'Text File' => 'Fichier texte', 'Text Message' => 'Message au format texte', + 'The HTML TITLE element is the most important element on your web page.' => 'L\'élément HTML TITLE est le plus important dans votre page', 'The TaxEngine should be passed to this form before using it.' => 'Le moteur de taxe doit être passé au formulaire avant d\'être utilisé.', + 'The brand name or title' => 'Le nom ou le titre de la marque', 'The cart item count should match the condition' => 'Le nombre d\'articles dans le panier doit vérifier la condition', 'The coupon applies if the cart contains at least one product of the selected categories' => 'Le code promo est valable si le panier contient/ne contient pas des produits appartenant aux catégories sélectionnées', 'The coupon applies if the cart contains at least one product of the specified product list' => 'Le code promo est valable si le panier contient/ne contient pas au moins un des produits selectionnés', 'The coupon applies to some customers only' => 'Ce code promo est valable pour les clients sélectionnés', 'The coupon applies to the selected delivery countries' => 'Ce code promo s\'applique pour les pays de livraison sélectionnés', 'The coupon is valid after a given date' => 'Le code promo est valide à partir de cette date', + 'The detailed description.' => 'La description détaillée', 'The image which replaces an undefined country flag (%file) was not found. Please check unknown-flag-path configuration variable, and check that the image exists.' => 'L\'image qui remplace un drapeau de pays manquant (%file) n\'a pas été trouvée. Merci de vérifier la variable de configuration unknown-flag-path.', 'The loop name \'%name\' is already defined in %className class' => 'La boucle \'%name\' est déjà définir dans la classe %className', + 'This brand is online' => 'Cette marque est en ligne', 'This category is online.' => 'Cette catégorie est en ligne.', 'This condition is always true' => 'Cette condition est troujours vérifiée', 'This content is online.' => 'Ce contenu est en ligne.', @@ -329,9 +344,9 @@ return array( 'Unconditionnal usage' => 'Utilisable sans conditions', 'Undefined loop argument "%name"' => 'Argument de boucle invalide: "%name" ', 'Undefined search mode \'%mode\'' => 'Mode de recherche \'%mode\' invalide', - 'Undefined translation type: %item' => 'Type de traduction inconnu:%item ', 'Unknown order ID: %id' => 'La commande ID %id est inconnue.', 'Unsupported magic method %name. only getArgname() is supported.' => 'La méthode magique %name n\'est pas supportée. Seule get() est supporté..', + 'Use the keyword phrase in your URL.' => 'Utilisez des mots clés dans votre URL', 'Username' => 'Nom d\'utilisateur', 'Username *' => 'Nom d\'utilisateur *', 'Valid only from %date% to the coupon expiration date' => 'Valide à partir de %date% jusqu\'à la date d\'expoiration', @@ -343,7 +358,7 @@ return array( 'Weight' => 'Poids', 'Yes, I have a password :' => 'Oui, j\'ai un mot de passe :', 'You are already registered!' => 'Vous êtes déjà enregistré !', - 'You can only upload images (.png, .jpg, .jpeg, .gif)' => 'Seules les images sont autorisées (.png, .jpg, .jpeg, .gif)', + 'You don\'t need to use commas or other punctuations.' => 'Vous n\'avez pas besoin d\'utiliser de virgules ou d\'autres signes de ponctuation', 'Your Email Address' => 'Votre adresse mail', 'Your Message' => 'Votre message', 'Your current password does not match.' => 'Votre mot de passe actuel ne correspond pas', From a3a2b8ad8e78de561af32642bd27a28e8070bb1c Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 15:18:22 +0200 Subject: [PATCH 25/64] Added brand data access --- .../Smarty/Plugins/DataAccessFunctions.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/DataAccessFunctions.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/DataAccessFunctions.php index f9f8725bd..8c7023bcf 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/DataAccessFunctions.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/DataAccessFunctions.php @@ -137,6 +137,19 @@ class DataAccessFunctions extends AbstractSmartyPlugin } } + public function brandDataAccess($params, &$smarty) + { + $contentId = $this->request->get('brand_id'); + + if ($contentId !== null) { + + $search = ContentQuery::create() + ->filterById($contentId); + + return $this->dataAccessWithI18n("Brand", $params, $search); + } + } + /** * currency global data * @@ -462,6 +475,7 @@ class DataAccessFunctions extends AbstractSmartyPlugin new SmartyPluginDescriptor('function', 'category', $this, 'categoryDataAccess'), new SmartyPluginDescriptor('function', 'content', $this, 'contentDataAccess'), new SmartyPluginDescriptor('function', 'folder', $this, 'folderDataAccess'), + new SmartyPluginDescriptor('function', 'brand', $this, 'brandDataAccess'), new SmartyPluginDescriptor('function', 'currency', $this, 'currencyDataAccess'), new SmartyPluginDescriptor('function', 'country', $this, 'countryDataAccess'), new SmartyPluginDescriptor('function', 'lang', $this, 'langDataAccess'), From a06b0a57e37a0380e2d9b7d8e4ccad81087d2a0c Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 19:15:07 +0200 Subject: [PATCH 26/64] Fixed "save & close" --- templates/backOffice/default/brand-edit.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/backOffice/default/brand-edit.html b/templates/backOffice/default/brand-edit.html index 17a819c1b..487ebd722 100644 --- a/templates/backOffice/default/brand-edit.html +++ b/templates/backOffice/default/brand-edit.html @@ -69,7 +69,7 @@ {form_hidden_fields form=$form} - {admin_form_field form=$form name="success_url" value={url path="/admin/brand/update/{$ID}"}} + {admin_form_field form=$form name="success_url" value={url path="/admin/brand"}} {admin_form_field form=$form name="locale" value={$edit_language_locale}} {if $form_error} From e972a4be60b3e6640a85a15686ade4a9d88fa9d1 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 19:24:47 +0200 Subject: [PATCH 27/64] Fixed renderRaw method comment --- core/lib/Thelia/Controller/Front/BaseFrontController.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/lib/Thelia/Controller/Front/BaseFrontController.php b/core/lib/Thelia/Controller/Front/BaseFrontController.php index 665b63400..39889a6e6 100644 --- a/core/lib/Thelia/Controller/Front/BaseFrontController.php +++ b/core/lib/Thelia/Controller/Front/BaseFrontController.php @@ -123,9 +123,9 @@ class BaseFrontController extends BaseController /** * Render the given template, and returns the result as a string. * - * @param $templateName the complete template name, with extension - * @param array $args the template arguments - * @param null $templateDir + * @param string $templateName the complete template name, with extension + * @param array $args the template arguments + * @param string$templateDir * * @return string */ From 4f7f26380aeef3d95f8668b7f11eb115062f3580 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 19:30:00 +0200 Subject: [PATCH 28/64] Fixed some more method comments --- .../Controller/Front/BaseFrontController.php | 28 +++++++++++++++---- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/core/lib/Thelia/Controller/Front/BaseFrontController.php b/core/lib/Thelia/Controller/Front/BaseFrontController.php index 39889a6e6..1e474c007 100644 --- a/core/lib/Thelia/Controller/Front/BaseFrontController.php +++ b/core/lib/Thelia/Controller/Front/BaseFrontController.php @@ -15,6 +15,7 @@ namespace Thelia\Controller\Front; use Symfony\Component\Routing\Router; use Thelia\Controller\BaseController; use Thelia\Core\HttpFoundation\Response; +use Thelia\Core\Template\ParserInterface; use Thelia\Core\Template\TemplateDefinition; use Thelia\Core\Template\TemplateHelper; use Thelia\Model\AddressQuery; @@ -30,17 +31,30 @@ class BaseFrontController extends BaseController * * @see \Thelia\Controller\BaseController::getRouteFromRouter() */ + + /** + * Return the route path defined for the givent route ID + * + * @param string $routeId the route ID, as found in Config/Resources/routing/admin.xml + * @param array $parameters the Route parameters, as a var/value pair array + * @param bool $referenceType Router::ABSOLUTE_PATH or Router::ABSOLUTE_URL + * + * @see \Thelia\Controller\BaseController::getRouteFromRouter() + * + * @return string the route path + */ protected function getRoute($routeId, $parameters = array(), $referenceType = Router::ABSOLUTE_PATH) { return $this->getRouteFromRouter('router.front', $routeId, $parameters, $referenceType); } /** - * Redirect to à route ID related URL - * - * @param string $routeId the route ID, as found in Config/Resources/routing/admin.xml - * @param array $urlParameters the URL parametrs, as a var/value pair array - * @param bool $referenceType + * Redirect to a specific route. + * + * @param string $routeId the route ID, as found in Config/Resources/routing/admin.xml + * @param array $urlParameters the URL parameters, as a var/value pair array + * @param array $routeParameters the Route parameters, as a var/value pair array + * @param bool $referenceType Router::ABSOLUTE_PATH or Router::ABSOLUTE_URL */ public function redirectToRoute($routeId, array $urlParameters = [], array $routeParameters = [], $referenceType = Router::ABSOLUTE_PATH) { @@ -95,7 +109,9 @@ class BaseFrontController extends BaseController } /** - * @return TemplateDefinition the template + * @param TemplateDefinition $template the template to process, or null for using the front template + * + * @return ParserInterface the Thelia parser² */ protected function getParser($template = null) { From dc63498180dccc32ca5f7a250724a552d3d46405 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 20:12:57 +0200 Subject: [PATCH 29/64] Added brand feed --- templates/frontOffice/default/layout.tpl | 1 + 1 file changed, 1 insertion(+) diff --git a/templates/frontOffice/default/layout.tpl b/templates/frontOffice/default/layout.tpl index 8a2d06a4c..914d003ca 100644 --- a/templates/frontOffice/default/layout.tpl +++ b/templates/frontOffice/default/layout.tpl @@ -67,6 +67,7 @@ GNU General Public License : http://www.gnu.org/licenses/ {* Feeds *} + {block name="feeds"}{/block} {* HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries *} From 30afbf14330ad5fbba422cc4bb620e1e6f7cd45a Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 20:13:14 +0200 Subject: [PATCH 30/64] Added brands feed processing --- local/modules/Front/Controller/FeedController.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/local/modules/Front/Controller/FeedController.php b/local/modules/Front/Controller/FeedController.php index 4167871df..307188d9b 100644 --- a/local/modules/Front/Controller/FeedController.php +++ b/local/modules/Front/Controller/FeedController.php @@ -18,6 +18,7 @@ use Thelia\Controller\Front\BaseFrontController; use Thelia\Core\HttpFoundation\Request; use Thelia\Core\HttpFoundation\Response; use Thelia\Log\Tlog; +use Thelia\Model\BrandQuery; use Thelia\Model\FolderQuery; use Thelia\Model\CategoryQuery; use Thelia\Model\ConfigQuery; @@ -56,6 +57,7 @@ class FeedController extends BaseFrontController { * @param $id string The id of the parent element. The id of the main parent category for catalog context. * The id of the content folder for content context * @return Response + * @throws \RuntimeException */ public function generateAction($context, $lang, $id) { @@ -66,7 +68,7 @@ class FeedController extends BaseFrontController { // context if ("" === $context){ $context = "catalog"; - } else if (! in_array($context, array("catalog", "content")) ){ + } else if (! in_array($context, array("catalog", "content", "brand")) ){ $this->pageNotFound(); } @@ -189,6 +191,9 @@ class FeedController extends BaseFrontController { if ("catalog" === $context){ $cat = CategoryQuery::create()->findPk($id); $ret = (null !== $cat && $cat->getVisible()); + } elseif ("brand" === $context) { + $brand = BrandQuery::create()->findPk($id); + $ret = (null !== $brand && $brand->getVisible()); } else { $folder = FolderQuery::create()->findPk($id); $ret = (null !== $folder && $folder->getVisible()); @@ -196,5 +201,4 @@ class FeedController extends BaseFrontController { } return $ret; } - -} \ No newline at end of file +} \ No newline at end of file From c209df59f58376b02b1263c4943c917dc58b9c1d Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 20:13:30 +0200 Subject: [PATCH 31/64] Added "brand" loop parameter --- core/lib/Thelia/Core/Template/Loop/Product.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/core/lib/Thelia/Core/Template/Loop/Product.php b/core/lib/Thelia/Core/Template/Loop/Product.php index fbf5303fa..5417446ac 100644 --- a/core/lib/Thelia/Core/Template/Loop/Product.php +++ b/core/lib/Thelia/Core/Template/Loop/Product.php @@ -64,6 +64,7 @@ class Product extends BaseI18nLoop implements PropelSearchLoopInterface, SearchL ) ), Argument::createIntListTypeArgument('category'), + Argument::createIntListTypeArgument('brand'), Argument::createIntListTypeArgument('category_default'), Argument::createBooleanTypeArgument('new'), Argument::createBooleanTypeArgument('promo'), @@ -327,6 +328,12 @@ class Product extends BaseI18nLoop implements PropelSearchLoopInterface, SearchL $search->filterById($this->request->get("product_id"), Criteria::NOT_IN); } + $brand_id = $this->getBrand(); + + if ($brand_id !== null) { + $search->filterByBrandId($brand_id, Criteria::IN); + } + $current_category = $this->getCurrent_category(); if ($current_category === true) { From 7a10a257800e05a497c07c4e851f8b55cd3690bf Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 20:13:51 +0200 Subject: [PATCH 32/64] Added "current" loop parameter --- core/lib/Thelia/Core/Template/Loop/Brand.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/core/lib/Thelia/Core/Template/Loop/Brand.php b/core/lib/Thelia/Core/Template/Loop/Brand.php index c177a7297..902d94b6f 100644 --- a/core/lib/Thelia/Core/Template/Loop/Brand.php +++ b/core/lib/Thelia/Core/Template/Loop/Brand.php @@ -49,6 +49,7 @@ class Brand extends BaseI18nLoop implements PropelSearchLoopInterface, SearchLoo Argument::createIntTypeArgument('product'), Argument::createBooleanOrBothTypeArgument('visible', 1), Argument::createAnyTypeArgument('title'), + Argument::createBooleanTypeArgument('current'), new Argument( 'order', new TypeCollection( @@ -121,6 +122,14 @@ class Brand extends BaseI18nLoop implements PropelSearchLoopInterface, SearchLoo $search->where("CASE WHEN NOT ISNULL(`requested_locale_i18n`.ID) THEN `requested_locale_i18n`.`TITLE` ELSE `default_locale_i18n`.`TITLE` END ".Criteria::LIKE." ?", "%".$title."%", \PDO::PARAM_STR); } + $current = $this->getCurrent(); + + if ($current === true) { + $search->filterById($this->request->get("brand_id")); + } elseif ($current === false) { + $search->filterById($this->request->get("brand_id"), Criteria::NOT_IN); + } + $orders = $this->getOrder(); foreach ($orders as $order) { From 63d8ea52dd6ce8307351027037d373626777bc28 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 22:04:09 +0200 Subject: [PATCH 33/64] No more Exception if ID cannot be found (e.g. content=0) --- core/lib/Thelia/Core/Template/Loop/Image.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/lib/Thelia/Core/Template/Loop/Image.php b/core/lib/Thelia/Core/Template/Loop/Image.php index b77609201..627b3eb79 100644 --- a/core/lib/Thelia/Core/Template/Loop/Image.php +++ b/core/lib/Thelia/Core/Template/Loop/Image.php @@ -179,7 +179,7 @@ class Image extends BaseI18nLoop implements PropelSearchLoopInterface $argValue = intval($this->getArgValue($source)); - if ($argValue > 0) { + if ($argValue >= 0) { $search = $this->createSearchQuery($source, $argValue); From 565de5d443c1c15124b62244456df32afd26242e Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 22:55:28 +0200 Subject: [PATCH 34/64] Added brand information --- templates/frontOffice/default/product.html | 56 ++++++++++++++++++---- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/templates/frontOffice/default/product.html b/templates/frontOffice/default/product.html index 5301d82f8..57289e42c 100644 --- a/templates/frontOffice/default/product.html +++ b/templates/frontOffice/default/product.html @@ -101,6 +101,10 @@

      {$TITLE}

      {if $REF}{intl l='Ref.'}: {$REF}{/if} + {loop name="brand_info" type="brand" product="{$ID}"} +

      {$TITLE}

      + {/loop} + {if $POSTSCRIPTUM}

      {$POSTSCRIPTUM}

      {/if} @@ -210,30 +214,59 @@ {strip} - {capture "additional"} - {ifloop rel="feature_info"} + {capture "additional"} + {ifloop rel="feature_info"}
        {loop name="feature_info" type="feature" product="{$ID}"} - {ifloop rel="feature_value_info"} + {ifloop rel="feature_value_info"}
      • {$TITLE} : {loop name="feature_value_info" type="feature_value" feature="{$ID}" product="{product attr="id"}"} {$TITLE} {/loop}
      • - {/ifloop} + {/ifloop} {/loop}
      - {/ifloop} - {/capture} + {/ifloop} + {/capture} + {/strip} + + {strip} + {capture "brand_info"} + {loop name="brand_info" type="brand" product="{$ID}"} +

      {$TITLE}

      + + {loop name="brand.image" type="image" source="brand" id={$LOGO_IMAGE_ID} width=218 height=146 resize_mode="borders"} +

      {$TITLE}

      + {/loop} + + {if $CHAPO} +
      + {$CHAPO} +
      + {/if} + {if $DESCRIPTION} +
      + {$DESCRIPTION nofilter} +
      + {/if} + {if $POSTSCRIPTUM} + + {$POSTSCRIPTUM} + + {/if} + {/loop} + {/capture} {/strip}
      @@ -241,9 +274,14 @@

      {$DESCRIPTION|default:'N/A' nofilter}

      {if $smarty.capture.additional ne ""} -
      - {$smarty.capture.additional nofilter} -
      +
      + {$smarty.capture.additional nofilter} +
      + {/if} + {if $smarty.capture.brand_info ne ""} +
      + {$smarty.capture.brand_info nofilter} +
      {/if}
    • From a4806132a122c31a52c95ee0805d5fa3de0abbf7 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 22:56:00 +0200 Subject: [PATCH 35/64] Fixed again excaption image is not found --- core/lib/Thelia/Core/Template/Loop/Image.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/lib/Thelia/Core/Template/Loop/Image.php b/core/lib/Thelia/Core/Template/Loop/Image.php index 627b3eb79..85ce14149 100644 --- a/core/lib/Thelia/Core/Template/Loop/Image.php +++ b/core/lib/Thelia/Core/Template/Loop/Image.php @@ -177,9 +177,11 @@ class Image extends BaseI18nLoop implements PropelSearchLoopInterface // Check for product="id" folder="id", etc. style arguments foreach ($this->possible_sources as $source) { - $argValue = intval($this->getArgValue($source)); + $argValue = $this->getArgValue($source); - if ($argValue >= 0) { + if (! empty($argValue)) { + + $argValue = intval($argValue); $search = $this->createSearchQuery($source, $argValue); From c1e3694ab8e8cdf1c5bcda3d841517dd33cd68c2 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 23:02:03 +0200 Subject: [PATCH 36/64] Typo --- core/lib/Thelia/Controller/Front/BaseFrontController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/lib/Thelia/Controller/Front/BaseFrontController.php b/core/lib/Thelia/Controller/Front/BaseFrontController.php index 1e474c007..2919d3a3f 100644 --- a/core/lib/Thelia/Controller/Front/BaseFrontController.php +++ b/core/lib/Thelia/Controller/Front/BaseFrontController.php @@ -50,7 +50,7 @@ class BaseFrontController extends BaseController /** * Redirect to a specific route. - * + * * @param string $routeId the route ID, as found in Config/Resources/routing/admin.xml * @param array $urlParameters the URL parameters, as a var/value pair array * @param array $routeParameters the Route parameters, as a var/value pair array From a6ab16908012d017ffb31c38c846c039ee8c333f Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 23:02:28 +0200 Subject: [PATCH 37/64] Added brand information page --- templates/frontOffice/default/brand.html | 157 ++++++++++++++++++ templates/frontOffice/default/feed.html | 87 +++++++--- .../default/includes/brand-menu.html | 12 ++ 3 files changed, 232 insertions(+), 24 deletions(-) create mode 100644 templates/frontOffice/default/brand.html create mode 100644 templates/frontOffice/default/includes/brand-menu.html diff --git a/templates/frontOffice/default/brand.html b/templates/frontOffice/default/brand.html new file mode 100644 index 000000000..23edbfb9d --- /dev/null +++ b/templates/frontOffice/default/brand.html @@ -0,0 +1,157 @@ +{extends file="layout.tpl"} + +{* Body Class *} +{block name="body-class"}page-content{/block} + +{* Page Title *} +{block name='no-return-functions' append} + {loop name="brand.seo.title" type="brand" id="{brand attr="id"}"} + {$page_title = {$META_TITLE}} + {/loop} +{/block} + +{* Meta *} +{block name="meta"} + {loop name="brand.seo.meta" type="brand" id="{brand attr="id"}"} + {if $META_DESCRIPTION} + {/if} + {if $META_KEYWORDS} + {/if} + {/loop} +{/block} + +{* Feeds *} +{block name="feeds"} + +{/block} + +{* Breadcrumb *} +{block name='no-return-functions' append} + {$breadcrumbs = []} + {loop type="brand" name="brand-breadcrumb" id="{brand attr="id"}"} + {$breadcrumbs[] = ['title' => {$TITLE}, 'url'=> {$URL}]} + {/loop} +{/block} + +{block name="main-content"} +
      + {$limit={$smarty.get.limit|default:8}} + {$product_page={$smarty.get.page|default:1}} + {$product_order={$smarty.get.order|default:'alpha'}} + {$mode=$smarty.get.mode|default:'grid'} + +
      + {loop name="brand.info" type="brand" current="yes"} +
      +

      {$TITLE}

      + + {loop name="brand.image" type="image" source="brand" id={$LOGO_IMAGE_ID} width=218 height=146 resize_mode="borders"} +

      {$TITLE}

      + {/loop} + + {if $CHAPO} +
      + {$CHAPO} +
      + {/if} + {if $DESCRIPTION} +
      + {$DESCRIPTION nofilter} +
      + {/if} + {if $POSTSCRIPTUM} + + {$POSTSCRIPTUM} + + {/if} +
      + + {ifloop rel="product_list"} +
      + {assign var="amount" value="{count type="product" brand="$ID"}"} + + +
      +
      +
        + {loop type="product" name="product_list" brand=$ID limit=$limit page=$product_page order=$product_order} + {include file="includes/single-product.html" product_id=$ID hasBtn=true hasDescription=true hasQuickView=true width="218" height="146"} + {/loop} +
      +
      +
      + + + {/ifloop} + + {elseloop rel="product_list"} +
      + {intl l="No products available in this brand"} +
      + {/elseloop} + + {/loop} +
      + + + +
      +{/block} diff --git a/templates/frontOffice/default/feed.html b/templates/frontOffice/default/feed.html index 2dd35a832..8e334a031 100644 --- a/templates/frontOffice/default/feed.html +++ b/templates/frontOffice/default/feed.html @@ -7,33 +7,72 @@ {/loop} {if $_context_ == "catalog"} - {if $_id_ == "" } - {intl l="All products in"} {$store_name} - {url path="/"} - {$store_name} - {$locale|replace:'_':'-'|lower} - {$smarty.now|date_format:'r'} - Thelia 2.0 - {else} - {loop type="category" name="category" id=$_id_ lang=$_lang_ } - {intl l="All products in"} {$TITLE} - {$store_name} - {$URL} - {$CHAPO} - {$LOCALE|replace:'_':'-'|lower} - {format_date date=$UPDATE_DATE format="r"} - {$smarty.now|date_format:'r'} - Thelia 2.0 + {if $_id_ == "" } + {intl l="All products in"} {$store_name} + {url path="/"} + {$store_name} + {$locale|replace:'_':'-'|lower} + {$smarty.now|date_format:'r'} + Thelia 2.0 + {else} + {loop type="category" name="category" id=$_id_ lang=$_lang_ } + {intl l="All products in"} {$TITLE} - {$store_name} + {$URL} + {$CHAPO} + {$LOCALE|replace:'_':'-'|lower} + {format_date date=$UPDATE_DATE format="r"} + {$smarty.now|date_format:'r'} + Thelia 2.0 + {/loop} + {/if} + {loop type="product" name="product" category_default=$_id_ lang=$_lang_ order="id_reverse" } + + {$TITLE} + {$URL} + {$CHAPO} + {format_date date=$CREATE_DATE format="r"} + {$URL} + {/loop} - {/if} - {loop type="product" name="product" category_default=$_id_ lang=$_lang_ order="id_reverse" } - - {$TITLE} + +{elseif $_context_ == "brand"} + + {if $_id_ == "" } + {intl l="All brands in %store" store="$store_name"} + {url path="/"} + {$store_name} + {$locale|replace:'_':'-'|lower} + {$smarty.now|date_format:'r'} + Thelia 2.0 + {loop type="brand" name="brand-list" lang=$_lang_ order="id-reverse" } + + {$TITLE} + {$URL} + {$CHAPO} + {format_date date=$CREATE_DATE format="r"} + {$URL} + + {/loop} + {else} + {loop type="brand" name="brand-desc" lang=$_lang_ id=$_id_} + {intl l="All products for brand %title in %store" title="$TITLE" store="$store_name"} {$URL} {$CHAPO} - {format_date date=$CREATE_DATE format="r"} - {$URL} - - {/loop} + {$locale|replace:'_':'-'|lower} + {$smarty.now|date_format:'r'} + Thelia 2.0 + {/loop} + {/if} + + {loop type="product" name="products-in-brand" brand=$_id_ lang=$_lang_ order="id_reverse" } + + {$TITLE} + {$URL} + {$CHAPO} + {format_date date=$CREATE_DATE format="r"} + {$URL} + + {/loop} {else} diff --git a/templates/frontOffice/default/includes/brand-menu.html b/templates/frontOffice/default/includes/brand-menu.html new file mode 100644 index 000000000..7d4b11884 --- /dev/null +++ b/templates/frontOffice/default/includes/brand-menu.html @@ -0,0 +1,12 @@ + From 1d94f454a7791aeeb779b1e3eeeeacc0cb695a58 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 30 Jun 2014 23:12:42 +0200 Subject: [PATCH 38/64] Brand related translations --- templates/frontOffice/default/I18n/en_US.php | 10 +++++++++- templates/frontOffice/default/I18n/fr_FR.php | 18 +++++++++++++----- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/templates/frontOffice/default/I18n/en_US.php b/templates/frontOffice/default/I18n/en_US.php index f30fd85d1..0d08a6b71 100755 --- a/templates/frontOffice/default/I18n/en_US.php +++ b/templates/frontOffice/default/I18n/en_US.php @@ -16,9 +16,13 @@ return array( 'Address' => 'Address', 'Address %nb' => 'Address %nb', 'Address Update' => 'Address update', + 'All brands' => 'All brands', + 'All brands in %store' => 'All brands in %store', 'All contents' => 'All contents', 'All contents in' => 'All contents in', + 'All product in brand %title' => 'All product in brand %title', 'All products' => 'All products', + 'All products for brand %title in %store' => 'All products for brand %title in %store', 'All products in' => 'All products in', 'Amount' => 'Amount', 'Availability' => 'Availability', @@ -26,6 +30,8 @@ return array( 'Back' => 'Back', 'Billing address' => 'Billing address', 'Billing and delivery' => 'Billing and delivery', + 'Brand information' => 'Brand information', + 'Brands' => 'Brands', 'Cancel' => 'Cancel', 'Cart' => 'Cart', 'Categories' => 'Categories', @@ -88,6 +94,7 @@ return array( 'Login Information' => 'Login Information', 'Main Navigation' => 'Main Navigation', 'Minimum 2 characters.' => 'Minimum 2 characters.', + 'More information about this brand' => 'More information about this brand', 'Multi-payment platform' => 'Multi-payment platform', 'My Account' => 'My Account', 'My Address Books' => 'My Address Books', @@ -106,15 +113,16 @@ return array( 'No Content in this folder.' => 'No Content in this folder.', 'No articles currently' => 'No articles currently', 'No deliveries available for this cart and this country' => 'No deliveries available for this cart and this country', + 'No products available in this brand' => 'No products available in this brand', 'No products available in this category' => 'No products available in this category', 'No results found' => 'No results found', 'No.' => 'No.', 'Offers' => 'Offers', 'Ok' => 'Ok', + 'Order Payment' => 'Order with payment obligation', 'Order details' => 'Order details', 'Order number' => 'Order number', 'Orders over $50' => 'Orders over $50', - 'Order Payment' => 'Order with payment obligation', 'Out of Stock' => 'Out of stock', 'Pagination' => 'Pagination', 'Password' => 'Password', diff --git a/templates/frontOffice/default/I18n/fr_FR.php b/templates/frontOffice/default/I18n/fr_FR.php index 5514e7cff..634b3179e 100755 --- a/templates/frontOffice/default/I18n/fr_FR.php +++ b/templates/frontOffice/default/I18n/fr_FR.php @@ -16,9 +16,13 @@ return array( 'Address' => 'Adresse', 'Address %nb' => 'Adresse n°', 'Address Update' => 'Mise à jour de l\'adresse', + 'All brands' => 'Toutes les marques', + 'All brands in %store' => 'Toutes les marques %store', 'All contents' => 'Tous les contenus', 'All contents in' => 'tous les contenus de', + 'All product in brand %title' => 'Tous les produits de la marque %title', 'All products' => 'Tous les produits', + 'All products for brand %title in %store' => 'Tous les produits %title de %store', 'All products in' => 'Tous les produits de', 'Amount' => 'Montant', 'Availability' => 'Disponibilité', @@ -26,6 +30,8 @@ return array( 'Back' => 'Retour', 'Billing address' => 'Adresse de facturation', 'Billing and delivery' => 'Facturation et livraison', + 'Brand information' => 'Marque', + 'Brands' => 'Marques', 'Cancel' => 'Annuler', 'Cart' => 'Panier', 'Categories' => 'Rubriques', @@ -88,6 +94,7 @@ return array( 'Login Information' => 'Informations de connexion', 'Main Navigation' => 'Navigation principale', 'Minimum 2 characters.' => '2 caractères minimum.', + 'More information about this brand' => 'Plus de détails sur cette marque', 'Multi-payment platform' => 'Plateforme de paiement multiple', 'My Account' => 'Mon compte', 'My Address Books' => 'Mes carnets d\'adresses', @@ -106,15 +113,16 @@ return array( 'No Content in this folder.' => 'Aucun contenu dans ce dossier.', 'No articles currently' => 'Aucun article en ce moment', 'No deliveries available for this cart and this country' => 'Aucun mode de livraison disponible pour ce panier et ce pays', + 'No products available in this brand' => 'Aucun produit de cette marque n\'est disponible', 'No products available in this category' => 'Aucun produit dans cette catégorie.', 'No results found' => 'Aucun résultat', 'No.' => 'N°', 'Offers' => 'Offres', 'Ok' => 'Ok', + 'Order Payment' => 'Commande avec obligation de paiement', 'Order details' => 'Détail de commande', 'Order number' => 'Commande numéro', 'Orders over $50' => 'Commande supérieure à 50€', - 'Order Payment' => 'Commande avec obligation de paiement', 'Out of Stock' => 'Hors stock', 'Pagination' => 'Pagination', 'Password' => 'Mot de passe', @@ -146,10 +154,10 @@ return array( 'Price descending' => 'Prix décroissant', 'Proceed checkout' => 'Continuer la commande', 'Product Empty Button' => 'Ajouter mon premier produit', - 'Product Empty Message' => 'Ajouter rapidement un produit. -
        -
      1. Cochez Nouveau dans l\'onglet Prix si vous voulez voir votre produit dans la section Nouveautés.
      2. -
      3. Cochez En promo dans l\'onglet Prix si vous voulez voir votre produit dans la section Offres.
      4. + 'Product Empty Message' => 'Ajouter rapidement un produit. +
          +
        1. Cochez Nouveau dans l\'onglet Prix si vous voulez voir votre produit dans la section Nouveautés.
        2. +
        3. Cochez En promo dans l\'onglet Prix si vous voulez voir votre produit dans la section Offres.
        ', 'Product Empty Title' => 'Bienvenue', 'Product Name' => 'Nom du produit', From 189ad9f7822e98624e85384ff353a4cbd6c025bf Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Tue, 1 Jul 2014 00:57:41 +0200 Subject: [PATCH 39/64] Added html_output_trim_level config var, fix for #490 --- .../Core/Template/Smarty/SmartyParser.php | 110 +++++++++++++++++- setup/insert.sql | 4 +- setup/update/2.0.3.sql | 8 ++ 3 files changed, 117 insertions(+), 5 deletions(-) diff --git a/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php b/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php index 53adfc88b..580da808e 100644 --- a/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php +++ b/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php @@ -24,6 +24,7 @@ use Thelia\Core\Template\ParserContext; use Thelia\Core\Template\TemplateDefinition; use Imagine\Exception\InvalidArgumentException; use Thelia\Core\Translation\Translator; +use Thelia\Model\ConfigQuery; /** * @@ -95,14 +96,115 @@ class SmartyParser extends Smarty implements ParserInterface // The default HTTP status $this->status = 200; - $this->registerFilter('output', array($this, "removeBlankLines")); - //$this->loadFilter('output', "trimwhitespace"); + $this->registerFilter('output', array($this, "trimWhitespaces")); $this->registerFilter('variable', array(__CLASS__, "theliaEscape")); } - public function removeBlankLines($tpl_source, \Smarty_Internal_Template $template) + /** + * Trim whitespaces from the HTML output, preserving required ones in pre, textarea, javascript. + * This methois uses 3 levels of trimming : + * + * - 0 : whitespaces are not trimmed, code remains as is. + * - 1 : only blank lines are trimmed, code remains indented and human-readable (the default) + * - 2 or more : all unnecessary whitespace are removed. Code is very hard to read. + * + * The trim level is defined by the configuration variable html_output_trim_level + * + * @param string $source the HTML source + * @param \Smarty_Internal_Template $template + * @return string + */ + public function trimWhitespaces($source, \Smarty_Internal_Template $template) { - return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $tpl_source); + $compressionMode = ConfigQuery::read('html_output_trim_level', 1); + + if ($compressionMode == 0) { + return $source; + } + + $store = array(); + $_store = 0; + $_offset = 0; + + // Unify Line-Breaks to \n + $source = preg_replace("/\015\012|\015|\012/", "\n", $source); + + // capture Internet Explorer Conditional Comments + if ($compressionMode == 1) { + $expressions = array( + // remove spaces between attributes (but not in attribute values!) + '#(([a-z0-9]\s*=\s*(["\'])[^\3]*?\3)|<[a-z0-9_]+)\s+([a-z/>])#is' => '\1 \4', + '/(^[\n]*|[\n]+)[\s\t]*[\n]+/' => "\n" + ); + } + else if ($compressionMode >= 2) { + if (preg_match_all('##is', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { + foreach ($matches as $match) { + $store[] = $match[0][0]; + $_length = strlen($match[0][0]); + $replace = '@!@SMARTY:' . $_store . ':SMARTY@!@'; + $source = substr_replace($source, $replace, $match[0][1] - $_offset, $_length); + + $_offset += $_length - strlen($replace); + $_store++; + } + } + + // Strip all HTML-Comments + // yes, even the ones in blocks.
        - * Install: Drop into the plugin directory, call - * $smarty->load_filter('output','trimwhitespace'); - * from application. - * @author Monte Ohrt - * @author Contributions from Lars Noschinski - * @version 1.3 - * @param string - * @param Smarty - */ -function smarty_outputfilter_trimwhitespace($source, &$smarty) -{ - // Pull out the script blocks - preg_match_all("!]*?>.*?!is", $source, $match); - $_script_blocks = $match[0]; - $source = preg_replace("!]*?>.*?!is", - '@@@SMARTY:TRIM:SCRIPT@@@', $source); - - // Pull out the pre blocks - preg_match_all("!]*?>.*?!is", $source, $match); - $_pre_blocks = $match[0]; - $source = preg_replace("!]*?>.*?!is", - '@@@SMARTY:TRIM:PRE@@@', $source); - - // Pull out the textarea blocks - preg_match_all("!]*?>.*?!is", $source, $match); - $_textarea_blocks = $match[0]; - $source = preg_replace("!]*?>.*?!is", - '@@@SMARTY:TRIM:TEXTAREA@@@', $source); - - // remove all leading spaces, tabs and carriage returns NOT - // preceeded by a php close tag. - $source = trim(preg_replace('/((?)\n)[\s]+/m', '\1', $source)); - - // replace textarea blocks - smarty_outputfilter_trimwhitespace_replace("@@@SMARTY:TRIM:TEXTAREA@@@",$_textarea_blocks, $source); - - // replace pre blocks - smarty_outputfilter_trimwhitespace_replace("@@@SMARTY:TRIM:PRE@@@",$_pre_blocks, $source); - - // replace script blocks - smarty_outputfilter_trimwhitespace_replace("@@@SMARTY:TRIM:SCRIPT@@@",$_script_blocks, $source); - - return $source; -} - -function smarty_outputfilter_trimwhitespace_replace($search_str, $replace, &$subject) -{ - $_len = strlen($search_str); - $_pos = 0; - for ($_i=0, $_count=count($replace); $_i<$_count; $_i++) - if (($_pos=strpos($subject, $search_str, $_pos))!==false) - $subject = substr_replace($subject, $replace[$_i], $_pos, $_len); - else - break; - -} From f820a09a1ae77e883e7beda38d55767b345832f8 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Tue, 1 Jul 2014 01:07:03 +0200 Subject: [PATCH 41/64] Added brand loop test --- .../Tests/Core/Template/Loop/BrandTest.php | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 core/lib/Thelia/Tests/Core/Template/Loop/BrandTest.php diff --git a/core/lib/Thelia/Tests/Core/Template/Loop/BrandTest.php b/core/lib/Thelia/Tests/Core/Template/Loop/BrandTest.php new file mode 100644 index 000000000..f9a601693 --- /dev/null +++ b/core/lib/Thelia/Tests/Core/Template/Loop/BrandTest.php @@ -0,0 +1,63 @@ + + * + */ +class BrandTest extends BaseLoopTestor +{ + public function getTestedClassName() + { + return 'Thelia\Core\Template\Loop\Brand'; + } + + public function getTestedInstance() + { + return new Brand($this->container); + } + + public function getMandatoryArguments() + { + return array(); + } + + public function testSearchById() + { + $brand = BrandQuery::create()->findOne(); + if (null === $brand) { + $brand = new \Thelia\Model\Brand(); + $brand->setVisible(1); + $brand->setTitle('foo'); + $brand->save(); + } + + $otherParameters = array( + "visible" => "*", + ); + + $this->baseTestSearchById($brand->getId(), $otherParameters); + } + + public function testSearchLimit() + { + $this->baseTestSearchWithLimit(3); + } +} From 811e89f74012e58ce55f62d6b5eb255432c27f69 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Tue, 1 Jul 2014 01:07:56 +0200 Subject: [PATCH 42/64] PHP-CS fixer pass --- core/lib/Thelia/Action/BaseCachedFile.php | 4 +--- core/lib/Thelia/Action/Document.php | 4 ---- core/lib/Thelia/Action/Image.php | 6 +---- .../Controller/Admin/FileController.php | 24 ++++++++----------- .../Controller/Admin/ProductController.php | 2 +- .../Controller/Front/BaseFrontController.php | 16 ++++++------- .../Core/Event/Brand/BrandUpdateEvent.php | 3 ++- .../Document/DocumentCreateOrUpdateEvent.php | 6 ++--- .../Event/Document/DocumentDeleteEvent.php | 8 +++---- .../Core/Event/File/FileDeleteEvent.php | 2 +- .../Core/Event/Image/ImageDeleteEvent.php | 2 +- .../Thelia/Core/Event/Image/ImageEvent.php | 6 +++-- .../Core/Event/Product/ProductUpdateEvent.php | 4 ++-- .../Thelia/Core/Template/Element/BaseLoop.php | 2 +- core/lib/Thelia/Core/Template/Loop/Coupon.php | 1 - .../Thelia/Core/Template/Loop/Document.php | 1 - .../lib/Thelia/Core/Template/Loop/Product.php | 2 +- .../Core/Template/Smarty/SmartyParser.php | 10 ++++---- core/lib/Thelia/Model/Category.php | 4 ++-- core/lib/Thelia/Model/Folder.php | 4 ++-- 20 files changed, 48 insertions(+), 63 deletions(-) diff --git a/core/lib/Thelia/Action/BaseCachedFile.php b/core/lib/Thelia/Action/BaseCachedFile.php index 42e67f5c8..3c8f98061 100644 --- a/core/lib/Thelia/Action/BaseCachedFile.php +++ b/core/lib/Thelia/Action/BaseCachedFile.php @@ -13,7 +13,7 @@ namespace Thelia\Action; use Thelia\Core\Event\CachedFileEvent; use Thelia\Core\Event\File\FileCreateOrUpdateEvent; -use Thelia\Core\Event\Image\FileDeleteEvent; +use Thelia\Core\Event\File\FileDeleteEvent; use Thelia\Core\Event\UpdateFilePositionEvent; use Thelia\Exception\FileException; use Thelia\Files\FileManager; @@ -181,7 +181,6 @@ abstract class BaseCachedFile extends BaseAction return $path; } - /** * Take care of saving a file in the database and file storage * @@ -213,7 +212,6 @@ abstract class BaseCachedFile extends BaseAction $event->setUploadedFile($newUploadedFile); } - /** * Take care of updating file in the database and file storage * diff --git a/core/lib/Thelia/Action/Document.php b/core/lib/Thelia/Action/Document.php index 8499fd087..187552944 100644 --- a/core/lib/Thelia/Action/Document.php +++ b/core/lib/Thelia/Action/Document.php @@ -12,13 +12,9 @@ namespace Thelia\Action; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent; -use Thelia\Core\Event\Document\DocumentDeleteEvent; use Thelia\Core\Event\Document\DocumentEvent; use Thelia\Core\Event\TheliaEvents; -use Thelia\Core\Event\UpdateFilePositionEvent; use Thelia\Exception\DocumentException; -use Thelia\Exception\ImageException; use Thelia\Model\ConfigQuery; use Thelia\Tools\URL; diff --git a/core/lib/Thelia/Action/Image.php b/core/lib/Thelia/Action/Image.php index eb338e219..481ba850d 100644 --- a/core/lib/Thelia/Action/Image.php +++ b/core/lib/Thelia/Action/Image.php @@ -18,12 +18,8 @@ use Imagine\Image\ImageInterface; use Imagine\Image\ImagineInterface; use Imagine\Image\Point; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Thelia\Core\Event\File\FileCreateOrUpdateEvent; -use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent; -use Thelia\Core\Event\Image\ImageDeleteEvent; use Thelia\Core\Event\Image\ImageEvent; use Thelia\Core\Event\TheliaEvents; -use Thelia\Core\Event\UpdateFilePositionEvent; use Thelia\Exception\ImageException; use Thelia\Model\ConfigQuery; use Thelia\Tools\URL; @@ -86,7 +82,7 @@ class Image extends BaseCachedFile implements EventSubscriberInterface * * This method updates the cache_file_path and file_url attributes of the event * - * @param ImageEvent $event + * @param ImageEvent $event * * @throws \Thelia\Exception\ImageException * @throws \InvalidArgumentException diff --git a/core/lib/Thelia/Controller/Admin/FileController.php b/core/lib/Thelia/Controller/Admin/FileController.php index a89234350..b4f373413 100644 --- a/core/lib/Thelia/Controller/Admin/FileController.php +++ b/core/lib/Thelia/Controller/Admin/FileController.php @@ -15,7 +15,7 @@ namespace Thelia\Controller\Admin; use Propel\Runtime\Exception\PropelException; use Symfony\Component\HttpFoundation\File\UploadedFile; use Thelia\Core\Event\File\FileCreateOrUpdateEvent; -use Thelia\Core\Event\Image\FileDeleteEvent; +use Thelia\Core\Event\File\FileDeleteEvent; use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\UpdateFilePositionEvent; use Thelia\Core\HttpFoundation\Response; @@ -56,10 +56,10 @@ class FileController extends BaseAdminController /** * Manage how a file collection has to be saved * - * @param int $parentId Parent id owning files being saved - * @param string $parentType Parent Type owning files being saved (product, category, content, etc.) - * @param string $objectType Object type, e.g. image or document - * @param array $validMimeTypes an array of valid mime types. If empty, any mime type is allowed. + * @param int $parentId Parent id owning files being saved + * @param string $parentType Parent Type owning files being saved (product, category, content, etc.) + * @param string $objectType Object type, e.g. image or document + * @param array $validMimeTypes an array of valid mime types. If empty, any mime type is allowed. * * @return Response */ @@ -322,14 +322,13 @@ class FileController extends BaseAdminController )); } - /** * Manage how a file is updated * - * @param int $fileId File identifier + * @param int $fileId File identifier * @param string $parentType Parent Type owning file being saved * @param string $objectType the type of the file, image or document - * @param string $eventName the event type. + * @param string $eventName the event type. * * @return FileModelInterface */ @@ -421,7 +420,6 @@ class FileController extends BaseAdminController return $fileModelInstance; } - /** * Manage how an image is updated * @@ -471,14 +469,13 @@ class FileController extends BaseAdminController )); } - /** * Manage how a image has to be deleted (AJAX) * - * @param int $fileId Parent id owning image being deleted + * @param int $fileId Parent id owning image being deleted * @param string $parentType Parent Type owning image being deleted * @param string $objectType the type of the file, image or document - * @param string $eventName the event type. + * @param string $eventName the event type. * * @return Response */ @@ -546,7 +543,6 @@ class FileController extends BaseAdminController return new Response($message); } - /** * Manage how a image has to be deleted (AJAX) * @@ -632,4 +628,4 @@ class FileController extends BaseAdminController return $this->updateFilePositionAction($parentType, $documentId, 'document', TheliaEvents::DOCUMENT_UPDATE_POSITION); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Controller/Admin/ProductController.php b/core/lib/Thelia/Controller/Admin/ProductController.php index f3a625807..ba78c830e 100644 --- a/core/lib/Thelia/Controller/Admin/ProductController.php +++ b/core/lib/Thelia/Controller/Admin/ProductController.php @@ -215,7 +215,7 @@ class ProductController extends AbstractSeoCrudController } /** - * @param Product $object + * @param Product $object * @return ProductModificationForm */ protected function hydrateObjectForm($object) diff --git a/core/lib/Thelia/Controller/Front/BaseFrontController.php b/core/lib/Thelia/Controller/Front/BaseFrontController.php index 2919d3a3f..c951aec32 100644 --- a/core/lib/Thelia/Controller/Front/BaseFrontController.php +++ b/core/lib/Thelia/Controller/Front/BaseFrontController.php @@ -35,9 +35,9 @@ class BaseFrontController extends BaseController /** * Return the route path defined for the givent route ID * - * @param string $routeId the route ID, as found in Config/Resources/routing/admin.xml - * @param array $parameters the Route parameters, as a var/value pair array - * @param bool $referenceType Router::ABSOLUTE_PATH or Router::ABSOLUTE_URL + * @param string $routeId the route ID, as found in Config/Resources/routing/admin.xml + * @param array $parameters the Route parameters, as a var/value pair array + * @param bool $referenceType Router::ABSOLUTE_PATH or Router::ABSOLUTE_URL * * @see \Thelia\Controller\BaseController::getRouteFromRouter() * @@ -51,10 +51,10 @@ class BaseFrontController extends BaseController /** * Redirect to a specific route. * - * @param string $routeId the route ID, as found in Config/Resources/routing/admin.xml - * @param array $urlParameters the URL parameters, as a var/value pair array - * @param array $routeParameters the Route parameters, as a var/value pair array - * @param bool $referenceType Router::ABSOLUTE_PATH or Router::ABSOLUTE_URL + * @param string $routeId the route ID, as found in Config/Resources/routing/admin.xml + * @param array $urlParameters the URL parameters, as a var/value pair array + * @param array $routeParameters the Route parameters, as a var/value pair array + * @param bool $referenceType Router::ABSOLUTE_PATH or Router::ABSOLUTE_URL */ public function redirectToRoute($routeId, array $urlParameters = [], array $routeParameters = [], $referenceType = Router::ABSOLUTE_PATH) { @@ -140,7 +140,7 @@ class BaseFrontController extends BaseController * Render the given template, and returns the result as a string. * * @param string $templateName the complete template name, with extension - * @param array $args the template arguments + * @param array $args the template arguments * @param string$templateDir * * @return string diff --git a/core/lib/Thelia/Core/Event/Brand/BrandUpdateEvent.php b/core/lib/Thelia/Core/Event/Brand/BrandUpdateEvent.php index 7b9398622..2fc42267c 100644 --- a/core/lib/Thelia/Core/Event/Brand/BrandUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/Brand/BrandUpdateEvent.php @@ -115,12 +115,13 @@ class BrandUpdateEvent extends BrandCreateEvent } /** - * @param int $logo_image_id + * @param int $logo_image_id * @return $this */ public function setLogoImageId($logo_image_id) { $this->logo_image_id = $logo_image_id; + return $this; } diff --git a/core/lib/Thelia/Core/Event/Document/DocumentCreateOrUpdateEvent.php b/core/lib/Thelia/Core/Event/Document/DocumentCreateOrUpdateEvent.php index b0c603e8d..175813b05 100644 --- a/core/lib/Thelia/Core/Event/Document/DocumentCreateOrUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/Document/DocumentCreateOrUpdateEvent.php @@ -32,8 +32,8 @@ class DocumentCreateOrUpdateEvent extends FileCreateOrUpdateEvent * Constructor * * @param string $documentType Document type - * ex : FileManager::TYPE_CATEGORY - * @param int $parentId Document parent id + * ex : FileManager::TYPE_CATEGORY + * @param int $parentId Document parent id * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead */ public function __construct($documentType, $parentId) @@ -128,4 +128,4 @@ class DocumentCreateOrUpdateEvent extends FileCreateOrUpdateEvent { return parent::getOldModel(); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/Document/DocumentDeleteEvent.php b/core/lib/Thelia/Core/Event/Document/DocumentDeleteEvent.php index a258eb0b1..20735c490 100644 --- a/core/lib/Thelia/Core/Event/Document/DocumentDeleteEvent.php +++ b/core/lib/Thelia/Core/Event/Document/DocumentDeleteEvent.php @@ -12,7 +12,7 @@ namespace Thelia\Core\Event\Document; -use Thelia\Core\Event\Image\FileDeleteEvent; +use Thelia\Core\Event\File\FileDeleteEvent; use Thelia\Model\CategoryDocument; use Thelia\Model\ContentDocument; use Thelia\Model\FolderDocument; @@ -35,8 +35,8 @@ class DocumentDeleteEvent extends FileDeleteEvent * Constructor * * @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $documentToDelete Document about to be deleted - * @param string $documentType Document type - * ex : FileManager::TYPE_CATEGORY + * @param string $documentType Document type + * ex : FileManager::TYPE_CATEGORY * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead */ public function __construct($documentToDelete, $documentType) @@ -94,4 +94,4 @@ class DocumentDeleteEvent extends FileDeleteEvent return parent::getFileToDelete(); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/File/FileDeleteEvent.php b/core/lib/Thelia/Core/Event/File/FileDeleteEvent.php index 38fd3203f..48a519dbf 100644 --- a/core/lib/Thelia/Core/Event/File/FileDeleteEvent.php +++ b/core/lib/Thelia/Core/Event/File/FileDeleteEvent.php @@ -10,7 +10,7 @@ /* file that was distributed with this source code. */ /*************************************************************************************/ -namespace Thelia\Core\Event\Image; +namespace Thelia\Core\Event\File; use Thelia\Core\Event\ActionEvent; use Thelia\Files\FileModelInterface; diff --git a/core/lib/Thelia/Core/Event/Image/ImageDeleteEvent.php b/core/lib/Thelia/Core/Event/Image/ImageDeleteEvent.php index 266875e67..b0b5098d9 100644 --- a/core/lib/Thelia/Core/Event/Image/ImageDeleteEvent.php +++ b/core/lib/Thelia/Core/Event/Image/ImageDeleteEvent.php @@ -93,4 +93,4 @@ class ImageDeleteEvent extends FileDeleteEvent return parent::getFileToDelete(); } -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Event/Image/ImageEvent.php b/core/lib/Thelia/Core/Event/Image/ImageEvent.php index 318265c26..392662436 100644 --- a/core/lib/Thelia/Core/Event/Image/ImageEvent.php +++ b/core/lib/Thelia/Core/Event/Image/ImageEvent.php @@ -217,19 +217,21 @@ class ImageEvent extends CachedFileEvent } /** - * @param ImageInterface $imageObject + * @param ImageInterface $imageObject * @return $this */ public function setImageObject($imageObject) { $this->imageObject = $imageObject; + return $this; } /** * @return ImageInterface */ - public function getImageObject() { + public function getImageObject() + { return $this->imageObject; } } diff --git a/core/lib/Thelia/Core/Event/Product/ProductUpdateEvent.php b/core/lib/Thelia/Core/Event/Product/ProductUpdateEvent.php index 4a20b491c..0dd38fdd1 100644 --- a/core/lib/Thelia/Core/Event/Product/ProductUpdateEvent.php +++ b/core/lib/Thelia/Core/Event/Product/ProductUpdateEvent.php @@ -21,7 +21,6 @@ class ProductUpdateEvent extends ProductCreateEvent protected $postscriptum; protected $brand_id; - public function __construct($product_id) { $this->product_id = $product_id; @@ -76,12 +75,13 @@ class ProductUpdateEvent extends ProductCreateEvent } /** - * @param int $brand_id + * @param int $brand_id * @return $this */ public function setBrandId($brand_id) { $this->brand_id = $brand_id; + return $this; } diff --git a/core/lib/Thelia/Core/Template/Element/BaseLoop.php b/core/lib/Thelia/Core/Template/Element/BaseLoop.php index e08d13dd6..1038541de 100644 --- a/core/lib/Thelia/Core/Template/Element/BaseLoop.php +++ b/core/lib/Thelia/Core/Template/Element/BaseLoop.php @@ -536,4 +536,4 @@ abstract class BaseLoop */ abstract protected function getArgDefinitions(); -} \ No newline at end of file +} diff --git a/core/lib/Thelia/Core/Template/Loop/Coupon.php b/core/lib/Thelia/Core/Template/Loop/Coupon.php index 310a760e2..d1d26c905 100644 --- a/core/lib/Thelia/Core/Template/Loop/Coupon.php +++ b/core/lib/Thelia/Core/Template/Loop/Coupon.php @@ -15,7 +15,6 @@ namespace Thelia\Core\Template\Loop; use Propel\Runtime\ActiveQuery\Criteria; use Thelia\Condition\ConditionFactory; use Thelia\Condition\Implementation\ConditionInterface; -use Thelia\Core\HttpFoundation\Request; use Thelia\Core\Template\Element\BaseI18nLoop; use Thelia\Core\Template\Element\LoopResult; use Thelia\Core\Template\Element\LoopResultRow; diff --git a/core/lib/Thelia/Core/Template/Loop/Document.php b/core/lib/Thelia/Core/Template/Loop/Document.php index 5a129afd6..2d5a7fbfb 100644 --- a/core/lib/Thelia/Core/Template/Loop/Document.php +++ b/core/lib/Thelia/Core/Template/Loop/Document.php @@ -23,7 +23,6 @@ use Propel\Runtime\ActiveQuery\Criteria; use Thelia\Model\ConfigQuery; use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Element\LoopResult; -use Thelia\Type\EnumType; use Thelia\Log\Tlog; /** diff --git a/core/lib/Thelia/Core/Template/Loop/Product.php b/core/lib/Thelia/Core/Template/Loop/Product.php index 5417446ac..06585240a 100644 --- a/core/lib/Thelia/Core/Template/Loop/Product.php +++ b/core/lib/Thelia/Core/Template/Loop/Product.php @@ -998,7 +998,7 @@ class Product extends BaseI18nLoop implements PropelSearchLoopInterface, SearchL /** * @param $loopResultRow - * @param \Thelia\Model\Product $product + * @param \Thelia\Model\Product $product * @param $default_category_id * @return mixed */ diff --git a/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php b/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php index 580da808e..188ccfcce 100644 --- a/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php +++ b/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php @@ -110,8 +110,8 @@ class SmartyParser extends Smarty implements ParserInterface * * The trim level is defined by the configuration variable html_output_trim_level * - * @param string $source the HTML source - * @param \Smarty_Internal_Template $template + * @param string $source the HTML source + * @param \Smarty_Internal_Template $template * @return string */ public function trimWhitespaces($source, \Smarty_Internal_Template $template) @@ -136,8 +136,7 @@ class SmartyParser extends Smarty implements ParserInterface '#(([a-z0-9]\s*=\s*(["\'])[^\3]*?\3)|<[a-z0-9_]+)\s+([a-z/>])#is' => '\1 \4', '/(^[\n]*|[\n]+)[\s\t]*[\n]+/' => "\n" ); - } - else if ($compressionMode >= 2) { + } elseif ($compressionMode >= 2) { if (preg_match_all('##is', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) { foreach ($matches as $match) { $store[] = $match[0][0]; @@ -166,8 +165,7 @@ class SmartyParser extends Smarty implements ParserInterface '#>\s+$#Ss' => '>', ); - } - else { + } else { $expressions = array(); } diff --git a/core/lib/Thelia/Model/Category.php b/core/lib/Thelia/Model/Category.php index 8e188c265..efa96c245 100644 --- a/core/lib/Thelia/Model/Category.php +++ b/core/lib/Thelia/Model/Category.php @@ -62,7 +62,7 @@ class Category extends BaseCategory implements FileModelParentInterface /** * Get the root category - * @param int $categoryId + * @param int $categoryId * @return mixed */ public function getRoot($categoryId) @@ -70,7 +70,7 @@ class Category extends BaseCategory implements FileModelParentInterface $category = CategoryQuery::create()->findPk($categoryId); - if(0 !== $category->getParent()) { + if (0 !== $category->getParent()) { $parentCategory = CategoryQuery::create()->findPk($category->getParent()); if (null !== $parentCategory) { diff --git a/core/lib/Thelia/Model/Folder.php b/core/lib/Thelia/Model/Folder.php index e722a560c..13ca25040 100644 --- a/core/lib/Thelia/Model/Folder.php +++ b/core/lib/Thelia/Model/Folder.php @@ -58,7 +58,7 @@ class Folder extends BaseFolder implements FileModelParentInterface /** * Get the root folder - * @param int $folderId + * @param int $folderId * @return mixed */ public function getRoot($folderId) @@ -66,7 +66,7 @@ class Folder extends BaseFolder implements FileModelParentInterface $folder = FolderQuery::create()->findPk($folderId); - if(0 !== $folder->getParent()) { + if (0 !== $folder->getParent()) { $parentFolder = FolderQuery::create()->findPk($folder->getParent()); if (null !== $parentFolder) { From 53b58515e09b80b8844e9d9af6bacbbb08e67a47 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Tue, 1 Jul 2014 01:08:27 +0200 Subject: [PATCH 43/64] Added html_output_trim_level variable --- setup/update/2.0.3.sql | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/setup/update/2.0.3.sql b/setup/update/2.0.3.sql index 39a35b9dc..1e029fded 100644 --- a/setup/update/2.0.3.sql +++ b/setup/update/2.0.3.sql @@ -200,12 +200,17 @@ CREATE TABLE `brand_image` ALTER TABLE `product` ADD `brand_id` INTEGER DEFAULT 0 AFTER `template_id`; ALTER TABLE `product` ADD CONSTRAINT `fk_product_brand` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`) ON DELETE SET NULL; +# Add html_output_trim_level config variable +# ------------------------------------------ + INSERT INTO `config` (`name`, `value`, `secured`, `hidden`, `created_at`, `updated_at`) VALUES ('html_output_trim_level','1', 0, 0, NOW(), NOW()); SELECT @max := MAX(`id`) FROM `config`; + INSERT INTO `config_i18n` (`id`, `locale`, `title`, `description`, `chapo`, `postscriptum`) VALUES (@max, 'en_US', 'Whitespace trim level of the generated HTML code (0 = none, 1 = medium, 2 = maximum)', NULL, NULL, NULL); - +# Done ! +# ------ SET FOREIGN_KEY_CHECKS = 1; \ No newline at end of file From 544060d06279c292090fafaf4aa098fdec401a2c Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Tue, 1 Jul 2014 01:21:59 +0200 Subject: [PATCH 44/64] NULL no longer returned by $BRAND_ID and $LOGO_IMAGE_ID --- core/lib/Thelia/Core/Template/Loop/Brand.php | 2 +- core/lib/Thelia/Core/Template/Loop/Product.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/lib/Thelia/Core/Template/Loop/Brand.php b/core/lib/Thelia/Core/Template/Loop/Brand.php index 902d94b6f..76fd4a888 100644 --- a/core/lib/Thelia/Core/Template/Loop/Brand.php +++ b/core/lib/Thelia/Core/Template/Loop/Brand.php @@ -200,7 +200,7 @@ class Brand extends BaseI18nLoop implements PropelSearchLoopInterface, SearchLoo ->set("META_KEYWORDS" , $brand->getVirtualColumn('i18n_META_KEYWORDS')) ->set("POSITION" , $brand->getPosition()) ->set("VISIBLE" , $brand->getVisible()) - ->set("LOGO_IMAGE_ID" , $brand->getLogoImageId()) + ->set("LOGO_IMAGE_ID" , $brand->getLogoImageId() ?: 0) ; $loopResult->addRow($loopResultRow); diff --git a/core/lib/Thelia/Core/Template/Loop/Product.php b/core/lib/Thelia/Core/Template/Loop/Product.php index 06585240a..ac3bedd61 100644 --- a/core/lib/Thelia/Core/Template/Loop/Product.php +++ b/core/lib/Thelia/Core/Template/Loop/Product.php @@ -1023,7 +1023,7 @@ class Product extends BaseI18nLoop implements PropelSearchLoopInterface, SearchL ->set("TEMPLATE" , $product->getTemplateId()) ->set("DEFAULT_CATEGORY" , $default_category_id) ->set("TAX_RULE_ID" , $product->getTaxRuleId()) - ->set("BRAND_ID" , $product->getBrandId()) + ->set("BRAND_ID" , $product->getBrandId() ?: 0) ; From 5307ce114334e0cdac57e04b9c95e0232c3e75f7 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Tue, 1 Jul 2014 01:24:12 +0200 Subject: [PATCH 45/64] Updated for new brand feature --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a707ba34b..6131b9805 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ #2.0.3 - New coupon type: Free product if selected products are in the cart. +- New feature: Product Brands / Suppliers management +- New 'brand' loop and substitution. product, image and document loop have been updated. +- Images and document processing have been refactored. #2.0.2 - Coupon UI has been redesigned. From b4e9f342907bdc7d755bd725da69d9f175d4c241 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Tue, 1 Jul 2014 01:28:18 +0200 Subject: [PATCH 46/64] Added Brand action test --- core/lib/Thelia/Tests/Action/BrandTest.php | 237 +++++++++++++++++++++ 1 file changed, 237 insertions(+) create mode 100644 core/lib/Thelia/Tests/Action/BrandTest.php diff --git a/core/lib/Thelia/Tests/Action/BrandTest.php b/core/lib/Thelia/Tests/Action/BrandTest.php new file mode 100644 index 000000000..e741e8cb0 --- /dev/null +++ b/core/lib/Thelia/Tests/Action/BrandTest.php @@ -0,0 +1,237 @@ + + */ +class BrandTest extends TestCaseWithURLToolSetup +{ + /** + * @var EventDispatcherInterface + */ + protected $dispatcher; + + public function setUp() + { + $this->dispatcher = $this->getMock("Symfony\Component\EventDispatcher\EventDispatcherInterface"); + } + + public function getUpdateEvent(&$brand) + { + if (!$brand instanceof \Thelia\Model\Brand) { + $brand = $this->getRandomBrand(); + } + + $event = new BrandUpdateEvent($brand->getId()); + $event->setDispatcher($this->dispatcher); + $event + ->setVisible(1) + ->setLocale($brand->getLocale()) + ->setTitle($brand->getTitle()) + ->setChapo($brand->getChapo()) + ->setDescription($brand->getDescription()) + ->setPostscriptum($brand->getPostscriptum()) + ; + + return $event; + } + + public function processUpdateAction($event) + { + $brandAction = new Brand($this->getContainer()); + $brandAction->update($event); + + return $event->getBrand(); + } + + public function testCreateBrand() + { + $event = new BrandCreateEvent(); + $event->setDispatcher($this->dispatcher); + $event + ->setVisible(1) + ->setLocale('en_US') + ->setTitle('test create brand') + ; + + $brandAction = new Brand($this->getContainer()); + $brandAction->create($event); + + $createdBrand = $event->getBrand(); + + $this->assertInstanceOf('Thelia\Model\Brand', $createdBrand); + $this->assertEquals(1, $createdBrand->getVisible()); + $this->assertEquals('test create brand', $createdBrand->getTitle()); + } + + public function testUpdateBrand() + { + $brand = $this->getRandomBrand(); + + $event = new BrandUpdateEvent($brand->getId()); + $event->setDispatcher($this->dispatcher); + $event + ->setVisible(1) + ->setLocale('en_US') + ->setTitle('test update brand title') + ->setChapo('test update brand short description') + ->setDescription('test update brand description') + ->setPostscriptum('test update brand postscriptum') + ; + + $brandAction = new Brand($this->getContainer()); + $brandAction->update($event); + + $updatedBrand = $event->getBrand(); + + $this->assertInstanceOf('Thelia\Model\Brand', $updatedBrand); + $this->assertEquals(1, $updatedBrand->getVisible()); + $this->assertEquals('test update brand title', $updatedBrand->getTitle()); + $this->assertEquals('test update brand short description', $updatedBrand->getChapo()); + $this->assertEquals('test update brand description', $updatedBrand->getDescription()); + $this->assertEquals('test update brand postscriptum', $updatedBrand->getPostscriptum()); + } + + public function testDeleteBrand() + { + $brand = $this->getRandomBrand(); + + $event = new BrandDeleteEvent($brand->getId()); + $event->setDispatcher($this->dispatcher); + + $brandAction = new Brand($this->getContainer()); + $brandAction->delete($event); + + $deletedBrand = $event->getBrand(); + + $this->assertInstanceOf('Thelia\Model\Brand', $deletedBrand); + $this->assertTrue($deletedBrand->isDeleted()); + + } + + public function testBrandToggleVisibility() + { + $brand = $this->getRandomBrand(); + + $visibility = $brand->getVisible(); + + $event = new BrandToggleVisibilityEvent($brand); + $event->setDispatcher($this->dispatcher); + + $brandAction = new Brand($this->getContainer()); + $brandAction->toggleVisibility($event); + + $updatedBrand = $event->getBrand(); + + $this->assertInstanceOf('Thelia\Model\Brand', $updatedBrand); + $this->assertEquals(!$visibility, $updatedBrand->getVisible()); + } + + public function testUpdatePositionUp() + { + $brand = BrandQuery::create() + ->filterByPosition(1, Criteria::GREATER_THAN) + ->findOne(); + + if (null === $brand) { + $this->fail('use fixtures before launching test, there is no brand in database'); + } + + $newPosition = $brand->getPosition()-1; + + $event = new UpdatePositionEvent($brand->getId(), UpdatePositionEvent::POSITION_UP); + $event->setDispatcher($this->dispatcher); + + $brandAction = new Brand($this->getContainer()); + $brandAction->updatePosition($event); + + $updatedBrand = BrandQuery::create()->findPk($brand->getId()); + + $this->assertEquals($newPosition, $updatedBrand->getPosition(),sprintf("new position is %d, new position expected is %d for brand %d", $newPosition, $updatedBrand->getPosition(), $updatedBrand->getId())); + } + + public function testUpdatePositionDown() + { + $brand = BrandQuery::create() + ->filterByPosition(1) + ->findOne(); + + if (null === $brand) { + $this->fail('use fixtures before launching test, there is no brand in database'); + } + + $newPosition = $brand->getPosition()+1; + + $event = new UpdatePositionEvent($brand->getId(), UpdatePositionEvent::POSITION_DOWN); + $event->setDispatcher($this->dispatcher); + + $brandAction = new Brand($this->getContainer()); + $brandAction->updatePosition($event); + + $updatedBrand = BrandQuery::create()->findPk($brand->getId()); + + $this->assertEquals($newPosition, $updatedBrand->getPosition(),sprintf("new position is %d, new position expected is %d for brand %d", $newPosition, $updatedBrand->getPosition(), $updatedBrand->getId())); + } + + public function testUpdatePositionWithSpecificPosition() + { + $brand = BrandQuery::create() + ->filterByPosition(1, Criteria::GREATER_THAN) + ->findOne(); + + if (null === $brand) { + $this->fail('use fixtures before launching test, there is no brand in database'); + } + + $event = new UpdatePositionEvent($brand->getId(), UpdatePositionEvent::POSITION_ABSOLUTE, 1); + $event->setDispatcher($this->dispatcher); + + $brandAction = new Brand($this->getContainer()); + $brandAction->updatePosition($event); + + $updatedBrand = BrandQuery::create()->findPk($brand->getId()); + + $this->assertEquals(1, $updatedBrand->getPosition(),sprintf("new position is 1, new position expected is %d for brand %d", $updatedBrand->getPosition(), $updatedBrand->getId())); + } + /** + * @return \Thelia\Model\Brand + */ + protected function getRandomBrand() + { + $brand = BrandQuery::create() + ->addAscendingOrderByColumn('RAND()') + ->findOne(); + + if (null === $brand) { + $this->fail('use fixtures before launching test, there is no brand in database'); + } + + return $brand; + } +} From ceb5b595a881f9087c1508d0d4949f831b77725b Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Tue, 1 Jul 2014 02:09:39 +0200 Subject: [PATCH 47/64] Generated more brands --- setup/faker.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup/faker.php b/setup/faker.php index e42abbd4c..285ac843b 100644 --- a/setup/faker.php +++ b/setup/faker.php @@ -398,7 +398,7 @@ try { $brandIdList = []; - for ($k=0; $k<4; $k++) { + for ($k=0; $k<10; $k++) { $brand = new Thelia\Model\Brand(); $brand->setVisible(1); From b4f3e3b60a0b5c6737cc4f7733853496d2c2dca2 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Tue, 1 Jul 2014 02:36:46 +0200 Subject: [PATCH 48/64] Fixed wrong fk in product table --- core/lib/Thelia/Model/Map/BrandTableMap.php | 3 +- core/lib/Thelia/Model/Map/ProductTableMap.php | 2 +- local/config/schema.xml | 2 +- setup/thelia.sql | 2 +- setup/update/2.0.3.sql | 84 +++++++++++++++---- 5 files changed, 72 insertions(+), 21 deletions(-) diff --git a/core/lib/Thelia/Model/Map/BrandTableMap.php b/core/lib/Thelia/Model/Map/BrandTableMap.php index 55e41bfa5..e7bced253 100644 --- a/core/lib/Thelia/Model/Map/BrandTableMap.php +++ b/core/lib/Thelia/Model/Map/BrandTableMap.php @@ -174,7 +174,7 @@ class BrandTableMap extends TableMap public function buildRelations() { $this->addRelation('BrandImageRelatedByLogoImageId', '\\Thelia\\Model\\BrandImage', RelationMap::MANY_TO_ONE, array('logo_image_id' => 'id', ), 'SET NULL', 'RESTRICT'); - $this->addRelation('Product', '\\Thelia\\Model\\Product', RelationMap::ONE_TO_MANY, array('id' => 'brand_id', ), 'RESTRICT', 'RESTRICT', 'Products'); + $this->addRelation('Product', '\\Thelia\\Model\\Product', RelationMap::ONE_TO_MANY, array('id' => 'brand_id', ), 'SET NULL', 'RESTRICT', 'Products'); $this->addRelation('BrandDocument', '\\Thelia\\Model\\BrandDocument', RelationMap::ONE_TO_MANY, array('id' => 'brand_id', ), 'CASCADE', 'RESTRICT', 'BrandDocuments'); $this->addRelation('BrandImageRelatedByBrandId', '\\Thelia\\Model\\BrandImage', RelationMap::ONE_TO_MANY, array('id' => 'brand_id', ), 'CASCADE', 'RESTRICT', 'BrandImagesRelatedByBrandId'); $this->addRelation('BrandI18n', '\\Thelia\\Model\\BrandI18n', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'BrandI18ns'); @@ -200,6 +200,7 @@ class BrandTableMap extends TableMap { // Invalidate objects in ".$this->getClassNameFromBuilder($joinedTableTableMapBuilder)." instance pool, // since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule. + ProductTableMap::clearInstancePool(); BrandDocumentTableMap::clearInstancePool(); BrandImageTableMap::clearInstancePool(); BrandI18nTableMap::clearInstancePool(); diff --git a/core/lib/Thelia/Model/Map/ProductTableMap.php b/core/lib/Thelia/Model/Map/ProductTableMap.php index 64d176029..4633d8a23 100644 --- a/core/lib/Thelia/Model/Map/ProductTableMap.php +++ b/core/lib/Thelia/Model/Map/ProductTableMap.php @@ -211,7 +211,7 @@ class ProductTableMap extends TableMap { $this->addRelation('TaxRule', '\\Thelia\\Model\\TaxRule', RelationMap::MANY_TO_ONE, array('tax_rule_id' => 'id', ), 'RESTRICT', 'RESTRICT'); $this->addRelation('Template', '\\Thelia\\Model\\Template', RelationMap::MANY_TO_ONE, array('template_id' => 'id', ), 'SET NULL', null); - $this->addRelation('Brand', '\\Thelia\\Model\\Brand', RelationMap::MANY_TO_ONE, array('brand_id' => 'id', ), 'RESTRICT', 'RESTRICT'); + $this->addRelation('Brand', '\\Thelia\\Model\\Brand', RelationMap::MANY_TO_ONE, array('brand_id' => 'id', ), 'SET NULL', 'RESTRICT'); $this->addRelation('ProductCategory', '\\Thelia\\Model\\ProductCategory', RelationMap::ONE_TO_MANY, array('id' => 'product_id', ), 'CASCADE', 'RESTRICT', 'ProductCategories'); $this->addRelation('FeatureProduct', '\\Thelia\\Model\\FeatureProduct', RelationMap::ONE_TO_MANY, array('id' => 'product_id', ), 'CASCADE', 'RESTRICT', 'FeatureProducts'); $this->addRelation('ProductSaleElements', '\\Thelia\\Model\\ProductSaleElements', RelationMap::ONE_TO_MANY, array('id' => 'product_id', ), 'CASCADE', 'RESTRICT', 'ProductSaleElementss'); diff --git a/local/config/schema.xml b/local/config/schema.xml index de1f058ef..d9305353f 100644 --- a/local/config/schema.xml +++ b/local/config/schema.xml @@ -49,7 +49,7 @@ - + diff --git a/setup/thelia.sql b/setup/thelia.sql index 100e8fd3b..369ae3cde 100644 --- a/setup/thelia.sql +++ b/setup/thelia.sql @@ -63,7 +63,7 @@ CREATE TABLE `product` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`) ON UPDATE RESTRICT - ON DELETE RESTRICT + ON DELETE SET NULL ) ENGINE=InnoDB; -- --------------------------------------------------------------------- diff --git a/setup/update/2.0.3.sql b/setup/update/2.0.3.sql index 1e029fded..cd465fd61 100644 --- a/setup/update/2.0.3.sql +++ b/setup/update/2.0.3.sql @@ -118,18 +118,12 @@ CREATE TABLE `brand` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `visible` TINYINT, - `title` VARCHAR(255), - `description` LONGTEXT, - `chapo` TEXT, - `postscriptum` TEXT, - `meta_title` VARCHAR(255), - `meta_description` TEXT, - `meta_keywords` TEXT, + `position` INTEGER, `logo_image_id` INTEGER, `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`), - INDEX `fk_brand_brand_image1_idx` (`logo_image_id`), + INDEX `fk_brand_brand_image_idx` (`logo_image_id`), CONSTRAINT `fk_logo_image_id_brand_image` FOREIGN KEY (`logo_image_id`) REFERENCES `brand_image` (`id`) @@ -149,10 +143,6 @@ CREATE TABLE `brand_document` `brand_id` INTEGER NOT NULL, `file` VARCHAR(255) NOT NULL, `position` INTEGER, - `title` VARCHAR(255), - `description` LONGTEXT, - `chapo` TEXT, - `postscriptum` TEXT, `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`), @@ -176,15 +166,10 @@ CREATE TABLE `brand_image` `brand_id` INTEGER NOT NULL, `file` VARCHAR(255) NOT NULL, `position` INTEGER, - `title` VARCHAR(255), - `description` LONGTEXT, - `chapo` TEXT, - `postscriptum` TEXT, `created_at` DATETIME, `updated_at` DATETIME, PRIMARY KEY (`id`), INDEX `idx_brand_image_brand_id` (`brand_id`), - INDEX `idx_brand_image_brand_id_is_brand_logo` (`brand_id`), CONSTRAINT `fk_brand_image_brand_id` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`) @@ -192,6 +177,71 @@ CREATE TABLE `brand_image` ON DELETE CASCADE ) ENGINE=InnoDB; +-- --------------------------------------------------------------------- +-- brand_i18n +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `brand_i18n`; + +CREATE TABLE `brand_i18n` +( + `id` INTEGER NOT NULL, + `locale` VARCHAR(5) DEFAULT 'en_US' NOT NULL, + `title` VARCHAR(255), + `description` LONGTEXT, + `chapo` TEXT, + `postscriptum` TEXT, + `meta_title` VARCHAR(255), + `meta_description` TEXT, + `meta_keywords` TEXT, + PRIMARY KEY (`id`,`locale`), + CONSTRAINT `brand_i18n_FK_1` + FOREIGN KEY (`id`) + REFERENCES `brand` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- brand_document_i18n +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `brand_document_i18n`; + +CREATE TABLE `brand_document_i18n` +( + `id` INTEGER NOT NULL, + `locale` VARCHAR(5) DEFAULT 'en_US' NOT NULL, + `title` VARCHAR(255), + `description` LONGTEXT, + `chapo` TEXT, + `postscriptum` TEXT, + PRIMARY KEY (`id`,`locale`), + CONSTRAINT `brand_document_i18n_FK_1` + FOREIGN KEY (`id`) + REFERENCES `brand_document` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- brand_image_i18n +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `brand_image_i18n`; + +CREATE TABLE `brand_image_i18n` +( + `id` INTEGER NOT NULL, + `locale` VARCHAR(5) DEFAULT 'en_US' NOT NULL, + `title` VARCHAR(255), + `description` LONGTEXT, + `chapo` TEXT, + `postscriptum` TEXT, + PRIMARY KEY (`id`,`locale`), + CONSTRAINT `brand_image_i18n_FK_1` + FOREIGN KEY (`id`) + REFERENCES `brand_image` (`id`) + ON DELETE CASCADE +) ENGINE=InnoDB; -- --------------------------------------------------------- -- Add brand field to product table, and related constraint. From c0541e3aa2c7c16d7e7a2bf79b41f55c6781e001 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 3 Jul 2014 16:25:50 +0200 Subject: [PATCH 49/64] Added getTemplateDirectories method to ParserInterface --- .../Thelia/Config/Resources/smarty-plugin.xml | 1 + .../Thelia/Core/Template/ParserInterface.php | 18 ++++++++++++++---- .../Core/Template/Smarty/SmartyParser.php | 2 +- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/core/lib/Thelia/Config/Resources/smarty-plugin.xml b/core/lib/Thelia/Config/Resources/smarty-plugin.xml index 222874903..ba6754bbb 100644 --- a/core/lib/Thelia/Config/Resources/smarty-plugin.xml +++ b/core/lib/Thelia/Config/Resources/smarty-plugin.xml @@ -52,6 +52,7 @@ + %thelia.parser.forms% diff --git a/core/lib/Thelia/Core/Template/ParserInterface.php b/core/lib/Thelia/Core/Template/ParserInterface.php index 0c32bd4ef..4eff151e4 100644 --- a/core/lib/Thelia/Core/Template/ParserInterface.php +++ b/core/lib/Thelia/Core/Template/ParserInterface.php @@ -35,22 +35,32 @@ interface ParserInterface */ public function setTemplateDefinition(TemplateDefinition $templateDefinition); + /** + * Get template definition + * + * @param bool $webAssetTemplate Allow to load asset from another template + * If the name of the template if provided + * + * @return TemplateDefinition + */ + public function getTemplateDefinition($webAssetTemplate = false); + /** * Add a template directory to the current template list * - * @param unknown $templateType the template type ( + * @param int $templateType the template type ( * * @param string $templateName the template name * @param string $templateDirectory path to the template dirtectory - * @param unknown $key ??? - * @param string $unshift ??? Etienne ? + * @param string $key ??? + * @param bool $unshift ??? Etienne ? */ public function addTemplateDirectory($templateType, $templateName, $templateDirectory, $key, $unshift = false); /** * Return the registeted template directories for a givent template type * - * @param unknown $templateType + * @param int $templateType * @throws \InvalidArgumentException if the templateType is not defined * @return array: an array of defined templates directories for the given template type */ diff --git a/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php b/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php index 188ccfcce..65bf85566 100644 --- a/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php +++ b/core/lib/Thelia/Core/Template/Smarty/SmartyParser.php @@ -211,7 +211,7 @@ class SmartyParser extends Smarty implements ParserInterface * @param int $templateType the template type (a TemplateDefinition type constant) * @param string $templateName the template name * @param string $templateDirectory path to the template dirtectory - * @param unknown $key ??? + * @param string $key ??? * @param boolean $unshift ??? Etienne ? */ public function addTemplateDirectory($templateType, $templateName, $templateDirectory, $key, $unshift = false) From c70a296ff2a43e136db97b3e45aafb9625eea5e0 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 3 Jul 2014 16:26:37 +0200 Subject: [PATCH 50/64] Refined the form fields html bindings --- .../Thelia/Form/Brand/BrandCreationForm.php | 5 +- .../Form/Brand/BrandModificationForm.php | 6 +- .../Form/Image/DocumentModification.php | 87 ++---------- .../Thelia/Form/Image/ImageModification.php | 93 +++---------- core/lib/Thelia/Form/SeoFieldsTrait.php | 92 +++++++------ .../Form/StandardDescriptionFieldsTrait.php | 21 ++- templates/backOffice/default/brand-edit.html | 32 ++--- templates/backOffice/default/brands.html | 22 ++- .../backOffice/default/document-edit.html | 14 +- ...rm-field-attributes-standard-renderer.html | 21 +++ .../forms/form-field-standard-renderer.html | 126 ++++++++++++++++++ .../backOffice/default/forms/form-field.html | 90 ------------- .../backOffice/default/forms/form-label.html | 8 -- templates/backOffice/default/image-edit.html | 14 +- .../default/includes/product-general-tab.html | 25 ++-- .../backOffice/default/includes/seo-tab.html | 23 ++-- .../standard-description-form-fields.html | 8 +- 17 files changed, 315 insertions(+), 372 deletions(-) create mode 100644 templates/backOffice/default/forms/form-field-attributes-standard-renderer.html create mode 100644 templates/backOffice/default/forms/form-field-standard-renderer.html delete mode 100644 templates/backOffice/default/forms/form-field.html delete mode 100644 templates/backOffice/default/forms/form-label.html diff --git a/core/lib/Thelia/Form/Brand/BrandCreationForm.php b/core/lib/Thelia/Form/Brand/BrandCreationForm.php index 65e0efb7b..88977dc5c 100644 --- a/core/lib/Thelia/Form/Brand/BrandCreationForm.php +++ b/core/lib/Thelia/Form/Brand/BrandCreationForm.php @@ -38,12 +38,13 @@ class BrandCreationForm extends BaseForm 'label' => Translator::getInstance()->trans('Brand name'), 'label_attr' => [ 'for' => 'title', - 'placeholder' => Translator::getInstance()->trans('The brand name or title'), 'help' => Translator::getInstance()->trans( 'Enter here the brand name in the default language (%title%)', [ '%title%' => Lang::getDefaultLanguage()->getTitle()] ), - 'i18n' => 'default' + ], + 'attr' => [ + 'placeholder' => Translator::getInstance()->trans('The brand name or title'), ] ] ) diff --git a/core/lib/Thelia/Form/Brand/BrandModificationForm.php b/core/lib/Thelia/Form/Brand/BrandModificationForm.php index d30b8ad0d..9d96a5b4b 100644 --- a/core/lib/Thelia/Form/Brand/BrandModificationForm.php +++ b/core/lib/Thelia/Form/Brand/BrandModificationForm.php @@ -48,8 +48,10 @@ class BrandModificationForm extends BrandCreationForm 'required' => true, 'label' => Translator::getInstance()->trans('Brand name'), 'label_attr' => [ - 'for' => 'title', - 'placeholder' => Translator::getInstance()->trans('The brand name or title'), + 'for' => 'title' + ], + 'attr' => [ + 'placeholder' => Translator::getInstance()->trans('The brand name or title') ] ] ) diff --git a/core/lib/Thelia/Form/Image/DocumentModification.php b/core/lib/Thelia/Form/Image/DocumentModification.php index 80278d4b1..62b5750e0 100644 --- a/core/lib/Thelia/Form/Image/DocumentModification.php +++ b/core/lib/Thelia/Form/Image/DocumentModification.php @@ -15,6 +15,7 @@ namespace Thelia\Form\Image; use Symfony\Component\Validator\Constraints\NotBlank; use Thelia\Core\Translation\Translator; use Thelia\Form\BaseForm; +use Thelia\Form\StandardDescriptionFieldsTrait; /** * Created by JetBrains PhpStorm. @@ -22,7 +23,6 @@ use Thelia\Form\BaseForm; * Time: 3:56 PM * * Form allowing to process a file - * @todo refactor make all document using propel inheritance and factorise image behaviour into one single clean action * * @package File * @author Guillaume MOREL @@ -30,6 +30,8 @@ use Thelia\Form\BaseForm; */ abstract class DocumentModification extends BaseForm { + use StandardDescriptionFieldsTrait; + /** * @inheritdoc */ @@ -38,81 +40,18 @@ abstract class DocumentModification extends BaseForm $this->formBuilder->add( 'file', 'file', - array( + [ 'required' => false, - 'constraints' => array(), + 'constraints' => [ ], 'label' => Translator::getInstance()->trans('Replace current document by this file'), - 'label_attr' => array( + 'label_attr' => [ 'for' => 'file' - ) - ) - ) - ->add( - 'title', - 'text', - array( - 'required' => true, - 'constraints' => array( - new NotBlank() - ), - 'label' => Translator::getInstance()->trans('Title'), - 'label_attr' => array( - 'for' => 'title' - ) - ) - ) - ->add( - 'description', - 'textarea', - array( - 'required' => false, - 'constraints' => array(), - 'label' => Translator::getInstance()->trans('Description'), - 'label_attr' => array( - 'for' => 'description', - 'rows' => 5 - ) - ) - ) - ->add( - 'chapo', - 'textarea', - array( - 'required' => false, - 'constraints' => array(), - 'label' => Translator::getInstance()->trans('Chapo'), - 'label_attr' => array( - 'for' => 'chapo', - 'rows' => 3 - ) - ) - ) - ->add( - 'postscriptum', - 'textarea', - array( - 'required' => false, - 'constraints' => array(), - 'label' => Translator::getInstance()->trans('Post Scriptum'), - 'label_attr' => array( - 'for' => 'postscriptum', - 'rows' => 3 - ) - ) - ) - ->add( - "locale", - "hidden", - array( - 'required' => true, - "constraints" => array( - new NotBlank() - ), - "label_attr" => array( - "for" => "locale_create" - ) - ) - ) - ; + ] + ] + ); + + // Add standard description fields + $this->addStandardDescFields(); + } } diff --git a/core/lib/Thelia/Form/Image/ImageModification.php b/core/lib/Thelia/Form/Image/ImageModification.php index 0af0eaeb2..d53fe84f6 100644 --- a/core/lib/Thelia/Form/Image/ImageModification.php +++ b/core/lib/Thelia/Form/Image/ImageModification.php @@ -16,6 +16,7 @@ use Symfony\Component\Validator\Constraints\Image; use Symfony\Component\Validator\Constraints\NotBlank; use Thelia\Core\Translation\Translator; use Thelia\Form\BaseForm; +use Thelia\Form\StandardDescriptionFieldsTrait; /** * Created by JetBrains PhpStorm. @@ -23,14 +24,14 @@ use Thelia\Form\BaseForm; * Time: 3:56 PM * * Form allowing to process an image - * @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action - * + * * @package Image * @author Guillaume MOREL * */ abstract class ImageModification extends BaseForm { + use StandardDescriptionFieldsTrait; /** * @inheritdoc @@ -40,88 +41,24 @@ abstract class ImageModification extends BaseForm $this->formBuilder->add( 'file', 'file', - array( + [ 'required' => false, - 'constraints' => array( + 'constraints' => [ new Image( - array( + [ // 'minWidth' => 200, // 'minHeight' => 200 - ) + ] ) - ), + ], 'label' => Translator::getInstance()->trans('Replace current image by this file'), - 'label_attr' => array( + 'label_attr' => [ 'for' => 'file' - ) - ) - ) - ->add( - 'title', - 'text', - array( - 'required' => true, - 'constraints' => array( - new NotBlank() - ), - 'label' => Translator::getInstance()->trans('Title'), - 'label_attr' => array( - 'for' => 'title' - ) - ) - ) - ->add( - 'description', - 'textarea', - array( - 'required' => false, - 'constraints' => array(), - 'label' => Translator::getInstance()->trans('Description'), - 'label_attr' => array( - 'for' => 'description', - 'rows' => 5 - ) - ) - ) - ->add( - 'chapo', - 'textarea', - array( - 'required' => false, - 'constraints' => array(), - 'label' => Translator::getInstance()->trans('Chapo'), - 'label_attr' => array( - 'for' => 'chapo', - 'rows' => 3 - ) - ) - ) - ->add( - 'postscriptum', - 'textarea', - array( - 'required' => false, - 'constraints' => array(), - 'label' => Translator::getInstance()->trans('Post Scriptum'), - 'label_attr' => array( - 'for' => 'postscriptum', - 'rows' => 3 - ) - ) - ) - ->add( - "locale", - "hidden", - array( - 'required' => true, - "constraints" => array( - new NotBlank() - ), - "label_attr" => array( - "for" => "locale_create" - ) - ) - ) - ; + ] + ] + ); + + // Add standard description fields + $this->addStandardDescFields(); } } diff --git a/core/lib/Thelia/Form/SeoFieldsTrait.php b/core/lib/Thelia/Form/SeoFieldsTrait.php index 91ee54f0d..6609ee198 100644 --- a/core/lib/Thelia/Form/SeoFieldsTrait.php +++ b/core/lib/Thelia/Form/SeoFieldsTrait.php @@ -29,56 +29,72 @@ trait SeoFieldsTrait protected function addSeoFields($exclude = array()) { if (! in_array('url', $exclude)) - $this->formBuilder - ->add('url', 'text', array( - 'label' => Translator::getInstance()->trans('Rewriten URL'), - 'label_attr' => array( - 'for' => 'rewriten_url_field', + $this->formBuilder->add( + 'url', + 'text', + [ + 'required' => false, + 'label' => Translator::getInstance()->trans('Rewriten URL'), + 'label_attr' => [ + 'for' => 'rewriten_url_field' + ], + 'attr' => [ 'placeholder' => Translator::getInstance()->trans('Use the keyword phrase in your URL.') - ), - 'required' => false - ) + ] + ] ); if (! in_array('meta_title', $exclude)) - $this->formBuilder - ->add('meta_title', 'text', array( - 'label' => Translator::getInstance()->trans('Page Title'), - 'label_attr' => array( + $this->formBuilder->add( + 'meta_title', + 'text', + [ + 'required' => false, + 'label' => Translator::getInstance()->trans('Page Title'), + 'label_attr' => [ 'for' => 'meta_title', - 'placeholder' => Translator::getInstance()->trans('Make sure that your title is clear, and contains many of the keywords within the page itself.'), 'help' => Translator::getInstance()->trans('The HTML TITLE element is the most important element on your web page.') - ), - 'required' => false - ) + ], + 'attr' => [ + 'placeholder' => Translator::getInstance()->trans('Make sure that your title is clear, and contains many of the keywords within the page itself.') + ] + ] ); if (! in_array('meta_description', $exclude)) - $this->formBuilder - ->add('meta_description', 'textarea', array( - 'label' => Translator::getInstance()->trans('Meta Description'), - 'label_attr' => array( + $this->formBuilder->add( + 'meta_description', + 'textarea', + [ + 'required' => false, + 'label' => Translator::getInstance()->trans('Meta Description'), + 'label_attr' => [ 'for' => 'meta_description', - 'rows' => 6, - 'placeholder' => Translator::getInstance()->trans('Make sure it uses keywords found within the page itself.'), 'help' => Translator::getInstance()->trans('Keep the most important part of your description in the first 150-160 characters.') - ), - 'required' => false - ) + ], + 'attr' => [ + 'rows' => 6, + 'placeholder' => Translator::getInstance()->trans('Make sure it uses keywords found within the page itself.') + ] + ] ); if (! in_array('meta_keywords', $exclude)) - $this->formBuilder - ->add('meta_keywords', 'textarea', array( - 'label' => Translator::getInstance()->trans('Meta Keywords'), - 'label_attr' => array( - 'for' => 'meta_keywords', - 'rows' => 3, - 'placeholder' => Translator::getInstance()->trans('Don\'t repeat keywords over and over in a row. Rather, put in keyword phrases.'), - 'help' => Translator::getInstance()->trans('You don\'t need to use commas or other punctuations.') - ), - 'required' => false - ) - ); + $this->formBuilder->add( + 'meta_keywords', + 'textarea', + [ + 'required' => false, + 'label' => Translator::getInstance()->trans('Meta Keywords'), + 'label_attr' => [ + 'for' => 'meta_keywords', + 'help' => Translator::getInstance()->trans('You don\'t need to use commas or other punctuations.') + ], + 'attr' => [ + 'rows' => 3, + 'placeholder' => Translator::getInstance()->trans('Don\'t repeat keywords over and over in a row. Rather, put in keyword phrases.') + ] + ] + ); } -} +} \ No newline at end of file diff --git a/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php b/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php index ba3beca2b..04fbbe033 100644 --- a/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php +++ b/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php @@ -51,6 +51,9 @@ trait StandardDescriptionFieldsTrait 'label_attr' => [ 'for' => 'title_field', 'placeholder' => Translator::getInstance()->trans('A descriptive title') + ], + 'attr' => [ + ] ] ); @@ -65,11 +68,13 @@ trait StandardDescriptionFieldsTrait 'label' => Translator::getInstance()->trans('Summary'), 'label_attr' => [ 'for' => 'summary_field', - 'rows' => 3, - 'placeholder' => Translator::getInstance()->trans('Short description text'), 'help' => Translator::getInstance()->trans('A short description, used when a summary or an introduction is required') + ], + 'attr' => [ + 'rows' => 3, + 'placeholder' => Translator::getInstance()->trans('Short description text') ] - ] + ] ); if (! in_array('description', $exclude)) @@ -82,8 +87,10 @@ trait StandardDescriptionFieldsTrait 'label' => Translator::getInstance()->trans('Detailed description'), 'label_attr' => [ 'for' => 'detailed_description_field', - 'rows' => 10, 'help' => Translator::getInstance()->trans('The detailed description.') + ], + 'attr' => [ + 'rows' => 10 ] ] ); @@ -98,9 +105,11 @@ trait StandardDescriptionFieldsTrait 'label' => Translator::getInstance()->trans('Conclusion'), 'label_attr' => [ 'for' => 'conclusion_field', - 'rows' => 3, - 'placeholder' => Translator::getInstance()->trans('Short additional text'), 'help' => Translator::getInstance()->trans('A short text, used when an additional or supplemental information is required.') + ], + 'attr' => [ + 'placeholder' => Translator::getInstance()->trans('Short additional text'), + 'rows' => 3, ] ] ); diff --git a/templates/backOffice/default/brand-edit.html b/templates/backOffice/default/brand-edit.html index 487ebd722..6be1c0bfd 100644 --- a/templates/backOffice/default/brand-edit.html +++ b/templates/backOffice/default/brand-edit.html @@ -69,8 +69,8 @@ {form_hidden_fields form=$form} - {admin_form_field form=$form name="success_url" value={url path="/admin/brand"}} - {admin_form_field form=$form name="locale" value={$edit_language_locale}} + {render_form_field form=$form field="success_url" value={url path="/admin/brand"}} + {render_form_field form=$form field="locale" value={$edit_language_locale}} {if $form_error}
        {$form_error_message}
        @@ -82,27 +82,17 @@
        - {admin_form_field form=$form name="visible"} + {render_form_field form=$form field="visible"} - {form_field form=$form field='logo_image_id'} -
        - - {admin_form_field_label form=$form name='logo_image_id'} - - - - {if $label_attr.help} - {$label_attr.help} - {/if} -
        - {/form_field} + {custom_render_form_field form=$form field='logo_image_id'} + + {/custom_render_form_field}
        diff --git a/templates/backOffice/default/brands.html b/templates/backOffice/default/brands.html index 361033606..c30a03690 100644 --- a/templates/backOffice/default/brands.html +++ b/templates/backOffice/default/brands.html @@ -190,12 +190,26 @@ {* Switch edition to the current locale *} - {admin_form_field form=$form name="locale" value=$LOCALE} + {render_form_field form=$form field="locale" value=$LOCALE} {/loop} - {admin_form_field form=$form name="success_url" value={url path='/admin/brand/update/_ID_'}} - {admin_form_field form=$form name="title"} - {admin_form_field form=$form name="visible"} + {render_form_field form=$form field="success_url" value={url path='/admin/brand/update/_ID_'}} + + {custom_render_form_field form=$form field="title"} + {loop type="lang" name="default-lang" default_only="1"} + {* Switch edition to the current locale *} + + + {render_form_field field="locale" value=$LOCALE} + +
        + + {$TITLE} +
        + {/loop} + {/custom_render_form_field} + + {render_form_field form=$form field="visible"} {module_include location='brand_create_form'} diff --git a/templates/backOffice/default/document-edit.html b/templates/backOffice/default/document-edit.html index c95c2daf2..09e06a6b8 100644 --- a/templates/backOffice/default/document-edit.html +++ b/templates/backOffice/default/document-edit.html @@ -40,8 +40,8 @@ {form_hidden_fields form=$form} - {admin_form_field form=$form name="success_url" value="{url path="/admin/document/type/{$documentType}/{$ID}/update"}"} - {admin_form_field form=$form name="locale" value="$edit_language_locale"} + {render_form_field form=$form field="success_url" value="{url path="/admin/document/type/{$documentType}/{$ID}/update"}"} + {render_form_field form=$form field="locale" value="$edit_language_locale"} {if $form_error}
        {$form_error_message}
        {/if} @@ -57,15 +57,15 @@
        - {admin_form_field form=$form name="file"} - {admin_form_field form=$form name="title" value=$TITLE} - {admin_form_field form=$form name="chapo" value=$CHAPO} - {admin_form_field form=$form name="postscriptum" value=$POSTSCRIPTUM} + {render_form_field form=$form field="file"} + {render_form_field form=$form field="title" value=$TITLE} + {render_form_field form=$form field="chapo" value=$CHAPO} + {render_form_field form=$form field="postscriptum" value=$POSTSCRIPTUM}
        - {admin_form_field form=$form name="description" value=$DESCRIPTION extra_class="wysiwyg"} + {render_form_field form=$form field="description" value=$DESCRIPTION extra_class="wysiwyg"}
        diff --git a/templates/backOffice/default/forms/form-field-attributes-standard-renderer.html b/templates/backOffice/default/forms/form-field-attributes-standard-renderer.html new file mode 100644 index 000000000..e1558d982 --- /dev/null +++ b/templates/backOffice/default/forms/form-field-attributes-standard-renderer.html @@ -0,0 +1,21 @@ +{* +This file defines the standard fields attributes, depending on input types. + +In addition to the standard form_field block output, this fragment uses the following additional variables : + +- field_template : the template style ('standard', or somethingelse) +- field_value : the value of the input field, which is used if the form_field value is empty. +- field_extra_class : an extra class to add to the input class (see form-field-attributes-standard-renderer.html) +*} + +{if $type == 'hidden'} + id="{$label_attr.for}" name="{$name}" value="{$value}" +{elseif $type == 'checkbox' || $type == 'radio'} + class="{$field_extra_class}" type="checkbox" id="{$label_attr.for}" name="{$name}" value="{$value}" {if $checked}checked="checked"{/if} +{elseif $type == 'choice'} + {if $multiple}multiple{/if} {if $lattr_list.size}size="{$lattr_list.size}"{/if} {if $required}aria-required="true" required{/if} id="{$label_attr.for}" name="{$name}"class="form-control class="{$field_extra_class}" +{elseif $type == 'textarea'} + {if $attr_list.rows}rows="{$attr_list.rows}"{/if} {if $required}aria-required="true" required{/if} placeholder="{$attr_list.placeholder|default:$label}" id="{$label_attr.for}" name="{$name}" class="form-control {$field_extra_class}" title="{$label}" +{else} + {if $required}aria-required="true" required{/if} placeholder="{$attr_list.placeholder|default:$label}" id="{$label_attr.for}" name="{$name}" value="{$value}" class="form-control {$field_extra_class}" +{/if} diff --git a/templates/backOffice/default/forms/form-field-standard-renderer.html b/templates/backOffice/default/forms/form-field-standard-renderer.html new file mode 100644 index 000000000..5e338117d --- /dev/null +++ b/templates/backOffice/default/forms/form-field-standard-renderer.html @@ -0,0 +1,126 @@ +{* +This file bind a form field to an HTML representation. In addition to the standard form_field block output, this +fragment uses the following additional variables : + +- field_template : the template style ('standard', or somethingelse) +- field_value : the value of the input field, which is used if the form_field value is empty. +- field_extra_class : an extra class to add to the input class (see form-field-attributes-standard-renderer.html) +- content : if this variable is not empty, we assume that it contains the input field definition. Used by the + custom_render_form_field block to pass a custom representation of the input field. +*} + +{* Use the optionnal $field_value parameter if no value is defined *} +{if empty($value)} + {$value = $field_value} +{/if} + +{* Synthetize an ID if none was given *} +{if empty({$label_attr.for})} + {$label_attr.for = "id-{$field_name}"} +{/if} + +{* Get standard fields attributes *} +{capture assign=attributes} + {include file="forms/form-field-attributes-$field_template-renderer.html"} +{/capture} + +{if $type == 'hidden'} + + + +{elseif $type == 'checkbox'} + +
        + +
        + +{elseif $type == 'radio'} + +
        + +
        + +{else} + +
        + + + + {if $multiple} + {intl l='Use Ctrl+click to select (or deselect) more that one item'} + {/if} + + {if $content == ''} + + {if $type == 'choice'} + + + + {elseif $type == 'textarea'} + + + + {elseif $type == 'money'} + +
        + + {loop name="input.addon" type="currency" default_only="true"}{$SYMBOL}{/loop} +
        + + {else} + + {$text_types = ['text', 'password', 'number', 'money', 'integer', 'time', 'date', 'datetime', 'email', 'url', 'file']} + + {if in_array($type, $text_types)} + {if $type == 'integer' || $type == 'money'}{$type='number'}{/if} + + + {else} +
        {intl l="Unsupported field type '%type' in form-field.html" type=$type}
        + {/if} + + {/if} + {else} + {$content nofilter} + {/if} + + {if ! empty($label_attr.help)} + {$label_attr.help} + {/if} +
        +{/if} diff --git a/templates/backOffice/default/forms/form-field.html b/templates/backOffice/default/forms/form-field.html deleted file mode 100644 index 48bd40471..000000000 --- a/templates/backOffice/default/forms/form-field.html +++ /dev/null @@ -1,90 +0,0 @@ -{form_field form=$form field=$field_name} - -{* Use the optionnal $field_value parameter if no value is defined *} -{if empty($value)} - {$value = $field_value} -{/if} - -{* Synthetize an ID if none was given *} -{if empty({$label_attr.for})} - {$label_attr.for = "id-{$field_name}"} -{/if} - -{if $type == 'hidden'} - -{elseif $type == 'checkbox'} - -
        - -
        - -{else} - -
        - - {admin_form_field_label form=$form name=$field_name label_attr=$label_attr} - - {if $multiple} - {intl l='Use Ctrl+click to select (or deselect) more that one item'} - {/if} - - {$lang_code = 0} - {if $label_attr.i18n == 'default'} - {loop type="lang" name="default-lang" default_only="1"} - {$lang_code = $CODE} - {$lang_title = $TITLE} -
        - {/loop} - {/if} - - {if $type == 'choice'} - - - {elseif $type == 'textarea'} - - - - {elseif $type == 'money'} - -
        - - {loop name="input.addon" type="currency" default_only="true"}{$SYMBOL}{/loop} -
        - - {else} - - {$text_types = ['text', 'password', 'number', 'money', 'integer', 'time', 'date', 'datetime', 'email', 'url', 'file']} - - {if in_array($type, $text_types)} - {if $type == 'integer' || $type == 'money'}{$type='number'}{/if} - - - - {else} -
        {intl l="Unsupported field type '%type' in form-field.html" type=$type}
        - {/if} - {/if} - - {if $lang_code} - {$lang_title} -
        - {/if} - - {if ! empty($label_attr.help)} - {$label_attr.help} - {/if} -
        -{/if} -{/form_field} diff --git a/templates/backOffice/default/forms/form-label.html b/templates/backOffice/default/forms/form-label.html deleted file mode 100644 index ce2af2a58..000000000 --- a/templates/backOffice/default/forms/form-label.html +++ /dev/null @@ -1,8 +0,0 @@ - \ No newline at end of file diff --git a/templates/backOffice/default/image-edit.html b/templates/backOffice/default/image-edit.html index 4a97112e2..697b08501 100644 --- a/templates/backOffice/default/image-edit.html +++ b/templates/backOffice/default/image-edit.html @@ -40,8 +40,8 @@ {form_hidden_fields form=$form} - {admin_form_field form=$form name="success_url" value="{url path="/admin/image/type/{$imageType}/{$ID}/update"}"} - {admin_form_field form=$form name="locale" value="$edit_language_locale"} + {render_form_field form=$form field="success_url" value="{url path="/admin/image/type/{$imageType}/{$ID}/update"}"} + {render_form_field form=$form field="locale" value="$edit_language_locale"} {if $form_error}
        {$form_error_message}
        {/if} @@ -60,15 +60,15 @@
        - {admin_form_field form=$form name="file"} - {admin_form_field form=$form name="title" value=$TITLE} - {admin_form_field form=$form name="chapo" value=$CHAPO} - {admin_form_field form=$form name="postscriptum" value=$POSTSCRIPTUM} + {render_form_field form=$form field="file"} + {render_form_field form=$form field="title" value=$TITLE} + {render_form_field form=$form field="chapo" value=$CHAPO} + {render_form_field form=$form field="postscriptum" value=$POSTSCRIPTUM}
        - {admin_form_field form=$form name="description" value=$DESCRIPTION extra_class="wysiwyg"} + {render_form_field form=$form field="description" value=$DESCRIPTION extra_class="wysiwyg"}
        diff --git a/templates/backOffice/default/includes/product-general-tab.html b/templates/backOffice/default/includes/product-general-tab.html index 6d26a9ed5..6628d55c4 100644 --- a/templates/backOffice/default/includes/product-general-tab.html +++ b/templates/backOffice/default/includes/product-general-tab.html @@ -71,24 +71,15 @@ {/form_field} - {form_field form=$form field='brand_id'} -
        + {custom_render_form_field form=$form field='brand_id'} + - - - {loop name="brand-list" type="brand" visible="*"} - - {/loop} - - - {if ! empty($label_attr.help)} - {$label_attr.help} - {/if} -
        - {/form_field} + {loop name="brand-list" type="brand" visible="*"} + + {/loop} + + {/custom_render_form_field} {form_field form=$form field='visible'}
        diff --git a/templates/backOffice/default/includes/seo-tab.html b/templates/backOffice/default/includes/seo-tab.html index 490078132..4fbbb3169 100644 --- a/templates/backOffice/default/includes/seo-tab.html +++ b/templates/backOffice/default/includes/seo-tab.html @@ -16,26 +16,21 @@ {form_hidden_fields form=$form} - {admin_form_field form=$form name="success_url"} + {render_form_field form=$form field="success_url"} {* Display error message if exist *} {include file='includes/notifications.html' message=$form_error_message} - {form_field form=$form field='url'} -
        - - {admin_form_field_label form=$form name='url'} - -
        - {$url_language|default:{config key="url_site"}}/ - -
        + {custom_render_form_field form=$form field='url'} +
        + {$url_language|default:{config key="url_site"}}/ +
        - {/form_field} + {/custom_render_form_field} - {admin_form_field form=$form name="meta_title"} - {admin_form_field form=$form name="meta_description"} - {admin_form_field form=$form name="meta_keywords"} + {render_form_field form=$form field="meta_title"} + {render_form_field form=$form field="meta_description"} + {render_form_field form=$form field="meta_keywords"} {include file = "includes/inner-form-toolbar.html" diff --git a/templates/backOffice/default/includes/standard-description-form-fields.html b/templates/backOffice/default/includes/standard-description-form-fields.html index 2072d83df..04337cad7 100644 --- a/templates/backOffice/default/includes/standard-description-form-fields.html +++ b/templates/backOffice/default/includes/standard-description-form-fields.html @@ -1,6 +1,6 @@ {* The standard description fields, used by many Thelia objects *} -{admin_form_field form=$form name='title'} -{admin_form_field form=$form name="chapo"} -{admin_form_field form=$form name="description" extra_class="wysiwyg"} -{admin_form_field form=$form name="postscriptum"} \ No newline at end of file +{render_form_field form=$form field='title'} +{render_form_field form=$form field="chapo"} +{render_form_field form=$form field="description" extra_class="wysiwyg"} +{render_form_field form=$form field="postscriptum"} \ No newline at end of file From af5e0bde23ec274a073dead0d00d54b337afcd05 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 3 Jul 2014 16:27:18 +0200 Subject: [PATCH 51/64] Refined form fields HTML bindings --- .../Smarty/Plugins/AdminUtilities.php | 36 +-- .../Core/Template/Smarty/Plugins/Form.php | 224 +++++++++++++----- 2 files changed, 171 insertions(+), 89 deletions(-) diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php index ff77aab6e..4e0c4aef3 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/AdminUtilities.php @@ -142,50 +142,16 @@ class AdminUtilities extends AbstractSmartyPlugin )); } - public function buildFormField($params, &$smarty) - { - $form = $this->getParam($params, 'form', false); - $field_name = $this->getParam($params, 'name', false); - $field_extra_class = $this->getParam($params, 'extra_class', ''); - $field_value = $this->getParam($params, 'value', ''); - - return $this->fetchSnippet($smarty, 'forms'.DS.'form-field', array( - 'form' => $form, - 'field_name' => $field_name, - 'field_extra_class' => $field_extra_class, - 'field_value' => $field_value - )); - } - - public function buildFormFieldLabel($params, &$smarty) - { - $form = $this->getParam($params, 'form', false); - $field_name = $this->getParam($params, 'name', false); - $label_attr = $this->getParam($params, 'label_attr', false); - - $args = [ - 'form' => $form, - 'field_name' => $field_name, - ]; - - if ($label_attr !== false) - $args['label_attr'] = $label_attr; - - return $this->fetchSnippet($smarty, 'forms'.DS.'form-label', $args); - } - /** * Define the various smarty plugins handled by this class * - * @return an array of smarty plugin descriptors + * @return array of smarty plugin descriptors */ public function getPluginDescriptors() { return array( new SmartyPluginDescriptor('function', 'admin_sortable_header' , $this, 'generateSortableColumnHeader'), new SmartyPluginDescriptor('function', 'admin_position_block' , $this, 'generatePositionChangeBlock'), - new SmartyPluginDescriptor('function', 'admin_form_field' , $this, 'buildFormField'), - new SmartyPluginDescriptor('function', 'admin_form_field_label' , $this, 'buildFormFieldLabel'), ); } } diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php index 3bdc715fd..7cf21db5e 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php @@ -12,17 +12,20 @@ namespace Thelia\Core\Template\Smarty\Plugins; -use Symfony\Component\Form\FormView; -use Thelia\Core\Form\Type\TheliaType; - -use Thelia\Core\Template\Element\Exception\ElementNotFoundException; -use Symfony\Component\HttpFoundation\Request; -use Thelia\Core\Template\Smarty\SmartyPluginDescriptor; -use Thelia\Core\Template\Smarty\AbstractSmartyPlugin; -use Thelia\Core\Template\ParserContext; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\CollectionType; use Symfony\Component\Form\Extension\Core\View\ChoiceView; +use Symfony\Component\Form\FormConfigInterface; +use Symfony\Component\Form\FormView; +use Thelia\Core\Form\Type\TheliaType; +use Thelia\Core\HttpFoundation\Request; +use Thelia\Core\Template\Element\Exception\ElementNotFoundException; +use Thelia\Core\Template\ParserContext; +use Thelia\Core\Template\ParserInterface; +use Thelia\Core\Template\Smarty\AbstractSmartyPlugin; +use Thelia\Core\Template\Smarty\SmartyPluginDescriptor; +use Thelia\Core\Template\TemplateHelper; +use Thelia\Form\BaseForm; /** * @@ -53,15 +56,22 @@ class Form extends AbstractSmartyPlugin private static $taggedFieldsStack = null; private static $taggedFieldsStackPosition = null; + /** @var Request $request */ protected $request; + + /** @var ParserContext $parserContext */ protected $parserContext; + /** @var ParserInterface $parser */ + protected $parser; + protected $formDefinition = array(); - public function __construct(Request $request, ParserContext $parserContext) + public function __construct(Request $request, ParserContext $parserContext, ParserInterface $parser) { $this->request = $request; $this->parserContext = $parserContext; + $this->parser = $parser; } public function setFormDefinition($formDefinition) @@ -78,7 +88,6 @@ class Form extends AbstractSmartyPlugin public function generateForm($params, $content, \Smarty_Internal_Template $template, &$repeat) { - if ($repeat) { $name = $this->getParam($params, 'name'); @@ -117,6 +126,14 @@ class Form extends AbstractSmartyPlugin } } + /** + * @param \Smarty_Internal_Template $template + * @param string $fieldName + * @param string $fieldValue + * @param string $fieldType + * @param array $fieldVars + * @param int $total_value_count + */ protected function assignFieldValues( $template, $fieldName, @@ -163,6 +180,11 @@ class Form extends AbstractSmartyPlugin $template->assign("attr_list", $fieldVars["attr"]); } + /** + * @param \Smarty_Internal_Template $template + * @param FormConfigInterface $formFieldConfig + * @param FormView $formFieldView + */ protected function assignFormTypeValues($template, $formFieldConfig, $formFieldView) { $formFieldType = $formFieldConfig->getType()->getInnerType(); @@ -204,58 +226,133 @@ class Form extends AbstractSmartyPlugin } } + /** + * @param array $params + * @param \Smarty_Internal_Template $template + */ + protected function processFormField($params, $template) + { + $formFieldView = $this->getFormFieldView($params); + $formFieldConfig = $this->getFormFieldConfig($params); + + $formFieldType = $formFieldConfig->getType()->getName(); + + $this->assignFormTypeValues($template, $formFieldConfig, $formFieldView); + + $value = $formFieldView->vars["value"]; + + $key = $this->getParam($params, 'value_key', null); + + // We (may) have a collection + if ($key !== null) { + + // Force array + if (! is_array($value)) $value = array(); + + // If the field is not found, use an empty value + $name = sprintf("%s[%s]", $formFieldView->vars["full_name"], $key); + + $val = $value[$key]; + + $this->assignFieldValues( + $template, + $name, + $val, + $formFieldType, + $formFieldView->vars, + count($formFieldView->children) + ); + } else { + $this->assignFieldValues( + $template, + $formFieldView->vars["full_name"], + $formFieldView->vars["value"], + $formFieldType, + $formFieldView->vars + ); + } + + $formFieldView->setRendered(); + } + public function renderFormField($params, $content, \Smarty_Internal_Template $template, &$repeat) { if ($repeat) { - $formFieldView = $this->getFormFieldView($params); - $formFieldConfig = $this->getFormFieldConfig($params); + $this->processFormField($params, $template); - $formFieldType = $formFieldConfig->getType()->getName(); - - $this->assignFormTypeValues($template, $formFieldConfig, $formFieldView); - - $value = $formFieldView->vars["value"]; - - $key = $this->getParam($params, 'value_key', null); - - // We (may) have a collection - if ($key !== null) { - - // Force array - if (! is_array($value)) $value = array(); - - // If the field is not found, use an empty value - $val = array_key_exists($key, $value) ? $value[$key] : ''; - - $name = sprintf("%s[%s]", $formFieldView->vars["full_name"], $key); - - $val = $value[$key]; - - $this->assignFieldValues( - $template, - $name, - $val, - $formFieldType, - $formFieldView->vars, - count($formFieldView->children) - ); - } else { - $this->assignFieldValues( - $template, - $formFieldView->vars["full_name"], - $formFieldView->vars["value"], - $formFieldType, - $formFieldView->vars - ); - } - - $formFieldView->setRendered(); - } else { + } else { return $content; } } + /** + * @param array $params + * @param string $content + * @param \Smarty_Internal_Template $template + * @param string $templateTypeName + * @return string + */ + protected function automaticFormFieldRendering($params, $content, $template, $templateTypeName) + { + $data = ''; + + $templateStyle = $this->getParam($params, 'template', 'standard'); + $templateFile = sprintf($templateTypeName, $templateStyle); + + $snippet_path = sprintf('%s/%s.html', + $this->parser->getTemplateDefinition()->getAbsolutePath(), + $templateFile + ); + + if (false !== $snippet_content = file_get_contents($snippet_path)) { + + $this->processFormField($params, $template); + + $form = $this->getParam($params, 'form', false); + $field_name = $this->getParam($params, 'field', false); + $field_extra_class = $this->getParam($params, 'extra_class', ''); + $field_value = $this->getParam($params, 'value', ''); + + $template->assign([ + 'content' => trim($content), + 'form' => $form, + 'field_name' => $field_name, + 'field_extra_class' => $field_extra_class, + 'field_value' => $field_value, + 'field_template' => $templateStyle + ]); + + $data = $template->fetch(sprintf('string:%s', $snippet_content)); + } + + return $data; + } + + /** + * @param $params + * @param $content + * @param \Smarty_Internal_Template $template + * @param $repeat + * @return mixed + */ + public function customFormFieldRendering($params, $content, $template, &$repeat) + { + if (! $repeat) { + return $this->automaticFormFieldRendering($params, $content, $template, 'forms'.DS.'form-field-%s-renderer'); + } + } + + public function standardFormFieldRendering($params, \Smarty_Internal_Template $template) + { + return $this->automaticFormFieldRendering($params, '', $template, 'forms'.DS.'form-field-%s-renderer'); + } + + public function standardFormFieldAttributes($params, \Smarty_Internal_Template $template) + { + return $this->automaticFormFieldRendering($params, '', $template, 'forms'.DS.'form-field-attributes-%s-renderer'); + } + public function renderTaggedFormFields($params, $content, \Smarty_Internal_Template $template, &$repeat) { if (null === $content) { @@ -360,6 +457,11 @@ class Form extends AbstractSmartyPlugin return array_search("hidden", $formView->vars["block_prefixes"]); } + /** + * @param $params + * @return FormView + * @throws \InvalidArgumentException + */ protected function getFormFieldView($params) { $instance = $this->getInstanceFromParams($params); @@ -397,6 +499,11 @@ class Form extends AbstractSmartyPlugin return $viewList; } + /** + * @param $params + * @return FormConfigInterface + * @throws \InvalidArgumentException + */ protected function getFormFieldConfig($params) { $instance = $this->getInstanceFromParams($params); @@ -416,6 +523,11 @@ class Form extends AbstractSmartyPlugin return $fieldData->getConfig(); } + /** + * @param $params + * @return BaseForm + * @throws \InvalidArgumentException + */ protected function getInstanceFromParams($params) { $instance = $this->getParam($params, 'form'); @@ -445,7 +557,11 @@ class Form extends AbstractSmartyPlugin new SmartyPluginDescriptor("block", "form_tagged_fields", $this, "renderTaggedFormFields"), new SmartyPluginDescriptor("function", "form_hidden_fields", $this, "renderHiddenFormField"), new SmartyPluginDescriptor("function", "form_enctype", $this, "formEnctype"), - new SmartyPluginDescriptor("block", "form_error", $this, "formError") + new SmartyPluginDescriptor("block", "form_error", $this, "formError"), + + new SmartyPluginDescriptor("function", "form_field_attributes" , $this, "standardFormFieldAttributes"), + new SmartyPluginDescriptor("function", "render_form_field" , $this, "standardFormFieldRendering"), + new SmartyPluginDescriptor("block" , "custom_render_form_field", $this, "customFormFieldRendering"), ); } } From 7576b9990bb9794d381c6883b4ac074101f2cb4b Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 3 Jul 2014 16:54:42 +0200 Subject: [PATCH 52/64] Fixed minor typos, improved field attributes generation --- .../Form/StandardDescriptionFieldsTrait.php | 5 ++- ...rm-field-attributes-standard-renderer.html | 34 ++++++++++++++++--- .../forms/form-field-standard-renderer.html | 10 ------ 3 files changed, 32 insertions(+), 17 deletions(-) diff --git a/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php b/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php index 04fbbe033..2d3793f7c 100644 --- a/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php +++ b/core/lib/Thelia/Form/StandardDescriptionFieldsTrait.php @@ -49,11 +49,10 @@ trait StandardDescriptionFieldsTrait 'required' => true, 'label' => Translator::getInstance()->trans('Title'), 'label_attr' => [ - 'for' => 'title_field', - 'placeholder' => Translator::getInstance()->trans('A descriptive title') + 'for' => 'title_field' ], 'attr' => [ - + 'placeholder' => Translator::getInstance()->trans('A descriptive title') ] ] ); diff --git a/templates/backOffice/default/forms/form-field-attributes-standard-renderer.html b/templates/backOffice/default/forms/form-field-attributes-standard-renderer.html index e1558d982..d986e7a50 100644 --- a/templates/backOffice/default/forms/form-field-attributes-standard-renderer.html +++ b/templates/backOffice/default/forms/form-field-attributes-standard-renderer.html @@ -8,14 +8,40 @@ In addition to the standard form_field block output, this fragment uses the foll - field_extra_class : an extra class to add to the input class (see form-field-attributes-standard-renderer.html) *} +{* Use the optionnal $field_value parameter if no value is defined *} +{if empty($value)} + {$value = $field_value} +{/if} + +{* Synthetize an ID if none was given *} +{if empty({$label_attr.for})} + {$label_attr.for = "id-{$field_name}"} +{/if} + +{if $disabled} + {$disabled = 'disabled'} +{/if} + +{if $disabled} + {$readonly = 'readonly'} +{/if} + +{if $required} + {$required='aria-required="true" required'} +{/if} + +{if $attr_list.placeholder} + {$placeholder = "placeholder=\"{$attr_list.placeholder}\""} +{/if} + {if $type == 'hidden'} id="{$label_attr.for}" name="{$name}" value="{$value}" {elseif $type == 'checkbox' || $type == 'radio'} - class="{$field_extra_class}" type="checkbox" id="{$label_attr.for}" name="{$name}" value="{$value}" {if $checked}checked="checked"{/if} + id="{$label_attr.for}" name="{$name}" class="{$field_extra_class}" value="{$value}" {if $checked}checked="checked"{/if} {$disabled} {$readonly} {$required} {elseif $type == 'choice'} - {if $multiple}multiple{/if} {if $lattr_list.size}size="{$lattr_list.size}"{/if} {if $required}aria-required="true" required{/if} id="{$label_attr.for}" name="{$name}"class="form-control class="{$field_extra_class}" + id="{$label_attr.for}" name="{$name} "class="form-control class="{$field_extra_class}" {if $multiple}multiple{/if} {if $lattr_list.size}size="{$lattr_list.size}"{/if} {$disabled} {$readonly} {$required} {elseif $type == 'textarea'} - {if $attr_list.rows}rows="{$attr_list.rows}"{/if} {if $required}aria-required="true" required{/if} placeholder="{$attr_list.placeholder|default:$label}" id="{$label_attr.for}" name="{$name}" class="form-control {$field_extra_class}" title="{$label}" + id="{$label_attr.for}" name="{$name}" class="form-control {$field_extra_class}" {if $attr_list.rows}rows="{$attr_list.rows}"{/if} {$placeholder nofilter} {$disabled} {$readonly} {$required} {else} - {if $required}aria-required="true" required{/if} placeholder="{$attr_list.placeholder|default:$label}" id="{$label_attr.for}" name="{$name}" value="{$value}" class="form-control {$field_extra_class}" + id="{$label_attr.for}" name="{$name}" value="{$value}" class="form-control {$field_extra_class}" {$placeholder nofilter} {$disabled} {$readonly} {$required} {/if} diff --git a/templates/backOffice/default/forms/form-field-standard-renderer.html b/templates/backOffice/default/forms/form-field-standard-renderer.html index 5e338117d..654abff2f 100644 --- a/templates/backOffice/default/forms/form-field-standard-renderer.html +++ b/templates/backOffice/default/forms/form-field-standard-renderer.html @@ -9,16 +9,6 @@ fragment uses the following additional variables : custom_render_form_field block to pass a custom representation of the input field. *} -{* Use the optionnal $field_value parameter if no value is defined *} -{if empty($value)} - {$value = $field_value} -{/if} - -{* Synthetize an ID if none was given *} -{if empty({$label_attr.for})} - {$label_attr.for = "id-{$field_name}"} -{/if} - {* Get standard fields attributes *} {capture assign=attributes} {include file="forms/form-field-attributes-$field_template-renderer.html"} From f46168f51815e85360bb09e6ef161a32c9f3259d Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Thu, 3 Jul 2014 19:19:21 +0200 Subject: [PATCH 53/64] Fixed some typos --- .../Core/Template/Smarty/Plugins/Form.php | 2 +- templates/backOffice/default/brands.html | 2 +- ...rm-field-attributes-standard-renderer.html | 22 +++++++++++-------- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php index 7cf21db5e..a8053cabc 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php @@ -153,7 +153,7 @@ class Form extends AbstractSmartyPlugin $template->assign("choices", isset($fieldVars['choices']) ? $fieldVars['choices'] : false); $template->assign("multiple", isset($fieldVars['multiple']) ? $fieldVars['multiple'] : false); $template->assign("disabled", isset($fieldVars['disabled']) ? $fieldVars['disabled'] : false); - $template->assign("readonly", isset($fieldVars['readonly']) ? $fieldVars['readonly'] : false); + $template->assign("read_only", isset($fieldVars['read_only']) ? $fieldVars['read_only'] : false); $template->assign("max_length", isset($fieldVars['max_length']) ? $fieldVars['max_length'] : false); $template->assign('required', isset($fieldVars['required']) ? $fieldVars['required'] : false); diff --git a/templates/backOffice/default/brands.html b/templates/backOffice/default/brands.html index c30a03690..290095252 100644 --- a/templates/backOffice/default/brands.html +++ b/templates/backOffice/default/brands.html @@ -203,7 +203,7 @@ {render_form_field field="locale" value=$LOCALE}
        - + {$TITLE}
        {/loop} diff --git a/templates/backOffice/default/forms/form-field-attributes-standard-renderer.html b/templates/backOffice/default/forms/form-field-attributes-standard-renderer.html index d986e7a50..735d35503 100644 --- a/templates/backOffice/default/forms/form-field-attributes-standard-renderer.html +++ b/templates/backOffice/default/forms/form-field-attributes-standard-renderer.html @@ -19,29 +19,33 @@ In addition to the standard form_field block output, this fragment uses the foll {/if} {if $disabled} - {$disabled = 'disabled'} + {$sDisabled = 'disabled'} {/if} -{if $disabled} - {$readonly = 'readonly'} +{if $read_only} + {$sRead_only = 'readonly'} +{/if} + +{if $max_length} + {$sMaxLength = "maxlength=\"{$max_length}\""} {/if} {if $required} - {$required='aria-required="true" required'} + {$sRequired='aria-required="true" required'} {/if} {if $attr_list.placeholder} - {$placeholder = "placeholder=\"{$attr_list.placeholder}\""} + {$sPlaceholder = "placeholder=\"{$attr_list.placeholder}\""} {/if} {if $type == 'hidden'} id="{$label_attr.for}" name="{$name}" value="{$value}" {elseif $type == 'checkbox' || $type == 'radio'} - id="{$label_attr.for}" name="{$name}" class="{$field_extra_class}" value="{$value}" {if $checked}checked="checked"{/if} {$disabled} {$readonly} {$required} + id="{$label_attr.for}" name="{$name}" class="{$field_extra_class}" value="{$value}" {if $checked}checked="checked"{/if} {$sDisabled} {$sReadonly} {$sRequired} {elseif $type == 'choice'} - id="{$label_attr.for}" name="{$name} "class="form-control class="{$field_extra_class}" {if $multiple}multiple{/if} {if $lattr_list.size}size="{$lattr_list.size}"{/if} {$disabled} {$readonly} {$required} + id="{$label_attr.for}" name="{$name} "class="form-control class="{$field_extra_class}" {if $multiple}multiple{/if} {if $lattr_list.size}size="{$lattr_list.size}"{/if} {$sDisabled} {$sReadonly} {$sRequired} {elseif $type == 'textarea'} - id="{$label_attr.for}" name="{$name}" class="form-control {$field_extra_class}" {if $attr_list.rows}rows="{$attr_list.rows}"{/if} {$placeholder nofilter} {$disabled} {$readonly} {$required} + id="{$label_attr.for}" name="{$name}" class="form-control {$field_extra_class}" {if $attr_list.rows}rows="{$attr_list.rows}"{/if} {$sMaxLength nofilter} {$sPlaceholder nofilter} {$sDisabled} {$sReadonly} {$sRequired} {else} - id="{$label_attr.for}" name="{$name}" value="{$value}" class="form-control {$field_extra_class}" {$placeholder nofilter} {$disabled} {$readonly} {$required} + id="{$label_attr.for}" name="{$name}" value="{$value}" class="form-control {$field_extra_class}" {$sMaxLength nofilter} {$sPlaceholder nofilter} {$sDisabled} {$sReadonly} {$sRequired} {/if} From a57d668e3cdbbb2aa517bed09ef30bab0edd6b5c Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Fri, 4 Jul 2014 11:54:02 +0200 Subject: [PATCH 54/64] Improved brand form declarations --- .../Thelia/Form/Brand/BrandCreationForm.php | 88 ++++++++++--------- .../Form/Brand/BrandModificationForm.php | 53 ++++------- templates/backOffice/default/brands.html | 2 +- 3 files changed, 66 insertions(+), 77 deletions(-) diff --git a/core/lib/Thelia/Form/Brand/BrandCreationForm.php b/core/lib/Thelia/Form/Brand/BrandCreationForm.php index 88977dc5c..57c00dbdc 100644 --- a/core/lib/Thelia/Form/Brand/BrandCreationForm.php +++ b/core/lib/Thelia/Form/Brand/BrandCreationForm.php @@ -25,51 +25,55 @@ use Thelia\Model\Lang; */ class BrandCreationForm extends BaseForm { + protected function doBuilForm($titleFieldHelpLabel) + { + $this->formBuilder->add( + 'title', + 'text', + [ + 'constraints' => [ new NotBlank() ], + 'required' => true, + 'label' => Translator::getInstance()->trans('Brand name'), + 'label_attr' => [ + 'for' => 'title', + 'help' => $titleFieldHelpLabel + ], + 'attr' => [ + 'placeholder' => Translator::getInstance()->trans('The brand name or title'), + ] + ] + ) + ->add( + 'locale', + 'hidden', + [ + 'constraints' => [ new NotBlank() ], + 'required' => true, + ] + ) + // Is this brand online ? + ->add( + 'visible', + 'checkbox', + [ + 'constraints' => [ ], + 'required' => false, + 'label' => Translator::getInstance()->trans('This brand is online'), + 'label_attr' => [ + 'for' => 'visible_create' + ] + ] + ); + } + protected function buildForm() { - $this->formBuilder - // Brand title - ->add( - 'title', - 'text', - [ - 'constraints' => [ new NotBlank() ], - 'required' => true, - 'label' => Translator::getInstance()->trans('Brand name'), - 'label_attr' => [ - 'for' => 'title', - 'help' => Translator::getInstance()->trans( - 'Enter here the brand name in the default language (%title%)', - [ '%title%' => Lang::getDefaultLanguage()->getTitle()] - ), - ], - 'attr' => [ - 'placeholder' => Translator::getInstance()->trans('The brand name or title'), - ] - ] + $this->doBuilForm( + Translator::getInstance()->trans( + 'Enter here the brand name in the default language (%title%)', + [ '%title%' => Lang::getDefaultLanguage()->getTitle()] ) - // Current locale - ->add( - 'locale', - 'hidden', - [ - 'constraints' => [ new NotBlank() ], - 'required' => true, - ] - ) - // Is this brand online ? - ->add( - 'visible', - 'checkbox', - [ - 'constraints' => [ ], - 'required' => true, - 'label' => Translator::getInstance()->trans('This brand is online'), - 'label_attr' => [ - 'for' => 'visible_create' - ] - ] - ); + ); } public function getName() diff --git a/core/lib/Thelia/Form/Brand/BrandModificationForm.php b/core/lib/Thelia/Form/Brand/BrandModificationForm.php index 9d96a5b4b..c4f1ce16f 100644 --- a/core/lib/Thelia/Form/Brand/BrandModificationForm.php +++ b/core/lib/Thelia/Form/Brand/BrandModificationForm.php @@ -28,42 +28,27 @@ class BrandModificationForm extends BrandCreationForm protected function buildForm() { - parent::buildForm(); + $this->doBuilForm( + Translator::getInstance()->trans('The brand name or title') + ); - $this->formBuilder - ->add( - 'id', - 'hidden', - [ - 'constraints' => [ new GreaterThan(['value' => 0]) ], - 'required' => true, + $this->formBuilder->add( + 'id', + 'hidden', + [ + 'constraints' => [ new GreaterThan(['value' => 0]) ], + 'required' => true, + ] + ) + ->add("logo_image_id", "integer", [ + 'constraints' => [ ], + 'required' => false, + 'label' => Translator::getInstance()->trans('Select the brand logo'), + 'label_attr' => [ + 'for' => 'mode', + 'help' => Translator::getInstance()->trans("Select the brand logo amongst the brand images") ] - ) - // Brand title - ->add( - 'title', - 'text', - [ - 'constraints' => [ new NotBlank() ], - 'required' => true, - 'label' => Translator::getInstance()->trans('Brand name'), - 'label_attr' => [ - 'for' => 'title' - ], - 'attr' => [ - 'placeholder' => Translator::getInstance()->trans('The brand name or title') - ] - ] - ) - ->add("logo_image_id", "integer", [ - 'constraints' => [ ], - 'required' => false, - 'label' => Translator::getInstance()->trans('Select the brand logo'), - 'label_attr' => [ - 'for' => 'mode', - 'help' => Translator::getInstance()->trans("Select the brand logo amongst the brand images") - ] - ]) + ]) ; // Add standard description fields, excluding title and locale, which are already defined diff --git a/templates/backOffice/default/brands.html b/templates/backOffice/default/brands.html index 290095252..a0c1a224e 100644 --- a/templates/backOffice/default/brands.html +++ b/templates/backOffice/default/brands.html @@ -200,7 +200,7 @@ {* Switch edition to the current locale *} - {render_form_field field="locale" value=$LOCALE} + {render_form_field form=$form field="locale" value=$LOCALE}
        From 3708fb317bcf76216846b435b16e92b186918867 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Fri, 4 Jul 2014 15:27:14 +0200 Subject: [PATCH 55/64] Typo --- core/lib/Thelia/Form/Brand/BrandModificationForm.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/lib/Thelia/Form/Brand/BrandModificationForm.php b/core/lib/Thelia/Form/Brand/BrandModificationForm.php index c4f1ce16f..b7671cd7a 100644 --- a/core/lib/Thelia/Form/Brand/BrandModificationForm.php +++ b/core/lib/Thelia/Form/Brand/BrandModificationForm.php @@ -45,7 +45,7 @@ class BrandModificationForm extends BrandCreationForm 'required' => false, 'label' => Translator::getInstance()->trans('Select the brand logo'), 'label_attr' => [ - 'for' => 'mode', + 'for' => 'logo_image_id', 'help' => Translator::getInstance()->trans("Select the brand logo amongst the brand images") ] ]) From 7580d5c869d7de8769b4e24cd34b68dbe40cfd34 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Fri, 4 Jul 2014 15:27:56 +0200 Subject: [PATCH 56/64] Template fragments are now in a subdirectory --- .../lib/Thelia/Core/Template/Smarty/Plugins/Form.php | 12 ++++++------ .../form-field-attributes-renderer.html} | 0 .../form-field-renderer.html} | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) rename templates/backOffice/default/forms/{form-field-attributes-standard-renderer.html => standard/form-field-attributes-renderer.html} (100%) rename templates/backOffice/default/forms/{form-field-standard-renderer.html => standard/form-field-renderer.html} (98%) diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php index a8053cabc..bddc07407 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php @@ -293,15 +293,15 @@ class Form extends AbstractSmartyPlugin * @param string $templateTypeName * @return string */ - protected function automaticFormFieldRendering($params, $content, $template, $templateTypeName) + protected function automaticFormFieldRendering($params, $content, $template, $templateFile) { $data = ''; $templateStyle = $this->getParam($params, 'template', 'standard'); - $templateFile = sprintf($templateTypeName, $templateStyle); - $snippet_path = sprintf('%s/%s.html', + $snippet_path = sprintf('%s'.DS.'forms'.DS.'%s'.DS.'%s.html', $this->parser->getTemplateDefinition()->getAbsolutePath(), + $templateStyle, $templateFile ); @@ -339,18 +339,18 @@ class Form extends AbstractSmartyPlugin public function customFormFieldRendering($params, $content, $template, &$repeat) { if (! $repeat) { - return $this->automaticFormFieldRendering($params, $content, $template, 'forms'.DS.'form-field-%s-renderer'); + return $this->automaticFormFieldRendering($params, $content, $template, 'form-field-renderer'); } } public function standardFormFieldRendering($params, \Smarty_Internal_Template $template) { - return $this->automaticFormFieldRendering($params, '', $template, 'forms'.DS.'form-field-%s-renderer'); + return $this->automaticFormFieldRendering($params, '', $template, 'form-field-renderer'); } public function standardFormFieldAttributes($params, \Smarty_Internal_Template $template) { - return $this->automaticFormFieldRendering($params, '', $template, 'forms'.DS.'form-field-attributes-%s-renderer'); + return $this->automaticFormFieldRendering($params, '', $template, 'form-field-attributes-renderer'); } public function renderTaggedFormFields($params, $content, \Smarty_Internal_Template $template, &$repeat) diff --git a/templates/backOffice/default/forms/form-field-attributes-standard-renderer.html b/templates/backOffice/default/forms/standard/form-field-attributes-renderer.html similarity index 100% rename from templates/backOffice/default/forms/form-field-attributes-standard-renderer.html rename to templates/backOffice/default/forms/standard/form-field-attributes-renderer.html diff --git a/templates/backOffice/default/forms/form-field-standard-renderer.html b/templates/backOffice/default/forms/standard/form-field-renderer.html similarity index 98% rename from templates/backOffice/default/forms/form-field-standard-renderer.html rename to templates/backOffice/default/forms/standard/form-field-renderer.html index 654abff2f..3835288d4 100644 --- a/templates/backOffice/default/forms/form-field-standard-renderer.html +++ b/templates/backOffice/default/forms/standard/form-field-renderer.html @@ -11,7 +11,7 @@ fragment uses the following additional variables : {* Get standard fields attributes *} {capture assign=attributes} - {include file="forms/form-field-attributes-$field_template-renderer.html"} + {include file="forms/$field_template/form-field-attributes-renderer.html"} {/capture} {if $type == 'hidden'} From b7d98d8648ec95df294ceb50e2fdea01a68d3675 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Fri, 4 Jul 2014 16:10:39 +0200 Subject: [PATCH 57/64] Fixed typos --- templates/backOffice/default/includes/product-general-tab.html | 2 +- templates/backOffice/default/includes/seo-tab.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/templates/backOffice/default/includes/product-general-tab.html b/templates/backOffice/default/includes/product-general-tab.html index 6628d55c4..8068ff7fd 100644 --- a/templates/backOffice/default/includes/product-general-tab.html +++ b/templates/backOffice/default/includes/product-general-tab.html @@ -72,7 +72,7 @@ {/form_field} {custom_render_form_field form=$form field='brand_id'} - {loop name="brand-list" type="brand" visible="*"} diff --git a/templates/backOffice/default/includes/seo-tab.html b/templates/backOffice/default/includes/seo-tab.html index 4fbbb3169..989e00672 100644 --- a/templates/backOffice/default/includes/seo-tab.html +++ b/templates/backOffice/default/includes/seo-tab.html @@ -24,7 +24,7 @@ {custom_render_form_field form=$form field='url'}
        {$url_language|default:{config key="url_site"}}/ - +
        {/custom_render_form_field} From 082a1905f654026d58dcce2dafc50bc8c0e462ed Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 7 Jul 2014 22:42:44 +0200 Subject: [PATCH 58/64] Fixed "it doesn't save anything when you want to edit textarea" --- .../default/forms/standard/form-field-renderer.html | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/templates/backOffice/default/forms/standard/form-field-renderer.html b/templates/backOffice/default/forms/standard/form-field-renderer.html index 3835288d4..3682a38a6 100644 --- a/templates/backOffice/default/forms/standard/form-field-renderer.html +++ b/templates/backOffice/default/forms/standard/form-field-renderer.html @@ -14,6 +14,10 @@ fragment uses the following additional variables : {include file="forms/$field_template/form-field-attributes-renderer.html"} {/capture} +{if empty($value)} + {$value = $field_value} +{/if} + {if $type == 'hidden'} From 77a94d06a0dbf0019ce54a9efe7793f4669253ed Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 7 Jul 2014 22:43:37 +0200 Subject: [PATCH 59/64] Fixed "you can not delete an image or a document" --- core/lib/Thelia/Action/BaseCachedFile.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/lib/Thelia/Action/BaseCachedFile.php b/core/lib/Thelia/Action/BaseCachedFile.php index 3c8f98061..b5cfabcbb 100644 --- a/core/lib/Thelia/Action/BaseCachedFile.php +++ b/core/lib/Thelia/Action/BaseCachedFile.php @@ -233,6 +233,7 @@ abstract class BaseCachedFile extends BaseAction // Update image modifications $event->getModel()->save(); + $event->setModel($event->getModel()); } @@ -241,7 +242,7 @@ abstract class BaseCachedFile extends BaseAction * * @param FileDeleteEvent $event Image event */ - public function deleteImage(FileDeleteEvent $event) + public function deleteFile(FileDeleteEvent $event) { $this->fileManager->deleteFile($event->getFileToDelete()); } From 6ebf2c7e42648733b6d96e1d81449ef1919fc655 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 7 Jul 2014 22:44:39 +0200 Subject: [PATCH 60/64] Fixed "with the close or save and close button you get an exception" --- .../Controller/Admin/FileController.php | 19 ++++++++++++------- core/lib/Thelia/Files/FileModelInterface.php | 2 +- core/lib/Thelia/Model/BrandDocument.php | 4 ++-- core/lib/Thelia/Model/BrandImage.php | 4 ++-- core/lib/Thelia/Model/CategoryDocument.php | 4 ++-- core/lib/Thelia/Model/CategoryImage.php | 4 ++-- core/lib/Thelia/Model/ContentDocument.php | 4 ++-- core/lib/Thelia/Model/ContentImage.php | 4 ++-- core/lib/Thelia/Model/FolderDocument.php | 4 ++-- core/lib/Thelia/Model/FolderImage.php | 4 ++-- core/lib/Thelia/Model/ProductDocument.php | 4 ++-- core/lib/Thelia/Model/ProductImage.php | 4 ++-- .../backOffice/default/document-edit.html | 6 +++--- templates/backOffice/default/image-edit.html | 6 +++--- 14 files changed, 39 insertions(+), 34 deletions(-) diff --git a/core/lib/Thelia/Controller/Admin/FileController.php b/core/lib/Thelia/Controller/Admin/FileController.php index b4f373413..c4f9401aa 100644 --- a/core/lib/Thelia/Controller/Admin/FileController.php +++ b/core/lib/Thelia/Controller/Admin/FileController.php @@ -269,10 +269,10 @@ class FileController extends BaseAdminController $fileManager = $this->getFileManager(); $imageModel = $fileManager->getModelInstance('image', $parentType); - $redirectUrl = $imageModel->getRedirectionUrl($imageId); - $image = $imageModel->getQueryInstance()->findPk($imageId); + $redirectUrl = $image->getRedirectionUrl(); + return $this->render('image-edit', array( 'imageId' => $imageId, 'imageType' => $parentType, @@ -306,7 +306,7 @@ class FileController extends BaseAdminController $document = $documentModel->getQueryInstance()->findPk($documentId); - $redirectUrl = $documentModel->getRedirectionUrl($documentId); + $redirectUrl = $document->getRedirectionUrl(); return $this->render('document-edit', array( 'documentId' => $documentId, @@ -394,7 +394,13 @@ class FileController extends BaseAdminController ); if ($this->getRequest()->get('save_mode') == 'close') { - $this->redirect(URL::getInstance()->absoluteUrl($fileModelInstance->getRedirectionUrl($fileId))); + + if ($objectType == 'document') + $tab = 'documents'; + else + $tab = 'images'; + + $this->redirect(URL::getInstance()->absoluteUrl($file->getRedirectionUrl(), ['current_tab' => $tab])); } else { $this->redirectSuccess($fileUpdateForm); } @@ -417,7 +423,7 @@ class FileController extends BaseAdminController ->setGeneralError($message); } - return $fileModelInstance; + return $file; } /** @@ -454,7 +460,6 @@ class FileController extends BaseAdminController */ public function updateDocumentAction($documentId, $parentType) { - if (null !== $response = $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE)) { return $response; } @@ -464,7 +469,7 @@ class FileController extends BaseAdminController return $this->render('document-edit', array( 'documentId' => $documentId, 'documentType' => $parentType, - 'redirectUrl' => $documentInstance->getRedirectionUrl($documentId), + 'redirectUrl' => $documentInstance->getRedirectionUrl(), 'formId' => $documentInstance->getUpdateFormId() )); } diff --git a/core/lib/Thelia/Files/FileModelInterface.php b/core/lib/Thelia/Files/FileModelInterface.php index 589e071ec..8165e3f36 100644 --- a/core/lib/Thelia/Files/FileModelInterface.php +++ b/core/lib/Thelia/Files/FileModelInterface.php @@ -75,7 +75,7 @@ interface FileModelInterface * * @return string the URL to redirect to after update from the back-office */ - public function getRedirectionUrl($objectId); + public function getRedirectionUrl(); /** * Get the Query instance for this object diff --git a/core/lib/Thelia/Model/BrandDocument.php b/core/lib/Thelia/Model/BrandDocument.php index 432ad69f3..b47ffe491 100644 --- a/core/lib/Thelia/Model/BrandDocument.php +++ b/core/lib/Thelia/Model/BrandDocument.php @@ -113,9 +113,9 @@ class BrandDocument extends BaseBrandDocument implements BreadcrumbInterface, Fi * * @return string the URL to redirect to after update from the back-office */ - public function getRedirectionUrl($objectId) + public function getRedirectionUrl() { - return '/admin/brand/update/' . $objectId . '?current_tab=document'; + return '/admin/brand/update/' . $this->getBrandId(); } /** diff --git a/core/lib/Thelia/Model/BrandImage.php b/core/lib/Thelia/Model/BrandImage.php index 9cd115a06..212847218 100644 --- a/core/lib/Thelia/Model/BrandImage.php +++ b/core/lib/Thelia/Model/BrandImage.php @@ -113,9 +113,9 @@ class BrandImage extends BaseBrandImage implements FileModelInterface, Breadcrum * * @return string the URL to redirect to after update from the back-office */ - public function getRedirectionUrl($objectId) + public function getRedirectionUrl() { - return '/admin/brand/update/' . $objectId . '?current_tab=image'; + return '/admin/brand/update/' . $this->getBrandId(); } /** diff --git a/core/lib/Thelia/Model/CategoryDocument.php b/core/lib/Thelia/Model/CategoryDocument.php index 3e13863bb..db3525341 100644 --- a/core/lib/Thelia/Model/CategoryDocument.php +++ b/core/lib/Thelia/Model/CategoryDocument.php @@ -123,9 +123,9 @@ class CategoryDocument extends BaseCategoryDocument implements BreadcrumbInterfa * * @return string the URL to redirect to after update from the back-office */ - public function getRedirectionUrl($objectId) + public function getRedirectionUrl() { - return '/admin/categories/update?category_id=' . $objectId . '?current_tab=document'; + return '/admin/categories/update?category_id=' . $this->getCategoryId(); } /** diff --git a/core/lib/Thelia/Model/CategoryImage.php b/core/lib/Thelia/Model/CategoryImage.php index 75c66f967..d6c6d9899 100644 --- a/core/lib/Thelia/Model/CategoryImage.php +++ b/core/lib/Thelia/Model/CategoryImage.php @@ -123,9 +123,9 @@ class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface, Fi * * @return string the URL to redirect to after update from the back-office */ - public function getRedirectionUrl($objectId) + public function getRedirectionUrl() { - return '/admin/categories/update?category_id=' . $objectId . '?current_tab=image'; + return '/admin/categories/update?category_id=' . $this->getCategoryId(); } /** diff --git a/core/lib/Thelia/Model/ContentDocument.php b/core/lib/Thelia/Model/ContentDocument.php index c2fb09ada..abde4f36a 100644 --- a/core/lib/Thelia/Model/ContentDocument.php +++ b/core/lib/Thelia/Model/ContentDocument.php @@ -123,9 +123,9 @@ class ContentDocument extends BaseContentDocument implements BreadcrumbInterface * * @return string the URL to redirect to after update from the back-office */ - public function getRedirectionUrl($objectId) + public function getRedirectionUrl() { - return '/admin/content/update/' . $objectId . '?current_tab=document'; + return '/admin/content/update/' . $this->getContentId(); } /** diff --git a/core/lib/Thelia/Model/ContentImage.php b/core/lib/Thelia/Model/ContentImage.php index 7172e8b51..cefcca112 100644 --- a/core/lib/Thelia/Model/ContentImage.php +++ b/core/lib/Thelia/Model/ContentImage.php @@ -121,9 +121,9 @@ class ContentImage extends BaseContentImage implements BreadcrumbInterface, File * * @return string the URL to redirect to after update from the back-office */ - public function getRedirectionUrl($objectId) + public function getRedirectionUrl() { - return '/admin/content/update/' . $objectId . '?current_tab=image'; + return '/admin/content/update/' . $this->getContentId(); } /** diff --git a/core/lib/Thelia/Model/FolderDocument.php b/core/lib/Thelia/Model/FolderDocument.php index caae33b31..14e660dd9 100644 --- a/core/lib/Thelia/Model/FolderDocument.php +++ b/core/lib/Thelia/Model/FolderDocument.php @@ -120,9 +120,9 @@ class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface, * @param int $objectId the ID of the parent object * @return string the URL to redirect to after update from the back-office */ - public function getRedirectionUrl($objectId) + public function getRedirectionUrl() { - return '/admin/folder/update/' . $objectId . '?current_tab=image'; + return '/admin/folder/update/' . $this->getFolderId(); } /** diff --git a/core/lib/Thelia/Model/FolderImage.php b/core/lib/Thelia/Model/FolderImage.php index 5082d089b..31b9024c6 100644 --- a/core/lib/Thelia/Model/FolderImage.php +++ b/core/lib/Thelia/Model/FolderImage.php @@ -120,9 +120,9 @@ class FolderImage extends BaseFolderImage implements BreadcrumbInterface, FileMo * @param int $objectId the ID of the parent object * @return string the URL to redirect to after update from the back-office */ - public function getRedirectionUrl($objectId) + public function getRedirectionUrl() { - return '/admin/folder/update/' . $objectId . '?current_tab=image'; + return '/admin/folder/update/' . $this->getFolderId(); } /** diff --git a/core/lib/Thelia/Model/ProductDocument.php b/core/lib/Thelia/Model/ProductDocument.php index 1706e2cd4..04f867342 100644 --- a/core/lib/Thelia/Model/ProductDocument.php +++ b/core/lib/Thelia/Model/ProductDocument.php @@ -123,9 +123,9 @@ class ProductDocument extends BaseProductDocument implements BreadcrumbInterface * * @return string the URL to redirect to after update from the back-office */ - public function getRedirectionUrl($objectId) + public function getRedirectionUrl() { - return '/admin/products/update?product_id=' . $objectId . '?current_tab=document'; + return '/admin/products/update?product_id=' . $this->getProductId(); } /** diff --git a/core/lib/Thelia/Model/ProductImage.php b/core/lib/Thelia/Model/ProductImage.php index d6a753cea..e33683917 100644 --- a/core/lib/Thelia/Model/ProductImage.php +++ b/core/lib/Thelia/Model/ProductImage.php @@ -122,9 +122,9 @@ class ProductImage extends BaseProductImage implements BreadcrumbInterface, File * * @return string the URL to redirect to after update from the back-office */ - public function getRedirectionUrl($objectId) + public function getRedirectionUrl() { - return '/admin/products/update?product_id=' . $objectId . '?current_tab=image'; + return '/admin/products/update?product_id=' . $this->getProductId(); } /** diff --git a/templates/backOffice/default/document-edit.html b/templates/backOffice/default/document-edit.html index 09e06a6b8..7be7ed9d4 100644 --- a/templates/backOffice/default/document-edit.html +++ b/templates/backOffice/default/document-edit.html @@ -35,7 +35,7 @@ hide_submit_buttons = false page_url = "{url path="/admin/document/type/{$documentType}/{$ID}/update"}" - close_url = "{url path="{$redirectUrl}" noamp=1}" + close_url = "{url path="{$redirectUrl}" current_tab="documents" noamp=1}" } {form_hidden_fields form=$form} @@ -75,7 +75,7 @@ hide_flags = true page_url = "{url path="/admin/document/type/{$documentType}/{$ID}/update"}" - close_url = "{url path="{$redirectUrl}"}" + close_url = "{url path="{$redirectUrl}" current_tab="documents"}" } {/form} @@ -95,7 +95,7 @@
        diff --git a/templates/backOffice/default/image-edit.html b/templates/backOffice/default/image-edit.html index 697b08501..0d0ea9096 100644 --- a/templates/backOffice/default/image-edit.html +++ b/templates/backOffice/default/image-edit.html @@ -35,7 +35,7 @@ hide_submit_buttons = false page_url = "{url path="/admin/image/type/{$imageType}/{$ID}/update"}" - close_url = "{url path="{$redirectUrl}" noamp=1}" + close_url = "{url path="{$redirectUrl}" current_tab="images" noamp=1}" } {form_hidden_fields form=$form} @@ -78,7 +78,7 @@ hide_flags = true page_url = "{url path="/admin/image/type/{$imageType}/{$ID}/update"}" - close_url = "{url path="{$redirectUrl}"}" + close_url = "{url path="{$redirectUrl}" current_tab="images"}" } {/form} @@ -98,7 +98,7 @@
        From f651a267c583fef2dec7be9440485110634d4c6f Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 7 Jul 2014 23:23:16 +0200 Subject: [PATCH 61/64] Fixed wrong escapin of "required" attribute --- .../forms/standard/form-field-attributes-renderer.html | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/templates/backOffice/default/forms/standard/form-field-attributes-renderer.html b/templates/backOffice/default/forms/standard/form-field-attributes-renderer.html index 735d35503..7f9ed124a 100644 --- a/templates/backOffice/default/forms/standard/form-field-attributes-renderer.html +++ b/templates/backOffice/default/forms/standard/form-field-attributes-renderer.html @@ -15,7 +15,7 @@ In addition to the standard form_field block output, this fragment uses the foll {* Synthetize an ID if none was given *} {if empty({$label_attr.for})} - {$label_attr.for = "id-{$field_name}"} + {$label_attr.for = "{$form->getName()}-id-{$field_name}"} {/if} {if $disabled} @@ -41,11 +41,11 @@ In addition to the standard form_field block output, this fragment uses the foll {if $type == 'hidden'} id="{$label_attr.for}" name="{$name}" value="{$value}" {elseif $type == 'checkbox' || $type == 'radio'} - id="{$label_attr.for}" name="{$name}" class="{$field_extra_class}" value="{$value}" {if $checked}checked="checked"{/if} {$sDisabled} {$sReadonly} {$sRequired} + id="{$label_attr.for}" name="{$name}" class="{$field_extra_class}" value="{$value}" {if $checked}checked="checked"{/if} {$sDisabled} {$sReadonly} {$sRequired nofilter} {elseif $type == 'choice'} - id="{$label_attr.for}" name="{$name} "class="form-control class="{$field_extra_class}" {if $multiple}multiple{/if} {if $lattr_list.size}size="{$lattr_list.size}"{/if} {$sDisabled} {$sReadonly} {$sRequired} + id="{$label_attr.for}" name="{$name} "class="form-control class="{$field_extra_class}" {if $multiple}multiple{/if} {if $lattr_list.size}size="{$lattr_list.size}"{/if} {$sDisabled} {$sReadonly} {$sRequired nofilter} {elseif $type == 'textarea'} - id="{$label_attr.for}" name="{$name}" class="form-control {$field_extra_class}" {if $attr_list.rows}rows="{$attr_list.rows}"{/if} {$sMaxLength nofilter} {$sPlaceholder nofilter} {$sDisabled} {$sReadonly} {$sRequired} + id="{$label_attr.for}" name="{$name}" class="form-control {$field_extra_class}" {if $attr_list.rows}rows="{$attr_list.rows}"{/if} {$sMaxLength nofilter} {$sPlaceholder nofilter} {$sDisabled} {$sReadonly} {$sRequired nofilter} {else} - id="{$label_attr.for}" name="{$name}" value="{$value}" class="form-control {$field_extra_class}" {$sMaxLength nofilter} {$sPlaceholder nofilter} {$sDisabled} {$sReadonly} {$sRequired} + id="{$label_attr.for}" name="{$name}" value="{$value}" class="form-control {$field_extra_class}" {$sMaxLength nofilter} {$sPlaceholder nofilter} {$sDisabled} {$sReadonly} {$sRequired nofilter} {/if} From c520f1e581b42f5d7d1ef9ea06022728b6abc719 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 7 Jul 2014 23:24:03 +0200 Subject: [PATCH 62/64] Fixed wrong "alt" attribute --- .../backOffice/default/includes/image-upload-list-ajax.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/backOffice/default/includes/image-upload-list-ajax.html b/templates/backOffice/default/includes/image-upload-list-ajax.html index 009cc6174..6ba0fccba 100644 --- a/templates/backOffice/default/includes/image-upload-list-ajax.html +++ b/templates/backOffice/default/includes/image-upload-list-ajax.html @@ -12,7 +12,7 @@ Parameters:
          {loop type="image" name="image" source="{$imageType}" order="manual" source_id="{$parentId}" width="200" height="100" resize_mode="borders"}
        • - + {$TITLE} From ab484973e1e5eff700ab378f3f2473e6e9ee9fea Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Mon, 7 Jul 2014 23:24:39 +0200 Subject: [PATCH 63/64] Fixed "success_url" appearing twice in forms --- .../Core/Template/Smarty/Plugins/Form.php | 9 +++-- core/lib/Thelia/Form/BaseForm.php | 36 ++++++++++++++++--- 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php index bddc07407..7322537b9 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php @@ -396,13 +396,18 @@ class Form extends AbstractSmartyPlugin $attrFormat = '%s="%s"'; $field = ''; - $instance = $this->getInstanceFromParams($params); + $baseFormInstance = $this->getInstanceFromParams($params); - $formView = $instance->getView(); + $formView = $baseFormInstance->getView(); $return = ""; + /** @var FormView $row */ foreach ($formView->getIterator() as $row) { + + // We have to exclude the fields for which value is defined in the template. + if ($baseFormInstance->isTemplateDefinedHiddenField($row)) continue; + if ($this->isHidden($row) && $row->isRendered() === false) { $attributeList = array(); if (isset($row->vars["attr"])) { diff --git a/core/lib/Thelia/Form/BaseForm.php b/core/lib/Thelia/Form/BaseForm.php index cea9bbba7..716c08ff8 100644 --- a/core/lib/Thelia/Form/BaseForm.php +++ b/core/lib/Thelia/Form/BaseForm.php @@ -12,12 +12,13 @@ namespace Thelia\Form; -use Symfony\Component\Form\Extension\Validator\ValidatorExtension; -use Symfony\Component\Form\Forms; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension; use Symfony\Component\Form\Extension\Csrf\CsrfExtension; use Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider; +use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension; +use Symfony\Component\Form\Extension\Validator\ValidatorExtension; +use Symfony\Component\Form\Forms; +use Symfony\Component\Form\FormView; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Validator\Validation; use Thelia\Core\Translation\Translator; use Thelia\Model\ConfigQuery; @@ -95,17 +96,38 @@ abstract class BaseForm $this->buildForm(); // If not already set, define the success_url field + // This field is not included in the standard form hidden fields + // This field is not included in the hidden fields generated by form_hidden_fields Smarty function if (! $this->formBuilder->has('success_url')) { $this->formBuilder->add("success_url", "hidden"); } + // The "error_message" field defines the error message displayed if + // the form could not be validated. If it is empty, a standard error message is displayed instead. + // This field is not included in the hidden fields generated by form_hidden_fields Smarty function if (! $this->formBuilder->has('error_message')) { - $this->formBuilder->add("error_message", "text"); + $this->formBuilder->add("error_message", "hidden"); } $this->form = $this->formBuilder->getForm(); } + /** + * Return true if the given field value is defined only in the HTML template, and its value is defined + * in the template file, not the form builder. + * Thus, it should not be included in the form hidden fields generated by form_hidden_fields + * Smarty function, to prevent it from exiting twice in the form. + * + * @param FormView $fieldView + * @return bool + */ + public function isTemplateDefinedHiddenField($fieldView) { + $name = $fieldView->vars['name']; + + return $name == 'success_url' || $name == 'error_message'; + } + + public function getRequest() { return $this->request; @@ -146,6 +168,10 @@ abstract class BaseForm return $this; } + /** + * @return FormView + * @throws \LogicException + */ public function getView() { if ($this->view === null) throw new \LogicException("View was not created. Please call BaseForm::createView() first."); From 6c1e45276bde1897ec36bed2a0da33f15db83026 Mon Sep 17 00:00:00 2001 From: Franck Allimant Date: Tue, 8 Jul 2014 10:33:47 +0200 Subject: [PATCH 64/64] PHP-CS fixer passed --- core/lib/Thelia/Core/Template/ParserInterface.php | 4 ++-- core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php | 1 - core/lib/Thelia/Form/BaseForm.php | 6 +++--- core/lib/Thelia/Form/Brand/BrandModificationForm.php | 1 - core/lib/Thelia/Form/Image/DocumentModification.php | 1 - core/lib/Thelia/Form/Image/ImageModification.php | 1 - core/lib/Thelia/Form/SeoFieldsTrait.php | 2 +- 7 files changed, 6 insertions(+), 10 deletions(-) diff --git a/core/lib/Thelia/Core/Template/ParserInterface.php b/core/lib/Thelia/Core/Template/ParserInterface.php index 4eff151e4..dfb312499 100644 --- a/core/lib/Thelia/Core/Template/ParserInterface.php +++ b/core/lib/Thelia/Core/Template/ParserInterface.php @@ -50,8 +50,8 @@ interface ParserInterface * * @param int $templateType the template type ( * - * @param string $templateName the template name - * @param string $templateDirectory path to the template dirtectory + * @param string $templateName the template name + * @param string $templateDirectory path to the template dirtectory * @param string $key ??? * @param bool $unshift ??? Etienne ? */ diff --git a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php index 7322537b9..b280529a9 100644 --- a/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php +++ b/core/lib/Thelia/Core/Template/Smarty/Plugins/Form.php @@ -24,7 +24,6 @@ use Thelia\Core\Template\ParserContext; use Thelia\Core\Template\ParserInterface; use Thelia\Core\Template\Smarty\AbstractSmartyPlugin; use Thelia\Core\Template\Smarty\SmartyPluginDescriptor; -use Thelia\Core\Template\TemplateHelper; use Thelia\Form\BaseForm; /** diff --git a/core/lib/Thelia/Form/BaseForm.php b/core/lib/Thelia/Form/BaseForm.php index 716c08ff8..08c5dfce1 100644 --- a/core/lib/Thelia/Form/BaseForm.php +++ b/core/lib/Thelia/Form/BaseForm.php @@ -118,16 +118,16 @@ abstract class BaseForm * Thus, it should not be included in the form hidden fields generated by form_hidden_fields * Smarty function, to prevent it from exiting twice in the form. * - * @param FormView $fieldView + * @param FormView $fieldView * @return bool */ - public function isTemplateDefinedHiddenField($fieldView) { + public function isTemplateDefinedHiddenField($fieldView) + { $name = $fieldView->vars['name']; return $name == 'success_url' || $name == 'error_message'; } - public function getRequest() { return $this->request; diff --git a/core/lib/Thelia/Form/Brand/BrandModificationForm.php b/core/lib/Thelia/Form/Brand/BrandModificationForm.php index b7671cd7a..29c07de44 100644 --- a/core/lib/Thelia/Form/Brand/BrandModificationForm.php +++ b/core/lib/Thelia/Form/Brand/BrandModificationForm.php @@ -13,7 +13,6 @@ namespace Thelia\Form\Brand; use Symfony\Component\Validator\Constraints\GreaterThan; -use Symfony\Component\Validator\Constraints\NotBlank; use Thelia\Core\Translation\Translator; use Thelia\Form\StandardDescriptionFieldsTrait; diff --git a/core/lib/Thelia/Form/Image/DocumentModification.php b/core/lib/Thelia/Form/Image/DocumentModification.php index 62b5750e0..2100b913f 100644 --- a/core/lib/Thelia/Form/Image/DocumentModification.php +++ b/core/lib/Thelia/Form/Image/DocumentModification.php @@ -12,7 +12,6 @@ namespace Thelia\Form\Image; -use Symfony\Component\Validator\Constraints\NotBlank; use Thelia\Core\Translation\Translator; use Thelia\Form\BaseForm; use Thelia\Form\StandardDescriptionFieldsTrait; diff --git a/core/lib/Thelia/Form/Image/ImageModification.php b/core/lib/Thelia/Form/Image/ImageModification.php index d53fe84f6..38d0ed836 100644 --- a/core/lib/Thelia/Form/Image/ImageModification.php +++ b/core/lib/Thelia/Form/Image/ImageModification.php @@ -13,7 +13,6 @@ namespace Thelia\Form\Image; use Symfony\Component\Validator\Constraints\Image; -use Symfony\Component\Validator\Constraints\NotBlank; use Thelia\Core\Translation\Translator; use Thelia\Form\BaseForm; use Thelia\Form\StandardDescriptionFieldsTrait; diff --git a/core/lib/Thelia/Form/SeoFieldsTrait.php b/core/lib/Thelia/Form/SeoFieldsTrait.php index 6609ee198..efba8567b 100644 --- a/core/lib/Thelia/Form/SeoFieldsTrait.php +++ b/core/lib/Thelia/Form/SeoFieldsTrait.php @@ -97,4 +97,4 @@ trait SeoFieldsTrait ] ); } -} \ No newline at end of file +}