gurl_o/plugins/tps/birzha/components/SearchOffers.php

93 lines
2.2 KiB
PHP

<?php namespace TPS\Birzha\Components;
use Cms\Classes\ComponentBase;
use TPS\Birzha\Models\Product;
use Input;
use Flash;
use RainLab\User\Models\User;
class SearchOffers extends ComponentBase
{
/**
* @var Collection A collection of user's posts
*/
public $products;
public $params;
public $keyword;
public function componentDetails()
{
return [
'name' => 'Search offers List',
'description' => 'List of searched offers'
];
}
public function defineProperties()
{
return [
'perPage' => [
'title' => 'Number of offers',
'description' => 'How many offers do you want to display',
'default' => 12,
'validationPattern' => '^[0-9]+$',
'validationMessage' => 'Only numbers allowed'
],
];
}
public function onRun() {
$allParams = \Input::all();
$params = '';
foreach ($allParams as $key => $item) {
if($key != 'page'){
$params .= '&'.$key.'='.$item;
}
}
$this->keyword = \Input::get('name');
$this->params = $params;
$this->products = $this->loadProducts();
}
protected function loadProducts() {
$perPage = $this->property('perPage');
$sort = \Input::get('sort');
$products = Product::query();
$title = \Input::get('name');
if (isset($sort) && $sort != '') {
$sort = self::getSort($sort);
$products = $products->where('name', 'like', '%'.$title.'%')->withCount("images")->orderBy( $sort[0], $sort[1]);
}else{
$products = $products->where('name', 'like', '%'.$title.'%')->withCount("images");
}
$products = $products->paginate($perPage);
return $products;
}
private static function getSort($sort): array
{
$sort_key = trim($sort, '-');
if (str_contains($sort, '-') && strpos($sort, '-') == 0) {
$sort_direction = 'desc';
}
return [
$sort_key,
$sort_direction ?? 'asc'
];
}
}