<?php
/**
* Pimcore
*
* This source file is available under two different licenses:
* - GNU General Public License version 3 (GPLv3)
* - Pimcore Enterprise License (PEL)
* Full copyright and license information is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license GPLv3 and PEL
*/
namespace App\Model;
use App\Model\Product\TraitClasses\Checkoutable;
use App\Tool\AdminStyle;
use App\Tool\SizeSort;
use Pimcore\Cache;
use Pimcore\Model\DataObject\AbstractObject;
use Pimcore\Model\DataObject\Folder;
use Pimcore\Model\DataObject\Product;
use App\Model\DefaultMarca;
class DefaultProduct extends Product
{
use Checkoutable;
private $internationalSizeOrden = array('XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', '3XL', '4XL');
public function getElementAdminStyle()
{
if (!$this->o_elementAdminStyle) {
$this->o_elementAdminStyle = new AdminStyle($this);
}
return $this->o_elementAdminStyle;
}
public function save()
{
parent::save();
Cache::clearTag('object_' . $this->internalGetBaseProduct()->getId());
}
public function isActive($inProductList = false): bool
{
return $this->isPublished();
}
public function getOSDoIndexProduct(): bool
{
if ($this->getType() == 'object' && $this->getParent() instanceof Product) {
return false;
} else {
return true;
}
}
public function getOSParentId()
{
if ($this->getType() == 'variant' && $this->getParent()->getParent() instanceof Product) {
return $this->getParent()->getParent()->getId();
} elseif ($this->getParent() instanceof Product) {
return parent::getOSParentId();
} else {
return $this->getId();
}
}
/*
*
* Own functions for bsnbarcelona products
*/
public function getMarcaObject()
{
if (method_exists($this, "getMarca")) {
$marcaId = $this->getMarca();
if ($marcaId > 0) {
return DefaultMarca::getById($marcaId);
}
}
return null;
}
public function getAttributeRelationProductTypeArray()
{
$types = array();
$attributes = $this->getAllAttributes($this);
if (key_exists("relationproducts", $attributes)) {
$relationsproducts = $this->getAttributeValue($attributes["relationproducts"]);
if ($relationsproducts) {
foreach ($relationsproducts as $item) {
if (!(array_key_exists($item->getTipo(), $types))) {
$types[$item->getTipo()] = array();
}
}
}
}
return $types;
}
public function getCatalizador()
{
$catalizadores = array();
$attributes = $this->getAllAttributes($this);
if (key_exists("relationproducts", $attributes)) {
$relationsproducts = $this->getAttributeValue($attributes["relationproducts"]);
if ($relationsproducts) {
foreach ($relationsproducts as $item) {
if ($item->getTipo() == "Catalizador") {
$catalizadores[] = $item;
}
}
}
}
return $catalizadores;
}
public function getKit()
{
$kit = array();
$attributes = $this->getAllAttributes($this);
if (key_exists("relationproducts", $attributes)) {
$relationsproducts = $this->getAttributeValue($attributes["relationproducts"]);
if ($relationsproducts) {
foreach ($relationsproducts as $item) {
if ($item->getTipo() == "Kit") {
$kit[] = $item;
}
}
}
}
return $kit;
}
public function getDisolvente()
{
$disolventes = array();
$attributes = $this->getAllAttributes($this);
if (key_exists("relationproducts", $attributes)) {
$relationsproducts = $this->getAttributeValue($attributes["relationproducts"]);
if ($relationsproducts) {
foreach ($relationsproducts as $item) {
if ($item->getTipo() == "Disolvente") {
$disolventes[] = $item;
}
}
}
}
return $disolventes;
}
public function getCleaner()
{
$cleaners = array();
$attributes = $this->getAllAttributes($this);
if (key_exists("relationproducts", $attributes)) {
$relationsproducts = $this->getAttributeValue($attributes["relationproducts"]);
if ($relationsproducts) {
foreach ($relationsproducts as $item) {
if ($item->getTipo() == "Cleaner") {
$cleaners[] = $item;
}
}
}
}
return $cleaners;
}
public function getReducer()
{
$reducers = array();
$attributes = $this->getAllAttributes($this);
if (key_exists("relationproducts", $attributes)) {
$relationsproducts = $this->getAttributeValue($attributes["relationproducts"]);
if ($relationsproducts) {
foreach ($relationsproducts as $item) {
if ($item->getTipo() == "Reducer") {
$reducers[] = $item;
}
}
}
}
return $reducers;
}
public function getActivador()
{
$activadores = array();
$attributes = $this->getAllAttributes($this);
if (key_exists("relationproducts", $attributes)) {
$relationsproducts = $this->getAttributeValue($attributes["relationproducts"]);
if ($relationsproducts) {
foreach ($relationsproducts as $item) {
if ($item->getTipo() == "Activador") {
$activadores[] = $item;
}
}
}
}
return $activadores;
}
public function getComplement()
{
$activadores = array();
$attributes = $this->getAllAttributes($this);
if (key_exists("relationproducts", $attributes)) {
$relationsproducts = $this->getAttributeValue($attributes["relationproducts"]);
if ($relationsproducts) {
foreach ($relationsproducts as $item) {
if ($item->getTipo() == "Complemento") {
$activadores[] = $item;
}
}
}
}
return $activadores;
}
public function getConverter()
{
$converters = array();
$attributes = $this->getAllAttributes($this);
if (key_exists("relationproducts", $attributes)) {
$relationsproducts = $this->getAttributeValue($attributes["relationproducts"]);
if ($relationsproducts) {
foreach ($relationsproducts as $item) {
if ($item->getTipo() == "Converter") {
$converters[] = $item;
}
}
}
}
return $converters;
}
public function getBase()
{
$base = array();
$attributes = $this->getAllAttributes($this);
if (key_exists("relationproducts", $attributes)) {
$relationsproducts = $this->getAttributeValue($attributes["relationproducts"]);
if ($relationsproducts) {
foreach ($relationsproducts as $item) {
if ($item->getTipo() == "Base") {
$base[] = $item;
}
}
}
}
return $base;
}
public function getProporcionMezcla()
{
$proporcion = array();
$attributes = $this->getAllAttributes($this);
if (key_exists("relationproducts", $attributes)) {
$relationsproducts = $this->getAttributeValue($attributes["relationproducts"]);
if ($relationsproducts) {
foreach ($relationsproducts as $item) {
if (!empty(trim("" . $item->getMezcla()))) {
$proporcion[] = trim("" . $item->getMezcla());
}
}
}
}
return $proporcion;
}
public function getDimensiones($fields = array('ancho', 'largo', 'alto'))
{
$dimension = "";
$attributes = $this->getAllAttributes($this);
$counter = -1;
$quantityArray = array();
$unitArray = array();
foreach ($fields as $field) {
if (key_exists($field, $attributes)) {
$value = $this->getAttributeValue($attributes[$field]);
switch ($attributes[$field]["fieldtype"]) {
case "inputQuantityValue":
case "quantityValue":
if ($value) {
$valorNumerico = trim("" . $value->getValue());
$unidad = !is_null($value->getUnit()) ? trim("" . $value->getUnit()->getAbbreviation()) : "";
if (!empty($valorNumerico)) {
$counter++;
$quantityArray[$counter] = $valorNumerico;
if (!empty($unidad)) {
$unitArray[$counter] = $unidad;
}
}
}
break;
default:
if (!empty($value)) {
$dimension = $value;
}
}
}
}
if (count($quantityArray) > 0) {
if (count(array_unique($unitArray)) > 1) {
foreach ($quantityArray as $key => $value) {
$unit = isset($unitArray[$key]) ? trim("" . $unitArray[$key]) : "";
if (!($unit == "\"" || $unit == "'" || $unit == "º" || $unit == "")) {
$unit = " " . $unit;
}
if (!empty(trim("" . $value))) {
$quantityArray[$key] = trim("" . $value . $unit);
}
}
$dimension = implode(" x ", $quantityArray);
} else {
$unit = count($unitArray) > 0 ? trim("" . array_pop($unitArray)) : "";
if (!($unit == "\"" || $unit == "'" || $unit == "º" || $unit == "")) {
$unit = " " . $unit;
}
$dimension = trim("" . implode(" x ", $quantityArray) . $unit);
}
} else {
return "";
}
return $dimension;
}
public function getOldDimensionesList($fields = array('ancho', 'largo', 'alto'))
{
$variants = $this->getAllActiveVariants();
$attributes = $this->getAllAttributes($this);
$dimensionesList = array();
if (count($variants) > 0) {
foreach ($variants as $variant) {
$dimension = $variant->getDimensiones($fields);
if (!empty($dimension)) {
$dimensionArray = explode_and_trim(" x ", $dimension);
$valueUnitArray = explode_and_trim(" ", $dimensionArray[count($dimensionArray) - 1]);
$defaultUnit = "";
if (count($valueUnitArray) == 2) {
$defaultUnit = $valueUnitArray[1];
}
$key = "";
foreach ($dimensionArray as $valueUnit) {
$valueUnitArray = explode_and_trim(" ", $valueUnit);
$unit = $defaultUnit;
$value = $valueUnitArray[0];
if (count($valueUnitArray) == 2) {
$unit = $valueUnitArray[1];
}
$key = is_string($this->convertToMM($value, $unit) ? '' : $key . "_" . str_pad(floor($this->convertToMM($value, $unit)), 6, "0", STR_PAD_LEFT));
}
$key = trim($key, "_");
if (in_array('tallainternational', $fields) && in_array($dimension, $this->internationalSizeOrden)) {
$key = array_search($dimension, $this->internationalSizeOrden);
$key = str_pad($key, 6, "0", STR_PAD_LEFT);
}
$dimensionesList[$key] = $dimension;
}
}
} else {
$dimension = $this->getDimensiones($fields);
if (!empty($dimension)) {
$dimensionesList["000000"] = $dimension;
}
}
ksort($dimensionesList);
return $dimensionesList;
}
public function getDimensionesList($fields = array('ancho', 'largo', 'alto'))
{
$dimensionesList = array();
$dimension = $this->getDimensiones($fields);
if (!empty($dimension)) {
$dimensionesList["000000"] = $dimension;
}
ksort($dimensionesList);
return $dimensionesList;
}
public function getCapacity()
{
try {
$capacity = $this->getAttributeValue($this->getAllAttributes($this)["capacidad"]);
return [
'value' => $capacity->getValue(),
'unit' => strtoupper($capacity->getUnit()->getAbbreviation())
];
} catch (\Throwable $th) {
return [
'value' => '',
'unit' => ''
];
}
}
public function getColor()
{
try {
$colorId = $this->getAttributeValue($this->getAllAttributes($this)["color"]);
$color = \Pimcore\Model\DataObject\Colores::getById($colorId);
return [
'name' => $color->getName(),
'hex' => implode(",", $color->getHex()->getCssRgba()),
];
} catch (\Throwable $th) {
if (is_null($color)){
return [
'name' => '',
'hex' => '',
];
}else{
return [
'name' => $color->getName(),
'hex' => '',
];
}
}
}
public function getPresentacionsList($fields = array('presentacion', 'capacidad'))
{
$variants = $this->getAllActiveVariants();
$attributes = $this->getAllAttributes($this);
$presentacionsList = array();
if (count($fields) == 2) {
if (count($variants) > 0) {
if (key_exists($fields[0], $attributes)) {
foreach ($variants as $variant) {
$key = $variant->getAttributeValue($attributes[$fields[0]]);
$value = "";
if (!key_exists($key, $presentacionsList)) {
$presentacionsList[$key] = array();
}
if (key_exists($fields[1], $attributes)) {
$value = $variant->getAttributeValue($attributes[$fields[1]]);
if (key_exists($fields[1], $attributes)) {
switch ($attributes[$fields[1]]["fieldtype"]) {
case "inputQuantityValue" :
case "quantityValue" :
$quantity = ($value && method_exists($value, "getValue")) ? trim("" . $value->getValue()) : "";
$unit = ($value && method_exists($value, "getValue")) ? trim("" . $value->getUnit()->getAbbreviation()) : "";
$value = "";
if (!empty($quantity)) {
$value = $quantity . " " . $unit;
switch (true) {
case(in_array($unit, array("ml", "l", "pt", "gal"))) :
$orderKey = floor($this->convertToML($quantity, $unit));
break;
case(in_array($unit, array("kg", "g"))) :
$orderKey = floor($this->convertToMG($quantity, $unit));
break;
case(in_array($unit, array("mm", "cm", "m"))) :
$orderKey = floor($this->convertToMM($quantity, $unit));
break;
default :
$orderKey = $quantity;
}
}
break;
default:
$orderKey = $variant->getAttributeValue($attributes[$fields[1]]);
}
}
if (!empty($value)) {
$orderKey = str_pad($orderKey, 6, "0", STR_PAD_LEFT);
$presentacionsList[$key][$orderKey] = trim("" . $value);
}
}
}
}
} else {
if (key_exists($fields[0], $attributes)) {
$key = $this->getAttributeValue($attributes[$fields[0]]);
// if ($key == null) {
// $parent = $this->getParent();
// if ($parent->o_type == "object") {
// // $key = $parent->getAttributeValue($attributes[$fields[0]]);
// }
// }
$presentacionsList[$key] = array();
if (key_exists($fields[1], $attributes)) {
$orderKey = str_pad("", 6, "0", STR_PAD_LEFT);
$value = $this->getAttributeValue($attributes[$fields[1]]);
if (key_exists($fields[1], $attributes)) {
switch ($attributes[$fields[1]]["fieldtype"]) {
case "inputQuantityValue" :
case "quantityValue" :
$quantity = ($value && method_exists($value, "getValue")) ? trim("" . $value->getValue()) : "";
$unit = ($value && method_exists($value, "getUnit") && $value->getUnit()) ? trim("" . $value->getUnit()->getAbbreviation()) : "";
$value = "";
if (!empty($quantity)) {
$value = $quantity . " " . $unit;
switch (true) {
case(in_array($unit, array("ml", "l", "pt", "gal"))) :
$orderKey = floatval($this->convertToML($quantity, $unit));
break;
case(in_array($unit, array("kg", "g"))) :
$sortvalue = floatval($this->convertToMG($quantity, $unit));
break;
case(in_array($unit, array("mm", "cm", "m"))) :
$sortvalue = floatval($this->convertToMM($quantity, $unit));
break;
default :
$orderKey = $quantity;
}
}
break;
default:
$orderKey = $this->getAttributeValue($attributes[$fields[1]]);
}
if (!empty($value)) {
$orderKey = str_pad($orderKey, 6, "0", STR_PAD_LEFT);
$presentacionsList[$key][$orderKey] = trim("" . $value);
}
}
}
}
}
}
foreach ($presentacionsList as $key => $value) {
ksort($presentacionsList[$key]);
}
$hasValues = true;
if (count($presentacionsList) == 1) {
foreach ($presentacionsList as $key => $value) {
if ((empty($key)) && (count($value) == 0)) {
$presentacionsList = array();
}
}
}
return $presentacionsList;
}
public function getPresentation(){
$attributes = $this->getAllAttributes($this);
$presentacion = "";
if (key_exists("presentacion", $attributes)) {
$key = $this->getAttributeValue($attributes["presentacion"]);
$presentacion = $key;
}
return $presentacion;
}
public function getCapacidad($field = 'capacidad'){
$attributes = $this->getAllAttributes($this);
$presentacionsList = array();
if (key_exists($field, $attributes)) {
$orderKey = str_pad("", 6, "0", STR_PAD_LEFT);
$value = $this->getAttributeValue($attributes[$field]);
if (key_exists($field, $attributes)) {
switch ($attributes[$field]["fieldtype"]) {
case "inputQuantityValue" :
case "quantityValue" :
$quantity = ($value && method_exists($value, "getValue")) ? trim("" . $value->getValue()) : "";
$unit = ($value && method_exists($value, "getUnit") && $value->getUnit()) ? trim("" . $value->getUnit()->getAbbreviation()) : "";
$value = "";
if (!empty($quantity)) {
$value = $quantity . " " . $unit;
switch (true) {
case(in_array($unit, array("ml", "l", "pt", "gal"))) :
$orderKey = floatval($this->convertToML($quantity, $unit));
break;
case(in_array($unit, array("kg", "g"))) :
$sortvalue = floatval($this->convertToMG($quantity, $unit));
break;
case(in_array($unit, array("mm", "cm", "m"))) :
$sortvalue = floatval($this->convertToMM($quantity, $unit));
break;
default :
$orderKey = $quantity;
}
}
break;
default:
$orderKey = $this->getAttributeValue($attributes[$fields[1]]);
}
if (!empty($value)) {
$orderKey = str_pad($orderKey, 6, "0", STR_PAD_LEFT);
$presentacionsList[$orderKey] = trim("" . $value);
}
}
}
return $presentacionsList;
}
public function getOldPresentation($fields = array('presentacion', 'capacidad'))
{
$attributes = $this->getAllAttributes($this);
$presentacionsList = array();
if (count($fields) == 2) {
if (key_exists($fields[0], $attributes)) {
$key = $this->getAttributeValue($attributes[$fields[0]]);
// if ($key == null) {
// $parent = $this->getParent();
// if ($parent->o_type == "object") {
// // $key = $parent->getAttributeValue($attributes[$fields[0]]);
// }
// }
$presentacionsList[$key] = array();
if (key_exists($fields[1], $attributes)) {
$orderKey = str_pad("", 6, "0", STR_PAD_LEFT);
$value = $this->getAttributeValue($attributes[$fields[1]]);
if (key_exists($fields[1], $attributes)) {
switch ($attributes[$fields[1]]["fieldtype"]) {
case "inputQuantityValue" :
case "quantityValue" :
$quantity = ($value && method_exists($value, "getValue")) ? trim("" . $value->getValue()) : "";
$unit = ($value && method_exists($value, "getUnit") && $value->getUnit()) ? trim("" . $value->getUnit()->getAbbreviation()) : "";
$value = "";
if (!empty($quantity)) {
$value = $quantity . " " . $unit;
switch (true) {
case(in_array($unit, array("ml", "l", "pt", "gal"))) :
$orderKey = floatval($this->convertToML($quantity, $unit));
break;
case(in_array($unit, array("kg", "g"))) :
$sortvalue = floatval($this->convertToMG($quantity, $unit));
break;
case(in_array($unit, array("mm", "cm", "m"))) :
$sortvalue = floatval($this->convertToMM($quantity, $unit));
break;
default :
$orderKey = $quantity;
}
}
break;
default:
$orderKey = $this->getAttributeValue($attributes[$fields[1]]);
}
if (!empty($value)) {
$orderKey = str_pad($orderKey, 6, "0", STR_PAD_LEFT);
$presentacionsList[$key][$orderKey] = trim("" . $value);
}
}
}
}
}
foreach ($presentacionsList as $key => $value) {
ksort($presentacionsList[$key]);
}
$hasValues = true;
if (count($presentacionsList) == 1) {
foreach ($presentacionsList as $key => $value) {
if ((empty($key)) && (count($value) == 0)) {
$presentacionsList = array();
}
}
}
return $presentacionsList;
}
public function getColorList()
{
$variants = $this->getAllActiveVariants();
$attributes = $this->getAllAttributes($this);
$colorList = array();
if (count($variants) > 0) {
if (key_exists('color', $attributes)) {
foreach ($variants as $variant) {
$colorId = $variant->getAttributeValue($attributes['color']);
if ($colorId > 0) {
$colorObj = \Pimcore\Model\DataObject\Colores::getById($colorId);
if (!empty($colorObj)) {
$colorList[$colorObj->getOrder()] = $colorObj;
}
}
}
}
} else {
if (key_exists('color', $attributes)) {
$colorId = $this->getAttributeValue($attributes['color']);
if ($colorId > 0) {
$colorObj = \Pimcore\Model\DataObject\Colores::getById($colorId);
if (!empty($colorObj)) {
$colorList[$colorObj->getOrder()] = $colorObj;
}
}
}
}
ksort($colorList, 1);
return $colorList;
}
public function getVariantPriceList()
{
$variants = $this->getAllActiveVariants();
$precios = array();
// $parentPrice = floatval(str_replace(",", ".", str_replace(".", "", $this->getPrice())));
$parentPrice = $this->getPrice();
if (!empty(trim("" . $parentPrice))) {
$precios[] = $parentPrice;
}
foreach ($variants as $variant) {
//$variantPrice = floatval(str_replace(",", ".", str_replace(".", "", $variant->getPrice())));
$variantPrice = $variant->getPrice();
if (!empty(trim("" . $variantPrice))) {
$precios[] = $variantPrice;
}
}
$precios = array_unique($precios);
sort($precios, SORT_NUMERIC);
return $precios;
}
public function getVariantPriceListV2($useLimitedVariants = false)
{
if ($useLimitedVariants){
$variants = $this->getLimitedChildren(35, [AbstractObject::OBJECT_TYPE_VARIANT]);
}else{
$variants = $this->getAllActiveVariants();
}
$precios = array();
// $parentPrice = floatval(str_replace(",", ".", str_replace(".", "", $this->getPrice())));
$parentPrice = $this->getPrice();
if (!empty(trim("" . $parentPrice))) {
$precios[] = $parentPrice;
}
foreach ($variants as $variant) {
//$variantPrice = floatval(str_replace(",", ".", str_replace(".", "", $variant->getPrice())));
$variantPrice = $variant->getPrice();
if (!empty(trim("" . $variantPrice))) {
$precios[] = $variantPrice;
}
}
$precios = array_unique($precios);
sort($precios, SORT_NUMERIC);
return $precios;
}
public function getVariantPriceAndIdList($useLimitedVariants = false)
{
if ($useLimitedVariants) {
$variants = $this->getLimitedChildren(35, [AbstractObject::OBJECT_TYPE_VARIANT]);
} else {
$variants = $this->getAllActiveVariants();
}
$precios = [];
// $parentPrice = floatval(str_replace(",", ".", str_replace(".", "", $this->getPrice())));
$parentPrice = $this->getPrice();
if (!empty(trim("" . $parentPrice))) {
$precios[$this->getId()] = $parentPrice;
}
foreach ($variants as $variant) {
//$variantPrice = floatval(str_replace(",", ".", str_replace(".", "", $variant->getPrice())));
$variantPrice = $variant->getPrice();
if (!empty(trim("" . $variantPrice))) {
$precios[$variant->getId()] = $variantPrice;
}
}
$precios = array_unique($precios);
return $precios;
}
public function getPriceNumeric()
{
return $this->floatvalue($this->getPrice());
}
/*
public function getPrice()
{
if (parent::getPrice() && "0" !== parent::getPrice()) {
return number_format($this->floatvalue(parent::getPrice()), 2, ",", "") ;
} else {
return parent::getPrice();
}
}
*/
public function getAllActiveVariants($orderKeys = array())
{
$productList = $this->getChildren([AbstractObject::OBJECT_TYPE_VARIANT]);
$variantsList = array(); // $this->getAllActiveVariantsOrderByPublication($productList);
if (count($variantsList) == 0) {
$variantsList = $this->getAllActiveVariantsOrderByKeys($productList, $orderKeys);
}
ksort($variantsList);
return $variantsList;
}
private function getAllActiveVariantsOrderByPublication($productList)
{
$variantsList = array();
if (class_exists('\IndabaPublicationBundle\Controller\TreeController')) {
$variantInfo = $this->getVariantsInfosFromPublication();
if (count($variantInfo)) {
foreach ($productList as $product) {
if (!in_array($product->getProductstatus(), array('new', 'decatelogized', 'for_delete'))) {
$key = str_pad("0", 6, "0", STR_PAD_LEFT);
$variantsList[$key] = $product;
}
}
}
}
return $variantsList;
}
private function getVariantsInfosFromPublication()
{
$variantInfo = array();
$db = \Pimcore\Db::get();
$query = "SELECT `id`,`structure_path`,`name` FROM `schrader_catalogue_structure` WHERE `object_id` = " . $this->getId();
$result = $db->query($query);
$structurePath = "";
if ($row = $result->fetch()) {
$structurePath = $row["structure_path"] . $row["name"] . "/";
}
if (!empty($structurePath)) {
$query = "SELECT `id`,`object_id`,`orden` FROM `schrader_catalogue_structure` WHERE `structure_path` = '" . $structurePath . "%' Order By `orden`;";
$result = $db->query($query);
while ($row = $result->fetch()) {
$variantInfo[$row["orden"]] = $row["object_id"];
}
}
return $variantInfo;
}
private function getAllActiveVariantsOrderByKeys($productList, $orderKeys = array())
{
$variantsList = array();
$attributes = $this->getAllAttributes($this);
foreach ($productList as $product) {
if (!in_array($product->getProductstatus(), array('new', 'decatelogized', 'for_delete'))) {
$keyArray = array();
foreach ($orderKeys as $orderKey) {
\Pimcore\Log\Simple::log("DefaultProduct", $orderKey);
if (key_exists($orderKey, $attributes)) {
switch ($attributes[$orderKey]["fieldtype"]) {
case "inputQuantityValue" :
case "quantityValue" :
$value = $product->getAttributeValue($attributes[$orderKey]);
$quantity = ($value && method_exists($value, "getValue")) ? $value->getValue() : "";
$unit = ($value && method_exists($value, "getUnit") && $value->getUnit()) ? $value->getUnit()->getAbbreviation() : "";
if (!empty($quantity)) {
switch (true) {
case(in_array($unit, array("ml", "l", "pt", "gal"))) :
$sortvalue = floor($this->convertToML($quantity, $unit));
break;
case(in_array($unit, array("kg", "g"))) :
$sortvalue = floor($this->convertToMG($quantity, $unit));
break;
case(in_array($unit, array("mm", "cm", "m"))) :
$sortvalue = floor($this->convertToMM($quantity, $unit));
break;
default :
$sortvalue = $quantity;
}
$keyArray[] = str_pad($sortvalue, 6, "0", STR_PAD_LEFT);
}
break;
default:
$sortvalue = $product->getAttributeValue($attributes[$orderKey]);
if ($orderKey == 'tallainternational') {
$key = array_search($sortvalue, $this->internationalSizeOrden);
$sortvalue = str_pad($key, 6, "0", STR_PAD_LEFT);
}
$keyArray[] = $sortvalue;
}
}
}
$keyArray[] = (!empty($product->getBsncode())) ? $product->getBsncode() : $product->getManufacturercode();
$key = implode("_", $keyArray);
$variantsList[$key] = $product;
}
}
return $variantsList;
}
public function getAttributeValue($fieldinfo)
{
// $value = "";
$fieldObj = $this;
for ($i = 0; $i < count($fieldinfo["getters"]) - 1; $i++) {
$getter = $fieldinfo["getters"][$i];
$fieldObj = $fieldObj->$getter();
}
$getter = $fieldinfo["getters"][count($fieldinfo["getters"]) - 1];
$value = $fieldObj->$getter();
return $value;
}
public function getAllAttributes($obj)
{
$fieldArray = array();
$this->getDataDefinition($obj, $fieldArray);
$allFields = array();
foreach ($fieldArray as $key => $field) {
if ($key == "attributes") {
$getterPrdAttribute = "get" . ucfirst($field["name"]);
foreach ($field["objectbricks"] as $objbr) {
$getterObjectBrick = $objbr["objectbrick"];
foreach ($objbr["fields"] as $fieldOB) {
$getterField = "get" . ucfirst($fieldOB->name);
$valueObject = $obj->$getterPrdAttribute()->$getterObjectBrick()->$getterField();
$allFields[$fieldOB->name] = array("fieldtype" => $fieldOB->fieldtype, "name" => $fieldOB->name, "title" => $fieldOB->title, "getters" => array($getterPrdAttribute, $getterObjectBrick, $getterField));
}
}
}
}
return $allFields;
}
public function getVariantsAttributes()
{
$excludeArray = $this->getExcludeVariantsFields();
$attributes = $this->getAllAttributes($this);
$variants = $this->getAllActiveVariants();
$variantsFieldArray = array();
foreach ($attributes as $key => $value) {
if (!in_array($key, $excludeArray)) {
$parentValue = $this->getAttributeValue($value);
foreach ($variants as $variant) {
$variantValue = $variant->getAttributeValue($value); {
if ($parentValue instanceof \Pimcore\Model\DataObject\Data\InputQuantityValue && $variantValue instanceof \Pimcore\Model\DataObject\Data\InputQuantityValue) {
if ($parentValue->getValue() !== $variantValue->getValue() || $parentValue->getUnitId() !== $variantValue->getUnitId()) {
$variantsFieldArray[$key] = $value;
}
}else{
if ($parentValue !== $variantValue ) {
$variantsFieldArray[$key] = $value;
}
}
}
}
}
}
return $variantsFieldArray;
}
public function getDataDefinition($obj, &$fieldArray, $excludeArray = array())
{
if (method_exists($obj, "getClass")) {
$classFielddefinition = $obj->getClass()->getFieldDefinitions();
} else {
$classFielddefinition = $obj->getDefinition()->getFieldDefinitions();
}
foreach ($classFielddefinition as $key => $fieldDefinition) {
if (in_array($key, $excludeArray)) {
continue;
}
switch ($fieldDefinition->fieldtype) {
case "panel" :
$this->getChildDataDefinition($fieldDefinition, $fieldArray);
break;
case "localizedfields" :
$this->getFieldDefinitionCache($fieldDefinition, $fieldArray);
break;
case "objectbricks" :
if ($obj && $obj->getAttributes()) {
$objectBricks = $obj->getAttributes()->getBrickGetters();
// $objectBricks = $obj->getAttributes()->items ;
foreach ($objectBricks as $objBr) {
if ($obj->getAttributes()->$objBr()) {
$fieldArrayObjBrick = array();
$this->getDataDefinition($obj->getAttributes()->$objBr(), $fieldArrayObjBrick);
$fieldArray[$key]["name"] = $fieldDefinition->name;
$fieldArray[$key]["type"] = $fieldDefinition->fieldtype;
$fieldArray[$key]["objectbricks"][] = array("objectbrick" => $objBr, "fields" => $fieldArrayObjBrick);
}
}
}
break;
default:
if ($fieldDefinition->datatype == "data") {
$fieldArray [$key] = $fieldDefinition;
}
}
}
}
private function getChildDataDefinition($fieldDefinition, &$fieldArray)
{
$childArray = $fieldDefinition->childs;
foreach ($childArray as $ch) {
if ($ch->datatype == "layout") {
$this->getChildDataDefinition($ch, $fieldArray);
} else {
$fieldArray[$ch->name] = $ch;
}
}
}
private function getFieldDefinitionCache($fieldDefinition, &$fieldArray)
{
$childArray = $fieldDefinition->fieldDefinitionsCache;
if ($childArray == null) {
$childArray = $fieldDefinition->childs;
}
foreach ($childArray as $ch) {
$fieldArray[$ch->name] = $ch;
}
}
private function getExcludeVariantsFields()
{
$excludeArray = array();
$excludeArray[] = "indaba";
$excludeArray[] = "view_in_web";
$excludeArray[] = "preview";
$excludeArray[] = "stock";
$excludeArray[] = "bsncode";
$excludeArray[] = "productstatus";
$excludeArray[] = "titleerp";
$excludeArray[] = "barcode";
$excludeArray[] = "ubicacion";
$excludeArray[] = "name";
$excludeArray[] = "shortdescription";
$excludeArray[] = "longdescription";
$excludeArray[] = "images";
$excludeArray[] = "categories";
$excludeArray[] = "documents";
$excludeArray[] = "urlseofriendly";
$excludeArray[] = "seodescription";
return $excludeArray;
}
private function convertToML($quantity, $unit)
{
$pintToMl = 473.1764;
$galToMl = 3785.4118;
if (!empty($quantity)) {
$quantity = trim("" . $quantity);
$quantityArray = explode(" ", $quantity);
foreach ($quantityArray as $key => $quantity) {
$quantityArray[$key] = $this->fractionToDecimal($quantity);
}
if ($unit != "ml") {
switch ($unit) {
case "l" :
$quantity = str_replace(",", ".", "" . $quantityArray[0]);
$quantity = floatval($quantity) * 1000;
break;
case "pt" :
$quantity = 0;
foreach ($quantityArray as $q) {
$quantity = $quantity + ($pintToMl * $q);
}
break;
case "gal" :
$quantity = 0;
foreach ($quantityArray as $q) {
$quantity = $quantity + ($galToMl * $q);
}
break;
}
}
}
return $quantity;
}
private function convertToMG($quantity, $unit)
{
if (!empty($quantity)) {
$quantity = trim("" . $quantity);
$quantityArray = explode(" ", $quantity);
foreach ($quantityArray as $key => $quantity) {
$quantityArray[$key] = $this->fractionToDecimal($quantity);
}
if ($unit != "g") {
switch ($unit) {
case "kg" :
$quantity = str_replace(",", ".", "" . $quantityArray[0]);
$quantity = floatval($quantity) * 1000;
break;
}
}
}
return $quantity;
}
private function convertToMM($quantity, $unit)
{
if (!empty($quantity)) {
$quantity = trim("" . $quantity);
$quantityArray = explode(" ", $quantity);
foreach ($quantityArray as $key => $quantity) {
$quantityArray[$key] = $this->fractionToDecimal($quantity);
}
if ($unit != "mm") {
switch ($unit) {
case "m" :
$quantity = str_replace(",", ".", "" . $quantityArray[0]);
$quantity = floatval($quantity) * 1000;
break;
case "cm" :
$quantity = str_replace(",", ".", "" . $quantityArray[0]);
$quantity = floatval($quantity) * 10;
break;
}
}
}
return $quantity;
}
private function fractionToDecimal($fraction)
{
$multipl = 1;
$numArray = explode("/", $fraction);
$numXArray = explode("x", $numArray[0]);
if (count($numXArray) == 2) {
$numArray[0] = $numXArray[1];
$multipl = $numXArray[0];
}
if (count($numArray) == 2) {
return (intval($numArray[0]) / intval($numArray[1])) * intval($multipl);
} else {
return $numArray[0];
}
}
/*
*
* Own functions bsnbarcelona end
*/
protected $prices = [];
/**
* Returns an array on min and max price for a product based on all it's children
*
* @param string $priceType (new|old)
*
* @return array|int|null
*/
public function getPriceRange($priceType = 'new')
{
if (!array_key_exists($priceType, $this->prices)) {
$method = $priceType == 'new' ? 'getPrice' : 'getPriceOld';
if ($this->isVariant()) {
return $this->$method();
} else {
$prices = [];
$colorSizeVariants = $this->internalGetSizeVariants();
foreach ($colorSizeVariants as $sizeVariants) {
foreach ($sizeVariants as $sizeVariant) {
$prices[] = $sizeVariant->$method();
}
}
if ($prices) {
$min = min($prices);
$max = max($prices);
if ($min == $max) {
$this->prices[$priceType] = $min;
} else {
$this->prices[$priceType] = ['min' => $min, 'max' => $max];
}
} else {
$this->prices[$priceType] = null;
}
}
}
return $this->prices[$priceType];
}
/**
* @return \Pimcore\Model\Asset\Image|null
*/
public function getFirstImageAsset()
{
if (method_exists($this, "getImages")) {
$imageList = $this->getImages();
$isOnlyOneImage = (count($imageList) == 1);
if (count($imageList) > 1) {
foreach ($imageList as $imageObject) {
if (($imageObject->getWww()) && (($isOnlyOneImage) || ($imageObject->getOrder() < 2))) {
return $imageObject->getElement();
}
}
} else {
if ($isOnlyOneImage) {
return $imageList[0]->getElement();
}
}
}
return null;
}
/**
* returns product variant that should be used for detail link
*
* @return \App\Model\DefaultProduct
*/
public function getLinkProduct()
{
$firstSizeVariants = $this->getColorVariants(true);
return $this; //Link of the same product, not to its variants
// if (count($firstSizeVariants) == 0) {
// // no variants
// return $this;
// } else {
// return $firstSizeVariants[0];
// }
}
/**
* Returns concatenated category names for product
*
* @param bool $seo to suppress seo name, default is true and returns the seo name if available
*
* @return string
*/
public function getCategoriesText($seo = true)
{
$categories = $this->getCategories();
$categoriesArray = [];
foreach ($categories as $item) {
$categoriesArray[] = ($item->getUrlseofriendly() && $seo) ? $item->getUrlseofriendly() : $item->getTitle();
}
return implode(',', $categoriesArray);
}
public function getMainMaterialText()
{
$mainMaterials = $this->getMaterialComposition() ? $this->getMaterialComposition() : [];
$mainMaterialsArray = [];
foreach ($mainMaterials as $item) {
if ($item->getPercent()) {
$mainMaterialsArray[] = $item->getPercent() . '% ' . $item->getObject()->getName();
} else {
$mainMaterialsArray[] = $item->getObject()->getName();
}
}
return implode(',', $mainMaterialsArray);
}
public function getSecondaryMaterialText()
{
$secondaryMaterials = $this->getSecondaryMaterialComposition() ? $this->getSecondaryMaterialComposition() : [];
$secondaryMaterialsArray = [];
foreach ($secondaryMaterials as $item) {
if ($item->getPercent()) {
$secondaryMaterialsArray[] = $item->getPercent() . '% ' . $item->getObject()->getName();
} else {
$secondaryMaterialsArray[] = $item->getObject()->getName();
}
}
return implode(',', $secondaryMaterialsArray);
}
public function getCanonicalId()
{
if ($this->isVariant()) {
return $this->getParent()->getCanonicalId();
} else {
return $this->getId();
}
}
/**
* Returns the first size variant for all color variants (or just the color variants) of a product regardless if it's the main product or already a color variant
*
* @param $withSize switch the color with ot without the first size variant
*
* @return \App\Model\DefaultProduct[]
*/
public function getColorVariants($withSize = true)
{
if ($withSize) {
$firstSizeVariants = [];
foreach ($this->internalGetFirstSizeVariants() as $id => $sizeVariant) {
if ($sizeVariant) {
$firstSizeVariants[] = $sizeVariant;
} else {
$firstSizeVariants[] = AbstractObject::getById($id);
}
}
return $firstSizeVariants;
} else {
return $this->internalGetColorVariants();
}
}
public $baseProduct = null;
public $baseColorVariant = null;
private $colorVariants = null;
public $firstSizeVariants = null;
private $sizeVariants = null;
protected function fillBaseProducts()
{
if (!$this->isVariant()) {
$this->baseProduct = $this;
$this->baseColorVariant = null;
} elseif ($this->getType() == AbstractObject::OBJECT_TYPE_OBJECT) {
$this->baseProduct = $this->getParent();
$this->baseColorVariant = $this;
} elseif ($this->getType() == AbstractObject::OBJECT_TYPE_VARIANT && $this->getParent()->getType() == AbstractObject::OBJECT_TYPE_OBJECT) {
$this->baseColorVariant = $this->getParent();
$this->baseProduct = $this->getParent()->getParent();
} else {
throw new \Exception('Invalid Product Tree with object ' . $this->getId());
}
}
protected function fillVariants()
{
$this->fillBaseProducts();
$this->colorVariants = $this->internalGetColorVariants();
$this->firstSizeVariants = [];
if (!empty($this->colorVariants)) {
foreach ($this->colorVariants as $colorVariant) {
$children = $colorVariant->getChildren(([AbstractObject::OBJECT_TYPE_VARIANT]));
$this->firstSizeVariants[$colorVariant->getId()] = reset($children);
}
}
}
public function internalGetBaseProduct()
{
if (empty($this->baseProduct)) {
$this->fillVariants();
}
return $this->baseProduct;
}
protected function internalGetColorVariants()
{
if ($this->colorVariants === null) {
$this->colorVariants = $this->internalGetBaseProduct()->getChildren([AbstractObject::OBJECT_TYPE_OBJECT]);
}
return $this->colorVariants;
}
protected function internalGetSizeVariants()
{
if ($this->sizeVariants === null) {
$this->sizeVariants = [];
if (!empty($this->colorVariants)) {
foreach ($this->colorVariants as $colorVariant) {
$this->sizeVariants[$colorVariant->getId()] = $colorVariant->getChildren(([AbstractObject::OBJECT_TYPE_VARIANT]));
}
}
}
return $this->sizeVariants;
}
protected function internalGetFirstSizeVariants()
{
if ($this->firstSizeVariants === null) {
$this->fillVariants();
}
return $this->firstSizeVariants;
}
public function getBaseColorVariant()
{
if (empty($this->baseColorVariant)) {
$this->fillVariants();
}
return $this->baseColorVariant;
}
/**
* Returns size variants for a product regardless if it's the main product, a color child or a size variant
*
* @return \App\Model\DefaultProduct[]|null
*/
public function getSizeVariants()
{
if (empty($this->baseProduct)) {
$this->fillBaseProducts();
}
if ($this->baseColorVariant) {
$list = new Product\Listing();
$list->setCondition('o_parentId = ?', $this->baseColorVariant->getId());
$list->setObjectTypes([AbstractObject::OBJECT_TYPE_VARIANT]);
$list->setOrderKey('size');
$list->setOrder('ASC');
return SizeSort::sort($list->load());
} else {
return [];
}
}
protected $isVariant = null;
/**
* Checks if a a product is a variant or the main product
*
* @return bool
*/
public function isVariant()
{
if ($this->isVariant === null) {
if ($this->getType() == 'object' && $this->getParent() instanceof Folder) {
$this->isVariant = false;
} else {
$this->isVariant = true;
}
}
return $this->isVariant;
}
public function hasTechnologyAttributes()
{
return $this->getMainMaterialText() || $this->getSecondaryMaterialText() || $this->getFeatures();
}
public function getFirstCategory()
{
//\Pimcore\Model\DataObject\AbstractObject::setGetInheritedValues(true);
if ($categories = $this->getCategories()) {
foreach ($categories as $cat) {
return $cat;
}
}
}
public function getPriceTax($tax)
{
$price = $this->floatvalue($this->getPrice());
return $price * $this->floatvalue($tax);
}
/**
* enables inheritance for field collections, if xxxInheritance field is available and set to string 'true'
*
* @param string $key
*
* @return mixed|\Pimcore\Model\DataObject\Fieldcollection
*/
public function preGetValue($key)
{
if ($this->getClass()->getAllowInherit() && AbstractObject::doGetInheritedValues() && $this->getClass()->getFieldDefinition($key) instanceof \Pimcore\Model\DataObject\ClassDefinition\Data\Fieldcollections
) {
$checkInheritanceKey = $key . 'Inheritance';
if ($this->{
'get' . $checkInheritanceKey
}() == 'true'
) {
$parentValue = $this->getValueFromParent($key);
$data = $this->$key;
if (!$data) {
$data = $this->getClass()->getFieldDefinition($key)->preGetData($this);
}
if (!$data) {
return $parentValue;
} else {
$value = new \Pimcore\Model\DataObject\Fieldcollection($data->getItems());
if (!empty($parentValue)) {
foreach ($parentValue as $entry) {
$value->add($entry);
}
}
return $value;
}
}
}
return parent::preGetValue($key);
}
function floatvalue($val)
{
$val = str_replace(",", ".", $val);
$val = preg_replace('/\.(?=.*\.)/', '', $val);
return floatval($val);
}
public function getLimitedChildren($limit = 10, $objectTypes = [self::OBJECT_TYPE_VARIANT]) {
$list = new Product\Listing();
$list->setCondition('o_parentId = ?', $this->getId());
$list->setOrderKey(sprintf('o_%s', $this->getChildrenSortBy()));
$list->setOrder($this->getChildrenSortOrder());
$list->setObjectTypes($objectTypes);
$list->setLimit($limit);
return $list->load();
}
}