Skip to content

Commit

Permalink
#7 and upload file fixes (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
UltimateModuleCreator authored May 8, 2020
1 parent d832c0d commit 59dc7ce
Show file tree
Hide file tree
Showing 39 changed files with 2,576 additions and 86 deletions.
4 changes: 2 additions & 2 deletions Generator/ListRepo.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ protected function _getDefaultConstructorDefinition()
],
[
'name' => 'param',
'description' => '\\' . $this->nameMatcher->getCollectionFactoryClass($this->getSourceClassName())
'description' => '\\'
. $this->nameMatcher->getCollectionFactoryClass($this->getSourceClassName())
. ' $collectionFactory',
]
]
Expand Down Expand Up @@ -269,5 +270,4 @@ private function getFilterConditions($indent)
$text .= $padd . '$conditions[] = [$condition => $filter->getValue()];' . "\n";
return $text;
}

}
67 changes: 67 additions & 0 deletions Model/FileChecker.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

/**
* Umc_Crud extension
*
* NOTICE OF LICENSE
*
* This source file is subject to the MIT License
* that is bundled with this package in the file LICENSE.txt
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/mit-license.php
*
* @category Umc
* @package Umc_Crud
* @copyright 2020 Marius Strajeru
* @license http://opensource.org/licenses/mit-license.php MIT License
* @author Marius Strajeru
*/

declare(strict_types=1);

namespace Umc\Crud\Model;

use Magento\Framework\Filesystem\Io\File;

class FileChecker
{
/**
* @var File
*/
private $file;

/**
* FileChecker constructor.
* @param File $file
*/
public function __construct(File $file)
{
$this->file = $file;
}

/**
* @param $destinationFile
* @param int $sparseLevel
* @return string
*/
public function getNewFileName($destinationFile, $sparseLevel = 2)
{
$fileInfo = $this->file->getPathInfo($destinationFile);
if ($this->file->fileExists($destinationFile)) {
$index = 1;
$baseName = $fileInfo['filename'] . '.' . $fileInfo['extension'];
while ($this->file->fileExists($fileInfo['dirname'] . '/' . $baseName)) {
$baseName = $fileInfo['filename'] . '_' . $index . '.' . $fileInfo['extension'];
$index++;
}
return $baseName;
} else {
$prefix = $sparseLevel > 0 ? '/' : '';
$fileName = $fileInfo['filename'];
for ($i = 0; $i < $sparseLevel; $i++) {
$prefix .= ($fileName[$i] ?? '_') . '/';
}
return $prefix . $fileInfo['basename'];
}
}
}
18 changes: 14 additions & 4 deletions Model/FileInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,18 @@ public function getMimeType($fileName)
return $result;
}

/**
* @param $fileName
* @return null|string
* @throws \Magento\Framework\Exception\FileSystemException
*/
public function getAbsoluteFilePath($fileName)
{
return $this->isExist($fileName)
? $this->getMediaDirectory()->getAbsolutePath($this->getFilePath($fileName))
: null;
}

/**
* @param $fileName
* @return array
Expand Down Expand Up @@ -168,7 +180,7 @@ public function isExist($fileName)
* @return bool|string
* @throws \Magento\Framework\Exception\FileSystemException
*/
private function getFilePath($fileName)
public function getFilePath($fileName)
{
$filePath = $this->removeStorePath($fileName);
$filePath = ltrim($filePath, '/');
Expand All @@ -194,9 +206,7 @@ public function isBeginsWithMediaDirectoryPath($fileName)
$filePath = ltrim($filePath, '/');

$mediaDirectoryRelativeSubpath = $this->getMediaDirectoryPathRelativeToBaseDirectoryPath($filePath);
$isFileNameBeginsWithMediaDirectoryPath = strpos($filePath, (string) $mediaDirectoryRelativeSubpath) === 0;

return $isFileNameBeginsWithMediaDirectoryPath;
return strpos($filePath, (string) $mediaDirectoryRelativeSubpath) === 0;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion Model/ResourceModel/Collection/AbstractCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
use Magento\Framework\Api\Search\SearchResultInterface;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection as DbCollection;

abstract class AbstractCollection extends DbCollection implements SearchResultInterface
class AbstractCollection extends DbCollection implements SearchResultInterface
{
/**
* @var AggregationInterface
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ protected function _afterLoad()
/**
* @throws \Exception
*/
public function _renderFiltersBefore()
protected function _renderFiltersBefore()
{
$entityMetadata = $this->metadataPool->getMetadata($this->interfaceClass);
$this->storeResource->joinStoreRelationTable($this, $this->storeTable, $entityMetadata->getLinkField());
Expand Down
22 changes: 11 additions & 11 deletions Model/ResourceModel/StoreAwareAbstractModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,9 @@ private function getEntityId(\Magento\Framework\Model\AbstractModel $object, $va
$entityId = $value;
if ($field != $entityMetadata->getIdentifierField() || $object->getData($this->storeIdField)) {
$select = $this->_getLoadSelect($field, $value, $object);
$select->reset(Select::COLUMNS)
->columns($this->getMainTable() . '.' . $entityMetadata->getIdentifierField())
->limit(1);
$select->reset(Select::COLUMNS);
$select->columns($this->getMainTable() . '.' . $entityMetadata->getIdentifierField());
$select->limit(1);
$result = $this->getConnection()->fetchCol($select);
$entityId = count($result) ? $result[0] : false;
}
Expand Down Expand Up @@ -159,14 +159,14 @@ public function lookupStoreIds($id): array
$idField = $entityMetadata->getIdentifierField();
$linkField = $entityMetadata->getLinkField();

$select = $connection->select()
->from(['entity_store_table' => $this->getTable($this->storeTable)], $this->storeIdField)
->join(
['entity_table' => $this->getMainTable()],
'entity_store_table.' . $linkField . ' = entity_table.' . $linkField,
[]
)
->where('entity_table.' . $entityMetadata->getIdentifierField() . ' = :' . $idField);
$select = $connection->select();
$select->from(['entity_store_table' => $this->getTable($this->storeTable)], $this->storeIdField);
$select->join(
['entity_table' => $this->getMainTable()],
'entity_store_table.' . $linkField . ' = entity_table.' . $linkField,
[]
);
$select->where('entity_table.' . $entityMetadata->getIdentifierField() . ' = :' . $idField);

return $connection->fetchCol($select, [$idField => (int)$id]);
}
Expand Down
56 changes: 33 additions & 23 deletions Model/Uploader.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
namespace Umc\Crud\Model;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\UrlInterface;
Expand Down Expand Up @@ -61,7 +63,10 @@ class Uploader
* @var string
*/
private $basePath;

/**
* @var FileChecker
*/
private $fileChecker;
/**
* @var array
*/
Expand All @@ -74,28 +79,31 @@ class Uploader
* @param UploaderFactory $uploaderFactory
* @param StoreManagerInterface $storeManager
* @param LoggerInterface $logger
* @param $baseTmpPath
* @param $basePath
* @param FileChecker $fileChecker
* @param string $baseTmpPath
* @param string $basePath
* @param array $allowedExtensions
* @throws \Magento\Framework\Exception\FileSystemException
* @throws FileSystemException
*/
public function __construct(
Database $coreFileStorageDatabase,
Filesystem $filesystem,
UploaderFactory $uploaderFactory,
StoreManagerInterface $storeManager,
LoggerInterface $logger,
FileChecker $fileChecker,
string $baseTmpPath,
string $basePath,
array $allowedExtensions = []
) {
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->uploaderFactory = $uploaderFactory;
$this->storeManager = $storeManager;
$this->logger = $logger;
$this->baseTmpPath = $baseTmpPath;
$this->basePath = $basePath;
$this->allowedExtensions = $allowedExtensions;
$this->uploaderFactory = $uploaderFactory;
$this->storeManager = $storeManager;
$this->logger = $logger;
$this->fileChecker = $fileChecker;
$this->baseTmpPath = $baseTmpPath;
$this->basePath = $basePath;
$this->allowedExtensions = $allowedExtensions;
$this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
}

Expand Down Expand Up @@ -146,15 +154,22 @@ public function getFilePath($path, $name)
*
* @param string $name
* @return string
* @throws \Magento\Framework\Exception\LocalizedException
* @throws LocalizedException
*/
public function moveFileFromTmp($name)
{
$baseTmpPath = $this->getBaseTmpPath();
$basePath = $this->getBasePath();

$baseFilePath = $this->getFilePath($basePath, $name);
$baseTmpFilePath = $this->getFilePath($baseTmpPath, $name);
$baseFilePath = $this->getFilePath(
$basePath,
$this->fileChecker->getNewFileName(
$this->mediaDirectory->getAbsolutePath(
$this->getFilePath($basePath, $name)
)
)
);

try {
$this->coreFileStorageDatabase->copyFile(
Expand All @@ -175,9 +190,8 @@ public function moveFileFromTmp($name)
}

/**
* get base url
*
* @return string
* @return mixed
* @throws NoSuchEntityException
*/
public function getBaseUrl()
{
Expand All @@ -189,13 +203,10 @@ public function getBaseUrl()
}

/**
* Checking file for save and save it to tmp dir
*
* @param string $fileId
*
* @return string[]
*
* @throws \Magento\Framework\Exception\LocalizedException
* @param $fileId
* @return array|bool
* @throws LocalizedException
* @throws NoSuchEntityException
*/
public function saveFileToTmpDir($fileId)
{
Expand Down Expand Up @@ -231,7 +242,6 @@ public function saveFileToTmpDir($fileId)
);
}
}

return $result;
}
}
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ This module is intended for Magento 2 developers, in order to reduce the boilerp

## Compatibility

This module was developed an tested on Magento Open Source 2.3.4. I plan to support this for later versions also.
This module was developed and tested on Magento Open Source 2.3.4 and 2.3.5. I plan to support this for later versions also.
It may work for versions before 2.3.4, but I didn't test.

## What it does:
Expand All @@ -30,7 +30,7 @@ And the only variables here are
This module provides a general admin `Save` controller that has as dependencies a set of other classes / interfaces that have only one of the responsibilities above
- an Entity manager responsible for retrieving the data from db or instantiating a new entity
- a data processor (interface) that processes the data
- an entity config class that will contain the details about the entity being processed.
- an entity config class will contain the details about the entity being processed.
- side objects: a data persistor (which is basically the session) to save the data submitted in case there is an error and you need to redirect back to the form with the previously submitted data prefilled.

All of these can be configured via `di.xml` for each entity you want to manage.
Expand All @@ -48,10 +48,10 @@ This module also adds a few more code generators (similar to the core ones for f

## Advantages in using this module
- less code to write, which means less code to test and less code that can malfunction
- your copy/paste analyzer will stop compalining that you have classes that look the same.
- your copy/paste analyzer will stop complaining you have classes that look the same.
- decrease development time. (hopefully)
- you will have a standard way of writing all your CRUD modules (no matter if it's good or bad, at least it is consistent)
- This covers most of the cases you will encounter in your development process. If one of your cases is not covered by this module you can chose not to extend or compose the classes in this module and use your own.
- This covers most of the cases you will encounter in your development process. If one of your cases is not covered by this module you can choose not to extend or compose the classes in this module and use your own.


## Disadvantages of using this module
Expand All @@ -67,8 +67,8 @@ This module also adds a few more code generators (similar to the core ones for f
- download a copy from `https://github.com/UltimateModuleCreator/umc-crud` and all the files in `app/code/Umc/Crud`.

After installation
- check if this file exists `app/etc/crud/di.xml`. If it does not exist, run the commmand `bin/magento umc:crud:deploy`. If you get an error you can copy it from `vendor/umc/module-crud/etc/crud/di.xml` to `app/etc/crud/di.xml`
- run `bin/magento setup:upgrade`
- run `php bin/magento setup:upgrade [--keep-generated]`
- check if this file exists `app/etc/crud/di.xml`. If it does not exist, run the command `bin/magento umc:crud:deploy`. If you get an error you can copy it from `vendor/umc/module-crud/etc/crud/di.xml` to `app/etc/crud/di.xml`.

# Documentation

Expand Down
24 changes: 24 additions & 0 deletions Test/Unit/Generator/ListRepoTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
use ReflectionParameter;
use Umc\Crud\Generator\ListRepo;
use Umc\Crud\Generator\NameMatcher;
use Umc\Crud\Model\ResourceModel\StoreAwareAbstractModel;

class ListRepoTest extends TestCase
{
Expand Down Expand Up @@ -98,4 +99,27 @@ public function testGenerate()
$this->classGenerator->expects($this->once())->method('generate')->willReturn('generated code');
$this->assertEquals('filename.php', $this->listRepo->generate());
}

/**
* @covers \Umc\Crud\Generator\ListRepo
*/
public function testGenerateStoreAwareModel()
{
$this->ioObject->expects($this->once())->method('generateResultFileName')->willReturn('filename.php');
$this->nameMatcher->expects($this->once())->method('getListRepoInterface');
$this->nameMatcher->expects($this->any())->method('getSearchResultsClass');
$this->nameMatcher->expects($this->any())->method('getSearchResultFactory')->willReturn('searchResults');
$this->nameMatcher->expects($this->any())->method('getCollectionFactoryClass');
$class = $this->createMock(StoreAwareAbstractModel::class);
$this->nameMatcher->method('getResourceClassName')->willReturn(get_class($class));
$this->definedClasses->method('isClassLoadable')->willReturn(true);
$this->ioObject->method('makeResultFileDirectory')->willReturn(true);
$this->ioObject->method('fileExists')->willReturn(true);
$this->classGenerator->expects($this->once())->method('setName')->willReturnSelf();
$this->classGenerator->expects($this->once())->method('addProperties')->willReturnSelf();
$this->classGenerator->expects($this->once())->method('addMethods')->willReturnSelf();
$this->classGenerator->expects($this->once())->method('setClassDocBlock')->willReturnSelf();
$this->classGenerator->expects($this->once())->method('generate')->willReturn('generated code');
$this->assertEquals('filename.php', $this->listRepo->generate());
}
}
Loading

0 comments on commit 59dc7ce

Please sign in to comment.