とんたんの技術メモ

注)ただのメモです。

PHP よく使う?ヘルパー関数

使い方

// addWhere
$sql = "SELECT * FROM [table]";
$binds = [];
Helper\Utils::addWhere($sql, $binds, [
    "status = ?" => [1]
]);
echo $sql; // SELECT * FROM [table] WHERE status = ?

コード

# Helper/Utils.php

<?php
namespace Helper;

class Utils
{
    // 配列から対象キーの値を取得
    public static function selection(array $array, $key, $default = null)
    {
        return array_key_exists($key, $array)? $array[$key] : $default;
    }

    public static function renderJson($array = [], $status = 200, $message = "")
    {
        http_response_code($status);
        header("Content-Type: application/json; charset=UTF-8");
        echo json_encode(["data" => $array, "message" => $message], JSON_UNESCAPED_UNICODE);
        exit();
    }

    // 値の型を最適化する
    public static function valueTypeOptimize($value)
    {
        if (is_numeric($value)) {
            return floatval($value);
        }
        if (is_string($value)) {
            return $value;
        }
        if (is_array($value)) {
            foreach ($value as $key => $val) {
                $value[$key] = self::valueTypeOptimize($val);
            }
        }
        return $value;
    }

   // 文字列をマスクする
    public static function stringMask($str)
    {
        return str_repeat("*", strlen($str));
    }

    // マスクされた文字列かチェック
    public static function isMask($str)
    {
        if (preg_match('/^\*+$/', $str)) {
            return true;
        }
        return false;
    }

    public static function convertArrayKv($array, $key_id, $val_id = null)
    {
        $result = [];
        foreach ($array as $val) {
            $result[$val[$key_id]] = ($val_id)? $val[$val_id] : $val;
        }
        return $result;
    }

    // sqlのWHERE区を生成
    public static function addWhere(&$sql, &$binds, $conditions)
    {
        $where = [];
        foreach ($conditions as $key => $vals) {
            $is_add = false;
            foreach ($vals as $val) {
                if ($val !== null) {
                    $is_add = true;
                    break;
                }
            }
            if (!$is_add) {
                continue;
            }
            if (strpos($key, ":in") !== false) {
                $placeholder = rtrim(str_repeat("?,", count($vals)), ",");
                $where[] = str_replace(":in", $placeholder, $key);
            } else {
                $where[] = $key;
            }
            $binds = array_merge($binds, $vals);
        }
        $sql .= ($where)? " WHERE " . join(" AND ", $where) : "";
    }
}