<?php
namespace Kiwi\EshopBundle\Service;
use Kiwi\EshopBundle\Entity\Product;
use Kiwi\EshopBundle\Entity\ProductHolders;
use Symfony\Component\HttpFoundation\Request;
class EshopGatewayHandle {
var $controller = null;
protected $languages;
/**
* @var \Doctrine\ORM\EntityManager
*/
private $em;
/**
* @var \Kiwi\PageBundle\Twig\PageExtensions
*/
private $pageExtensions;
/**
* @var \Kiwi\EshopBundle\Service\EshopProductsHandle
*/
private $eshopProductsHandle;
/**
* @var \Kiwi\SearchBundle\Service\SearchHandle
*/
private $searchHandle;
/**
* @var \Kiwi\EshopBundle\Service\EshopCategoriesHandle
*/
private $eshopCategoriesHandle;
/**
* @var \Kiwi\EshopBundle\Service\EshopParamsHandle
*/
private $eshopParamsHandle;
/**
* @var \Kiwi\EshopBundle\Service\EshopProducersHandle
*/
private $eshopProducersHandle;
/**
* @var \Kiwi\EshopBundle\Service\EshopAttachementsHandle
*/
private $eshopAttachementsHandle;
public function __construct(\Doctrine\ORM\EntityManager $em,
\Kiwi\LanguagesBundle\Service\LanguagesHandle $languages,
\Kiwi\PageBundle\Twig\PageExtensions $pageExtensions,
\Kiwi\EshopBundle\Service\EshopProductsHandle $eshopProductsHandle,
\Kiwi\SearchBundle\Service\SearchHandle $searchHandle,
\Kiwi\EshopBundle\Service\EshopCategoriesHandle $eshopCategoriesHandle,
\Kiwi\EshopBundle\Service\EshopParamsHandle $eshopParamsHandle,
\Kiwi\EshopBundle\Service\EshopProducersHandle $eshopProducersHandle,
\Kiwi\EshopBundle\Service\EshopAttachementsHandle $eshopAttachementsHandle) {
$this->em = $em;
$this->languages = $languages;
$this->pageExtensions = $pageExtensions;
$this->eshopProductsHandle = $eshopProductsHandle;
$this->searchHandle = $searchHandle;
$this->eshopCategoriesHandle = $eshopCategoriesHandle;
$this->eshopParamsHandle = $eshopParamsHandle;
$this->eshopProducersHandle = $eshopProducersHandle;
$this->eshopAttachementsHandle = $eshopAttachementsHandle;
}
public function setController($controller) {
$this->controller = $controller;
return $this;
}
public function getCategories($config, Request $request) {
$main_category = explode('/',$request->getUri()); $main_category = end($main_category);
return $this->eshopCategoriesHandle->getCategoriesBySeoName($main_category);
}
public function getParam($config, Request $request) {
$code = null;
if(isset($config['method_params'])) {
if(isset($config['method_params'][0])) {
$code = $config['method_params'][0];
}
}
if(!$config) {
return false;
}
$param = $this->eshopParamsHandle->getCustomParamByCode($code);
$list = $this->eshopParamsHandle->getCustomParamList($param->getId());
foreach ($list as $l) {
$l->full_link = $this->controller->get('page_twig_extension')->kpathFunction(12, $config['lang']);
$l->full_link .= $l->getCode();
}
return array(
'param' => $param,
'list' => $list
);
return $code;
}
private function getUrlCategory(Request $request){
$uri = explode('?', $request->getRequestUri());
$uri = explode('/', $uri[0]);
return $this->eshopCategoriesHandle->getCategoryBySeoName(end($uri));
}
private function getUrlKolekce(Request $request){
$uri = explode('?', $request->getRequestUri());
$uri = explode('/', $uri[0]);
return $this->eshopParamsHandle->getCustomListParamByCode(4, end($uri));
}
private function getUrlProducer(Request $request){
$uri = explode('?', $request->getRequestUri());
$uri = explode('/', $uri[0]);
return $this->eshopProducersHandle->getProducerByCode(end($uri));
}
private function getUrlStyl(Request $request){
$uri = explode('?', $request->getRequestUri());
$uri = explode('/', $uri[0]);
return $this->eshopParamsHandle->getCustomListParamByCode(9, end($uri));
}
private function getQQdataCategory(Request $request) {
$category = $this->getUrlCategory($request);
$qq = $request->get('qq');
if($category) {
$qq[0][$category->getId()] = 'on';
}
return $qq;
}
private function getQQdataKolekce(Request $request) {
$kolekce = $this->getUrlKolekce($request);
$qq = $request->get('qq');
if($kolekce) {
$qq[$kolekce->getCustomParamId()][$kolekce->getId()] = 'on';
}
return $qq;
}
private function getQQdataStyle(Request $request) {
$styl = $this->getUrlStyl($request);
if($styl) {
$qq[$styl->getCustomParamId()][$styl->getId()] = 'on';
}
return $qq;
}
public function getFilterData($config, Request $request) {
$context = null;
if(isset($config['method_params'])) {
if(isset($config['method_params'][0])) {
$context = $config['method_params'][0];
}
}
switch ($context) {
default:
$category = $this->getUrlCategory($request);
$qq = $this->getQQdataCategory($request);
break;
case 'style':
//$category = $this->getUrlCategory($request);
$category = null;
$qq = $this->getQQdataStyle($request);
break;
/*
case 'material':
$qq = $this->getQQdataCategory($request);
break;
case 'kolekce':
$qq = $this->getQQdataKolekce($request);
break;
*/
}
$fillingProducts = $this->getProducts($config, $request);
$fillingProductsAgreagted = [];
$fillingProductsCategoriesAgreagted = [];
foreach($fillingProducts['result']['data'] as $ag_product) {
//if($ag_product['id'] == 185)
// return $ag_product;
//categories filler
if(isset($ag_product['master_category'])) {
if(isset($ag_product['master_category']['id'])) {
$fillingProductsCategoriesAgreagted[] = $ag_product['master_category']['id'];
}
}
//params filler
foreach($ag_product['params_full'] as $ag_product_param) {
//declare if not defined
if(!isset($fillingProductsAgreagted[$ag_product_param['id']])) {
$fillingProductsAgreagted[$ag_product_param['id']] = [];
}
//agregate enabled values
if(count($ag_product_param['current']) >= 1) {
foreach($ag_product_param['current'] as $ag_product_param_current) {
if(!in_array($ag_product_param_current, $fillingProductsAgreagted[$ag_product_param['id']])) {
$fillingProductsAgreagted[$ag_product_param['id']][] = $ag_product_param_current;
}
}
}
}
}
$fillingProductsCategoriesAgreagted = array_unique($fillingProductsCategoriesAgreagted);
$ret = [];
if($category) {
$cpl = $this->eshopParamsHandle->getCustomParamsCategoryFiltered($category);
} else {
$cpl = $this->eshopParamsHandle->getCustomParams();
}
foreach($cpl as $opt){
if($opt->getIsVisible()) {
$options = $this->eshopParamsHandle->getCustomParamList($opt->getId(), (isset($fillingProductsAgreagted[$opt->getId()])) ? $fillingProductsAgreagted[$opt->getId()] : []);
if(count($options) >= 1) {
$ret[] = array(
'id' => $opt->getId(),
'name' => $opt->getName(),
'code' => $opt->getCode(),
'type' => $opt->getType(),
'options' => $options
);
}
}
}
if(is_null($category) or $category->getOptFour()) {
$ret[] = array(
'id' => 0,
'name' => '<?xml version="1.0" encoding="utf-8" ?><data><cz><![CDATA[Material]]></cz></data>',
'code' => 'category',
'type' => "list-multiple",
'options' => $this->eshopCategoriesHandle->getCategories(0, false, 'cz', $fillingProductsCategoriesAgreagted)
);
}
/*
* "id" => 2
"name" => "<?xml version="1.0" encoding="utf-8" ?><data><cz><![CDATA[Styl]]></cz></data>"
"code" => "style"
"type" => "list-multiple"
"options" => array:14 [▶]
]
* */
return array(
'data' => $ret,
'qq' => $qq,
'test' => $fillingProductsAgreagted,
'test2' => $fillingProducts['result']['data']
);
}
public function getProductsByProducer($config, Request $request) {
$producer = $this->getUrlProducer($request);
if(!$producer) {
return false;
}
$search = clone $this->searchHandle;
$search->generateRn();
$search->setRequest($request)
->setFrom($this->eshopCategoriesHandle->repo_categories,'c')
->setJoin('c.product', 'p')
->setJoin('p.producer', 'pr')
//->setJoin('h.article', 'a')
->addWhere('p.is_holder = true')
->addWhere('p.eshop_id = '.$this->eshopProductsHandle->getEshop()->getId())
->addWhere('pr.id = '.$producer->getId())
//->setSearchTextLike('p.transport_code', 'Kód')
//->setSearchTextLike('a.name', 'Jméno')
//->addWhere('p.eshop_id = '.$this->get('eshop_products_handle')->getEshop()->getId())
//->setSearchSelect('u.order_state')
//->setSearchTextLike('us.username', 'Uživatelské jméno')
//->setSearchTextLike('a.content', 'Jméno společnosti')
//->setSearchDateRange('u.created_time', 'Vytvořena')
->setSortMask(array())
->setRpp(99999);
//return $search->getResult();
$search->groupBy('p.id');
$holders_rs = $search->getResult();
//print_r($holders_rs['config']['query']); exit;
$_holders = [];
foreach ($holders_rs['data'] as $product) {
//$_holders[] = $product->getProduct();
//$_holders[] = $this->processHolder($product->getProduct());
$_holders[] = $this->eshopProductsHandle->getProductReturnArrayBlock($product->getProduct(), 'cz', []);
}
$holders_rs['data'] = $_holders;
return [
'producer' => $producer,
'search' => $search,
'form' => $search->getForm(),
'result' => $holders_rs,
'result_type' => 'holders'
//'paginator' => $this->controller->get('templating')->render('KiwiPaginatorBundle:Kbox:buttons.html.twig',array('paginator' => $holders_rs['config']['paginator'])),
];
}
public function getProducts($config, Request $request) {
$context = null;
if(isset($config['method_params'])) {
if(isset($config['method_params'][0])) {
$context = $config['method_params'][0];
}
}
$category = null;
switch ($context) {
default:
$category = $this->getUrlCategory($request);
$qq = $this->getQQdataCategory($request);
break;
case 'style':
//$category = $this->getUrlCategory($request);
$category = null;
$qq = $this->getQQdataStyle($request);
break;
/*
case 'material':
$qq = $this->getQQdataCategory($request);
break;
case 'kolekce':
$qq = $this->getQQdataKolekce($request);
break;
*/
}
if($qq) {
$products = [];
$required_score = count($qq);
foreach ($qq as $param_id => $opts) {
if($param_id == 0) {
$promoted = [];
foreach (array_keys($opts) as $_opt) {
foreach ($this->eshopCategoriesHandle->getCategoryProducts($_opt, false) as $_product) {
$pid = $_product->getProduct()->getId();
if(!in_array($pid, $promoted)) {
$products[$pid] = (isset($products[$pid])) ? ($products[$pid]+1) : 1;
$promoted[] = $pid;
}
}
}
} else {
$promoted = [];
foreach ($this->eshopParamsHandle->getCustomCoParamsByParamId($param_id) as $_opt) {
//print_r([$_opt->getProductId()]);
$pid = $_opt->getProductId();
$intersection = array_intersect(
array_keys(
$opts
),
array_keys(
unserialize($_opt->getParamValue())
)
);
if(count($intersection) >= 1) {
if(!in_array($pid, $promoted)) {
$products[$pid] = (isset($products[$pid])) ? ($products[$pid]+1) : 1;
$promoted[] = $pid;
}
}
}
}
}
$products_temp = $products;
$products = [];
foreach ($products_temp as $product_key => $product_score) {
if($product_score == $required_score) {
$products[] = $product_key;
}
}
//this is not needed at this context
/*
$products_rs = [];
//foreach (array_slice($products, 0, 99999) as $product_id) {
foreach ($products as $product_id) {
$products_rs[] = $this->eshopProductsHandle->getProductReturnArrayBlock(
$this->eshopProductsHandle->getProduct($product_id),
$config['lang'],
[]
);
}
*/
/*
$holders_rs = [];
foreach ($products as $product_id) {
$product = $this->eshopProductsHandle->getProduct($product_id);
if($product->getIsHidden() == false or is_null($product->getIsHidden())) {
if($product->getIsDeleted() == false or is_null($product->getIsDeleted())) {
if(!array_key_exists($product->getHolder()->getId(), $holders_rs)) {
$holders_rs[$product->getHolder()->getId()] = $this->processHolder($product->getHolder());
}
}
}
}
*/
$holders_rs = [];
foreach ($products as $product_id) {
$product = $this->eshopProductsHandle->getProduct($product_id);
if($product->getIsHidden() == false or is_null($product->getIsHidden())) {
if($product->getIsDeleted() == false or is_null($product->getIsDeleted())) {
if(!array_key_exists($product->getId(), $holders_rs)) {
//$holders_rs[$product->getId()] = $this->processHolder($product);
$holders_rs[$product->getId()] = $this->eshopProductsHandle->getProductReturnArrayBlock($product, 'cz', []);
}
}
}
}
return [
//'search' => $search,
//'form' => $search->getForm(),
'qq' => $qq,
//'result_products' => $products_rs,
'result' => array('data' => $holders_rs),
'result_type' => 'holders'
//'paginator' => $this->controller->get('templating')->render('KiwiPaginatorBundle:Kbox:buttons.html.twig',array('paginator' => $holders_rs['config']['paginator'])),
];
}
/*
* $qb = $this->em->createQueryBuilder();
$qb->select('c')
->from($phObj->repo_categories, 'c')
->join('c.product', 'p')
->where('c.category_id = :category_id')
->andWhere('p.is_deleted = false')
->andwhere('p.eshop_id = '.$phObj->getEshop()->getId())
->setParameter('category_id', (int)$category_id)
->setMaxResults(1000);
if(!$show_hidden) {
$qb->andWhere('p.is_hidden = false OR p.is_hidden IS NULL');
}
* */
$search = clone $this->searchHandle;
$search->generateRn();
$search->setRequest($request)
->setFrom($this->eshopCategoriesHandle->repo_categories,'c')
->setJoin('c.product', 'p')
->setJoin('p.producer', 'pr')
//->setJoin('h.article', 'a')
->addWhere('p.is_holder = true')
->addWhere('p.eshop_id = '.$this->eshopProductsHandle->getEshop()->getId())
//->setSearchTextLike('p.transport_code', 'Kód')
//->setSearchTextLike('a.name', 'Jméno')
//->addWhere('p.eshop_id = '.$this->get('eshop_products_handle')->getEshop()->getId())
//->setSearchSelect('u.order_state')
//->setSearchTextLike('us.username', 'Uživatelské jméno')
//->setSearchTextLike('a.content', 'Jméno společnosti')
//->setSearchDateRange('u.created_time', 'Vytvořena')
->setSortMask(array())
->setRpp(99999);
if($category) {
$search->addWhere('c.category_id = '.$category->getId());
}
if($request->get('q')) {
$search->setSearchTextLike('a.name', 'Jméno');
$search->addWhere('
p.code LIKE \'%'.addslashes($request->get('q')).'%\' OR
pr.name LIKE \'%'.addslashes($request->get('q')).'%\' OR
p.name LIKE \'%'.addslashes($request->get('q')).'%\'
');
}
/*
$search = clone $this->searchHandle;
$search->setRequest($request)
->setFrom('Kiwi\EshopBundle\Entity\ProductHolders','p')
->setJoin('p.article','a')
->setSearchTextLike('p.transport_code', 'Kód')
->setSearchTextLike('a.name', 'Jméno')
//->addWhere('p.eshop_id = '.$this->get('eshop_products_handle')->getEshop()->getId())
//->setSearchSelect('u.order_state')
//->setSearchTextLike('us.username', 'Uživatelské jméno')
//->setSearchTextLike('a.content', 'Jméno společnosti')
//->setSearchDateRange('u.created_time', 'Vytvořena')
->setSortMask(array())
->setRpp(25);
if($request->get('q')) {
$search->addWhere('
p.transport_code LIKE \'%'.addslashes($request->get('q')).'%\' OR
a.name LIKE \'%'.addslashes($request->get('q')).'%\'
');
}
*/
//return $search->getResult();
$search->groupBy('p.id');
$holders_rs = $search->getResult();
//print_r($holders_rs['config']['query']); exit;
$_holders = [];
foreach ($holders_rs['data'] as $product) {
//$_holders[] = $product->getProduct();
//$_holders[] = $this->processHolder($product->getProduct());
$_holders[] = $this->eshopProductsHandle->getProductReturnArrayBlock($product->getProduct(), 'cz', []);
}
$holders_rs['data'] = $_holders;
return [
'search' => $search,
'form' => $search->getForm(),
'result' => $holders_rs,
'result_type' => 'holders'
//'paginator' => $this->controller->get('templating')->render('KiwiPaginatorBundle:Kbox:buttons.html.twig',array('paginator' => $holders_rs['config']['paginator'])),
];
}
public function getActionProducts($config, Request $request) {
return $this->eshopProductsHandle->findProducts('cz', array('action' => 1))['filtered'];
}
public function getCatalogues($config, Request $request) {
return $this->eshopAttachementsHandle->getAllCatalogues();
}
public function getProductsByStyle($config, Request $request) {
}
public function getProduct($config, Request $request) {
$uri = explode('/', $request->getRequestUri());
$id = end($uri); $id = explode("?",$id); $id = $id[0];
//search for holder
$search = clone $this->searchHandle;
$search->setRequest($request)
->setFrom('Kiwi\EshopBundle\Entity\Product','p')
->addWhere(sprintf("p.id = %d", $id))
->addWhere('p.is_holder = true')
->setSortMask(array())
->setRpp(1);
$holder = $search->getResult();
$product = null;
if(!isset($holder['data'][0])) {
//if holder not found try extrapolate from product
$search = clone $this->searchHandle;
$search->setRequest($request)
->setFrom('Kiwi\EshopBundle\Entity\Product','p')
->addWhere(sprintf("p.id = %d", $id))
->addWhere('p.is_holder = false')
->setSortMask(array())
->setRpp(1);
$product = $search->getResult();
if(isset($product['data'][0])) {
$product = $product['data'][0];
$holder['data'][0] = $product->getHolder();
}
}
if(!isset($holder['data'][0])) {
$product = null;
//if holder not found try extrapolate from holder name
$search = clone $this->searchHandle;
$search->setRequest($request)
->setFrom('Kiwi\EshopBundle\Entity\ProductHolders','p')
->setJoin('p.article', 'a')
->addWhere('a.name LIKE \'%'.addslashes($id).'%\'')
->setSortMask(array())
->setRpp(1);
$holder = $search->getResult();
}
if(!isset($holder['data'][0])) {
return false;
}
//return $this->eshopProductsHandle->getProductReturnArrayBlock($holder['data'][0], 'cz', []);
//return $holder['data'][0];
$out = $this->processHolderExtended($holder['data'][0], 'cz', $product);
if(count($out['variants']) <= 0) {
//return false;
}
if(isset($out['id'])) {
if($config['response']) {
$this->eshopProductsHandle->storeCookieProductReference($out['id'], $request, $config['response']);
}
}
if(isset($out['id'])) {
$seotitle = 'F.a.r.line - '.$out['name'];
$seodescription = strip_tags($out['description']);
$seoimage = $out['main_product_image'];
$this->controller->get('page_frontend_handle')->setPageMeta($seotitle,$seoimage,$seodescription);
}
return $out;
}
public function getProducers($config, Request $request) {
return $this->eshopProducersHandle->getProducers(null,true, true);
}
public function getProducer($config, Request $request) {
$producer = $this->getUrlProducer($request);
if(!$producer) {
return false;
}else{
$out = $this->eshopProducersHandle->getProducers($producer,true, true);
$seotitle = 'F.a.r.line - '.$this->languages->getLangEntry($out->getName(), 'cz');
$seodescription = strip_tags($out->getArticle()->getContent());
$seoimage = '/cut-image-strict/640/480/'.$out->getImage()->getName().'.'.$out->getImage()->getExtension();
$this->controller->get('page_frontend_handle')->setPageMeta($seotitle,$seoimage,$seodescription);
}
return $this->eshopProducersHandle->getProducers($producer,true, true);
}
private function processHolder(Product $holder, $lang = 'cz') {
return $this->eshopProductsHandle->getProductReturnArrayBlock($holder, $lang, []);
return [
'id' => $holder->getId(),
'code' => $holder->getCode(),
'name' => $this->languages->getLangEntry($holder->getName(), $lang),
'images_id' => [
'main' => ($holder->getArticle()->getImage()) ? $holder->getArticle()->getImage()->getId() : null
],
'url' => [
'detail' => $this->getHolderUrl($holder, $lang)
]
];
}
private function processHolderExtended(Product $holder, $lang = 'cz', Product $active_product = null) {
$data = $this->processHolder($holder, $lang);
$search = clone $this->searchHandle;
//->setRequest($request)
$search->setFrom('Kiwi\EshopBundle\Entity\Product','p')
->addWhere(sprintf("p.holder_id = '%d'", $holder->getId()))
->setSortMask(array())
->setOrderBy('p.sort_num', 'ASC')
->setRpp(100);
$variants_pattern = array();
for ($i = 1; $i <= 99; $i++) {
foreach (array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z') as $letter) {
$k = strtolower(
sprintf('%d%s',$i,$letter)
);
$variants_pattern[$k] = null;
}
}
$data['variants'] = [];
$temp = [];
foreach ($search->getResult()['data'] as $product) {
if($product->getIsDeleted() == false && $product->getIsHidden() == false) {
$variant = $this->eshopProductsHandle->getProductReturnArrayBlock($product, $lang, []);
//$variant['detail_url'] = $this->getHolderUrl($product->getHolder(), $lang).'/'.$product->getCode();
//$variant['detail_url'] = $this->eshopProductsHandle->getProductUrl();
if($active_product) {
if($active_product->getId() == $product->getId()) {
$variant['is_selected'] = true;
}
}
if(array_key_exists(strtolower($variant['name']), $variants_pattern)) {
$variants_pattern[strtolower($variant['name'])] = $variant;
} else {
$temp[] = $variant;
}
}
}
$data['variants'] = array_values(
array_filter($variants_pattern)
);
//append rest
foreach ($temp as $temp_variant) {
$data['variants'][] = $temp_variant;
}
$data['recommended'] = $this->eshopProductsHandle->getRecommended($holder);
$data['producer_products'] = ($holder->getProducer()) ? $this->eshopProducersHandle->getProducerProducts([$holder->getProducer()->getId()])['filtered'] : [];
return $data;
}
private function getHolderUrl(Product $holder, $lang) {
$dev_prefix = '';
$url = '/'.$lang.'/';
if($this->controller->get( 'kernel' )->getEnvironment() == 'dev')
$dev_prefix = '/app_dev.php';
/*
$category = null;
foreach($this->controller->get('eshop_categories_handle')->getProductCategories($product) as $product_category) {
if($product_category->getCategory()->getParentRow()) {
$category = $product_category->getCategory();
break;
}
}
if($category)
{
if($category->getParentRow())
{
if($category->getParentRow()->getParentRow())
{
if($category->getParentRow()->getParentRow()->getParentRow())
{
$url .= $category->getParentRow()->getParentRow()->getParentRow()->getName().'/';
}
$url .= $category->getParentRow()->getParentRow()->getName().'/';
}
$url .= $category->getParentRow()->getName().'/';
}
$url .= $category->getName().'/';
$url .= str_replace(array(' '),' ',$this->getProductName($product, $lang)).'/';
$url .= $product->getId();
}
else
{
$url .= 'produkt/'; //$category->GetName().'/';//'drevene-podlahy/';//$category->getName().'/';
$url .= str_replace(array(' '),' ',$this->getProductName($product, $lang)).'/';
$url .= $product->getId();
}
*/
$url .= 'produkt/';
$product = $this->em->getRepository('Kiwi\EshopBundle\Entity\Product')->findOneBy(array(
'holder_id' => $holder->getId()
));
if($product) {
foreach($this->eshopCategoriesHandle->getProductCategoriesNoCache($product) as $product_category) {
if($product_category->getCategory()) {
$url .= $product_category->getCategory()->getSeoName()."/";
}
}
}
$url .= $this->languages->getLangEntry($holder->getArticle()->getName(), $lang).'/';
$url .= $holder->getTransportCode();
$url = $dev_prefix.$this->pageExtensions->webalizeFunction($url);
return $url;
}
}