Automation init...3

This commit is contained in:
최준흠 2024-09-11 15:36:25 +09:00
parent d1f462bce3
commit d6b6e71661
15 changed files with 314 additions and 246 deletions

View File

@ -15,25 +15,28 @@ $routes->addPlaceholder('uuid', '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}
//2. Config/Filters.php -> $aliases = ['authFilter' => AuthFilter::class] //2. Config/Filters.php -> $aliases = ['authFilter' => AuthFilter::class]
$routes->get('/', 'Home::index'); $routes->get('/', 'Home::index');
$routes->group('crawler', ['namespace' => 'App\Controllers\Crawler'], function ($routes) {
$routes->cli('yamap/crawling', 'YamapController::crawling');
$routes->cli('yamap/crawling/(:any)', 'YamapController::crawling/$1');
$routes->cli('yamap/small_image', 'YamapController::small_image');
$routes->cli('yamap/small_image/(:any)', 'YamapController::small_image/$1');
});
$routes->group('admin', ['namespace' => 'App\Controllers\Admin', 'filter' => 'authFilter:manager'], function ($routes) { $routes->group('admin', ['namespace' => 'App\Controllers\Admin', 'filter' => 'authFilter:manager'], function ($routes) {
$routes->get('/', 'Home::index'); $routes->get('/', 'Home::index');
$routes->group('user', function ($routes) { $routes->group('user', function ($routes) {
$routes->get('', 'UserController::index'); $routes->get('', 'UserController::index');
}); });
}); });
$routes->group('yamap', ['namespace' => 'App\Controllers\Yamap'], function ($routes) {});
$routes->group('mangboard', ['namespace' => 'App\Controllers\Mangboard'], function ($routes) { $routes->group('mangboard', ['namespace' => 'App\Controllers\Mangboard'], function ($routes) {
$routes->group('user', function ($routes) { $routes->group('user', function ($routes) {
$routes->get('/', 'UserController::index'); $routes->get('/', 'UserController::index');
$routes->cli('point/(:alpha)/(:num)', 'UserController::point/$1/$2'); $routes->cli('point/(:alpha)/(:num)', 'UserController::point/$1/$2');
$routes->cli('point/(:alpha)/(:num)/(:any)', 'UserController::point/$1/$2/$3'); $routes->cli('point/(:alpha)/(:num)/(:any)', 'UserController::point/$1/$2/$3');
$routes->cli('level', 'UserController::level'); $routes->cli('level/(:alpha)/(:num)', 'UserController::level/$1/$2');
$routes->cli('check_level', 'UserController::check_level');
$routes->cli('check_level/(:alpha)', 'UserController::check_level/$1');
});
$routes->group('crawler', function ($routes) {
$routes->cli('yamap', 'CrawlerController::yamap');
$routes->cli('yamap/(:any)', 'CrawlerController::yamap/$1');
});
$routes->group('image', function ($routes) {
$routes->cli('yamap', 'ImageController::yamap');
$routes->cli('yamap/(:any)', 'ImageController::yamap/$1');
}); });
}); });

View File

@ -1,38 +1,13 @@
<?php <?php
namespace App\Controllers\Crawler; namespace App\Controllers\Mangboard;
use App\Controllers\CommonController; use App\Controllers\CommonController;
use App\Libraries\MyCrawler\YamapLibrary as MyCrawler; use App\Libraries\MyCrawler\YamapLibrary as MyCrawler;
use App\Libraries\MyUtil\ImageLibrary;
class YamapController extends CommonController class CrawlerController extends CommonController
{ {
public function small_image(...$params) public function yamap(...$params): string
{
try {
$fullPath = WRITEPATH . "uploads" . DIRECTORY_SEPARATOR . getenv('yamap.storage.upload.path');
$image = new ImageLibrary();
if (in_array("debug", $params)) {
$image->setDebug(true);
}
$image->setSourcePath($fullPath);
$image->setDestinationPath($fullPath);
foreach ($image->getFilesByExtentionType($image->getSourcePath()) as $file) {
//저장파일명
$fileInfos = pathinfo($image->getDestinationPath() . DIRECTORY_SEPARATOR . $file, PATHINFO_ALL);
$dstFile = $fileInfos['filename'] . "_small." . $fileInfos['extension'];
$image->setDestinationFile($dstFile);
$image->create($file);
}
log_message("notice", "Crawler->" . __FUNCTION__ . " 작업이 완료되었습니다.");
return "완료되었습니다.";
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return $e->getMessage();
}
}
public function crawling(...$params): string
{ {
try { try {
$crawler = new MyCrawler(); $crawler = new MyCrawler();
@ -65,18 +40,19 @@ class YamapController extends CommonController
} else { } else {
$max_limit = count($items); $max_limit = count($items);
} }
$i = 0; $i = 1;
foreach ($items as $item) { foreach ($items as $item) {
if ($i <= $max_limit) { if ($i < $max_limit) {
try { try {
log_message("notice", "게시물 {$i}번째 {$item["nickname"]} 작업시작");
//3. DetailPage 처리 : bbs_view > div.contents 가진 객체를 찾아서 처리 //3. DetailPage 처리 : bbs_view > div.contents 가진 객체를 찾아서 처리
$fileEntitys = $crawler->detailPage($item["detail_url"]); $fileEntitys = $crawler->detailPage($item["detail_url"]);
//4.망보드 일반게시판에 게시물 등록 처리 //4.망보드 일반게시판에 게시물 등록 처리
if (count($fileEntitys)) { if (count($fileEntitys)) {
$crawler->createBoard($item, $fileEntitys); $crawler->createBoard($item, $fileEntitys);
} }
$i++;
log_message("notice", "게시물 {$i}번째 {$item["nickname"]} 작업완료."); log_message("notice", "게시물 {$i}번째 {$item["nickname"]} 작업완료.");
$i++;
} catch (\Exception $e) { } catch (\Exception $e) {
log_message("debug", $e->getMessage()); log_message("debug", $e->getMessage());
} }

View File

@ -0,0 +1,34 @@
<?php
namespace App\Controllers\Mangboard;
use App\Controllers\CommonController;
use App\Libraries\MyUtil\ImageLibrary;
class ImageController extends CommonController
{
public function yamap(...$params)
{
try {
$fullPath = WRITEPATH . "uploads" . DIRECTORY_SEPARATOR . getenv('yamap.storage.upload.path');
$image = new ImageLibrary();
if (in_array("debug", $params)) {
$image->setDebug(true);
}
$image->setSourcePath($fullPath);
$image->setDestinationPath($fullPath);
foreach ($image->getFilesByExtentionType($image->getSourcePath()) as $file) {
//저장파일명
$fileInfos = pathinfo($image->getDestinationPath() . DIRECTORY_SEPARATOR . $file, PATHINFO_ALL);
$dstFile = $fileInfos['filename'] . "_small." . $fileInfos['extension'];
$image->setDestinationFile($dstFile);
$image->create($file);
}
log_message("notice", "Crawler->" . __FUNCTION__ . " 작업이 완료되었습니다.");
return "완료되었습니다.";
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return $e->getMessage();
}
}
}

View File

@ -28,24 +28,50 @@ class UserController extends CommonController
public function point(string $id, string $point, string $sign = "+"): string public function point(string $id, string $point, string $sign = "+"): string
{ {
try { try {
$entity = $this->getModel()->getEntityByID($id); $entity = is_numeric($id) ? $this->getModel()->getEntityByPK(intval($id)) : $this->getModel()->getEntityByID($id);
if ($entity === null) { if (!$entity) {
throw new \Exception("해당 ID{$id}는 사용자가 존재하지 않습니다."); throw new \Exception("해당 {$id}의 회원이 없습니다.");
} }
$this->getModel()->setPoint($id, intval($point), $sign); $this->getModel()->setPoint($entity, intval($point), $sign);
return "완료되었습니다."; return __FUNCTION__ . " 작업이 완료되었습니다.";
} catch (\Exception $e) { } catch (\Exception $e) {
log_message("error", $e->getMessage()); log_message("error", $e->getMessage());
return $e->getMessage(); return $e->getMessage();
} }
} }
public function level(): string public function level(string $id, string $level): string
{ {
try { try {
$userModel = new UserModel(); $entity = is_numeric($id) ? $this->getModel()->getEntityByPK(intval($id)) : $this->getModel()->getEntityByID($id);
$userModel->setLevel(); if (!$entity) {
throw new \Exception("해당 {$id}의 회원이 없습니다.");
}
$this->getModel()->setLevel($entity, intval($level));
log_message("notice", "Mangboard->level 작업이 완료되었습니다."); log_message("notice", "Mangboard->level 작업이 완료되었습니다.");
return "완료되었습니다."; return __FUNCTION__ . " 작업이 완료되었습니다.";
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return $e->getMessage();
}
}
public function check_level($id = false): string
{
try {
if (!$id) {
foreach ($this->getModel()->getEntitys() as $entity) {
$level = $this->getModel->checkLevel($entity);
$this->getModel()->setLevel($entity, intval($level));
}
} else {
$entity = is_numeric($id) ? $this->getModel()->getEntityByPK(intval($id)) : $this->getModel()->getEntityByID($id);
if (!$entity) {
throw new \Exception("해당 {$id}의 회원이 없습니다.");
}
$level = $this->getModel->checkLevel($entity);
$this->getModel()->setLevel($entity, intval($level));
}
return __FUNCTION__ . " 작업이 완료되었습니다.";
} catch (\Exception $e) { } catch (\Exception $e) {
log_message("error", $e->getMessage()); log_message("error", $e->getMessage());
return $e->getMessage(); return $e->getMessage();

View File

@ -46,9 +46,14 @@ abstract class MyCrawlerLibrary extends CommonLibrary
list($fileName, $content) = $this->getMySocket()->download($node->attr($options["attr"])); list($fileName, $content) = $this->getMySocket()->download($node->attr($options["attr"]));
$entitys[] = $this->getMyStorage()->save($fileName, $mediaType, $content, $file_sequence); $entitys[] = $this->getMyStorage()->save($fileName, $mediaType, $content, $file_sequence);
$file_sequence++; $file_sequence++;
log_message("notice", __FUNCTION__ . " {$mediaType} 작업 완료"); log_message("notice", __FUNCTION__ . " MediaType->{$mediaType} 작업 완료");
} catch (\Exception $e) { } catch (\Exception $e) {
log_message("warning", "\n---" . __FUNCTION__ . "--\n" . $e->getMessage() . "\n-----------------------------------------\n"); log_message("warning", sprintf(
"\n---%s,MediaType->%s 오류---\n%s\n-----------------------------------------\n",
__FUNCTION__,
$mediaType,
$e->getMessage()
));
} }
} }
return $entitys; return $entitys;

View File

@ -3,7 +3,7 @@
namespace App\Libraries\MyCrawler; namespace App\Libraries\MyCrawler;
use App\Libraries\MySocket\WebLibrary as MySocketLibrary; use App\Libraries\MySocket\WebLibrary as MySocketLibrary;
use App\Libraries\MyStorage\MangboardLibrary as MyStorageLibrary; use App\Libraries\MyStorage\Mangboard\FileLibrary as MyStorageLibrary;
use App\Models\Mangboard\UserModel; use App\Models\Mangboard\UserModel;
use App\Models\Mangboard\BoardModel; use App\Models\Mangboard\BoardModel;
use App\Entities\Mangboard\BoardEntity; use App\Entities\Mangboard\BoardEntity;
@ -91,6 +91,7 @@ class YamapLibrary extends MyCrawlerLibrary
if (!count($items)) { if (!count($items)) {
throw new \Exception("Target URL이 없습니다."); throw new \Exception("Target URL이 없습니다.");
} }
log_message("notice", __FUNCTION__ . " 작업 완료");
return $items; return $items;
} }
@ -100,7 +101,9 @@ class YamapLibrary extends MyCrawlerLibrary
//3. Image 처리 //3. Image 처리
$fileEntitys = $this->download("image", $crawler, ["tag" => "img", "attr" => "src"]); $fileEntitys = $this->download("image", $crawler, ["tag" => "img", "attr" => "src"]);
//4. Video(mp4) 처리 //4. Video(mp4) 처리
return $this->download("video", $crawler, ["tag" => "video", "attr" => "src"], $fileEntitys); $fileEntitys = $this->download("video", $crawler, ["tag" => "video", "attr" => "src"], $fileEntitys);
log_message("notice", __FUNCTION__ . " 작업 완료");
return $fileEntitys;
} }
public function createBoard(array $item, array $fileEntitys): BoardEntity public function createBoard(array $item, array $fileEntitys): BoardEntity
@ -132,7 +135,7 @@ class YamapLibrary extends MyCrawlerLibrary
//망보드 게시판에 등록 //망보드 게시판에 등록
$entity = $this->getBoardModel()->create($entity); $entity = $this->getBoardModel()->create($entity);
//망보드 파일관리툴에 등록된 파일게시물에 등록한 게시판번호 수정하기 //망보드 파일관리툴에 등록된 파일게시물에 등록한 게시판번호 수정하기
$this->getMyStorage()->setBoardPID($fileEntitys, $entity->getPK()); $this->getMyStorage()->setBoardPID($fileEntitys, intval($entity->getPK()));
log_message("notice", __FUNCTION__ . " 작업 완료"); log_message("notice", __FUNCTION__ . " 작업 완료");
return $entity; return $entity;
} }

View File

@ -74,7 +74,7 @@ class FileLibrary extends MyStorageLibrary
$entity->setSize(filesize($saveFilePath)); $entity->setSize(filesize($saveFilePath));
$entity->setSequence($file_sequence); $entity->setSequence($file_sequence);
$entity->setMediaHTML($this->getMediaTag($mediaType, $entity)); $entity->setMediaHTML($this->getMediaTag($mediaType, $entity));
log_message("notice", __FUNCTION__ . " {$file_sequence}번째 " . $entity->getTitle() . " 작업 완료"); log_message("notice", __FUNCTION__ . " 원본 {$file_sequence}번째 " . $entity->getTitle() . " 작업 완료");
return $entity; return $entity;
} }
} }

View File

@ -1,14 +1,14 @@
<?php <?php
namespace App\Libraries\MyStorage; namespace App\Libraries\MyStorage\Mangboard;
use App\Libraries\MyStorage\FileLibrary as MyStorageLibrary;
use App\Libraries\MyUtil\ImageLibrary; use App\Libraries\MyUtil\ImageLibrary;
use App\Libraries\MyStorage\FileLibrary;
use App\Models\Mangboard\FileModel; use App\Models\Mangboard\FileModel;
use App\Entities\Mangboard\UserEntity; use App\Entities\Mangboard\UserEntity;
use App\Entities\Mangboard\FileEntity; use App\Entities\Mangboard\FileEntity;
class MangboardLibrary extends FileLibrary class FileLibrary extends MyStorageLibrary
{ {
private $_user = null; private $_user = null;
private $_boardName = ""; private $_boardName = "";
@ -77,8 +77,18 @@ class MangboardLibrary extends FileLibrary
return new FileEntity(); return new FileEntity();
} }
//망보드 Board Table생성 후 관련된 mb_files Table에 Board번호를 넣기 위함
public function setBoardPID(array $fileEntitys, int $board_pid): void
{
foreach ($fileEntitys as $fileEntity) {
$formDatas['board_pid'] = $board_pid;
$this->getModel()->modify($fileEntity, $formDatas);
}
log_message("notice", __FUNCTION__ . " 작업 완료");
}
private function create_small_image(FileEntity $entity, string $file, int $width = 480, int $height = 319): FileEntity //작은이미지 생성
private function save_small_image(FileEntity $entity, string $file, int $width = 480, int $height = 319): FileEntity
{ {
$fullPath = WRITEPATH . $this->getUploadPath() . DIRECTORY_SEPARATOR . $this->getPath(); $fullPath = WRITEPATH . $this->getUploadPath() . DIRECTORY_SEPARATOR . $this->getPath();
$image = new ImageLibrary(); $image = new ImageLibrary();
@ -89,24 +99,50 @@ class MangboardLibrary extends FileLibrary
$fileInfos = pathinfo($image->getDestinationPath() . DIRECTORY_SEPARATOR . $file, PATHINFO_ALL); $fileInfos = pathinfo($image->getDestinationPath() . DIRECTORY_SEPARATOR . $file, PATHINFO_ALL);
$dstFile = $fileInfos['filename'] . "_small." . $fileInfos['extension']; $dstFile = $fileInfos['filename'] . "_small." . $fileInfos['extension'];
$image->setDestinationFile($dstFile); $image->setDestinationFile($dstFile);
//작은이미지 생성후 목적지 Path와 파일명을 다시 file_path에 넣는다.
$result = $image->create($file, $width, $height); $result = $image->create($file, $width, $height);
//개인적인 생각방식
// if ($result) { // if ($result) {
// //URL이 되기때문에 /로 넣어야함 // //작은이미지 생성후 목적지 Path와 파일명을 다시 file_path에 넣는다. URL이 되기때문에 /로 넣어야함
// $entity->setPath(sprintf( // $entity->setPath(sprintf(
// "/%s/%s/%s", // "/%s/%s/%s",
// $this->getUploadPath(), // $this->getUploadPath(),
// $entity->getPath(), // $entity->getPath(),
// $image->getDestinationFile() // $image->getDestinationFile()
// )); // ));
// } else {
// //원본이미지 생성후 목적지 Path와 파일명을 다시 file_path에 넣는다. URL이 되기때문에 /로 넣어야함
// $entity->setPath(sprintf(
// "/%s/%s/%s",
// $this->getUploadPath(),
// $entity->getPath(),
// $entity->getTitle()
// ));
// } // }
//개인적인 생각방식
//
//망보드 방식
//mb_files에서 file_path가 망보드 게시판 파일관리에서 image로 표시되어 file_path+file_name로 설정
//원본이미지 생성후 목적지 Path와 파일명을 다시 file_path에 넣는다. URL이 되기때문에 /로 넣어야함
$entity->setPath(sprintf(
"/%s/%s/%s",
$this->getUploadPath(),
$entity->getPath(),
$entity->getTitle()
));
//망보드 방식
log_message("notice", sprintf(
"%s %s번째:%s 작업 완료",
__FUNCTION__,
$entity->getSequence(),
$entity->getPath()
));
return $entity; return $entity;
} }
//망보드 파일관리 table에 등록 //망보드 파일관리 table에 등록
private function create_db(FileEntity $entity, int $file_sequence): FileEntity private function save_db(FileEntity $entity): FileEntity
{ {
// log_message("notice", __FUNCTION__ . " {$file_sequence}번째 작업 시작"); // log_message("notice", sprintf("%s %s번째 작업 시작",__FUNCTION__ ,$entity->getSequence()));
$entity->user_pid = $this->getUser()->getPK(); $entity->user_pid = $this->getUser()->getPK();
$entity->user_name = $this->getUser()->getTitle(); $entity->user_name = $this->getUser()->getTitle();
$entity->board_name = $this->getBoardName(); $entity->board_name = $this->getBoardName();
@ -117,34 +153,17 @@ class MangboardLibrary extends FileLibrary
$entity->file_description = "Filedata"; $entity->file_description = "Filedata";
// log_message("debug", "\n-----Entity Value-----\n" . var_export($entity->toArray(), true) . "\n---------------------------\n"); // log_message("debug", "\n-----Entity Value-----\n" . var_export($entity->toArray(), true) . "\n---------------------------\n");
$entity = $this->getModel()->create($entity); $entity = $this->getModel()->create($entity);
log_message("notice", __FUNCTION__ . " {$file_sequence}번째 작업 완료"); log_message("notice", sprintf(
"%s %s번째 작업 완료",
__FUNCTION__,
$entity->getSequence()
));
return $entity; return $entity;
} }
public function save(string $fileName, string $mediaType, string $content, int $file_sequence): FileEntity public function save(string $fileName, string $mediaType, string $content, int $file_sequence): FileEntity
{ {
$entity = parent::save($fileName, $mediaType, $content, $file_sequence); $entity = parent::save($fileName, $mediaType, $content, $file_sequence);
//mb_files에서 file_path가 망보드 게시판 파일관리에서 image로 표시되어 file_path+file_name로 설정 $entity = $this->save_small_image($entity, $fileName);
//원본이미지 생성후 목적지 Path와 파일명을 다시 file_path에 넣는다. return $this->save_db($entity);
//URL이 되기때문에 /로 넣어야함
$entity->setPath(sprintf(
"/%s/%s/%s",
$this->getUploadPath(),
$entity->getPath(),
$entity->getTitle()
));
//작은이미지 생성
$entity = $this->create_small_image($entity, $fileName);
return $this->create_db($entity, $file_sequence);
}
public function setBoardPID(array $fileEntitys, int $board_pid)
{
//망보드 파일관리툴에 등록된 파일게시물에 등록한 게시판번호 수정하기
foreach ($fileEntitys as $fileEntity) {
$fileEntity->board_pid = $board_pid;
//수정시 mb_files에서 file_path가 변경하지 못하게 하기위함
$this->getModel()->setFields($this->getModel()->getFields("except", ['file_path']));
$this->getModel()->modify($fileEntity);
}
log_message("notice", __FUNCTION__ . " 작업 완료");
} }
} }

View File

@ -139,7 +139,14 @@ class ImageLibrary extends MyUtilLibrary
$this->save($this->getDestinationPath() . DIRECTORY_SEPARATOR . $this->getDestinationFile()); $this->save($this->getDestinationPath() . DIRECTORY_SEPARATOR . $this->getDestinationFile());
// 메모리 해제 // 메모리 해제
$this->destroy(); $this->destroy();
log_message("notice", __FUNCTION__ . " Image 작업 완료"); log_message("debug", sprintf(
"%s %s->%s(W:%s,H:%s) 작업완료)",
__FUNCTION__,
$file,
$this->getDestinationFile(),
$width,
$height
));
return true; return true;
} }
} }

View File

@ -46,10 +46,9 @@ abstract class CommonModel extends Model
protected $afterDelete = []; protected $afterDelete = [];
private $_action = DB_ACTION["CREATE"]; private $_action = DB_ACTION["CREATE"];
protected function __construct(array $fields) protected function __construct()
{ {
parent::__construct(); parent::__construct();
$this->setFields($fields);
} }
abstract public function getTitleField(): string; abstract public function getTitleField(): string;
@ -65,9 +64,9 @@ abstract class CommonModel extends Model
{ {
return $this->_action = $action; return $this->_action = $action;
} }
final public function getFields(string $key = "", $fields = []): array final public function getFields(string $key = ""): array
{ {
$this->allowedFields = array_filter( $allowedFields = array_filter(
$this->allowedFields, $this->allowedFields,
function ($value) use (&$key, &$fields) { function ($value) use (&$key, &$fields) {
if ($key == 'except') { if ($key == 'except') {
@ -79,7 +78,7 @@ abstract class CommonModel extends Model
} }
} }
); );
return $this->allowedFields; return $allowedFields;
} }
final public function setFields(array $fields): void final public function setFields(array $fields): void
{ {
@ -112,8 +111,10 @@ abstract class CommonModel extends Model
$rules[$field] = "required|string"; $rules[$field] = "required|string";
break; break;
case "passwd": case "passwd":
$rules[$field] = $this->getAction() == DB_ACTION["CREATE"] ? "required|trim|string" : "if_exist|trim|string"; $rules[$field] = $this->getAction() == DB_ACTION["CREATE"] ? "required" : "if_exist" . "|trim|string";
$rules["confirmpassword"] = $this->getAction() == DB_ACTION["CREATE"] ? "required|trim|string|matches[passwd]" : "if_exist|trim|string|matches[passwd]"; break;
case "confirmpassword":
$rules["confirmpassword"] = $this->getAction() == DB_ACTION["CREATE"] ? "required" : "if_exist" . "|trim|string|matches[passwd]";
break; break;
case "email": case "email":
$rules[$field] = "if_exist|trim|valid_email"; $rules[$field] = "if_exist|trim|valid_email";
@ -143,16 +144,14 @@ abstract class CommonModel extends Model
} }
//create , modify 직전 작업용 작업 //create , modify 직전 작업용 작업
protected function convertEntityData($entity, $field): mixed final protected function convertEntityData(string $field, array $formDatas): string|int
{ {
if ($entity->$field === null) {
return $entity;
}
switch ($field) { switch ($field) {
case $this->getPKField(): case $this->getPKField():
if ($entity->$field === null) { //$formDatas에 전달된 값이 없는경우
if (!array_key_exists($field, $formDatas)) {
$randomBytes = bin2hex(random_bytes(32)); $randomBytes = bin2hex(random_bytes(32));
$entity->$field = sprintf( $value = sprintf(
'%08s-%04s-%04x-%04x-%12s', '%08s-%04s-%04x-%04x-%12s',
substr($randomBytes, 0, 8), substr($randomBytes, 0, 8),
substr($randomBytes, 8, 4), substr($randomBytes, 8, 4),
@ -160,59 +159,70 @@ abstract class CommonModel extends Model
substr($randomBytes, 16, 4), substr($randomBytes, 16, 4),
substr($randomBytes, 20, 12) substr($randomBytes, 20, 12)
); );
} else {
$value = $formDatas[$field];
} }
break; break;
case "passwd": case "passwd":
$entity->$field = password_hash($entity->$field, PASSWORD_DEFAULT); $value = password_hash($formDatas[$field], PASSWORD_DEFAULT);
break;
case "confirmpassword":
$value = password_hash($formDatas[$field], PASSWORD_DEFAULT);
break; break;
case "content": case "content":
$entity->$field = htmlentities($entity->$field, ENT_QUOTES); $value = htmlentities($formDatas[$field], ENT_QUOTES);
break;
default:
$value = $formDatas[$field];
break; break;
} }
return $entity; return $value;
} }
private function save_process($entity): mixed private function save_process($entity): mixed
{ {
//변경이 필요한 Field 재정의
foreach ($this->getFields() as $field) {
$entity = $this->convertEntityData($entity, $field);
}
//최종 변경사항이 있으면 저장 //최종 변경사항이 있으면 저장
if ($entity->hasChanged()) { if ($entity->hasChanged()) {
if (!$this->save($entity)) { if (!$this->save($entity)) {
log_message("error", __FUNCTION__ . "에서 호출:" . $this->getLastQuery()); throw new \Exception(sprintf(
log_message("error", implode("\n", $this->errors())); "\n------%s SQL오류-----\n%s\n%s\n------------------------------\n",
throw new \Exception(__FUNCTION__ . " 오류 발생.\n" . $this->getLastQuery() . "\n" . var_dump($this->errors(), true)); __FUNCTION__,
$this->getLastQuery(),
var_export($this->errors(), true)
));
} }
} else {
throw new \Exception(__FUNCTION__ . " 오류 발생.\n 기존정보와 동일하여 수정되지 않았습니다.");
} }
return $entity; return $entity;
} }
final protected function create_process($entity): mixed final protected function create_process($entity, array $formDatas): mixed
{ {
$this->setAction(DB_ACTION['CREATE']);
//Field에 맞는 Validation Rule 재정의 //Field에 맞는 Validation Rule 재정의
$this->setValidationRules($this->getFieldRules($this->getFields())); $this->setAction(DB_ACTION['CREATE']);
//수동입력인경우 $this->setValidationRules($this->getFieldRules($this->allowedFields));
$pkField = $this->getPKField();
if (!$this->useAutoIncrement && $entity->$pkField === null) { //저장하기 전에 데이터 값 변경이 필요한 Field
$entity = $this->convertEntityData($entity, $this->getPKField()); foreach (array_keys($formDatas) as $field) {
$entity->$field = $this->convertEntityData($field, $formDatas);
} }
$entity = $this->save_process($entity); $entity = $this->save_process($entity);
//primaryKey가 자동입력이면 //primaryKey가 자동입력이면
if ($this->useAutoIncrement) { if ($this->useAutoIncrement) {
$pkField = $this->getPKField();
$entity->$pkField = $this->getInsertID(); $entity->$pkField = $this->getInsertID();
} }
// log_message("debug", $this->getTable() . " CREATE 작업 완료"); // log_message("debug", $this->getTable() . " CREATE 작업 완료");
return $entity; return $entity;
} }
final protected function modify_process($entity): mixed final protected function modify_process($entity, array $formDatas): mixed
{ {
$this->setAction(DB_ACTION['MODIFY']);
//Field에 맞는 Validation Rule 재정의 //Field에 맞는 Validation Rule 재정의
$this->setValidationRules($this->getFieldRules($this->getFields())); $this->setAction(DB_ACTION['MODIFY']);
$this->setValidationRules($this->getFieldRules($this->allowedFields));
//저장하기 전에 데이터 값 변경이 필요한 Field
foreach (array_keys($formDatas) as $field) {
$entity->$field = $this->convertEntityData($field, $formDatas);
}
$this->save_process($entity); $this->save_process($entity);
// log_message("debug", $this->getTable() . " MODIFY 작업 완료"); // log_message("debug", $this->getTable() . " MODIFY 작업 완료");
return $entity; return $entity;

View File

@ -71,24 +71,24 @@ class BoardModel extends CommonModel
// protected $table = 'mb_board_free'; // protected $table = 'mb_board_free';
protected $primaryKey = 'pid'; protected $primaryKey = 'pid';
protected $returnType = BoardEntity::class; protected $returnType = BoardEntity::class;
protected $allowedFields = [
"gid",
"title",
"user_pid",
"user_id",
"user_name",
"level",
"data_type",
"editor_type",
"image_path",
"reg_date",
"hit",
"content"
];
public function __construct(string $table) public function __construct(string $table)
{ {
$this->table = $table; $this->table = $table;
$fields = [ parent::__construct();
"gid",
"title",
"user_pid",
"user_id",
"user_name",
"level",
"data_type",
"editor_type",
"image_path",
"reg_date",
"hit",
"content"
];
parent::__construct($fields);
} }
public function getTitleField(): string public function getTitleField(): string
{ {
@ -136,14 +136,16 @@ class BoardModel extends CommonModel
} }
//create용 //create용
public function create(BoardEntity $entity): BoardEntity public function create(BoardEntity $entity, array $formDatas = []): BoardEntity
{ {
return $this->create_process($entity); $entity = $this->create_process($entity, $formDatas);
//입력후 PID값을 GID값에 넣어주기 위함
return $this->modify($entity, ['gid' => intval($entity->getPK())]);
} }
//modify용 //modify용
public function modify(BoardEntity $entity): BoardEntity public function modify(BoardEntity $entity, array $formDatas): BoardEntity
{ {
return $this->modify_process($entity); return $this->modify_process($entity, $formDatas);
} }
} }

View File

@ -35,25 +35,25 @@ class FileModel extends CommonModel
protected $table = 'mb_files'; protected $table = 'mb_files';
protected $primaryKey = 'pid'; protected $primaryKey = 'pid';
protected $returnType = FileEntity::class; protected $returnType = FileEntity::class;
protected $allowedFields = [
"user_pid",
"user_name",
"board_pid",
"board_name",
"table_name",
"file_name",
"file_path",
"file_type",
"file_caption",
"file_alt",
"file_description",
"file_size",
"file_sequence",
"reg_date"
];
public function __construct() public function __construct()
{ {
$fields = [ parent::__construct();
"user_pid",
"user_name",
"board_pid",
"board_name",
"table_name",
"file_name",
"file_path",
"file_type",
"file_caption",
"file_alt",
"file_description",
"file_size",
"file_sequence",
"reg_date"
];
parent::__construct($fields);
} }
public function getTitleField(): string public function getTitleField(): string
{ {
@ -101,28 +101,24 @@ class FileModel extends CommonModel
return $this->getEntity(); return $this->getEntity();
} }
final protected function convertEntityData($entity, $field): mixed // protected function convertEntityData(string $field, array $formDatas): string|int
{ // {
if ($entity->$field === null) { // switch ($field) {
return $entity; // default:
} // $value = parent::convertEntityData($field, $formDatas);
switch ($field) { // break;
default: // }
$entity = parent::convertEntityData($entity, $field); // return $value;
break; // }
}
return $entity;
}
//create용 //create용
public function create(FileEntity $entity): FileEntity public function create(FileEntity $entity, array $formDatas = []): FileEntity
{ {
return $this->create_process($entity); return $this->create_process($entity, $formDatas);
} }
//modify용 //modify용
public function modify(FileEntity $entity): FileEntity public function modify(FileEntity $entity, array $formDatas): FileEntity
{ {
return $this->modify_process($entity); return $this->modify_process($entity, $formDatas);
} }
} }

View File

@ -99,18 +99,18 @@ class UserModel extends CommonModel
protected $table = 'mb_users'; protected $table = 'mb_users';
protected $primaryKey = 'pid'; protected $primaryKey = 'pid';
protected $returnType = UserEntity::class; protected $returnType = UserEntity::class;
protected $allowedFields = [
"user_id",
"passwd",
"user_name",
"user_email",
"user_state",
"user_level",
"user_point"
];
public function __construct() public function __construct()
{ {
$fields = [ parent::__construct();
"user_id",
"passwd",
"user_name",
"user_email",
"user_state",
"user_level",
"user_point"
];
parent::__construct($fields);
} }
public function getTitleField(): string public function getTitleField(): string
{ {
@ -151,12 +151,12 @@ class UserModel extends CommonModel
return $this->getEntity(); return $this->getEntity();
} }
private function checkLevel(UserEntity $entity): UserEntity private function getLevelByPoint(UserEntity $entity): int
{ {
//Admin용 Level로는 변경불가 //Admin용 Level로는 변경불가
if ($entity->getLevel() == getenv('mangboard.admin.level')) { if ($entity->getLevel() == getenv('mangboard.admin.level')) {
// throw new \Exception("Admin용 Level을 변경하실수 없습니다.\n"); log_message("notice", "Admin용 Level을 변경하실수 없습니다.");
return $entity; return $entity->getLevel();
} }
//사용자 Point별 Level 계산 //사용자 Point별 Level 계산
@ -175,24 +175,11 @@ class UserModel extends CommonModel
$level = getenv('mangboard.user.level.max') < $level ? getenv('mangboard.user.level.max') : $level; $level = getenv('mangboard.user.level.max') < $level ? getenv('mangboard.user.level.max') : $level;
} }
// echo "point:" . $entity->getPoint() . ",level:" . $level . "\n"; // echo "point:" . $entity->getPoint() . ",level:" . $level . "\n";
return $level;
//기존정보와 Level값이 다르면 저장
if ($entity->getLevel() != $level) {
$old_level = $entity->getLevel();
$entity->setLevel($level);
$entity = $this->modify($entity);
log_message("notice", __FUNCTION__ . "=>{$entity}의 Level이 {$old_level}에서 {$entity->getLevel()}로 변경되었습니다.");
}
return $entity;
} }
public function setPoint($id, int $point, $sign = '+'): UserEntity public function setPoint(UserEntity $entity, int $point, $sign = '+'): UserEntity
{ {
$entity = is_numeric($id) ? $this->getEntityByPK(intval($id)) : $this->getEntityByID($id);
if (!$entity) {
throw new \Exception("해당 회원[{$id}]이 없습니다.");
}
switch ($sign) { switch ($sign) {
case '-': case '-':
if ($point < $point) { if ($point < $point) {
@ -210,30 +197,31 @@ class UserModel extends CommonModel
//기존정보와 Point값이 다르면 저장 //기존정보와 Point값이 다르면 저장
if ($entity->getPoint() != $point) { if ($entity->getPoint() != $point) {
$old_point = $entity->getPoint(); $formDatas = ["point" => $point];
$entity->setPoint($point); $entity = $this->modify($entity, $formDatas);
$entity = $this->modify($entity); log_message("notice", __FUNCTION__ . "=>{$entity->getTitle()}님의 Point가 {$entity->getPoint()}에서 {$point}로 변경되었습니다.");
log_message("notice", __FUNCTION__ . "=>{$entity}의 Point가 {$old_point}에서 {$entity->getPoint()}로 변경되었습니다.");
} }
return $this->checkLevel($entity); return $this->setLevel($entity, $this->getLevelByPoint($entity));
} }
public function setLevel(): void public function setLevel(UserEntity $entity, int $level): UserEntity
{ {
foreach ($this->getEntitys() as $entity) { //기존정보와 Level값이 다르면 저장
$entity = $this->checkLevel($entity); if ($entity->getLevel() != $level) {
log_message("debug", __FUNCTION__ . "=>[{$entity}] 회원님의 Level은 {$entity->getLevel()} 입니다."); $formDatas = ["level" => $level];
$entity = $this->modify($entity, $formDatas);
log_message("notice", __FUNCTION__ . "=>{$entity->getTitle()}님의 Level이 {$entity->getLevel()}에서 {$level}로 변경되었습니다.");
} }
return $entity;
} }
//create용 //create용
public function create(UserEntity $entity): UserEntity public function create(UserEntity $entity, array $formDatas = []): UserEntity
{ {
return $this->create_process($entity); return $this->create_process($entity, $formDatas);
} }
//modify용 //modify용
public function modify(UserEntity $entity): UserEntity public function modify(UserEntity $entity, array $formDatas): UserEntity
{ {
return $this->modify_process($entity); return $this->modify_process($entity, $formDatas);
} }
} }

View File

@ -10,17 +10,16 @@ class SNSUserModel extends CommonModel
protected $table = 'sns_users'; protected $table = 'sns_users';
protected $primaryKey = 'uid'; protected $primaryKey = 'uid';
protected $returnType = SNSUSerEntity::class; protected $returnType = SNSUSerEntity::class;
protected $allowedFields = [
"id",
"name",
"email",
"detail",
"status"
];
public function __construct() public function __construct()
{ {
$fields = [ parent::__construct();
"id",
"passwd",
"name",
"email",
"detail",
"status"
];
parent::__construct($fields);
} }
public function getTitleField(): string public function getTitleField(): string
{ {
@ -56,14 +55,14 @@ class SNSUserModel extends CommonModel
} }
//create용 //create용
public function create(SNSUSerEntity $entity): SNSUSerEntity public function create(SNSUSerEntity $entity, array $formDatas = []): SNSUSerEntity
{ {
return $this->create_process($entity); return $this->create_process($entity, $formDatas);
} }
//modify용 //modify용
public function modify(SNSUSerEntity $entity): SNSUSerEntity public function modify(SNSUSerEntity $entity, array $formDatas): SNSUSerEntity
{ {
return $this->modify_process($entity); return $this->modify_process($entity, $formDatas);
} }
} }

View File

@ -10,19 +10,19 @@ class UserModel extends CommonModel
protected $table = 'users'; protected $table = 'users';
protected $primaryKey = 'uid'; protected $primaryKey = 'uid';
protected $returnType = UserEntity::class; protected $returnType = UserEntity::class;
protected $allowedFields = [
"id",
"passwd",
"name",
"email",
"pohne",
"mobild",
"role",
"status"
];
public function __construct() public function __construct()
{ {
$fields = [ parent::__construct();
"id",
"passwd",
"name",
"email",
"pohne",
"mobild",
"role",
"status"
];
parent::__construct($fields);
} }
public function getTitleField(): string public function getTitleField(): string
{ {
@ -70,14 +70,14 @@ class UserModel extends CommonModel
} }
//create용 //create용
public function create(UserEntity $entity): UserEntity public function create(UserEntity $entity, array $formDatas = []): UserEntity
{ {
return $this->create_process($entity); return $this->create_process($entity, $formDatas);
} }
//modify용 //modify용
public function modify(UserEntity $entity): UserEntity public function modify(UserEntity $entity, array $formDatas): UserEntity
{ {
return $this->modify_process($entity); return $this->modify_process($entity, $formDatas);
} }
} }