Skip to content

Instantly share code, notes, and snippets.

@eonarik
Last active April 7, 2019 16:24
Show Gist options
  • Save eonarik/dfd0f029f9d3e86727a44521b0e95c1f to your computer and use it in GitHub Desktop.
Save eonarik/dfd0f029f9d3e86727a44521b0e95c1f to your computer and use it in GitHub Desktop.
modx processor web/resources/getdata
<?php // v. 2.0.2
require_once dirname(dirname(dirname(__FILE__))).'/site/web/resources/getdata.class.php';
class modWebResourcesGetdataProcessor extends modSiteWebResourcesGetdataProcessor {
public function initialize(){
$this->setDefaultProperties(array(
'cache' => true, // Use cache
'cache_lifetime' => 3600, // cache seconds
'discount_tv_id' => 0, // tv id from discount
'params_category_id' => 0, // category id from display params
'image_tv_name' => 'image',
'image_absolute_path' => false,
'thumb' => null,
'date_format' => array('createdon' => 2), // date format from createdon timestamp
'page' => !empty($_REQUEST['page']) ? $_REQUEST['page'] : 1,
));
$ok = parent::initialize();
if($sortby = $this->getProperty('sortby')){
$this->setProperty('sort', '');
}
return $ok;
}
public function prepareQueryBeforeCount(xPDOQuery $c) {
$c = parent::prepareQueryBeforeCount($c);
$alias = $c->getAlias();
// доп параметр - depth: глубина вложенности
if($depth = $this->getProperty('depth')){
$where = $this->getProperty('where');
$parents = explode(',',$where['parent']);
unset($where['parent']);
$where['parent:IN'] = $parents;
//
foreach($parents as $par){
$where['parent:IN'] = array_merge($where['parent:IN'],$this->modx->getChildIds($par));
}
$this->setProperty('where', $where);
$c->where($where);
}
// Обработаем параметр tvFilter
if($filter = $this->getProperty('tvFilter')){
foreach($filter as $key => $value){
if(!is_numeric($key)){
// ключ может быть такого вида 'tv.value:>' либо 'or:tv.value:like'
$ev = explode(':',$key);
if(count($ev) > 2){
$key = str_replace('.value','',$ev[1]);
} else {
$key = str_replace('.value','',$ev[0]);
}
} else {
preg_match('/([a-zA-Z0-9_]+?)\.value/is', is_array($value) ? $value[0] : $value, $matches);
$key = $matches[1];
}
// проверим указан ли ключ тв как строка ли число (ид)
if(is_numeric($key)){
$tv = $this->modx->getObject('modTemplateVar', $key);
} else {
$tv = $this->modx->getObject('modTemplateVar', array('name' => $key));
}
// приджойним все это дело
if($tv){
$c->innerJoin('modTemplateVarResource', "{$tv->name}", "`{$alias}`.`id` = `{$tv->name}`.`contentid` AND `{$tv->name}`.`tmplvarid` = {$tv->id}");
$c->select(array("{$tv->name}.value"));
# $c->select();
}
}
$c->where($filter);
}
// $c->prepare();
// echo $c->toSQL();
# exit;
// if($where = $this->getProperty('where')){
// $c->where($where);
// }
return $c;
}
public function prepareQueryAfterCount(xPDOQuery $c){
$c = parent::prepareQueryAfterCount($c);
$alias = $c->getAlias();
if($sortby = $this->getProperty('sortby')){
$resource_fields = array_keys($this->modx->newObject($alias)->toArray());
if(!is_array($sortby)){
$sortby = json_decode($sortby, true);
}
foreach($sortby as $sort => $dir){
if(in_array($sort, $resource_fields)){
$c->sortby($sort, $dir);
} else {
$tv = $this->modx->getObject('modTemplateVar', array('name' => $sort));
$table_alias = "{$tv->name}{$tv->id}";
$c->leftJoin('modTemplateVarResource', "{$table_alias}", "`{$alias}`.`id` = `{$table_alias}`.`contentid` AND `{$table_alias}`.`tmplvarid` = {$tv->id}");
if(in_array($sort, array('price', 'discount', 'sale_price'))){
$sort = 'cast(`' . $table_alias . '`.`value` as unsigned)';
} else {
$sort = $table_alias . '.value';
}
$c->sortby($sort, $dir);
}
}
}
return $c;
}
public function afterIteration(array $list){
$list = parent::afterIteration($list);
$discountTVid = $this->getProperty('discount_tv_id');
$paramsCategoryId = $this->getProperty('params_category_id');
$image_tv = $this->getProperty('image_tv_name');
$image_source = $this->modx->getObject('modTemplateVar',array('name' => $image_tv))->source;
foreach($list as & $l){
foreach ($l as & $value) {
if (is_numeric($value)) {
$value = intval($value);
}
}
if($date_format = $this->getProperty('date_format')) {
foreach($date_format as $key=>$value){
$rusMonths1 = array('Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Декабрь');
$rusMonths2 = array('января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','декабря');
$date = explode('-',date('Y-m-d',$l[$key]));
switch($value) {
case 1:
$l[$key . '_format'] = $rusMonths1[$date[1]-1]." ".$date[2].", ".$date[0];
break;
case 2:
$l[$key . '_format'] = $date[2]." ".$rusMonths2[$date[1]-1]." ".$date[0];
break;
default:
}
}
}
// Картинка
$l['image'] = '';
if($image = $l['tvs'][$image_tv]['value']) {
if(strpos($image, 'http') === 0){
$l['image'] = $image;
}
else {
$l['image'] = $this->setImageSource($image, $image_source, false);
if(!file_exists(MODX_BASE_PATH . ltrim($l['image'], '/'))){
$l['image'] = $this->modx->getOption('no_image');
} else {
$l['image'] = $l['image'];
}
}
} else {
$l['image'] = $this->modx->getOption('no_image');
}
if ($this->getProperty('image_absolute_path')) {
$l['image'] = $this->modx->getOption('site_url') . ltrim($l['image'], '/');
}
if($options = $this->getProperty('thumb')){
$l['thumb'] = $this->modx->runSnippet('phpthumbof',array('input'=>$l['image'],'options'=>$options));
}
if(!empty($l['tvs']['more_photos']['value'])){
$l['gallery'] = json_decode($l['tvs']['more_photos']['value'], 1);
foreach($l['gallery'] as & $img) {
$img['src'] = $this->setImageSource($img['src'], $image_source);
}
}
if(
!empty($l['tvs']['price']['value'])
AND $price = $l['tvs']['price']['value']
){
if(!$product_discount = $this->getDiscount($l['id'], $this->discountTVid)){
$product_discount = $this->modx->getOption('site.discount');
}
if($product_discount){
$l['old_price'] = $price;
$l['price'] = $l['old_price']*(1 - $product_discount/100);
} else {
if($sale_price = $l['tvs']['sale_price']['value']){
$l['price'] = $sale_price;
$l['old_price'] = $price;
$l['discount'] = number_format((1 - $l['price'] / $l['old_price']) * 100, 0, '.', ' ');
} else {
$l['price'] = $price;
}
}
}
if ($l['tvs']['_views'] AND $views = $l['tvs']['_views']['value']) {
$l['views'] = $views;
} else {
$l['views'] = 0;
}
foreach($l['tvs'] as $key => &$tv){
if(
$tv_object = $this->modx->getObject('modTemplateVar', $tv['tv_id'])
AND !empty($tv['value'])
){
// картинки
if($tv_object->type == 'image'){
$tv['value'] = $this->setImageSource($tv['value'], $tv_object->source);
}
// параметры
if($tv_object->category == $this->paramsCategoryId){
$tv_object = $tv_object->toArray();
// $i = $tv_object['rank'];
// if(!empty($l['params']) && !empty($l['params'][$i])){
// $i = md5($i);
// }
$l['params'][] = array(
'rank' => $tv_object['rank'],
'name' => $key,
'caption' => $tv_object['caption'],
'description' => $tv_object['description'],
'value' => $tv['value'],
'properties' => $tv_object['properties'],
);
}
}
}
if($l['params'])
ksort($l['params']);
unset($l['tv_caption']);
unset($l['tv_category']);
unset($l['tv_id']);
unset($l['tv_name']);
unset($l['tv_value']);
unset($l['tv_value_id']);
unset($l['type']);
}
return array_values($list);
}
public function setImageSource($image_path, $image_source = '', $full_url = true){
if(substr($image_path,0,1)!='/' && $image_source){
$source_path = $this->getSourcePath($image_source);
$image_path = $source_path . $image_path;
}
if ($full_url) {
$image_path = $this->modx->getOption('site_url') . ltrim($image_path,'/');
}
return $image_path;
}
// рекурсивная функция для получения всех дочерних id по критерию
public function getChildIds($parent=0,$depth=9,$options=array('isfolder'=>1),$alias='modResource'){
$ids = array();
$q = $this->modx->newQuery($alias);
$q->where($options);
$q->select(array(
"{$alias}.id"
));
if(!$q->prepare()) $this->modx->log(modX::LOG_LEVEL_ERROR,'['. __CLASS__ .'] !prepare');
if(!$q->stmt->execute()) $this->modx->log(modX::LOG_LEVEL_ERROR,"[". __CLASS__ ."] !execute \r\n" . $q->toSQL());
foreach($q->stmt->fetchAll(PDO::FETCH_ASSOC) as $ob){
$ids[] = $ob['id'];
$ids = array_merge($ids,$this->getChildIds($parent,$depth,$options,$alias));
}
return $ids;
}
// получаем скидку. Товар - Категория - Системная настройка
private function getDiscount($resource_id,$tv_id = 0){
$discount = 0;
if($tv_id && $resource_id){
if($tv = $this->modx->getObject('modTemplateVarResource',array('contentid'=>$resource_id,'tmplvarid'=>$tv_id))) {
$discount = $tv->get('value');
} else {
$discount = $this->getDiscount($this->modx->getObject('modResource',array('id'=>$resource_id))->get('parent'),$tv_id);
}
}
return $discount;
}
}
return 'modWebResourcesGetdataProcessor';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment