Commit b6b45de1 by halweg

csv导入评论脚本

parent b9ca17a4
<?php
namespace Joshine\Script\Console\Command;
use Joshine\Review\Helper\ImageHelper;
use Joshine\Review\Model\ImageUploader;
use Magento\Framework\App\Area;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\App\State;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\File\Csv;
use Magento\Framework\ObjectManager\ObjectManager;
use Magento\Setup\Exception;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Review\Model\Review;
use Magento\Customer\Model\Customer;
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;
class ReviewsImporter extends Command
{
/**
* @var Csv
*/
private $csv;
/**
* @var Customer
*/
private $customer;
/**
* @var DirectoryList
*/
private $directoryList;
/**
* @var ResourceConnection
*/
private $resource;
/**
* @var AdapterInterface
*/
private $connection;
/**
* @var State
*/
private $state;
/**
* @var Magento\Customer\Model\ResourceModel\Customer\Collection
*/
private $collection;
/**
* @var CollectionFactory
*/
private $collectionFactory;
const FILE = "csv";
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @var OutputInterface
*/
private $_output;
/**
* @var mixed
*/
private $storeId;
/**
* @var ImageUploader
*/
private $imageUploader;
/**
* @var \Joshine\Review\Model\ImagesFactory
*/
private $imagesFactory;
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
private $messageManager;
/**
* @var \Joshine\Review\Model\ResourceModel\Images
*/
private $imagesResource;
/**
* @var \Magento\Framework\Filesystem
*/
private $filesystem;
public function __construct(
\Magento\Framework\Filesystem $filesystem,
ObjectManager $objectManager,
CollectionFactory $collectionFactory,
Csv $csv,
Customer $customer,
DirectoryList $directoryList,
ResourceConnection $resource,
State $state,
\Magento\Framework\Filesystem\Io\File $ioFile,
\Magento\Framework\App\RequestInterface $request,
ImageUploader $imageUploader,
\Joshine\Review\Model\ImagesFactory $imagesFactory,
\Magento\Framework\Message\ManagerInterface $messageManager,
\Joshine\Review\Model\ResourceModel\Images $imagesResource,
string $name = null
)
{
parent::__construct($name);
$this->imageUploader = $imageUploader;
$this->filesystem = $filesystem;
$this->imagesFactory = $imagesFactory;
$this->messageManager = $messageManager;
$this->imagesResource = $imagesResource;
$this->collectionFactory = $collectionFactory;
$this->csv = $csv;
$this->customer = $customer;
$this->directoryList = $directoryList;
$this->state = $state;
$this->ioFile = $ioFile;
}
protected function configure()
{
$this->setName('joshine:review-import');
$this->setDescription('导入产品评论');
$this->setDefinition([
new InputOption('csv-path', null, InputOption::VALUE_OPTIONAL, 'import the csv file'),
]);
$this->addOption(
self::FILE,
null,
InputOption::VALUE_REQUIRED,
'csv路径'
);
$this->addOption(
"store_id",
null,
InputOption::VALUE_REQUIRED,
'store id'
);
parent::configure();
}
protected function execute(
InputInterface $input,
OutputInterface $output
)
{
$this->_output = $output;
try {
$path = $input->getOption(self::FILE);
if (!$path) {
$output->writeln($this->errorWrapper("路径不对"));
return;
}
$storeId = $input->getOption('store_id');
if (!$storeId) {
$output->writeln($this->errorWrapper("store_id没填"));
return;
}
$this->storeId = $storeId;
$this->importCsvFile($path);
} catch (\Exception $e) {
$output->writeln($this->errorWrapper($e->getMessage()));
}
}
private function importCsvFile($filename)
{
$data = $this->loadAndCheck($filename);
$data = $this->formatImagePath($data);
foreach ($data as $row) {
$this->insertDB($row);
}
}
private function insertDB($data)
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$reviewFactory = $objectManager->get("Magento\Review\Model\ReviewFactory");
$ratingFactory = $objectManager->get("Magento\Review\Model\RatingFactory");
$productId = $objectManager->get('Magento\Catalog\Model\Product')->getIdBySku('202301-Black');
if ($productId) {
$review = $reviewFactory->create()->setData($data);
$review->unsetData('review_id');
$review->setEntityId($review->getEntityIdByCode(Review::ENTITY_PRODUCT_CODE))
->setEntityPkValue($productId)
->setStatusId(Review::STATUS_PENDING)
->setStoreId($this->storeId)
->setStores([$this->storeId])
->save();
$rating = [];
//前端实测
$rating[4] = strval($data['ratings'] + 15);
foreach ($rating as $ratingId => $optionId) {
$ratingFactory->create()
->setRatingId($ratingId)
->setReviewId($review->getId())
->addOptionVote($optionId, $productId);
}
$review->aggregate();
$this->storeImage($data['image'], $review->getId());
}
}
private function storeImage($images, $id)
{
foreach ($images as $image) {
$result = $this->copy($image);
if ($result) {
$this->saveImage($result, $id);
}
}
}
public function copy(string $imagePath)
{
$from = $imagePath;
if ($this->ioFile->fileExists($from)) {
$realPath = $this->filesystem->getDirectoryRead(
DirectoryList::MEDIA
)->getAbsolutePath(
ImageHelper::IMAGE_PATH
);
$counter = 0;
while ($this->ioFile->fileExists($realPath . $imagePath)) {
$imagePathArray = explode('.', $imagePath);
$imagePathArray[0] .= $counter++;
$imagePath = implode('.', $imagePathArray);
}
$this->ioFile->checkAndCreateFolder($this->ioFile->dirname($realPath . $imagePath));
if ($this->ioFile->mv($from, $realPath . $imagePath)) {
return $imagePath;
}
}
return false;
}
private function formatImagePath($data)
{
foreach ($data as $index => $row) {
if (!empty($row["image"])) {
$urls = array_filter(explode("https://", $row["image"]));
$path = $this->downLoadImage($urls);
$data[$index]['image'] = $path;
}
}
return $data;
}
private function downLoadImage($urls)
{
$res = [];
$path = $this->directoryList->getPath('var');
foreach ($urls as $index => $url) {
$url = trim($url, ",");
$url = trim($url, " ");
$url = trim($url, ",");
$url = trim($url, ",");
$url = trim($url, ".");
$url = trim($url, ".");
$url = trim($url, ",");
$file = $path.DIRECTORY_SEPARATOR.mt_rand(10000,99999).time().md5($url).".jpeg";
if(!file_exists($file)){
$this->_output->writeln($this->successWrapper("图片${url}下载中..."));
try {
file_put_contents($file,file_get_contents("https://".$url));
$res[] = $file;
} catch (\Exception $e) {
$output->writeln($this->errorWrapper($e->getMessage()));
}
}else{
$this->_output->writeln($this->errorWrapper("图片${url}已下载过"));
$res[] = $file;
}
}
return $res;
}
private function loadAndCheck($filename)
{
$file = $this->directoryList->getPath('var') . DIRECTORY_SEPARATOR . $filename;
$csvData = fopen($file, 'r');
$data = [];
$firstLine = true;
while ($row = fgetcsv($csvData)) {
if ($firstLine == true) {
$this->checkHeader($row);
$firstLine = false;
continue;
}
$review['sku'] = $row[0];
$review['detail'] = $row[3];
$review['nickname'] = $row[1];
$review['date'] = $row[5];
$review['image'] = $row[4];
$review['ratings'] = $row[2];
$review['title'] = 'test';
if (empty(trim($review["sku"])) || empty(trim($review["detail"]) || empty(trim($review['nickname'])) || empty($review['date']))
) {
throw new \Exception("表格数据有空: {$row["name"]}");
}
$data[] = $review;
break;
}
fclose($csvData);
return $data;
}
/**
* @return \Magento\Customer\Model\ResourceModel\Customer\Collection
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function getCollection()
{
$this->collection = $this->collectionFactory->create();
$this->collection->addAttributeToSelect(['entity_id', 'firstname', 'lastname', 'email']);
return $this->collection;
}
private function successWrapper($msg)
{
return "<info>$msg</info>";
}
private function errorWrapper($msg)
{
return "<error>$msg</error>";
}
private function checkHeader($header)
{
$field = [
//'size_fits',
'sku',
'name',
'content',
'rating',
'image',
'date'
];
foreach ($field as $row) {
if (!in_array($row, $header)) {
throw new \Exception("表格字段不全!,必须包含".implode(' ',$field));
}
}
}
/**
* @return array
*/
private function getHeaders($line)
{
if (count($line) < 7 ) {
throw new \Exception("csv格式不对!");
}
if ($line[0] != 'sku') {
throw new \Exception("第一列应该是sku!");
}
if ($line[1] != 'name') {
throw new \Exception('第2列应该是name');
}
if ($line[2] != 'rating') {
throw new \Exception('第3列应该是rating');
}
if ($line[3] != 'content') {
throw new \Exception('第4列应该是content');
}
if ($line[4] != 'image') {
throw new \Exception('第二列应该是image');
}
if ($line[5] != 'date') {
throw new \Exception('第二列应该是date');
}
return $line;
}
private function saveImage($result, $reviewId)
{
$model = $this->imagesFactory->create();
$model->setReviewId($reviewId);
$model->setPath($result['file']);
if ($model->getImageId()) {
$model = $this->getFullImage($model->getImageId())->addData($model->getData());
}
$this->imagesResource->save($model);
}
private function getFullImage($imageId) {
$image = $this->imagesFactory->create();
$this->imagesResource->load($image, $imageId);
if (!$image->getImageId()) {
throw new NoSuchEntityException(__('Rule with specified ID "%1" not found.', $imageId));
}
return $image;
}
}
......@@ -6,6 +6,9 @@
<argument name="commands" xsi:type="array">
<item name="joshine_fix-base-image" xsi:type="object">Joshine\Script\Console\Command\ProductFirstImageAsBaseFixer</item>
</argument>
<argument name="commands" xsi:type="array">
<item name="reviews-import" xsi:type="object">Joshine\Script\Console\Command\ReviewsImporter</item>
</argument>
</arguments>
</type>
</config>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment