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

129 lines
3.4 KiB
PHP

<?php namespace TPS\Birzha\Components;
use Cms\Classes\ComponentBase;
use TPS\Birzha\Models\Product;
use TPS\Birzha\Models\Category;
use Input;
use Flash;
use RainLab\User\Models\User;
class UserOffers extends ComponentBase
{
/**
* @var Collection A collection of user's posts
*/
public $userProducts;
public $userCategories;
public $user;
public $params;
public function componentDetails()
{
return [
'name' => 'User offers List',
'description' => 'List of users 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'
],
'slug' => [
'title' => 'Select by category :slug',
'description' => 'Select by category',
'type' => 'string',
'default' => ''
],
'id' => [
'title' => 'Select by vendor :id',
'description' => 'Select by vendor',
'type' => 'string',
'default' => ''
],
];
}
public function onRun() {
$allParams = \Input::all();
$params = '';
foreach ($allParams as $key => $item) {
if($key != 'page'){
$params .= '&'.$key.'='.$item;
}
}
$this->params = $params;
$this->userCategories = $this->loadCategories();
$this->user = $this->loadUser();
$this->userProducts = $this->loadProducts();
}
protected function loadProducts() {
$perPage = $this->property('perPage');
$sort = \Input::get('sort');
$vendor_id = $this->property('id');
$categorySlug = $this->property('slug');
$category = Category::where('slug', $categorySlug)->first();
$products = Product::query();
if($category){
if (isset($sort) && $sort != '') {
$sort = self::getSort($sort);
$products = $category->products()->where('vendor_id', $vendor_id)->withCount("images")->orderBy( $sort[0], $sort[1]);
}else{
$products = $category->products()->where('vendor_id', $vendor_id)->withCount("images");
}
}else{
if (isset($sort) && $sort != '') {
$sort = self::getSort($sort);
$products = $products->where("vendor_id", $vendor_id)->withCount("images")->orderBy( $sort[0], $sort[1]);
}
}
$products = $products->paginate($perPage);
return $products;
}
private static function getSort($sort): array
{
// dd($sort);
$sort_key = trim($sort, '-');
if (str_contains($sort, '-') && strpos($sort, '-') == 0) {
$sort_direction = 'desc';
}
return [
$sort_key,
$sort_direction ?? 'asc'
];
}
protected function loadCategories(){
$user = User::find($this->property('id'));
$categories = $user->categories()->get();
return $categories;
}
protected function loadUser(){
$user = User::find($this->property('id'));
return $user;
}
}