FeedController.php 1.75 KB
<?php
/**
 * Created by PhpStorm.
 * User: Alex Savenko
 * Date: 05.12.2016
 * Time: 18:36
 */

namespace console\controllers;

use yii\console\Controller;
use Yii;
use yii\helpers\Url;
use common\modules\product\models\Product;

use common\modules\product\models\Category;
use frontend\models\ProductFrontendSearch;
use common\models\Page;
use yii\filters\VerbFilter;

use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;


class FeedController extends Controller
{
    private $urlList = [];
    private $count = 1;

    public function getProducts() {
        return Product::find()->limit(100)->all();
    }

    public function checkUrl($url){
        if(!in_array($url, $this->urlList)){
            $this->urlList[] = $url;
            return true;
        } else {
            return false;
        }
    }

    public function createRow( $product, &$content ){
        $url = Url::to(['catalog/product', 'product' => $product]);
        if($this->checkUrl($url)){
            print $url;
            print $this->count++ . "\n";
            $content[] = [$url];
        }
    }

    public function actionProcess() {

        $dirName = Yii::getAlias('@frontend').'/web';
        $filename = 'feed.csv';
        setlocale(LC_ALL, 'ru_RU.CP1251');

        $handle = fopen($dirName .'/'. $filename, "w");

        $content[] = ['ID', 'ID2', 'Item Category', 'Item title', 'Item description', 'Price'];
        $content[] = ['ID', 'ID2', 'Item Category', 'Item title', 'Item description', 'Price'];

        foreach ($this->getProducts() as $product) {
            $this->createRow($product, $content);
        }

        foreach ($content as $item) {
            fputcsv($handle, $item);
        }
        fclose($handle);

        print $dirName .'/'. $filename;
    }
}