Advertisement
Guest User

Untitled

a guest
Sep 4th, 2015
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.20 KB | None | 0 0
  1. <?php namespace Fonix\Products\Models;
  2.  
  3. use App;
  4. use Str;
  5. use Html;
  6. use Lang;
  7. use Model;
  8. use Markdown;
  9. use ValidationException;
  10. use Fonix\Products\Classes\TagProcessor;
  11. use Backend\Models\User;
  12.  
  13. class Post extends Model
  14. {
  15. use \October\Rain\Database\Traits\Validation;
  16.  
  17. public $table = 'fonix_products_posts';
  18.  
  19. /*
  20. * Validation
  21. */
  22. public $rules = [
  23. 'title' => 'required',
  24. 'slug' => ['required', 'regex:/^[a-z0-9\/\:_\-\*\[\]\+\?\|]*$/i'],
  25. 'content' => 'required',
  26. 'excerpt' => ''
  27. ];
  28.  
  29. /**
  30. * The attributes that should be mutated to dates.
  31. * @var array
  32. */
  33. protected $dates = ['published_at'];
  34.  
  35. /**
  36. * @var array Guarded fields
  37. */
  38. protected $guarded = ['*'];
  39.  
  40. /**
  41. * @var array Fillable fields
  42. */
  43. protected $fillable = [];
  44.  
  45. /**
  46. * The attributes on which the post list can be ordered
  47. * @var array
  48. */
  49. public static $allowedSortingOptions = array(
  50. 'title asc' => 'Title (ascending)',
  51. 'title desc' => 'Title (descending)',
  52. 'created_at asc' => 'Created (ascending)',
  53. 'created_at desc' => 'Created (descending)',
  54. 'updated_at asc' => 'Updated (ascending)',
  55. 'updated_at desc' => 'Updated (descending)',
  56. 'published_at asc' => 'Published (ascending)',
  57. 'published_at desc' => 'Published (descending)',
  58. );
  59.  
  60. /*
  61. * Relations
  62. */
  63. public $belongsTo = [
  64. 'user' => ['Backend\Models\User']
  65. ];
  66.  
  67. /*
  68. * $belongsToMany - Seleciona várias categorias
  69. * $hasOne - Somente uma categoria
  70. */
  71. public $belongsToMany = [
  72. 'categories' => ['Fonix\Products\Models\Category', 'table' => 'fonix_products_posts_categories', 'order' => 'name']
  73. ];
  74.  
  75. public $attachMany = [
  76. 'featured_images' => ['System\Models\File', 'order' => 'sort_order'],
  77. 'thumbnail' => ['System\Models\File'],
  78. 'share' => ['System\Models\File'],
  79. 'banner' => ['System\Models\File'],
  80. 'content_images' => ['System\Models\File']
  81. ];
  82.  
  83. /**
  84. * @var array The accessors to append to the model's array form.
  85. */
  86. protected $appends = ['summary', 'has_summary'];
  87.  
  88. public $preview = null;
  89.  
  90. /**
  91. * Lists posts for the front end
  92. * @param array $options Display options
  93. * @return self
  94. */
  95. public function scopeListFrontEnd($query, $options)
  96. {
  97. /*
  98. * Default options
  99. */
  100. extract(array_merge([
  101. 'page' => 1,
  102. 'perPage' => 30,
  103. 'sort' => 'created_at',
  104. 'categories' => null,
  105. 'search' => '',
  106. 'published' => true
  107. ], $options));
  108.  
  109. $searchableFields = ['title', 'slug', 'excerpt', 'content'];
  110.  
  111. if ($published)
  112. $query->isPublished();
  113. /*
  114. * Sorting
  115. */
  116. if (!is_array($sort)) $sort = [$sort];
  117. foreach ($sort as $_sort) {
  118.  
  119. if (in_array($_sort, array_keys(self::$allowedSortingOptions))) {
  120. $parts = explode(' ', $_sort);
  121. if (count($parts) < 2) array_push($parts, 'desc');
  122. list($sortField, $sortDirection) = $parts;
  123.  
  124. $query->orderBy($sortField, $sortDirection);
  125. }
  126. }
  127.  
  128. /*
  129. * Search
  130. */
  131. $search = trim($search);
  132. if (strlen($search)) {
  133. $query->searchWhere($search, $searchableFields);
  134. }
  135.  
  136. /*
  137. * Categories
  138. */
  139. if ($categories !== null) {
  140. if (!is_array($categories)) $categories = [$categories];
  141. $query->whereHas('categories', function($q) use ($categories) {
  142. $q->whereIn('id', $categories);
  143. });
  144. }
  145.  
  146. return $query->paginate($perPage, $page);
  147. }
  148.  
  149. /**
  150. * Allows filtering for specifc categories
  151. * @param Illuminate\Query\Builder $query QueryBuilder
  152. * @param array $categories List of category ids
  153. * @return Illuminate\Query\Builder QueryBuilder
  154. */
  155. public function scopeFilterCategories($query, $categories)
  156. {
  157. return $query->whereHas('categories', function($q) use ($categories) {
  158. $q->whereIn('id', $categories);
  159. });
  160. }
  161.  
  162. public function afterValidate()
  163. {
  164. if ($this->published && !$this->published_at) {
  165. throw new ValidationException([
  166. 'published_at' => Lang::get('fonix.products::lang.post.published_validation')
  167. ]);
  168. }
  169. }
  170.  
  171. public function getPublishedOptions($keyValue = null)
  172. {
  173. return [1 => 'Publicado', 0 => 'Rascunho'];
  174. }
  175.  
  176. public function beforeSave()
  177. {
  178. #dd($this->published);
  179. $this->content_html = self::formatHtml($this->content);
  180. }
  181.  
  182. /**
  183. * Sets the "url" attribute with a URL to this object
  184. * @param string $pageName
  185. * @param Cms\Classes\Controller $controller
  186. */
  187. public function setUrl($pageName, $controller)
  188. {
  189. $params = [
  190. 'id' => $this->id,
  191. 'slug' => $this->slug,
  192. ];
  193.  
  194. if (array_key_exists('categories', $this->getRelations())) {
  195. $params['category'] = $this->categories->count() ? $this->categories->first()->slug : null;
  196. }
  197.  
  198. return $this->url = $controller->pageUrl($pageName, $params);
  199. }
  200.  
  201. /**
  202. * Used to test if a certain user has permission to edit post,
  203. * returns TRUE if the user is the owner or has other posts access.
  204. * @param User $user
  205. * @return bool
  206. */
  207. public function canEdit(User $user)
  208. {
  209. return ($this->user_id == $user->id) || $user->hasAnyAccess(['fonix.products.access_other_posts']);
  210. }
  211.  
  212. public static function formatHtml($input, $preview = false)
  213. {
  214. $result = Markdown::parse(trim($input));
  215.  
  216. if ($preview)
  217. $result = str_replace('<pre>', '<pre class="prettyprint">', $result);
  218.  
  219. $result = TagProcessor::instance()->processTags($result, $preview);
  220.  
  221. return $result;
  222. }
  223.  
  224. //
  225. // Scopes
  226. //
  227.  
  228. public function scopeIsPublished($query)
  229. {
  230. return $query
  231. ->whereNotNull('published')
  232. ->where('published', true)
  233. ;
  234. }
  235.  
  236. //
  237. // Summary / Excerpt
  238. //
  239.  
  240. /**
  241. * Used by "has_summary", returns true if this post uses a summary (more tag)
  242. * @return boolean
  243. */
  244. public function getHasSummaryAttribute()
  245. {
  246. return strlen($this->getSummaryAttribute()) < strlen($this->content_html);
  247. }
  248.  
  249. /**
  250. * Used by "summary", if no excerpt is provided, generate one from the content.
  251. * Returns the HTML content before the <!-- more --> tag or a limited 600
  252. * character version.
  253. *
  254. * @return string
  255. */
  256. public function getSummaryAttribute()
  257. {
  258. $excerpt = array_get($this->attributes, 'excerpt');
  259. if (strlen(trim($excerpt))) {
  260. return $excerpt;
  261. }
  262.  
  263. $more = '<!-- more -->';
  264. if (strpos($this->content_html, $more) !== false) {
  265. $parts = explode($more, $this->content_html);
  266. return array_get($parts, 0);
  267. }
  268.  
  269. return Str::limit(Html::strip($this->content_html), 600);
  270. }
  271. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement