Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Controller周辺のリファクタリング、型の厳格化、コードのデカップリング等 #108 #256 #321

Merged
merged 34 commits into from
Jun 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
64d32df
remove Controller::getDeviceType(), move to Request.
uzulla Jun 4, 2021
31d6d15
remove Controller::setToken().
uzulla Jun 4, 2021
093a2b1
Improve pseudo array model. add dynamic pattern(disabled normally).
uzulla Jun 4, 2021
28ceb2c
remove Controller::getBlog().
uzulla Jun 4, 2021
5831661
move Controller::tokenValidate() to EntriesController::captchaTokenVa…
uzulla Jun 4, 2021
0416157
Refactoring around captcha.
uzulla Jun 4, 2021
dcaf2b3
Decouple preprocessingDataForFc2Template from Controller.
uzulla Jun 4, 2021
d0e3902
remove unnecessary define variable.
uzulla Jun 4, 2021
7fb03cc
move renderByFc2Template() to UserController from (base)Controller.
uzulla Jun 4, 2021
122452f
refactoring, move getHostUrl() to Request.
uzulla Jun 4, 2021
56a3930
Avoid implicit 404 Notfound call.
uzulla Jun 4, 2021
dbc4b08
fix typo.
uzulla Jun 4, 2021
d880ced
Chore, reorder some methods in the class.
uzulla Jun 4, 2021
c9fac01
Decouple Fc2Template compile,syntax check,other methods from Model.
uzulla Jun 4, 2021
7345d07
remove unnecessary method.
uzulla Jun 4, 2021
04cf415
avoid unnecessary public access modifier.
uzulla Jun 4, 2021
f01b39a
remove unnecessary TODO.
uzulla Jun 4, 2021
12e323a
Avoid implicit 404 Notfound call.
uzulla Jun 4, 2021
74ef1cd
Explicit getter naming that get current blog id.
uzulla Jun 5, 2021
710aade
add type definition.
uzulla Jun 5, 2021
4282618
fix omission of corrections
uzulla Jun 5, 2021
6e916ea
chore
uzulla Jun 5, 2021
b4de194
use isValidSig() instead of raw Session::get... code.
uzulla Jun 5, 2021
b310ced
add type definition.
uzulla Jun 5, 2021
8228417
fix correct type definition.
uzulla Jun 5, 2021
8b874e6
add declare(strict_types=1); to all controllers. avoid auto type cast.
uzulla Jun 5, 2021
d624d2f
fix broken test.
uzulla Jun 5, 2021
0749041
comment out unused arg.
uzulla Jun 5, 2021
a479e95
Add return type.
uzulla Jun 5, 2021
815e05d
Improve 500 error page. #256
uzulla Jun 5, 2021
8efce71
change UserController::getBlogId to $request->getBlogId() and remove …
uzulla Jun 5, 2021
185f5dc
errorXXX method change access modifier to protected from public.
uzulla Jun 5, 2021
6cf0e8e
Refactoring Router. remove unnecessary validation. tidy up.
uzulla Jun 5, 2021
0899189
Refactoring Router.
uzulla Jun 5, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ private static function _set(string $key, $value, array &$config)
* @param string $name
* @param bool $force_reload UnitTest内などで再読み込みを強制したい場合に指定
*/
public static function read(string $name, $force_reload = false)
public static function read(string $name, bool $force_reload = false)
{
if (!$force_reload && !empty(self::$read_files[$name])) {
// 既に読み込み済みのファイルは読み込まないが、強制的に再読み込みの指定があれば読み込みする。
Expand Down
4 changes: 2 additions & 2 deletions app/src/Lib/CaptchaImage.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class CaptchaImage
* @param $src_img_size_y 1 以上が必要
* @param bool $hirakana_mode
*/
public function __construct($src_img_size_x, $src_img_size_y, $hirakana_mode = true)
public function __construct($src_img_size_x, $src_img_size_y, bool $hirakana_mode = true)
{
$this->img_size_x = $src_img_size_x;
$this->img_size_y = $src_img_size_y;
Expand All @@ -33,7 +33,7 @@ public function __construct($src_img_size_x, $src_img_size_y, $hirakana_mode = t
* @param bool $mini_mode
* @throws Exception
*/
public function drawNumber($number, $mini_mode = false): void
public function drawNumber($number, bool $mini_mode = false): void
{
//memo. sjisの書体はサーバー環境によっては使えない
$arr_fonts = array(
Expand Down
13 changes: 12 additions & 1 deletion app/src/Model/ArrayIterableTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public static function factory(array $list): ?self
$props = (new ReflectionClass(static::class))->getProperties();
foreach ($props as $prop) {
$name = $prop->getName();
if (preg_match("/@dynamic/u", (string)$prop->getDocComment())) continue;
$self->{$name} = $list[$name];
}
return $self;
Expand All @@ -43,11 +44,21 @@ public function offsetSet($offset, $value)
$r = new ReflectionClass(static::class);
try {
$prop = $r->getProperty($offset);
// # Dynamicにプロパティを追加しようとした時の一時的回避パッチ。遭遇したら以下を生やす
// # /** @dynamic */
// # public $url;
// } catch (ReflectionException $e) {
// // 取得できない場合、無いプロパティを動的に生やす。最終的にはこの箇所はなくす。
// $this->{$offset} = $value;
// error_log("WARN: found undefined dynamic property {$offset} to ".static::class);
// return;
// }
// try {
if ($prop->isPublic()) {
$this->{$prop->getName()} = $value;
}
} catch (ReflectionException $e) {
throw new LogicException("touch missing property " . $e->getMessage());
throw new LogicException("touch missing property " . $e->getMessage() . " at " . $e->getFile() . ":" . $e->getLine());
}
}

Expand Down
4 changes: 4 additions & 0 deletions app/src/Model/Blog.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,8 @@ class Blog implements ArrayAccess, IteratorAggregate, Countable
public $last_posted_at;
public $created_at;
public $updated_at;

// === Not available in DB, Dynamic properties
/** @dynamic */
public $url;
}
5 changes: 3 additions & 2 deletions app/src/Model/BlogPluginsModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Fc2blog\App;
use Fc2blog\Config;
use Fc2blog\Util\PhpCodeLinter;
use Fc2blog\Web\Fc2BlogTemplate;
use Fc2blog\Web\Session;

class BlogPluginsModel extends Model
Expand Down Expand Up @@ -161,7 +162,7 @@ public static function fc2PluginSyntax(string $php_code)
}

// HTMLをPHPテンプレートに変換してテンプレートファイルの作成
$html = BlogTemplatesModel::convertFC2Template($php_code);
$html = Fc2BlogTemplate::convertToPhp($php_code);
file_put_contents($plugin_path, $html);
chmod($plugin_path, 0777);

Expand Down Expand Up @@ -426,7 +427,7 @@ public static function createPlugin(string $html, string $blog_id, string $id =
}

// HTMLをPHPテンプレートに変換してテンプレートファイルの作成
$html = BlogTemplatesModel::convertFC2Template($html);
$html = Fc2BlogTemplate::convertToPhp($html);
file_put_contents($plugin_path, $html);
chmod($plugin_path, 0777);
}
Expand Down
109 changes: 5 additions & 104 deletions app/src/Model/BlogTemplatesModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@

use Fc2blog\App;
use Fc2blog\Config;
use Fc2blog\Util\PhpCodeLinter;
use Fc2blog\Web\Session;
use Fc2blog\Web\Fc2BlogTemplate;

class BlogTemplatesModel extends Model
{
Expand Down Expand Up @@ -68,37 +67,13 @@ public function validate(array $data, ?array &$valid_data = [], array $white_lis
}

/**
* FC2テンプレートの構文チェック
* バリデーションでつかうために、Proxy呼び出し
* @param string $php_code
* @return bool|string
*/
public static function fc2TemplateSyntax(string $php_code)
{
if (defined("THIS_IS_TEST")) {
// テンプレート検証用にテンポラリディレクトリが必要だが、テストやCLIでSessionを汚染したくないので
$blog_id = "unitTestOrCliExecute";
} else {
$blog_id = Session::get('blog_id');
}

// フォルダが存在しない場合作成
$templatePath = Config::get('BLOG_TEMPLATE_DIR') . App::getBlogLayer($blog_id) . '/syntax.php';
$templateDir = dirname($templatePath);
if (!file_exists($templateDir)) {
mkdir($templateDir, 0777, true);
}

// HTMLをPHPテンプレートに変換してテンプレートファイルの作成
$html = self::convertFC2Template($php_code);
file_put_contents($templatePath, $html);

chmod($templatePath, 0777);
// PHPのシンタックスチェック
if (PhpCodeLinter::isParsablePhpCode($html)) {
return true;
} else {
return __('There may be a problem with the template or plug-in, installed in the blog.');
}
return Fc2BlogTemplate::fc2TemplateSyntax($php_code);
}

/**
Expand Down Expand Up @@ -165,8 +140,8 @@ public static function createTemplate($templateId, $blog_id, $device_type, $html
}

// HTMLをPHPテンプレートに変換してテンプレートファイルの作成
$html = self::convertFC2Template($html);
file_put_contents($templatePath, $html);
$php_code = Fc2BlogTemplate::convertToPhp($html);
file_put_contents($templatePath, $php_code);
chmod($templatePath, 0777);

// pluginのPHPを再生成(すでにファイルがあれば不要な処理だが、このタイミングよりよい再生成タイミングがない)
Expand Down Expand Up @@ -272,80 +247,6 @@ public function updateByIdAndBlogId($values, $id, $blog_id, $options = array())
return true;
}

/**
* HTMLを解読しPHPテンプレートに変換する
* @param string $html 置換前HTML
* @return string 置換後PHPテンプレート
*/
public static function convertFC2Template(string $html)
{
// PHP文(PHP開始、終了タグ)のエスケープ `<?php〜?>` → `<?php echo '<?'; ?><?php echo 'php'; ?>〜<?php echo '?>' ?>`
$delimit = "\xFF";
$searches = ['<?', '?>'];
$replaces = [$delimit . 'START_TAG_ESCAPE', $delimit . 'END_TAG_ESCAPE'];
$html = str_replace($searches, $replaces, $html);

$html = preg_replace('/(php)/i', "<?php echo '$1'; ?>", $html);

$searches = $replaces;
$replaces = ['<?php echo \'<?\'; ?>', '<?php echo \'?>\'; ?>'];
$html = str_replace($searches, $replaces, $html);

// テンプレート置換用変数読み込み
Config::read('fc2_template.php');
$ambiguous = []; // 既存FC2テンプレートの曖昧置換用

// ループ文用の置き換え
$loop = Config::get('fc2_template_foreach');
foreach ($loop as $key => $value) {
$ambiguous[] = $key;
do {
$html = preg_replace('/<!--' . $key . '-->(.*?)<!--\/' . $key . '-->/s', $value . '$1<?php } ?>', $html, -1, $count);
} while ($count > 0);
}

// 条件判断文用の置き換え
$cond = Config::get('fc2_template_if');
foreach ($cond as $key => $value) {
$ambiguous[] = $key;
do {
$html = preg_replace('/<!--' . $key . '-->(.*?)<!--\/' . $key . '-->/s', $value . '$1<?php } ?>', $html, -1, $count);
} while ($count > 0);
}

// 既存FC2テンプレートの曖昧置換
// (置換しきれなかった(正しく記述されていない)テンプレートをできるだけ処理する)
$ambiguous = implode('|', $ambiguous);
// <!--topentry-->〜<!--/edit_area--> 左記を許容する
foreach ($loop as $key => $value) {
do {
$html = preg_replace('/<!--' . $key . '-->(.*?)<!--\/(' . $ambiguous . ')-->/s', $value . '$1<?php } ?>', $html, -1, $count);
} while ($count);
}
foreach ($cond as $key => $value) {
do {
$html = preg_replace('/<!--' . $key . '-->(.*?)<!--\/(' . $ambiguous . ')-->/s', $value . '$1<?php } ?>', $html, -1, $count);
} while ($count);
}
// <!--/topentry-->〜<!--topentry--> 左記を許容する(テンプレートによってシンタックスエラーが発生する可能性あり)
// 代わりに既存FC2で動作しているテンプレートでタグの相互がおかしいテンプレートも動作する
foreach ($loop as $key => $value) {
do {
$html = preg_replace('/<!--\/(' . $ambiguous . ')-->(.*?)<!--' . $key . '-->/s', '<?php } ?>$2' . $value, $html, -1, $count);
} while ($count);
}
foreach ($cond as $key => $value) {
do {
$html = preg_replace('/<!--\/(' . $ambiguous . ')-->(.*?)<!--' . $key . '-->/s', '<?php } ?>$2' . $value, $html, -1, $count);
} while ($count);
}

// 変数タグの置き換え
$html = str_replace(Config::get('fc2_template_var_search'), Config::get('fc2_template_var_replace'), $html);
// 処理されなかった(対応がなかった)変数タグの削除
return preg_replace('/<%[0-9a-zA-Z_]+?>/', '', $html);
}

static public function getPathDefaultTemplate(): string
{
return static::getPathDefaultTemplateWithDevice(Config::get('DEVICE_PC'));
Expand Down
10 changes: 5 additions & 5 deletions app/src/Model/BlogsModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -310,10 +310,10 @@ public function getLoginBlog($user)

/**
* ユーザーIDをキーにブログのリストを取得
* @param string $user_id
* @param int $user_id
* @return mixed
*/
public function getListByUserId(string $user_id)
public function getListByUserId(int $user_id)
{
return $this->find('list', array(
'fields' => array('id', 'name'),
Expand Down Expand Up @@ -621,13 +621,13 @@ public function getAppliedTemplateId(string $blog_id, int $device_type): int
/**
* Blog 設定が今アクセスしているSchemaと一致しているか確認
* @param Request $request
* @param array $blog blog array
* @param Blog $blog blog array
* @return bool
*/
static public function isCorrectHttpSchemaByBlogArray(Request $request, array $blog): bool
static public function isCorrectHttpSchemaByBlog(Request $request, Blog $blog): bool
{
$is_https = (isset($request->server['HTTPS']) && $request->server['HTTPS'] == 'on');
return ($blog['ssl_enable'] === 1 && $is_https) || ($blog['ssl_enable'] === 0 && !$is_https);
return ($blog->ssl_enable === 1 && $is_https) || ($blog->ssl_enable === 0 && !$is_https);
}

/**
Expand Down
4 changes: 3 additions & 1 deletion app/src/Service/BlogService.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@

class BlogService
{
public static function getById(string $blog_id): ?Blog
public static function getById(?string $blog_id): ?Blog
{
if (is_null($blog_id)) return null;

$repo = new BlogsModel();
$res = $repo->findById($blog_id);
if ($res === false) return null;
Expand Down
2 changes: 1 addition & 1 deletion app/src/Util/PhpCodeLinter.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class PhpCodeLinter
* @param $string
* @return bool
*/
public static function isParsablePhpCode($string)
public static function isParsablePhpCode($string): bool
{
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
try {
Expand Down
7 changes: 5 additions & 2 deletions app/src/Util/StringCaseConverter.php
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
<?php

declare(strict_types=1);

namespace Fc2blog\Util;

use InvalidArgumentException;

class StringCaseConverter
{

/**
* パスカルケースへの変換
* @param string $snake_case
* @return string
*/
public static function pascalCase(string $snake_case): string
{
if (preg_match('/[^a-zA-Z0-9_ ]/u', $snake_case)) throw new InvalidArgumentException("contain non allowable string {$snake_case}");
$snake_case = str_replace('_', ' ', $snake_case);
$snake_case = ucwords($snake_case);
return str_replace(' ', '', $snake_case);
Expand All @@ -26,6 +27,7 @@ public static function pascalCase(string $snake_case): string
*/
public static function camelCase(string $snake_case): string
{
if (preg_match('/[^a-zA-Z0-9_ ]/u', $snake_case)) throw new InvalidArgumentException("contain non allowable string {$snake_case}");
return lcfirst(static::pascalCase($snake_case));
}

Expand All @@ -36,6 +38,7 @@ public static function camelCase(string $snake_case): string
*/
public static function snakeCase(string $camel_case): string
{
if (preg_match('/[^a-zA-Z0-9_ ]/u', $camel_case)) throw new InvalidArgumentException("contain non allowable string {$camel_case}");
return strtolower(preg_replace("/([A-Z])/u", "_$0", lcfirst($camel_case)));
}
}
Loading