Skip to content

Commit

Permalink
Code improvements for crudEAV templates generation
Browse files Browse the repository at this point in the history
  • Loading branch information
jalogut committed Dec 12, 2017
1 parent aa727bf commit 06ceb70
Show file tree
Hide file tree
Showing 14 changed files with 317 additions and 206 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ public function getButtonData()
'data_attribute' => [
'url' => $this->getDeleteUrl()
],
'on_click' => 'deleteConfirm(\'' . __("Are you sure you want to do this?") . '\', \'' . $this->getDeleteUrl() . '\')',
'on_click' =>
'deleteConfirm(\'' . __("Are you sure you want to do this?") . '\', \'' . $this->getDeleteUrl() . '\')',
'sort_order' => 20,
];
return $data;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ class Delete extends Action
* @param ${Entityname}Factory $objectFactory
*/
public function __construct(
Context $context,
${Entityname}Factory $objectFactory
Context $context,
${Entityname}Factory $objectFactory
) {
$this->objectFactory = $objectFactory;
parent::__construct($context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ public function execute()
try {
$this->objectCollection
->setStoreId($this->getRequest()->getParam('store', 0))
->addFieldToFilter('entity_id', array('in' => array_keys($postItems)))
->walk('saveCollection', array($postItems));
->addFieldToFilter('entity_id', ['in' => array_keys($postItems)])
->walk('saveCollection', [$postItems]);
} catch (\Exception $e) {
$messages[] = __('There was an error saving the data: ') . $e->getMessage();
$error = true;
Expand Down
1 change: 0 additions & 1 deletion templates/crudEAV/Model/ResourceModel/${Entityname}.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ public function getStoreId()
return $this->_storeId;
}


/**
* Set Attribute values to be saved
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;

/**
* Class Collection
* @package ${Vendorname}\${Modulename}\Model\ResourceModel\${Entityname}
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Collection extends AbstractCollection
{
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@

/**
* Class Collection
* Collection for displaying grid
* @package ${Vendorname}\${Modulename}\Model\ResourceModel\${Entityname}\Grid
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Collection extends ${Entityname}Collection implements SearchResultInterface
{
Expand Down Expand Up @@ -69,9 +70,21 @@ public function __construct(
$eventObject,
$resourceModel,
$model = '${Vendorname}\${Modulename}\Ui\Component\Listing\DataProvider\Document',
AdapterInterface $connection = null)
{
parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $eavConfig, $resource, $eavEntityFactory, $resourceHelper, $universalFactory, $storeManager, $connection);
AdapterInterface $connection = null
) {
parent::__construct(
$entityFactory,
$logger,
$fetchStrategy,
$eventManager,
$eavConfig,
$resource,
$eavEntityFactory,
$resourceHelper,
$universalFactory,
$storeManager,
$connection
);
$this->_eventPrefix = $eventPrefix;
$this->_eventObject = $eventObject;
$this->_init($model, $resourceModel);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use ${Vendorname}\${Modulename}\Model\${Entityname}\Attribute\Backend\ImageFactory;
use ${Vendorname}\${Modulename}\Model\${Entityname}Factory;

class Save extends Action
Expand Down Expand Up @@ -58,7 +59,8 @@ public function execute()
$objectInstance->load($data['entity_id']);
$params['entity_id'] = $data['entity_id'];
}
$this->${fileattributename}Preprocessing($data);
$imageData = $this->preparedImagesData($data);
$data = array_merge($data, $imageData);
$objectInstance->addData($data);

$this->_eventManager->dispatch(
Expand Down Expand Up @@ -87,19 +89,16 @@ public function execute()
return $resultRedirect->setPath('*/*/');
}

/**
* ${Fileattributename} data preprocessing
*
* @param array $data
*
* @return array
*/
protected function ${fileattributename}Preprocessing(&$data)
protected function preparedImagesData(array $data): array
{
if (empty($data['${fileattributename}'])) {
unset($data['${fileattributename}']);
$data['${fileattributename}']['delete'] = true;
$imagesData = [];
$imageAttributeCodes = array_keys(ImageFactory::IMAGE_ATTRIBUTE_CODES);
foreach ($imageAttributeCodes as $imageAttrCode) {
if (empty($data[$imageAttrCode])) {
$imagesData[$imageAttrCode]['delete'] = true;
}
}
return $imagesData;
}

}
45 changes: 15 additions & 30 deletions templates/fileEAVAttribute/Model/${Entityname}.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,29 @@
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Registry;
use ${Vendorname}\${Modulename}\Model\${Entityname}\Attribute\Backend\${Fileattributename}Factory;
use ${Vendorname}\${Modulename}\Model\${Entityname}\Attribute\Backend\ImageAbstract;
use ${Vendorname}\${Modulename}\Model\${Entityname}\Attribute\Backend\ImageFactory;

class ${Entityname} extends AbstractModel implements IdentityInterface
{
/**
* CMS page cache tag
*/
const CACHE_TAG = '${vendorname}_${modulename}_${entityname}';

/**
* @var string
*/
protected $_cacheTag = '${vendorname}_${modulename}_${entityname}';

/**
* Prefix of model events names
*
* @var string
*/
protected $_eventPrefix = '${vendorname}_${modulename}_${entityname}';

/**
* @var ${Fileattributename}Factory
* @var ImageFactory
*/
private $${fileattributename}Factory;
private $imageFactory;

/**
* Initialize resource model
Expand All @@ -52,17 +50,8 @@ protected function _construct()
$this->_init('${Vendorname}\${Modulename}\Model\ResourceModel\${Entityname}');
}

/**
* Reference constructor.
* @param ${Fileattributename}Factory $${fileattributename}Factory
* @param Context $context
* @param Registry $registry
* @param AbstractResource|null $resource
* @param AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
${Fileattributename}Factory $${fileattributename}Factory,
ImageFactory $imageFactory,
Context $context,
Registry $registry,
AbstractResource $resource = null,
Expand All @@ -76,7 +65,7 @@ public function __construct(
$resourceCollection,
$data
);
$this->${fileattributename}Factory = $${fileattributename}Factory;
$this->imageFactory = $imageFactory;
}

/**
Expand Down Expand Up @@ -104,26 +93,22 @@ public function saveCollection(array $data)
return $this;
}

/**
* Get ${Fileattributename} in right format to edit in admin form
*
* @return array
*/
public function get${Fileattributename}ValueForForm()
public function getImageValueForForm(string $imageAttrCode): array
{
$${fileattributename} = $this->${fileattributename}Factory->create();
return $${fileattributename}->getFileValueForForm($this);
/** @var ImageAbstract $image */
$image = $this->imageFactory->create($imageAttrCode);
return $image->getFileValueForForm($this);
}

/**
* Get ${Fileattributename} Src to display in frontend
*
* @param string $imageAttrCode
* @return mixed
*/
public function get${Fileattributename}Src()
public function getMainImageSrc(string $imageAttrCode)
{
$${fileattributename} = $this->${fileattributename}Factory->create();
return $${fileattributename}->getFileInfo($this)->getUrl();
/** @var ImageAbstract $image */
$image = $this->imageFactory->create($imageAttrCode);
return $image->getFileInfo($this)->getUrl();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,150 +8,21 @@

namespace ${Vendorname}\${Modulename}\Model\${Entityname}\Attribute\Backend;

use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend;
use Magento\Framework\DataObject;
use ${Vendorname}\${Modulename}\Helper\FileProcessor;

class ${Fileattributename} extends AbstractBackend
class ${Fileattributename} extends ImageAbstract
{
/**
* @var string
*/
const FILES_SUBDIR = '${fileattributename}';

/**
* @var FileProcessor
*/
protected $fileProcessor;

/**
* @param FileProcessor $fileProcessor
*/
public function __construct(FileProcessor $fileProcessor)
{
$this->fileProcessor = $fileProcessor;
}

/**
* Prepare File data before saving object
*
* @param \Magento\Framework\DataObject $object
*
* @return $this
* @throws \Exception
*/
public function beforeSave($object) //@codingStandardsIgnoreLine
{
parent::beforeSave($object);
$file = $object->get${Fileattributename}();
if (!is_array($file)) {
$object->setSkipSave${Fileattributename}(true);
return $this;
}

if (isset($file['delete'])) {
$object->set${Fileattributename}(null);
return $this;
}

$file = reset($file) ?: [];
if (!isset($file['file'])) {
throw new LocalizedException(
__('${Fileattributename} does not contain field \'file\'')
);
}
// Add file related data to object
$object->set${Fileattributename}($file['file']);
$object->setFileExists(isset($file['exists']));

return $this;
}

/**
* Save uploaded file and remove temporary file after saving object
*
* @param \Magento\Framework\DataObject $object
*
* @return $this
* @throws \Exception
*/
public function afterSave($object) //@codingStandardsIgnoreLine
{
parent::afterSave($object);
// if file already exists we do not need to save any new file
if ($object->getFileExists() || $object->getSkipSave${Fileattributename}()) {
return $this;
}
const ATTRIBUTE_CODE = '${fileattributename}';

// Delete old file if new one has changed
if ($object->getOrigData('${fileattributename}') && $object->get${Fileattributename}() != $object->getOrigData('${fileattributename}')) {
$this->fileProcessor->delete($this->getFileSubDir($object), $object->getOrigData('${fileattributename}'));
}

if ($object->get${Fileattributename}()) {
if (!$this->fileProcessor->saveFileFromTmp($object->get${Fileattributename}(), $this->getFileSubDir($object))) {
throw new \Exception('There was an error saving the file');
}
}
}

/**
* Subdir where files are stored
*
* @param \Magento\Framework\DataObject $object
* @return string
*/
protected function getFileSubDir($object)
{
return self::FILES_SUBDIR . '/' . $object->getId();
}

/**
* Delete media file before an ${fileattributename} row in database is removed
* @param \Magento\Framework\DataObject $object
* @return $this
*/
public function beforeDelete($object) //@codingStandardsIgnoreLine
{
parent::beforeDelete($object);
// Delete file from disk before the object is deleted from database
if ($object->get${Fileattributename}()) {
$this->fileProcessor->delete($this->getFileSubDir($object), $object->get${Fileattributename}());
}
return $this;
}

/**
* Get full info from file
*
* @param \Magento\Framework\DataObject $object
* @return DataObject
*/
public function getFileInfo($object)
{
if (!$object->getData('file_info') && $object->get${Fileattributename}()) {
$fileInfoObject = new DataObject();
$fileInfo = $this->fileProcessor->getFileInfo($object->get${Fileattributename}(), $this->getFileSubDir($object));
if ($fileInfo) {
$fileInfoObject->setData($fileInfo);
}
$object->setFileInfo($fileInfoObject);
}
protected function subdirName(): string
{
return self::ATTRIBUTE_CODE;
}

return $object->getData('file_info');
}
protected function attributeCode(): string
{
return self::ATTRIBUTE_CODE;
}

/**
* Return file info in a format valid for ui form fields
*
* @param \Magento\Framework\DataObject $object
* @return array
*/
public function getFileValueForForm($object)
{
if ($this->getFileInfo($object)->getFile()) {
return [$this->getFileInfo($object)->getData()];
}
return [];
}
}
Loading

0 comments on commit 06ceb70

Please sign in to comment.