<?php
namespace App\project\OfficeBrain\CustomBundle\SearchBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Translation\Translator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Doctrine\ORM\Query\ResultSetMapping;
use App\project\OfficeBrain\CustomBundle\SearchBundle\Form\Type\ProductSearchType;
use App\project\OfficeBrain\CustomBundle\SearchBundle\Form\Data\ProductSearchData;
use App\OfficeBrain\Bundle\CategoryBundle\Entity\CultureCategory;
use App\OfficeBrain\Bundle\ProductBundle\Entity\CultureAttributeMaster;
use App\OfficeBrain\Bundle\ProductBundle\Entity\AttributeValues;
use App\OfficeBrain\Bundle\SearchBundle\Helper\SearchHelper;
use App\OfficeBrain\Bundle\SolrBundle\Helper\StandardHelper;
use App\OfficeBrain\Bundle\SearchBundle\Controller\SearchController as BaseSearchController;
use App\OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use App\OfficeBrain\Bundle\SearchBundle\Manager\Service\SearchManager;
use App\project\OfficeBrain\CustomBundle\SearchBundle\Manager\Service\SearchManager as CustomSearchManager;
use App\OfficeBrain\Bundle\CoreBundle\Service\SessionManager;
use App\OfficeBrain\Bundle\SearchBundle\Manager\Service\BrowseCategoryManager;
/**
* Default Search Controller
*
* @author Employee Id: 4861
*
* Desciption: This is a search controler returns search results
*
* @param NULL
*
* @return Html Response
*
* @throws NULL
*
* @Route("/{_locale}")
*/
class SearchController extends BaseSearchController
{
/**
*
* @author Employee Id: 4861
*
* Desciption: To set member variables default value
*
* @param NULL
*
* @return null
*
* @throws NULL
**/
public function __construct(ContainerInterface $container, SearchManager $searchManager, CustomSearchManager $customSearchManager, SessionManager $sessionManager, BrowseCategoryManager $browserCategoryManager)
{
parent::__construct($container, $searchManager, $sessionManager);
$this->statsh_cache_wrapper=RedisCacheService::create();
$this->container = $container;
$this->searchManager = $searchManager->getSolrSearchExtended();
$this->customSearchManager = $customSearchManager->getSolrSearchExtended();
$this->browserCategoryManager = $browserCategoryManager->getBrowserCategoryExtended();
}
/**
*
* @author Employee Id: 4861
*
* Desciption: To unset member variables
*
* @param NULL
*
* @return null
*
* @throws NULL
*/
public function __destruct()
{
parent::__destruct();
unset($this->statsh_cache_wrapper);
}
/**
*
* @author Employee Id: 4861
*
* Desciption: Create various objects required action in this class
*
* @param NULL
*
* @return NULL
*
* @throws NULL
*/
public function initAction(Request $request)
{
parent::initAction($request);
$this->request = $request;
$this->projectSetting = $this->request->get('project_setting');
// $this->searchManager = $this->get('office_brain_custom_bundle_search_manager'); // symfony 4
// $this->searchManager = $this->serviceContainer->get('office_brain_custom_bundle_search_manager_extended');
$this->searchManager = $this->customSearchManager;
$this->productSearchForm = ProductSearchType::class;
$this->twigManager = $this->get('twig');
}
/**
*
* @author Employee Id: 5460
*
* Desciption: Bind request paramater with form
*
* @param Array paramaters
*
* @return NULL
*
* @throws NULL
*/
private function prepareSearchForm($searchArray)
{
$this->productSearchData = new ProductSearchData($this->entityManager, $this->languageId);
$this->form = $this->createForm(ProductSearchType::class, $this->productSearchData, array('csrf_protection' => false,'allow_extra_fields' => true, 'searchData' => $searchArray));
$this->form->submit($searchArray);
}
/**
* @author Employee Id: 5460
*
* List products
*
* @param string tag slug
*
* @return if result found return tag products else null
*
* @Route("/tag-product-list/{tagSlug}", name="office_brain_search_bundle_tag_product_list", options={"expose"=true}, methods={"GET"})
*
* @Template("project/OfficeBrain/CustomBundle/SearchBundle/Search/search.html.twig")
*/
public function tagProductListAction(Request $request, $tagSlug)
{
$this->initAction($request);
$searchQuery = $this->searchManager->getSearchArray();
$searchQuery['product_search']['tagSlug'] = $tagSlug;
/*echo "<pre>";
print_r($searchQuery);*/
$renderFromModel = $searchQuery['render_model'];
$this->prepareSearchForm($searchQuery['product_search']);
$this->responseArray['search_result_array'] = array();
if ($this->form->isValid()) {
$this->responseArray = $this->searchManager->searchResult($this->form->getData());
if (!$this->request->get('page', null)) {
$this->searchManager->setContinueShoppingUrl();
$this->responseArray['search_attribute_filter_array'] = $this->searchManager->searchFilter($this->form->getData());
}
}
$this->responseArray['attr_value_id'] = $this->searchManager->getFilterAttributeValueId($this->request->query->get('color_filter_id', ''));
$this->responseArray['render_model'] = $renderFromModel;
if ($this->request->isXmlHttpRequest()) {
if (is_array($this->responseArray['search_result_array']) && array_key_exists('data', $this->responseArray['search_result_array']) && ! count($this->responseArray['search_result_array']['data'])) {
return new JsonResponse(array( 'status'=>'error','error_code' => 'END_OF_PAGINATION','error_message' => 'error_message' ));
}
return $this->responseArray;
}
$this->responseArray['tag_slug'] = $tagSlug;
$this->responseArray['search_query'] = $searchQuery['search']['query'];
$this->responseArray['main_filter'] = $searchQuery['search']['main_filter'];
$this->responseArray['form'] = $this->form->createView();
$this->responseArray['save_search'] = $this->searchManager->getSaveSearch();
$recentSearch = $this->request->query->get('is_filter', 'check');
if ($recentSearch == 'check') {
$this->searchManager->setRecentSearch();
}
return $this->responseArray;
}
private function getRefererRouteName(Request $request){
$this->initAction($request);
$referer = $this->request->headers->get('referer');
$referer_url_para = parse_url($referer);
$lastPath = $referer_url_para['path'];
if( isset($referer_url_para['scheme']) ){
$referer = $referer_url_para['scheme'].'://'.$referer_url_para['host'].$referer_url_para['path'];
}
$basePath = $this->request->getBaseUrl()?$this->request->getBaseUrl():( $referer_url_para['scheme'].'://'.$referer_url_para['host']);
$lastPath = substr($referer, strpos($referer, $basePath));
$lastPath = str_replace($basePath, '', $lastPath);
if(!$lastPath) $lastPath = '/';
$matcher = $this->get('router')->getMatcher();
$parameters = $matcher->match($lastPath);
$routeName = $parameters['_route'];
return $routeName;
}
/**
*
* @author Employee Id: 5460
*
* Desciption: Perform search based on search query in selected culture
*
* @param string search_query
*
* @return Html/json Response
*
* @throws if result found search result page else no record found error
*
* @Route("/search", name="office_brain_search_bundle_search", options={"expose"=true}, methods={"GET", "POST"})
*
* @Template("project/OfficeBrain/CustomBundle/SearchBundle/Search/search.html.twig")
*
*/
public function searchAction(Request $request)
{
$this->initAction($request);
// this is for you first and child category array
$youFirstMatchCat = array(); // this is match side filter with all category of you first
$cateogryApiManager= $this->serviceContainer->get("officebrain_category_api_manager");
$youFistcatId = 16115;
$youFirstChidrenCat = $cateogryApiManager->getChildrenCatByCatId($youFistcatId);
$youFirstChidrenCat= array_column($youFirstChidrenCat, 'pms_id');
array_push($youFirstChidrenCat,$youFistcatId);
// ---END -----
$categoryTagId=$this->request->query->get('tag_category_id', '');
$tag=$this->request->query->get('tag_id', '');
$searchQuery = $this->searchManager->getSearchArray();
$renderFromModel = $searchQuery['render_model'];
$tagSlug = $this->request->get('tagSlug');
$searchQuery['product_search']['tagSlug'] = $tagSlug;
// if(empty($categoryId)==true)
// {
// $categoryId=$this->request->query->get('category_filter', '');
// $tag=$this->request->query->get('tag_filter', '');
// $searchQuery['product_search']['categoryId'] = $categoryId;
// }
// else
// {
// $categoryObj = $this->container->get('office_brain_category_manager');
// $subCategoryList = $categoryObj->getSubCategoryList($categoryId[0]);
// if( isset($subCategoryList['child']) ){
// $categoryListJson = json_encode(array_keys($subCategoryList['child']));
// }else{
// $caregoryArray[] = (int)$categoryId[0];
// $categoryListJson = json_encode($caregoryArray);
// }
// $searchQuery['product_search']['categoryId'] = $categoryListJson;
// }
//------------------kjethi ----------------
if($categoryTagId)
{
// $categoryObj = $this->container->get('office_brain_category_manager'); // symfony 4
// $categoryObj = $this->serviceContainer->get('office_brain_browse_category_extended');
$categoryObj = $this->browserCategoryManager;
$subCategoryList = $categoryObj->getSubCategoryList($categoryTagId);
if( isset($subCategoryList['child']) ){
$caregoryArray= array_keys($subCategoryList['child']);
array_push($caregoryArray,(int)$categoryTagId);
$categoryListJson = json_encode($caregoryArray);
}else{
$caregoryArray[] = (int)$categoryTagId;
$categoryListJson = json_encode($caregoryArray);
}
$searchQuery['product_search']['categoryTagId'] = $categoryListJson;
$routeName = $this->getRefererRouteName($request);
if($routeName == "office_brain_search_bundle_category_product_list" && trim($this->request->query->get('sort_by', '')) == ''){
$searchQuery['product_search']['sort'] = array(
'field' => 'category||sorting_product_by_categoryid_'. $categoryTagId.'_i',
'order' => 'desc'
);
}
}
// you first
$catFilterArr = array();
if($categoryTagId){
$catFilterArr = $caregoryArray;
}
$categoryId=$this->request->query->get('category_filter', '');
if(!is_array($categoryId)) {
$searchQuery['product_search']['categoryId'] = json_decode($categoryId);
} else {
$searchQuery['product_search']['categoryId'] = $categoryId;
}
if(!empty($categoryId) && is_array($categoryId)){
// $catFilterArr = array_merge($catFilterArr,json_decode($categoryId));
$catFilterArr = array_merge($catFilterArr,$categoryId);
}
$youFirstMatchCat= array_intersect($catFilterArr,$youFirstChidrenCat);
// foreach ($youFirstChidrenCat as $youFirstCatId){
// foreach ($catFilterArr as $catIdFilter){
// if($catIdFilter == $youFirstCatId)
// $youFirstFlag
// }
// }
$tag=$this->request->query->get('tag_filter', '');
if(!is_array($tag)) {
$searchQuery['product_search']['tag'] = json_decode($tag);
} else {
$searchQuery['product_search']['tag'] = $tag;
}
// ------------------kjethi ----------------
$min_price =$this->request->query->get('min_price', '');
if($min_price!=""){
$searchQuery['product_search']['min_price'] = $min_price;
}
$max_price = $this->request->query->get('max_price', '');
if($max_price!=""){
$searchQuery['product_search']['max_price'] = $max_price;
}
$tag=$this->request->query->get('tag_filter', '');
$this->prepareSearchForm($searchQuery['product_search']);
$this->responseArray['search_result_array'] = array();
// echo "<pre>";
// foreach ($this->form->getErrors(true) as $error) {
// $formField = $error->getOrigin()->getName(); // Get the form field name
// $errorMessage = $error->getMessage(); // Get the error message
// echo $formField . ': ' . $errorMessage . "\n";
// }
// exit;
if ($this->form->isValid()) {
$this->responseArray = $this->searchManager->searchResult($this->form->getData());
if (!$this->request->get('page', null)) {
$this->searchManager->setContinueShoppingUrl();
$this->responseArray['search_attribute_filter_array'] = $this->searchManager->searchFilter($this->form->getData());
}else{
$this->responseArray['search_attribute_filter_array'] = $this->searchManager->searchFilter($this->form->getData());
}
}
$this->responseArray['youFirstChidrenCat'] = $youFirstMatchCat;
// $this->responseArray['search_attribute_filter_array']['Ideas_by_market_Cat'] = array(array("id"=>16115,"name"=>"Youfirst","count"=>310));
// echo "<pre>";print_r($this->responseArray['search_attribute_filter_array']);exit;
// -----------------------------------------------------------------------
if (!$this->request->isXmlHttpRequest()) {
// get IdeasByMarket cat from All search filter cat
$api_manager = $this->serviceContainer->get('officebrain_category_api_manager');
$dataOfIdeas = $api_manager->getIdeasByMarketCat();
$dataOfIdeas_final = array_column($dataOfIdeas, 'pms_id');
// echo "<pre>";print_r($this->responseArray['search_attribute_filter_array']['categoryNameId']);exit;
if(isset($this->responseArray['search_attribute_filter_array'])){
$this->responseArray['search_attribute_filter_array']['Ideas_by_market_Cat'] = array_filter($this->responseArray['search_attribute_filter_array']['categoryNameId'], function($array) use($dataOfIdeas_final){
if (in_array($array['id'], $dataOfIdeas_final)) {
return true ;
}
else{
return false;
}
});
$arr = array_filter($this->responseArray['search_attribute_filter_array']['categoryNameId'], function($array) use($dataOfIdeas_final){
if (in_array($array['id'], $dataOfIdeas_final)) {
return false ;
}
else{
return true;
}
});
$this->responseArray['search_attribute_filter_array']['categoryNameId'] = $arr;
}
else{
$this->responseArray['search_attribute_filter_array']['Ideas_by_market_Cat'] = null;
$this->responseArray['search_attribute_filter_array']['categoryNameId'] = null;
}
$categoryArray = array();
foreach($this->responseArray['search_attribute_filter_array']['categoryNameId'] as $category){
$categoryArray[$category['id']] = $category['name'];
}
$this->responseArray['category_list'] = $categoryArray;
/* Remove Categories From Category Filter */
$allCategoryIds = array_column($this->responseArray['search_attribute_filter_array']['parentchildCategoryIdName'], 'id');
$categoryIdsToRemove = $this->serviceContainer->getParameter('category_remove_from_filter');
foreach($categoryIdsToRemove as $catId){
$keyToUnset = array_search ($catId, $allCategoryIds);
if(isset($this->responseArray['search_attribute_filter_array']['parentchildCategoryIdName'][$keyToUnset])){
unset($this->responseArray['search_attribute_filter_array']['parentchildCategoryIdName'][$keyToUnset]);
}
}
/* Remove Categories From Category Filter */
/* EO - Category Brand Merging */
if(isset($this->responseArray['search_attribute_filter_array']['publicCustomTagText']) && is_array($this->responseArray['search_attribute_filter_array']['publicCustomTagText'])){
$parentCategoryNamesArray = array_column($this->responseArray['search_attribute_filter_array']['parentchildCategoryIdName'], 'name');
$brandSlugs = array('barware','circular-cup','dyln','ecovessel','halcyon','hitch','illusion','mag-lites','otaria','pul','reduce','snowfox','stojo','swig','takeya','vinglace','zing-line','mood','microhalt','bindle','hydrapak','made-in-usa','hidratespark','hip','maglite','oceanworks','perfect-shaker','polar-bottle','stojo-1','perf||ma');
$brandFinalArray = array();
$count = 0;
foreach($this->responseArray['search_attribute_filter_array']['publicCustomTagText'] as $brandData => $productCount){
$brandArray = explode('|', $brandData);
if(in_array(trim($brandArray[5]), $brandSlugs) && !in_array(trim($brandArray[1]), $parentCategoryNamesArray)){
$brandFinalArray[$count]['id'] = trim($brandArray[0]);
$brandFinalArray[$count]['name'] = trim($brandArray[1]);
$brandFinalArray[$count]['slug'] = trim($brandArray[5]);
$brandFinalArray[$count]['count'] = $productCount;
$brandFinalArray[$count]['type'] = 'brand';
$count++;
}
}
if(!empty($brandFinalArray)){
$this->responseArray['search_attribute_filter_array']['parentchildCategoryIdName'] = array_merge($this->responseArray['search_attribute_filter_array']['parentchildCategoryIdName'], $brandFinalArray);
$price = array_column($this->responseArray['search_attribute_filter_array']['parentchildCategoryIdName'], 'name');
array_multisort($price, SORT_ASC, $this->responseArray['search_attribute_filter_array']['parentchildCategoryIdName']);
}
}
/* EO - Category Brand Merging */
$locale=$this->request->getLocale();
$search = base64_encode(json_encode($searchQuery));
// $cacheSiteKey = array('SearchFilter',$search,$locale,$this->instanceId,$this->container->getParameter('kernel.environment')); // symfony 4
$cacheSiteKey = array('SearchFilter',$search,$locale,$this->instanceId,$this->projectSetting['kernelEnvironment']);
$this->moduleCachePrefix='__Search__:';
$cacheKey = $this->moduleCachePrefix.RedisCacheService::generateKey($this->statsh_cache_wrapper,$cacheSiteKey);
$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
/*if($cacheData){
$this->responseArray['filterHtml']= $cacheData;
}
else{ */
$response = $this->twigManager->render('project/OfficeBrain/CustomBundle/SearchBundle/Search/searchAttributeFilterList.html.twig', $this->responseArray);
if(!empty($cacheKey))
{
RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$response);
}
$this->responseArray['filterHtml'] = $response;
// }
}
$this->responseArray['sub_category_list'] = $catFilterArr;
$this->responseArray['attr_value_id'] = $this->searchManager->getFilterAttributeValueId($this->request->query->get('color_filter_id', ''));
$this->responseArray['render_model'] = $renderFromModel;
$this->responseArray['tag_slug'] = $tagSlug;
$this->responseArray['category_id'] = $categoryTagId;
if ($this->request->isXmlHttpRequest()) {
$this->responseArray['copy_url'] = $this->serviceContainer->getParameter('base_url').$_SERVER['REQUEST_URI'];
if (is_array($this->responseArray['search_result_array']) && array_key_exists('data', $this->responseArray['search_result_array']) && ! count($this->responseArray['search_result_array']['data'])) {
return new JsonResponse(array( 'status'=>'error','error_code' => 'END_OF_PAGINATION','error_message' => 'error_message' ));
}
return $this->responseArray;
}
$this->responseArray['search_query'] = $searchQuery['search']['query'];
$this->responseArray['main_filter'] = $searchQuery['search']['main_filter'];
$this->responseArray['search_data'] = $searchQuery;
$this->responseArray['form'] = $this->form->createView();
$this->responseArray['save_search'] = $this->searchManager->getSaveSearch();
$recentSearch = $this->request->query->get('is_filter', 'check');
if ($recentSearch == 'check') {
$this->searchManager->setRecentSearch();
}
//print_r($this->responseArray['search_attribute_filter_array']);die;
return $this->responseArray;
}
/**
*
* @author Employee Id: 4861
*
* Desciption: Perform search to find attribute list for given search criteria
*
* @param string search_query
*
* @return json Response
*
* @throws if result found return attribute list along with product count else null
*
* @Route("/search-attribute-filter-list-without-ajax/{search}",
* name="office_brain_search_bundle_search_attribute_filter_list_withoutAjax",)
* @Template("project/OfficeBrain/CustomBundle/SearchBundle/Search/searchAttributeFilterList.html.twig")
*
*/
public function searchAttributeFilterListWithoutAjaxAction(Request $request)
{
$this->initAction($request);
$search = $this->request->get('search');
$searchQuery = json_decode(base64_decode($search),true);
if(array_key_exists('browse-category-search',$searchQuery)){
$this->prepareSearchForm($searchQuery['product_search'],$searchQuery['browse-category-search']);
unset($searchQuery['browse-category-search']);
}
else{
$this->prepareSearchForm($searchQuery['product_search']);
}
$this->form->getData('browse-category-search');
$this->responseArray['search_attribute_filter_array'] = array();
if ($this->form->isValid()) {
$this->responseArray['search_attribute_filter_array'] = $this->searchManager->searchFilter($this->form->getData());
}
// -----------------------------------------------------------------------
$locale=$this->request->getLocale();
// $cacheSiteKey = array('SearchFilter',$search,$locale,$this->instanceId,$this->container->getParameter('kernel.environment')); symfony 4
$cacheSiteKey = array('SearchFilter',$search,$locale,$this->instanceId,$this->projectSetting['kernelEnvironment']);
$this->moduleCachePrefix='__Search__:';
$cacheKey = $this->moduleCachePrefix.RedisCacheService::generateKey($this->statsh_cache_wrapper,$cacheSiteKey);
$cacheData = RedisCacheService::getCacheData($this->statsh_cache_wrapper,$cacheKey);
if($cacheData){
return $cacheData;
}
$response = $this->render('project/OfficeBrain/CustomBundle/SearchBundle/Search/searchAttributeFilterList.html.twig', $this->responseArray);
if(!empty($cacheKey))
{
RedisCacheService::saveCacheData($this->statsh_cache_wrapper,$cacheKey,$response);
}
return $response;
// -----------------------------------------------------------------------
//}
}
}