You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.8 KiB

6 years ago
<?php
namespace common\modules\banners\services;
use common\modules\banners\entities\Banner;
use common\modules\banners\forms\BannerForm;
use common\modules\banners\repositories\BannerRepository;
3 years ago
use Yii;
use yii\base\Exception;
6 years ago
use yii\base\Security;
3 years ago
use yii\db\StaleObjectException;
6 years ago
class BannerManageService
{
3 years ago
private BannerRepository $repository;
6 years ago
public function __construct(BannerRepository $repository)
{
3 years ago
$this->repository = $repository;
6 years ago
}
3 years ago
/**
* @param BannerForm $form
* @return Banner
* @throws Exception
*/
6 years ago
public function create(BannerForm $form): Banner
{
if ($form->image) {
$filename = $form->image->baseName . '_' . (new Security())->generateRandomString(5) . '.' . $form->image->extension;
3 years ago
$path = Yii::getAlias(Banner::FILE_ORIGINAL_PATH);
if (!file_exists($path)) {
mkdir($path, 0777, true);
}
$form->image->saveAs($path . '/' . $filename);
$form->image = $filename;
}
6 years ago
$banner = Banner::create(
$form->title,
$form->image,
6 years ago
$form->url,
$form->target,
$form->start_at,
$form->end_at,
$form->include_urls,
$form->exclude_urls,
$form->active,
$form->place_id
);
3 years ago
$this->repository->save($banner);
6 years ago
return $banner;
}
3 years ago
/**
* @param $id
* @param BannerForm $form
* @throws Exception
*/
6 years ago
public function edit($id, BannerForm $form): void
{
3 years ago
$banner = $this->repository->get($id);
6 years ago
if ($form->image) {
$filename = $form->image->baseName . '_' . (new Security())->generateRandomString(5) . '.' . $form->image->extension;
3 years ago
$path = Yii::getAlias(Banner::FILE_ORIGINAL_PATH);
$form->image->saveAs($path . '/' . $filename);
$form->image = $filename;
} else {
$form->image = $banner->image;
}
6 years ago
$banner->edit(
$form->title,
$form->image,
$form->url,
$form->target,
$form->start_at,
$form->end_at,
$form->include_urls,
$form->exclude_urls,
$form->active,
$form->place_id
6 years ago
);
3 years ago
$this->repository->save($banner);
6 years ago
}
3 years ago
/**
* @param $id
* @throws StaleObjectException
*/
6 years ago
public function remove($id): void
{
3 years ago
$banner = $this->repository->get($id);
$this->repository->remove($banner);
6 years ago
}
public function addView(Banner $banner)
{
$banner->views++;
3 years ago
$this->repository->save($banner);
}
public function addClick(Banner $banner)
{
$banner->clicks++;
3 years ago
$this->repository->save($banner);
}
6 years ago
}