This repository has been archived on 2024-10-25. You can view files and clone it, but cannot push or open issues or pull requests.
Sequenzia/app/models/Advertisement.php

115 lines
2.9 KiB
PHP
Raw Normal View History

2013-11-18 05:33:10 +01:00
<?php
class Advertisement extends Rails\ActiveRecord\Base
{
# Valid positions for horizontal advertisements: any, top, bottom.
static protected $POSITIONS = ['a', 't', 'b'];
2013-11-21 20:08:11 +01:00
protected function validations()
{
return [
'ad_type' => [
'inclusion' => ['in' => ['horizontal', 'vertical']]
],
2013-12-02 03:26:35 +01:00
'ad_type' => [ 'presence' => true ],
'status' => [ 'presence' => true ],
'validateType',
'validatePosition',
2013-11-21 20:08:11 +01:00
];
}
2013-11-18 05:33:10 +01:00
static public function random($type = 'vertical', $position = null)
2013-11-21 20:08:11 +01:00
{
$sql = self::where(['ad_type' => $type, 'status' => 'active'])->order('RAND()');
if ($position) {
$sql->where('position IN (?)', ['a', $position]);
}
return $sql->first();
2013-11-21 20:08:11 +01:00
}
static public function reset_hit_count($ids)
{
foreach (self::where('id IN (?)', $ids)->take() as $ad) {
$ad->updateAttribute('hit_count', 0);
}
}
# virtual method for resetting hit count in view
public function setResetHitCount($is_reset)
{
if ($is_reset) {
$this->hit_count = 0;
}
}
# virtual method for no-reset default in view's form
public function getResetHitCount()
{
return '0';
}
2013-12-02 03:26:35 +01:00
public function prettyPosition()
{
switch ($this->position) {
case 'a':
return 'Any';
case 't':
return 'Top';
case 'b':
return 'Bottom';
default:
return 'Unknown';
}
}
protected function validatePosition()
{
if ($this->ad_type == 'vertical') {
$this->position = null;
} else {
if (!in_array($this->position, self::$POSITIONS)) {
$this->errors()->add('position', "is invalid");
return false;
}
}
}
2013-12-02 03:26:35 +01:00
protected function validateType()
{
# Common needed attributes, width and height.
$attr = null;
if (!$this->width) {
$attr = 'width';
} elseif (!$this->height) {
$attr = 'height';
}
if ($attr) {
$this->errors()->add($attr, "can't be blank");
return false;
}
2013-12-02 03:26:35 +01:00
if ($this->html) {
$this->image_url = null;
$this->referral_url = null;
} else {
$attr = '';
if (!$this->image_url) {
$attr = 'image_url';
} elseif (!$this->referral_url) {
$attr = 'referral_url';
}
if ($attr) {
$this->errors()->add($attr, "can't be blank");
return false;
}
$this->html = null;
}
}
2013-11-18 05:33:10 +01:00
}