Query.php

<?php

namespace Phad;

/**
 * Grants access to an item's node & loads item list
 */
class Query {


    public ?\PDO $pdo;

    /** true to throw exception when query failes. false to silently fail & return false  */
    public $throw_on_query_failure = false;

    public function __construct(){
    }

    /**
     *
     * @param $item_name the item name. will be converted to an all-lowercase version for the table name
     */
    public function get(string $item_name, $query_info, $args=[], $item_type='view', $data_node=null){
        // var_dump(array_keys($args));
        // switch ($args['phad_mode']??null){
        //     case "submit":
        //         return [$args['phad_submit_values']] ?? [];
        //     case "display_with_empty_object":
        //         // return [ new \Phad\BlackHole() ];
        //         return [ '_object'=>'Phad\\BlackHole'];
        // }

        // var_dump($query_info);
        // exit;

        if (isset($args[$item_name.'List'])){
            return $args[$item_name.'List'];
        } else if (isset($args[$item_name])){
            return [ $args[$item_name] ];
        }
// echo "\n\n\n-----------\n\n";
// echo "\n\n\n-----------\n\n";
// echo "\n\n\n-----------\n\n";
// echo "\n\n\n-----------\n\n";
//         print_r($args);
//         exit;
        // var_dump($query_info);
        // exit;
        if (($query_info['type']??null)=='default'&&$item_type=='form'){
                // echo 'here here';
                // exit;
            if (isset($_GET['id'])){
                $query_info['name']='form_default';
                $query_info['where'] = "{$item_name}.id = :id";
                $args['id'] = $_GET['id'];
            } else {
                return [ [ '_object'=> 'Phad\BlackHole' ] ];
            }
        } else if (($query_info['type']??null)=='black_hole'){
            return [ [ '_object'=> 'Phad\BlackHole' ] ];
        }


        if (is_array($data_node)
            &&$data_node['type']=='default'
            &&isset($data_node['index'])
            &&$data_node['index']!==0){
            return false;
        }
        else if (!isset($this->pdo)||!($this->pdo instanceof \PDO)){
            return false;
        }

        $pdo = $this->pdo;
        if (!is_object($pdo))return false;
        $binds = [];
        $sql = $this->buildSql($item_name, $query_info, $args, $binds);

        $stmt = $pdo->prepare($sql);
        if ($stmt===false){
            if ($this->throw_on_query_failure){
                print_r($pdo->errorInfo());
                throw new \PDOException("Could not prepare query...");
            }
            return false;
        }
        $stmt->execute($binds);
        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        return $rows;
    }


    public function buildSql($item_name, $query_info, $args, &$binds){
        $table = strtolower($item_name);
        $table = "`$table`";
        $item_name = "`$item_name`";
        $binds = [];

        // print_r($query_info);
        // exit;
        if (isset($query_info['sql'])){
            $sql = $query_info['sql'];
        } else {
            // $cols = '*';
            $cols = empty($query_info['cols']) ? '*' : $query_info['cols'];
            $where = empty($query_info['where']) ? ' ' : "\nWHERE ".$query_info['where'].' ';
            $limit =  empty($query_info['limit']) ? '' : "\nLIMIT ".$query_info['limit'].' ';
            $orderby = empty($query_info['orderby']) ? '' : "\nORDER BY ".$query_info['orderby'].' ';

            $join = empty($query_info['join']) ? '' : "\nJOIN ".$query_info['join'].' ';

            $sql = "SELECT {$cols} FROM {$table} AS {$item_name}{$join}{$where}{$orderby}{$limit}";
        }

        // var_dump($sql);
        $bindTargets = preg_match_all('/ \:([a-zA-Z\_\.]+)(\r|\n|\s|$)/', $sql.' ', $matches);
        // var_dump($matches);
        // exit;
        foreach ($matches[1] as $col){
            $parts = explode('.', $col);
            if (count($parts)==2&&$parts[0]=='get'){
                $key = str_replace('.','_', $col);
                $sql = str_replace($col, $key, $sql);
                $col = $key;
                $args[$key] = $_GET[$parts[1]] ?? null;
            }
            $binds[':'.$col] = $args[$col] ?? null;
        }
        // var_dump($binds);
        // var_dump($sql);
        return $sql;
    }

}