b374k
m1n1 1.01
Apache/2.4.41 (Ubuntu)
Linux vmi616275.contaboserver.net 5.4.0-84-generic #94-Ubuntu SMP Thu Aug 26 20:27:37 UTC 2021 x86_64
uid=33(www-data) gid=33(www-data) groups=33(www-data)
server ip : 62.171.164.128 | your ip : 127.0.0.1
safemode OFF
 >  / home / dev2.destoffenstraat.com / app / code / Makarovsoft / Email / Model / ResourceModel /
Filename/home/dev2.destoffenstraat.com/app/code/Makarovsoft/Email/Model/ResourceModel/Template.php
Size23.3 kb
Permissionrwxrwxrwx
Ownerroot : root
Create time17-Aug-2025 10:26
Last modified06-Apr-2021 18:06
Last accessed22-Aug-2025 10:51
Actionsedit | rename | delete | download (gzip)
Viewtext | code | image
<?php
namespace Makarovsoft\Email\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Magento\Framework\Model\ResourceModel\Db\Context;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Stdlib\DateTime as LibDateTime;
use Magento\Framework\Model\AbstractModel;
use Magento\Store\Model\Store;
use Makarovsoft\Email\Model\Template as TemplateModel;
use Magento\Framework\Event\ManagerInterface;
use Magento\Catalog\Model\Product;
use Makarovsoft\Email\Model\Template\Product as TemplateProduct;
use Makarovsoft\Email\Model\Template\Category as TemplateCategory;

class Template extends AbstractDb
{
/**
* Store model
*
* @var \Magento\Store\Model\Store
*/
protected $store = null;

/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
protected $date;

/**
* Store manager
*
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;

/**
* @var \Magento\Framework\Stdlib\DateTime
*/
protected $dateTime;

/**
* @var string
*/
protected $templateProductTable;

/**
* @var string
*/
protected $templateCategoryTable;

/**
* @var \Magento\Framework\Event\ManagerInterface
*/
protected $eventManager;

/**
* @var \Makarovsoft\Email\Model\Template\Product
*/
protected $templateProduct;

/**
* @param Context $context
* @param DateTime $date
* @param StoreManagerInterface $storeManager
* @param LibDateTime $dateTime
* @param ManagerInterface $eventManager
* @param TemplateProduct $templateProduct
* @param TemplateCategory $templateCategory
*/
public function __construct(
Context $context,
DateTime $date,
StoreManagerInterface $storeManager,
LibDateTime $dateTime,
ManagerInterface $eventManager,
TemplateProduct $templateProduct,
TemplateCategory $templateCategory
)
{
$this->date = $date;
$this->storeManager = $storeManager;
$this->dateTime = $dateTime;
$this->eventManager = $eventManager;
$this->templateProduct = $templateProduct;
$this->templateCategory = $templateCategory;

parent::__construct($context);
$this->templateProductTable = $this->getTable('makarovsoft_email_template_product');
$this->templateCategoryTable = $this->getTable('makarovsoft_email_template_category');

}

/**
* Initialize resource model
*
* @return void
*/
protected function _construct()
{
$this->_init('makarovsoft_email_template', 'template_id');
}

/**
* Process template data before deleting
*
* @param \Magento\Framework\Model\AbstractModel $object
* @return $this
*/
protected function _beforeDelete(AbstractModel $object)
{
$condition = ['template_id = ?' => (int)$object->getId()];
$this->getConnection()->delete($this->getTable('makarovsoft_email_template_store'), $condition);
return parent::_beforeDelete($object);
}

/**
* before save callback
*
* @param AbstractModel|\Makarovsoft\Email\Model\Template $object
* @return $this
*/
protected function _beforeSave(AbstractModel $object)
{
foreach (['dob'] as $field) {
$value = !$object->getData($field) ? null : $object->getData($field);
$object->setData($field, $this->dateTime->formatDate($value));
}
$object->setUpdatedAt($this->date->gmtDate());
if ($object->isObjectNew()) {
$object->setCreatedAt($this->date->gmtDate());
}
return parent::_beforeSave($object);
}

/**
* Assign template to store views
*
* @param AbstractModel|\Makarovsoft\Email\Model\Template $object
* @return $this
*/
protected function _afterSave(AbstractModel $object)
{
$this->saveStoreRelation($object);
return parent::_afterSave($object);
}

/**
* Load an object using 'url_key' field if there's no field specified and value is not numeric
*
* @param AbstractModel|\Makarovsoft\Email\Model\Template $object
* @param mixed $value
* @param string $field
* @return $this
*/
public function load(AbstractModel $object, $value, $field = null)
{
return parent::load($object, $value, $field);
}

/**
* Perform operations after object load
*
* @param AbstractModel $object
* @return $this
*/
protected function _afterLoad(AbstractModel $object)
{
if ($object->getId()) {
$stores = $this->lookupStoreIds($object->getId());
$object->setData('store_id', $stores);
}
return parent::_afterLoad($object);
}

/**
* Retrieve select object for load object data
*
* @param string $field
* @param mixed $value
* @param \Makarovsoft\Email\Model\Template $object
* @return \Zend_Db_Select
*/
protected function _getLoadSelect($field, $value, $object)
{
$select = parent::_getLoadSelect($field, $value, $object);

if ($object->getStoreId()) {
$storeIds = [
Store::DEFAULT_STORE_ID,
(int)$object->getStoreId()
];
$select->join(
[
'makarovsoft_email_template_store' => $this->getTable('makarovsoft_email_template_store')
],
$this->getMainTable() . '.template_id = makarovsoft_email_template_store.template_id',
[]
)//TODO: check if is_active filter is needed
->where('is_active = ?', 1)
->where(
'makarovsoft_email_template_store.store_id IN (?)',
$storeIds
)
->order('makarovsoft_email_template_store.store_id DESC')
->limit(1);
}
return $select;
}

/**
* Retrieve load select with filter by url_key, store and activity
*
* @param string $urlKey
* @param int|array $store
* @param int $isActive
* @return \Magento\Framework\DB\Select
*/
protected function getLoadByUrlKeySelect($urlKey, $store, $isActive = null)
{
$select = $this->getConnection()
->select()
->from(['template' => $this->getMainTable()])
->join(
['template_store' => $this->getTable('makarovsoft_email_template_store')],
'template.template_id = template_store.template_id',
[]
)
->where(
'template.url_key = ?',
$urlKey
)
->where(
'template_store.store_id IN (?)',
$store
);
if (!is_null($isActive)) {
$select->where('template.is_active = ?', $isActive);
}
return $select;
}


/**
* Check if template url_key exist
* return template id if template exists
*
* @param string $urlKey
* @param int $storeId
* @return int
*/
public function checkUrlKey($urlKey, $storeId)
{
$stores = [Store::DEFAULT_STORE_ID, $storeId];
$select = $this->getLoadByUrlKeySelect($urlKey, $stores, 1);
$select->reset(\Zend_Db_Select::COLUMNS)
->columns('template.template_id')
->order('template_store.store_id DESC')
->limit(1);
return $this->getConnection()->fetchOne($select);
}

/**
* Retrieves template name from DB by passed url key.
*
* @param string $urlKey
* @return string|bool
*/
public function getTemplateNameByUrlKey($urlKey)
{
$stores = [Store::DEFAULT_STORE_ID];
if ($this->store) {
$stores[] = (int)$this->getStore()->getId();
}
$select = $this->getLoadByUrlKeySelect($urlKey, $stores);
$select->reset(\Zend_Db_Select::COLUMNS)
->columns('template.name')
->order('template.store_id DESC')
->limit(1);
return $this->getConnection()->fetchOne($select);
}

/**
* Retrieves template name from DB by passed id.
*
* @param string $id
* @return string|bool
*/
public function getTemplateNameById($id)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'name')
->where('template_id = :template_id');
$binds = ['template_id' => (int)$id];
return $adapter->fetchOne($select, $binds);
}

/**
* Retrieves template url key from DB by passed id.
*
* @param int $id
* @return string|bool
*/
public function getTemplateUrlKeyById($id)
{
$adapter = $this->getConnection();
$select = $adapter->select()
->from($this->getMainTable(), 'url_key')
->where('template_id = :template_id');
$binds = ['template_id' => (int)$id];
return $adapter->fetchOne($select, $binds);
}

/**
* Get store ids to which specified item is assigned
*
* @param int $templateId
* @return array
*/
public function lookupStoreIds($templateId)
{
$adapter = $this->getConnection();
$select = $adapter->select()->from(
$this->getTable('makarovsoft_email_template_store'),
'store_id'
)
->where(
'template_id = ?',
(int)$templateId
);
return $adapter->fetchCol($select);
}

/**
* Set store model
*
* @param Store $store
* @return $this
*/
public function setStore(Store $store)
{
$this->store = $store;
return $this;
}

/**
* Retrieve store model
*
* @return Store
*/
public function getStore()
{
return $this->storeManager->getStore($this->store);
}

/**
* check if url key is unique
*
* @param AbstractModel|\Makarovsoft\Email\Model\Template $object
* @return bool
*/
public function getIsUniqueTemplateToStores(AbstractModel $object)
{
if ($this->storeManager->hasSingleStore() || !$object->hasStores()) {
$stores = [Store::DEFAULT_STORE_ID];
} else {
$stores = (array)$object->getData('stores');
}
$select = $this->getLoadByUrlKeySelect($object->getData('url_key'), $stores);
if ($object->getId()) {
$select->where('template_store.template_id <> ?', $object->getId());
}
if ($this->getConnection()->fetchRow($select)) {
return false;
}
return true;
}

/**
* @param TemplateModel $template
* @return array
*/
public function getProductsPosition(TemplateModel $template)
{
$select = $this->getConnection()->select()->from(
$this->templateProductTable,
['product_id', 'position']
)
->where(
'template_id = :template_id'
);
$bind = ['template_id' => (int)$template->getId()];
return $this->getConnection()->fetchPairs($select, $bind);
}

/**
* @param TemplateModel $template
* @return $this
*/
protected function saveStoreRelation(TemplateModel $template)
{
$oldStores = $this->lookupStoreIds($template->getId());
$newStores = (array)$template->getStores();
if (empty($newStores)) {
$newStores = (array)$template->getStoreId();
}
$table = $this->getTable('makarovsoft_email_template_store');
$insert = array_diff($newStores, $oldStores);
$delete = array_diff($oldStores, $newStores);

if ($delete) {
$where = [
'template_id = ?' => (int)$template->getId(),
'store_id IN (?)' => $delete
];
$this->getConnection()->delete($table, $where);
}
if ($insert) {
$data = [];
foreach ($insert as $storeId) {
$data[] = [
'template_id' => (int)$template->getId(),
'store_id' => (int)$storeId
];
}
$this->getConnection()->insertMultiple($table, $data);
}
return $this;
}

/**
* @param TemplateModel $template
* @return $this
*/
protected function saveProductRelation(TemplateModel $template)
{
$template->setIsChangedProductList(false);
$id = $template->getId();
$products = $template->getProductsData();

if ($products === null) {
return $this;
}
$oldProducts = $template->getProductsPosition();
$insert = array_diff_key($products, $oldProducts);
$delete = array_diff_key($oldProducts, $products);
$update = array_intersect_key($products, $oldProducts);
$_update = array();
foreach ($update as $key=>$settings) {
if ( isset($oldProducts[$key]) && isset($settings['position']) &&
$oldProducts[$key] != $settings['position']
) {
$_update[$key] = $settings;
}
}
$update = $_update;
$adapter = $this->getConnection();
if (!empty($delete)) {
$condition = ['product_id IN(?)' => array_keys($delete), 'template_id=?' => $id];
$adapter->delete($this->templateProductTable, $condition);
}
if (!empty($insert)) {
$data = [];
foreach ($insert as $productId => $position) {
$data[] = [
'template_id' => (int)$id,
'product_id' => (int)$productId,
'position' => (int)$position
];
}
$adapter->insertMultiple($this->templateProductTable, $data);
}

if (!empty($update)) {
foreach ($update as $productId => $position) {
$where = ['template_id = ?' => (int)$id, 'product_id = ?' => (int)$productId];
$bind = ['position' => (int)$position['position']];
$adapter->update($this->templateProductTable, $bind, $where);
}
}

if (!empty($insert) || !empty($delete)) {
$productIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
$this->eventManager->dispatch(
'makarovsoft_email_template_change_products',
['template' => $template, 'product_ids' => $productIds]
);
}

if (!empty($insert) || !empty($update) || !empty($delete)) {
$template->setIsChangedProductList(true);
$productIds = array_keys($insert + $delete + $update);
$template->setAffectedProductIds($productIds);
}
return $this;
}

/**
* @param Product $product
* @param $templates
* @return $this
*/
public function saveTemplateProductRelation(Product $product, $templates)
{
$product->setIsChangedTemplateList(false);
$id = $product->getId();
if ($templates === null) {
return $this;
}
$oldTemplateObjects = $this->templateProduct->getSelectedTemplates($product);
if (!is_array($oldTemplateObjects)) {
$oldTemplateObjects = [];
}
$oldTemplates = [];
foreach ($oldTemplateObjects as $template) {
/** @var \Makarovsoft\Email\Model\Template $template */
$oldTemplates[$template->getId()] = ['position' => $template->getPosition()];
}
$insert = array_diff_key($templates, $oldTemplates);

$delete = array_diff_key($oldTemplates, $templates);

$update = array_intersect_key($templates, $oldTemplates);
$toUpdate = [];
foreach ($update as $productId => $values) {
if (isset($oldTemplates[$productId]) && $oldTemplates[$productId]['position'] != $values['position']) {
$toUpdate[$productId] = [];
$toUpdate[$productId]['position'] = $values['position'];
}
}

$update = $toUpdate;
$adapter = $this->getConnection();
if (!empty($delete)) {
$condition = ['template_id IN(?)' => array_keys($delete), 'product_id=?' => $id];
$adapter->delete($this->templateProductTable, $condition);
}
if (!empty($insert)) {
$data = [];
foreach ($insert as $templateId => $position) {
$data[] = [
'product_id' => (int)$id,
'template_id' => (int)$templateId,
'position' => (int)$position['position']
];
}
$adapter->insertMultiple($this->templateProductTable, $data);
}

if (!empty($update)) {
foreach ($update as $templateId => $position) {
$where = ['product_id = ?' => (int)$id, 'template_id = ?' => (int)$templateId];
$bind = ['position' => (int)$position['position']];
$adapter->update($this->templateProductTable, $bind, $where);
}
}

if (!empty($insert) || !empty($delete)) {
$templateIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
$this->eventManager->dispatch(
'makarovsoft_email_product_change_templates',
['product' => $product, 'template_ids' => $templateIds]
);
}

if (!empty($insert) || !empty($update) || !empty($delete)) {
$product->setIsChangedTemplateList(true);
$templateIds = array_keys($insert + $delete + $update);
$product->setAffectedTemplateIds($templateIds);
}
return $this;
}

protected function saveCategoryRelation(TemplateModel $template)
{
$template->setIsChangedCategoryList(false);
$id = $template->getId();
$categories = $template->getCategoriesIds();

if ($categories === null) {
return $this;
}
$oldCategoryIds = $template->getCategoryIds();
$insert = array_diff_key($categories, $oldCategoryIds);
$delete = array_diff_key($oldCategoryIds, $categories);

$adapter = $this->getConnection();
if (!empty($delete)) {
$condition = array('category_id IN(?)' => $delete, 'template_id=?' => $id);
$adapter->delete($this->templateCategoryTable, $condition);
}
if (!empty($insert)) {
$data = array();
foreach ($insert as $categoryId) {
$data[] = array(
'template_id' => (int)$id,
'category_id' => (int)$categoryId,
'position' => 1
);
}
$adapter->insertMultiple($this->templateCategoryTable, $data);
}

if (!empty($insert) || !empty($delete)) {
$categoryIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
$this->eventManager->dispatch(
'makarovsoft_email_template_change_categories',
array('template' => $template, 'category_ids' => $categoryIds)
);
}

if (!empty($insert) /*|| !empty($update)*/ || !empty($delete)) {
$template->setIsChangedCategoryList(true);
$categoryIds = array_keys($insert + $delete /* + $update*/);
$template->setAffectedCategoryIds($categoryIds);
}
return $this;
}

/**
* @param TemplateModel $template
*
* @return array
*/
public function getCategoryIds(TemplateModel $template)
{
$adapter = $this->getConnection();
$select = $adapter->select()->from(
$this->templateCategoryTable,
'category_id'
)
->where(
'template_id = ?',
(int)$template->getId()
);
return $adapter->fetchCol($select);
}

/**
* @param $category
* @param $templates
* @return $this
*/
public function saveTemplateCategoryRelation($category, $templates)
{
/** @var \Magento\Catalog\Model\Category $category */
$category->setIsChangedTemplateList(false);
$id = $category->getId();
if ($templates === null) {
return $this;
}
$oldTemplateObjects = $this->templateCategory->getSelectedTemplates($category);
if (!is_array($oldTemplateObjects)) {
$oldTemplateObjects = array();
}
$oldTemplates = [];
foreach ($oldTemplateObjects as $template) {
/** @var \Makarovsoft\Email\Model\Template $template */
$oldTemplates[$template->getId()] = $template->getPosition();
}
$insert = array_diff_key($templates, $oldTemplates);
$delete = array_diff_key($oldTemplates, $templates);
$update = array_intersect_key($templates, $oldTemplates);
$update = array_diff_assoc($update, $oldTemplates);


$adapter = $this->getConnection();
if (!empty($delete)) {
$condition = array('template_id IN(?)' => array_keys($delete), 'template_id=?' => $id);
$adapter->delete($this->templateCategoryTable, $condition);
}
if (!empty($insert)) {
$data = array();
foreach ($insert as $templateId => $position) {
$data[] = [
'category_id' => (int)$id,
'template_id' => (int)$templateId,
'position' => (int)$position
];
}
$adapter->insertMultiple($this->templateCategoryTable, $data);
}

if (!empty($update)) {
foreach ($update as $templateId => $position) {
$where = ['category_id = ?' => (int)$id, 'template_id = ?' => (int)$templateId];
$bind = ['position' => (int)$position];
$adapter->update($this->templateCategoryTable, $bind, $where);
}
}

if (!empty($insert) || !empty($delete)) {
$templateIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
$this->eventManager->dispatch(
'makarovsoft_email_category_change_templates',
array('category' => $category, 'template_ids' => $templateIds)
);
}

if (!empty($insert) || !empty($update) || !empty($delete)) {
$category->setIsChangedTemplateList(true);
$templateIds = array_keys($insert + $delete + $update);
$category->setAffectedTemplateIds($templateIds);
}
return $this;
}

}