<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Pimcore\Model\Document;
use Pimcore\Model\Site;
use Twig\TwigFunction;
use Symfony\Component\Intl\Countries;
use Pimcore\Bundle\EcommerceFrameworkBundle\FilterService\ListHelper;
use Pimcore\Bundle\EcommerceFrameworkBundle\IndexService\ProductList\ProductListInterface;
use Symfony\Component\HttpFoundation\Request;
use Twig\TwigFilter;
use App\Model\DataObject\CategoryAlcoholType;
use PHPExcel;
use Carbon\Carbon;
use ZipArchive;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class AppExtension extends AbstractExtension
{
private $filterService;
public function __construct(ListHelper $filterService) {
$this->filterService = $filterService;
}
public function getFunctions()
{
return [
new TwigFunction('checkbox', [$this, 'renderCheckbox']),
new TwigFunction('addhttp', [$this, 'addhttp']),
new TwigFunction('getNavStartNode', [$this, 'getNavStartNode']),
new TwigFunction('setCookie', [$this, 'setCookie']),
new TwigFunction('getRegionBundle', [$this, 'getRegionBundle']),
new TwigFunction('getDigitalMarketingList', [$this, 'getDigitalMarketingList']),
new TwigFunction('getsubCategories', [$this, 'getsubCategories']),
new TwigFunction('getFilterDefinitions', [$this, 'getFilterDefinitions']),
new TwigFunction('getProductList', [$this, 'getProductList']),
new TwigFunction('basename', [$this, 'basenameFilter']),
new TwigFunction('getValueIndex', [$this, 'getValueIndex']),
new TwigFunction('getBrand', [$this, 'getBrand']),
new TwigFunction('numeric', [$this, 'isNumeric']),
new TwigFunction('get_object_vars', [$this, 'getObjectVars']),
new TwigFunction('getSort', [$this, 'sort']),
new TwigFunction('getValueIndex2', [$this, 'getValueIndex2']),
new TwigFunction('getFilterType', [$this, 'getFilterType']),
new TwigFunction('check_file_exists', [$this, 'check_file_exists']),
new TwigFunction('create_directory', [$this, 'create_directory']),
new TwigFunction('getDate', [$this, 'getDate']),
new TwigFunction('create_download_file', [$this, 'create_download_file']),
new TwigFunction('create_zip', [$this, 'create_zip']),
new TwigFunction('get_class_methods', [$this, 'getClassMethods']),
new TwigFunction('isInstanceof', [$this, 'isInstanceof']),
new TwigFunction('format_bytes', [$this, 'formatBytes']),
new TwigFunction('document_icon', [$this, 'getDocumentIcon']),
];
}
/** @return array<int, TwigFilter> */
public function getFilters(): array
{
return [
new TwigFilter('int', function ($value) {
return (int) $value;
}),
new TwigFilter('float', function ($value) {
return (float) $value;
}),
new TwigFilter('string', function ($value) {
return (string) $value;
}),
new TwigFilter('bool', function ($value) {
return (bool) $value;
}),
new TwigFilter('array', function (object $value) {
return (array) $value;
}),
new TwigFilter('object', function (array $value) {
return (object) $value;
}),
new TwigFilter('range', function ($start, $end, $step = 1) {
return range($start, $end, $step);
}),
];
}
public function check_file_exists($file)
{
return file_exists($file);
}
public function create_directory($file)
{
return mkdir($file, 0777, true);
}
public function getObjectVars($object)
{
return get_object_vars($object);
}
/**
* @var string $value
* @return string
*/
public function basenameFilter($value, $suffix = '')
{
return basename($value, $suffix);
}
public function renderCheckbox($name)
{
// return the HTML code for a checkbox with the given name
return '<input type="checkbox" name="' . $name . '">';
}
public function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "https://" . $url;
}
return $url;
}
public function getNavStartNode(): Document
{
if (Site::isSiteRequest()) {
$site = Site::getCurrentSite();
return $site->getRootDocument();
} else {
return Document::getById(1);
}
}
public function setCookie($referal): void
{
$urlBaseName = basename(parse_url($referal, PHP_URL_PATH));
if ($urlBaseName !== 'sign-in') {
setcookie("isvalidemail", 'false', 2147483647, '/');
}
}
public function getRegionBundle($countryName): string
{
return Countries::getName($countryName);
}
public function getDigitalMarketingList($country): array
{
$list = new \Pimcore\Model\DataObject\DigitalMarketing\Listing();
$list->setOrderKey("name");
$list->setOrder("asc");
$list->setCondition(" `CountryAvailabilityList` LIKE '%" . $country->getId() . "%'");
$list->setLimit(1);
return $list->getObjects();
}
public function getsubCategories(): array
{
$subCategories = CategoryAlcoholType::getTopLevelCategories();
return $subCategories;
}
public function getFilterDefinitions(){
$filterDefinition2 = \Pimcore\Model\DataObject\FilterDefinition::getByPath("/filter-definitions/default");
return $filterDefinition2;
}
public function getProductList($filterDefinition2,$request){
$params = array_merge($request->query->all(), $request->attributes->all());
$products2 = \Pimcore\Bundle\EcommerceFrameworkBundle\Factory::getInstance()->getIndexService()->getProductListForCurrentTenant();
$filterService2 = \Pimcore\Bundle\EcommerceFrameworkBundle\Factory::getInstance()->getFilterService();
$this->filterService->setupProductList($filterDefinition2, $products2, $params, $filterService2, true);
$products2->setVariantMode(ProductListInterface::VARIANT_MODE_VARIANTS_ONLY);
return $products2;
}
public function getValueIndex($filterDefinition2,$products2)
{
$values= [];
$valuesIndex = array();
if (!empty($products2)) {
foreach ($filterDefinition2->getFilters() as $filter) {
$rawValues = $products2->getGroupByValues("parentCategoryids", true);
foreach($rawValues as $v) {
$values[$v['value']] = array('value' => $v['value'], "count" => $v['count']);
}
// resort values
if ($values) {
foreach($values as $entry){
$ids = explode(",",$entry['value']);
foreach ($ids as $id) {
if (!empty($id)) {
if (array_key_exists($id, $valuesIndex)) {
$valuesIndex[ $id ] += $entry['count'];
} else {
$valuesIndex[ $id ] = $entry['count'];
}
}
}
}
}
}
}
return $valuesIndex;
}
public function getBrand($filteritem, $brands, $num, $country){
if (is_numeric($filteritem) || preg_match('#[^A-Za-z0-9 ]#', $filteritem) === 1) {
if (!$num) {
$num = true;
$brands->setCondition(" BrandName REGEXP '^[1-9|(|)]' AND `CountryAvailabilityList` LIKE '%" . $country->getId() . "%'");
$filteritem = "[1-9]";
}
} else {
$brands->setCondition(" BrandName LIKE " . $brands->quote($filteritem . "%") . " AND `CountryAvailabilityList` LIKE '%" . $country->getId() . "%'");
}
return $brands->load();
}
public function isNumeric($value)
{
return is_numeric($value);
}
public function sort($values){
@usort($values, function($left, $right) {
$object = \Pimcore\Model\DataObject\AbstractObject::getById($left["value"]);
if($object) {
$nameLeft = $object->getName();
}
$object = \Pimcore\Model\DataObject\AbstractObject::getById($right["value"]);
if($object) {
$nameRight = $object->getName();
}
return strcmp($nameLeft, $nameRight);
});
if(count($values) == 0) {
return;
}
}
public function getValueIndex2($values){
$valuesIndex = [];
foreach($values as $entry)
{
$valuesIndex[ $entry['value'] ] = $entry['count'];
}
return $valuesIndex;
}
public function getFilterType() {
return \Pimcore\Bundle\EcommerceFrameworkBundle\FilterService\FilterType\AbstractFilterType::EMPTY_STRING;
}
function create_download_file($order) {
$objPHPExcel = new Spreadsheet();
// Set properties
$objPHPExcel->getProperties()->setCreator("BeamSuntory");
$objPHPExcel->getProperties()->setLastModifiedBy("BeamSuntory");
$objPHPExcel->getProperties()->setTitle("Products Download");
$objPHPExcel->getProperties()->setSubject("Products Download");
$objPHPExcel->getProperties()->setDescription("Products Download");
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'ObjectType');
$objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Brand');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'BrandExtensionName');
$objPHPExcel->getActiveSheet()->SetCellValue('D1', 'BrandExtensionNameTrademark');
$objPHPExcel->getActiveSheet()->SetCellValue('E1', 'BottleSize');
$objPHPExcel->getActiveSheet()->SetCellValue('F1', 'BrandExtensionDiscontinued');
$objPHPExcel->getActiveSheet()->SetCellValue('G1', 'Proof');
$objPHPExcel->getActiveSheet()->SetCellValue('H1', 'ABV');
$objPHPExcel->getActiveSheet()->SetCellValue('I1', 'ShortDescription');
$objPHPExcel->getActiveSheet()->SetCellValue('J1', 'FullDescription');
$objPHPExcel->getActiveSheet()->SetCellValue('K1', 'Aging');
$objPHPExcel->getActiveSheet()->SetCellValue('L1', 'BottlePhoto');
$objPHPExcel->getActiveSheet()->SetCellValue('M1', 'LifestylePhotoList');
$objPHPExcel->getActiveSheet()->SetCellValue('N1', 'OriginCountry');
$objPHPExcel->getActiveSheet()->SetCellValue('O1', 'OriginRegion');
$objPHPExcel->getActiveSheet()->SetCellValue('P1', 'AlcoholType');
$objPHPExcel->getActiveSheet()->SetCellValue('Q1', 'FlavoringType');
$objPHPExcel->getActiveSheet()->SetCellValue('R1', 'PricingSegment');
$objPHPExcel->getActiveSheet()->SetCellValue('S1', 'WhyBuy1');
$objPHPExcel->getActiveSheet()->SetCellValue('T1', 'WhyBuy2');
$objPHPExcel->getActiveSheet()->SetCellValue('U1', 'WhyBuy3');
$objPHPExcel->getActiveSheet()->SetCellValue('B1', 'WhyBuy4');
$objPHPExcel->getActiveSheet()->SetCellValue('W1', 'WhyBuy5');
$objPHPExcel->getActiveSheet()->SetCellValue('X1', 'WhyBuy6');
$objPHPExcel->getActiveSheet()->SetCellValue('Y1', 'WhyBuy7');
$objPHPExcel->getActiveSheet()->SetCellValue('Z1', 'WhyBuy8');
$objPHPExcel->getActiveSheet()->SetCellValue('AA1', 'Keywords1');
$objPHPExcel->getActiveSheet()->SetCellValue('AB1', 'Keywords2');
$objPHPExcel->getActiveSheet()->SetCellValue('AC1', 'Keywords3');
$objPHPExcel->getActiveSheet()->SetCellValue('AD1', 'Keywords4');
$objPHPExcel->getActiveSheet()->SetCellValue('AE1', 'Keywords5');
$objPHPExcel->getActiveSheet()->SetCellValue('AF1', 'Keywords6');
$objPHPExcel->getActiveSheet()->SetCellValue('AG1', 'Keywords7');
$objPHPExcel->getActiveSheet()->SetCellValue('AH1', 'Keywords8');
$objPHPExcel->getActiveSheet()->SetCellValue('AI1', 'Keywords9');
$objPHPExcel->getActiveSheet()->SetCellValue('AJ1', 'Keywords10');
$objPHPExcel->getActiveSheet()->SetCellValue('AK1', 'BSIID');
$objPHPExcel->getActiveSheet()->SetCellValue('AL1', 'modificationDate');
$objPHPExcel->getActiveSheet()->SetCellValue('AM1', 'creationDate');
$counter = 1;
foreach ($order->getItems() as $item) {
$counter++;
$product = $item->getProduct();
$this->create_excel_row($objPHPExcel, $product, "BrandExtension", $counter);
$sizeVariants = $product->getSizeVariants();
if ($sizeVariants) {
foreach($sizeVariants as $variant) {
$counter++;
$this->create_excel_row ($objPHPExcel, $variant, "BottleVariant", $counter);
}
}
}
$objPHPExcel->getActiveSheet()->setTitle('Products Download');
//$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xlsx');
$objWriter->save($_SERVER['DOCUMENT_ROOT'] . "/downloads/excel/Products_Download_" . $order->getId() . ".xls");
return $_SERVER['DOCUMENT_ROOT'] . "/downloads/excel/Products_Download_" . $order->getId() . ".xls";
}
function create_excel_row($objPHPExcel,$product,$producttype,$counter) {
$brandname = "";
$brandextname = "";
$brandextensionnametrademark = "";
$bottlesize = "";
$BrandExtensionDiscontinued = "";
$proof = "";
$abv = "";
$shortdesc = "";
$fulldesc = "";
$region ="";
$country = "";
$alcoholtype = "";
$aging = "";
$lifestylephotos = "";
$bottlephotos = "";
$bottleGTIN = "";
$bottleBottleMaterial = "";
$bottleBottleHeight = "";
$bottleBottleWidth = "";
$bottleBottleDepth = "";
$bottleBottleWeight = "";
$flv = "";
$seg = "";
if ($producttype == "BrandExtension") {
$brandextname = $product->getBrandExtensionName();
$brandextensionnametrademark = $product->getBrandExtensionNameTrademark();
$brand = $product->getBrand();
if ($brand) $brandname = $brand[0]->getObject()->getBrandName();
if ($product->getBrandExtensionDiscontinued()) $BrandExtensionDiscontinued = "1";
$proof = $product->getProof();
$abv = $product->getABV();
$shortdesc = $product->getShortDescription();
$fulldesc = $product->getFullDescription();
//Country Origin
$region = $product->getOriginRegion();
$country = $product->getOriginCountry();
$countrydic = $product->getClass()->getFieldDefinition("OriginCountry")->getOptions();
if (!empty($countrydic)) {
foreach($countrydic as $countrydicitem) {
if($countrydicitem['value']==$country) { $country = $countrydicitem['key']; break;}
}
}
//Aging
$aging = $product->getAging();
//Pricing Segment
$segs = $product->getPricingSegment();
if ($segs) foreach ($segs as $seg) {break;}
if ($seg) $seg = $seg->getObject();
//Flavoring Type
$flvs = $product->getFlavoringType();
if ($flvs) foreach ($flvs as $flv) {break;}
if ($flv) $flv = $flv->getObject();
if ($flv) $flv = $flv->getFlavoringType();
$categories = $product->getCategories();
if ($categories) foreach ($categories as $category) {break;}
if ($category) $alcoholtype = $category->getAlcoholType();
//Get all the lifesize
if ($product->getLifestylePhotoList()) {
foreach($product->getLifestylePhotoList()->getItems() as $item) {
if (!empty($lifestylephotos)) $lifestylephotos .= ",";
$lifestylephotos .= $item->getPhotoLifestyle()->getFullPath();
}
}
} else {
$bottlesize = $product->getBottleSize();
//Get all the bottle-size photos
$bottlephoto = $product->getBottlePhoto();
if ($bottlephoto) $bottlephotos = $bottlephoto->getFullPath();
}
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $counter, $producttype);
$objPHPExcel->getActiveSheet()->SetCellValue('B' . $counter, $brandname);
$objPHPExcel->getActiveSheet()->SetCellValue('C' . $counter, $brandextname);
$objPHPExcel->getActiveSheet()->SetCellValue('D' . $counter, $brandextensionnametrademark);
$objPHPExcel->getActiveSheet()->SetCellValue('E' . $counter, $bottlesize);
$objPHPExcel->getActiveSheet()->SetCellValue('F' . $counter, $BrandExtensionDiscontinued);
$objPHPExcel->getActiveSheet()->SetCellValue('G' . $counter, $proof);
$objPHPExcel->getActiveSheet()->SetCellValue('H' . $counter, $abv);
$objPHPExcel->getActiveSheet()->SetCellValue('I' . $counter, $shortdesc);
$objPHPExcel->getActiveSheet()->SetCellValue('J' . $counter, $fulldesc);
$objPHPExcel->getActiveSheet()->SetCellValue('K' . $counter, $aging);
$objPHPExcel->getActiveSheet()->SetCellValue('L' . $counter, $bottlephotos);
$objPHPExcel->getActiveSheet()->SetCellValue('M' . $counter, $lifestylephotos);
$objPHPExcel->getActiveSheet()->SetCellValue('N' . $counter, $country);
$objPHPExcel->getActiveSheet()->SetCellValue('O' . $counter, $region);
$objPHPExcel->getActiveSheet()->SetCellValue('P' . $counter, $alcoholtype);
$objPHPExcel->getActiveSheet()->SetCellValue('Q' . $counter, $flv);
$objPHPExcel->getActiveSheet()->SetCellValue('R' . $counter, $seg);
$buyAlpha = array("S","T","U","V","W","X","Y","Z");
for($i=1;$i<=8;$i++) {
if ($producttype == "BrandExtension") {
$whybuy = "getWhyBuy" . $i;
$whybuys = $product->$whybuy();
if (is_null($whybuys)) {
$whybuys = "";
}
$objPHPExcel->getActiveSheet()->SetCellValue($buyAlpha[$i-1] . $counter, $whybuys);
} else {
$objPHPExcel->getActiveSheet()->SetCellValue($buyAlpha[$i-1] . $counter, "");
}
}
$keyAlpha = array("A","B","C","D","E","F","G","H","I","J");
for($i=1;$i<=10;$i++) {
if ($producttype == "BrandExtension") {
$keyword = "getKeywords" . $i;
$kwords = $product->$keyword();
if (is_null($kwords)) {
$keywords = "";
}
$objPHPExcel->getActiveSheet()->SetCellValue('A'. $keyAlpha[$i-1] . $counter, $kwords);
} else {
$objPHPExcel->getActiveSheet()->SetCellValue('A'. $keyAlpha[$i-1] . $counter, "");
}
}
$objPHPExcel->getActiveSheet()->SetCellValue('AK' . $counter, $product->getId());
$create_date = Carbon::createFromTimestamp($product->getcreationDate());
$create_date = $create_date->format("YYYY/MM/dd");
$modify_date = Carbon::createFromTimestamp($product->getmodificationDate());
$modify_date = $modify_date->format("YYYY/MM/dd");
$objPHPExcel->getActiveSheet()->SetCellValue('AL' . $counter, $modify_date);
$objPHPExcel->getActiveSheet()->SetCellValue('AM' . $counter, $create_date);
}
public function getDate($date) {
return Carbon::instance($date);
}
/**
* @param $var
* @param $instance
* @return bool
*/
public function isInstanceof($var, $instance) {
return $var instanceof $instance;
}
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination)) {
$overwrite = true;
} else {
$overwrite = false;
}
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if (preg_match('#excel#', $file) !== 1) {
$file = $_SERVER['DOCUMENT_ROOT'] . "/website/var/assets" . $file;
}
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$new_filename = substr($file,strrpos($file,'/') + 1);
if (preg_match('#bottle-photos#', $file) === 1) {
$new_filename = "/product-media/bottle-photos/" . $new_filename;
} else if (preg_match('#lifestyle-photos#', $file) === 1) {
$new_filename = "/product-media/lifestyle-photos/" . $new_filename;
}
$zip->addFile($file,$new_filename);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
public function getClassMethods($object){
return get_class_methods($object);
}
public function formatBytes($bytes, $precision = 2)
{
if ($bytes < 1024) {
return $bytes.' B';
} elseif ($bytes < 1048576) {
return round($bytes / 1024, $precision).' KB';
} elseif ($bytes < 1073741824) {
return round($bytes / 1048576, $precision).' MB';
} else {
return round($bytes / 1073741824, $precision).' GB';
}
}
public function getDocumentIcon($mimeType)
{
// Mapping MIME types to Font Awesome icon classes
$icons = [
'application/pdf' => 'fas fa-file-pdf',
'application/msword' => 'fas fa-file-word',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'fas fa-file-word',
'application/vnd.ms-excel' => 'fas fa-file-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'fas fa-file-excel',
'application/vnd.ms-powerpoint' => 'fas fa-file-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'fas fa-file-powerpoint',
'text/plain' => 'fas fa-file-alt',
'image/jpeg' => 'fas fa-file-image',
'image/png' => 'fas fa-file-image',
'application/zip' => 'fas fa-file-archive',
'application/x-rar-compressed' => 'fas fa-file-archive',
// Add more MIME types and corresponding icons as needed
];
return $icons[$mimeType] ?? 'fas fa-file'; // Default icon
}
}