blessing-skin-server/app/Services/Utils.php

98 lines
2.4 KiB
PHP
Raw Normal View History

2016-07-21 22:01:57 +08:00
<?php
namespace App\Services;
use App\Exceptions\PrettyPageException;
2016-08-28 20:33:35 +08:00
use Storage;
2016-07-21 22:01:57 +08:00
class Utils
{
/**
* Simple SQL injection protection
*
* @param string $string
* @return string
*/
public static function convertString($string)
{
2016-07-21 22:01:57 +08:00
return addslashes(trim($string));
}
/**
* Get the value of key in an array if index exist
*
* @param string $key
2016-08-11 12:47:02 +08:00
* @param array $array
* @param string $default
* @return string
2016-07-21 22:01:57 +08:00
*/
public static function getValue($key, $array, $default = "")
{
return array_key_exists($key, $array) ? $array[$key] : $default;
2016-07-21 22:01:57 +08:00
}
/**
* Rename uploaded file
*
* @param array $file files uploaded via HTTP POST
* @return string $hash sha256 hash of file
*/
public static function upload($file)
{
2016-08-28 20:33:35 +08:00
$path = 'tmp'.time();
$absolute_path = BASE_DIR."/storage/textures/$path";
2016-08-28 20:33:35 +08:00
if (false === move_uploaded_file($file['tmp_name'], $absolute_path)) {
throw new App\Exceptions\E('Failed to remove uploaded files, please check the permission', 1);
} else {
2016-08-28 20:33:35 +08:00
$hash = hash_file('sha256', $absolute_path);
if (!Storage::disk('textures')->has($hash)) {
Storage::disk('textures')->move($path, $hash);
}
return $hash;
}
}
2016-07-21 22:01:57 +08:00
/**
* Generate random string
*
2016-08-18 21:51:39 +08:00
* @param int $length
* @param bool $special_chars
2016-07-21 22:01:57 +08:00
* @return string
*/
2016-08-18 21:51:39 +08:00
public static function generateRndString($length, $special_chars = true)
{
2016-08-18 21:51:39 +08:00
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
if ($special_chars) $chars .= "!@#$%^&*()-_ []{}<>~`+=,.;:/?|";
2016-07-21 22:01:57 +08:00
$rnd_string = '';
for ($i = 0; $i < $length; $i++) {
$rnd_string .= $chars[mt_rand(0, strlen($chars) - 1)];
}
return $rnd_string;
}
public static function getTimeFormatted($timestamp = 0)
{
return ($timestamp == 0) ? date('Y-m-d H:i:s') : date('Y-m-d H:i:s', $timestamp);
}
2016-08-11 12:47:02 +08:00
/**
* Replace content of string according to given rules
*
* @param string $str
* @param array $rules
* @return string
*/
2016-08-11 22:56:36 +08:00
public static function getStringReplaced($str, $rules)
2016-08-11 12:47:02 +08:00
{
foreach ($rules as $search => $replace) {
$str = str_replace($search, $replace, $str);
}
return $str;
}
2016-07-21 22:01:57 +08:00
}