Your IP : 216.73.216.240


Current Path : /home/juvelize/saulnois/tmp/install_695d2cf0b4957/src/
Upload File :
Current File : /home/juvelize/saulnois/tmp/install_695d2cf0b4957/src/TDb.php

<?php
/*
* @package		Tech Fry Library
* @license		https://www.gnu.org/licenses/gpl-3.0.en.html
*/

namespace TechFry\Library;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;

class TDb
{
    /*
        libraries/vendor/joomla/database/src: dropTable(), getCount(), getName(), getNumRows(), getPrefix(),
        createQuery() instead of getQuery(), insertObject(), loadAssoc(), loadAssocList(), loadColumn(), loadRow(), loadRowList(), updateObject()
    */
    
    // A. Read or Select - get_single, get_item, get_column, get_items
    // B. Create or Update - insert_update, update_records
    // C. Aggregate Methods - total_rows
    // D. Delete - delete_item, delete_items
    // E. Table Structure - get_all_tables, get_table_columns, create_table, add_column, modify_column, drop_column
    // F. Helper Methods - table_exists, set_conditions, custom_query
    // replace_column

    public $db;

    public $table;

    public $table_alias = 'a';

    public $select = '*';

    public $conditions = [];
    public $in_conditions = [];

    public $order;
    public $limit;
    public $offset = 0;

    public $query;

    public $joins = [];

    public $group;

    public $having;

    public function __construct($table = '')
    {        
        $this->table = $table;

        $this->db = Factory::getDbo();
        $this->query = $this->db->getQuery(true);
    }

    public function set_table($table)
    {
        $this->table = $table;
    }

    // A1. Get single value based on primary key of record or conditions
    public function get_single($config = [])
    {
        // $config - select, conditions (or id, column), order

        $this->query = $this->db->getQuery(true);
        
        $this->select = $config['select'] ?? 'title';
        $this->order = $config['order'] ?? '';

        $column = $config['conditions'] ?? 'id';
        $conditions = $config['conditions'] ?? array($column . ' = ' . $config['id']);

        $this->query = $this->db->getQuery(true);
        
        $this->query->select($this->select)
                    ->from($this->db->quoteName('#__' . $this->table, $this->table_alias));

        $this->set_conditions($conditions);

        if ($this->order)
        {
            $this->query->order($this->order);
        }
        
        $this->db->setQuery($this->query);

        $result = $this->db->loadResult();

        return $result;
    }

    // A2. Get single row based on primary key of record or conditions
    public function get_item($config = [])
    {
        // $config - select, conditions (or id, column), offset, order

        $this->select = $config['select'] ?? 'a.*';
        $this->offset = $config['offset'] ?? 0;
        $this->order = $config['order'] ?? '';
        $this->joins = $config['joins'] ?? [];

        if (isset($config['conditions']) || isset($config['id']))
        {
            $column = $config['column'] ?? 'id';
            $conditions = $config['conditions'] ?? array($this->db->quoteName($column) . ' = ' . $this->db->quote($config['id']));
        }
        else
        {
            $conditions = [];
        }
        
        $this->query = $this->db->getQuery(true);
        
        $this->query->select($this->select)
                    ->from($this->db->quoteName('#__' . $this->table, $this->table_alias))
                    ->setLimit(1, $this->offset);

        if (!empty($this->joins))
        {
            foreach ($this->joins as $join)
            {
                $this->table_alias++;
                
                $this->query->join('LEFT', $this->db->quoteName('#__' . $join['table'], $this->table_alias) . ' ON ' . $join['on1'] . ' = ' . $join['on2']);
            }
        }

        $this->set_conditions($conditions);

        if ($this->order)
        {
            $this->query->order($this->order);
        }

        //$this->print_query();

        $this->db->setQuery($this->query);

        $row = $this->db->loadObject();

        return $row;
    }
  
    // A3. Get single column as array
  	public function get_column($config = [])
    {
        $this->select = $config['select'] ?? 'id';
        $this->limit = $config['limit'] ?? 0;
        $this->offset = $config['offset'] ?? 0;
        $this->order = $config['order'] ?? '';
        $conditions = $config['conditions'] ?? [];
    
        $this->query = $this->db->getQuery(true);

        $this->query->select($this->select)
                    ->from($this->db->quoteName('#__' . $this->table, $this->table_alias));
        
        $this->set_conditions($conditions);

        if ($this->order)
        {
            $this->query->order($this->order);
        }

        if ($this->limit)
        {
            $this->query->setLimit($this->limit, $this->offset);
        }

        $this->db->setQuery($this->query);

        $column = $this->db->loadColumn();

        return $column;
    }

    // A4. Get multiple rows from table based on conditions
    public function get_items($config = [])
    {
        $this->select = $config['select'] ?? '*';
        $this->limit = $config['limit'] ?? 0;
        $this->offset = $config['offset'] ?? 0;
        $this->order = $config['order'] ?? '';
        $conditions = $config['conditions'] ?? [];
        $this->joins = $config['joins'] ?? [];
        
        $this->query = $this->db->getQuery(true);
        
        $this->query->select($this->select)
                    ->from($this->db->quoteName('#__' . $this->table, $this->table_alias));
        
        if (!empty($this->joins))
        {
            foreach ($this->joins as $join)
            {
                $this->table_alias++;
                
                $this->query->join('LEFT', $this->db->quoteName('#__' . $join['table'], $this->table_alias) . ' ON ' . $join['on1'] . ' = ' . $join['on2']);
            }
        }

        $this->set_conditions($conditions);

        if ($this->order)
        {
            $this->query->order($this->order);
        }

        if ($this->limit)
        {
            $this->query->setLimit($this->limit, $this->offset);
        }

        //$this->print_query();

        $this->db->setQuery($this->query);
        
        $data = $this->db->loadObjectList();
            
        return $data;
    }

    // B1. Insert or update record in table
    public function insert_update($data, $pk = 'id')
    {
        if (\is_array($data))
        {
            $data = (object) $data;
        }
        
        $data->id = $data->id ?? 0;

        if ($pk)
        {
            if ($data->id == 0)
            {
                $result = Factory::getDbo()->insertObject('#__' . $this->table, $data, $pk);
            }
            else
            {
                $result = Factory::getDbo()->updateObject('#__' . $this->table, $data, $pk);
            }
        }
        else
        {
            $result = Factory::getDbo()->insertObject('#__' . $this->table, $data);
        }
        
        return $data;
    }

    // B2. Update records based on conditions
    public function update_records($sets = [], $conditions = [])
    {        
        $this->query = $this->db->getQuery(true);
        
        $this->query->update($this->db->quoteName('#__' . $this->table));
		
		foreach ($sets as $column => $value)
		{
		    // Dont quote if value is NULL
            if (strtoupper($value) == 'NULL')
		    {
		        $this->query->set($this->db->quoteName($column) . ' = ' . $value);
		    }
		    else
		    {
		        $this->query->set($this->db->quoteName($column) . ' = ' . $this->db->quote($value));
		    }
		}

        if ($conditions)
        {
            $this->set_conditions($conditions);
        }
		
		$this->db->setQuery($this->query);
	    
        $this->db->execute();
	    
	    return $this->db->getAffectedRows();
    }

    // C1. Get total rows in table based on conditions
    public function total_rows($conditions = [])
    {        
        $this->query = $this->db->getQuery(true);
		
		$this->query->select('COUNT(*)')
		    ->from($this->db->quoteName('#__' . $this->table));

        $this->set_conditions($conditions);
		    
	    $this->db->setQuery($this->query);
	    
        $total = $this->db->loadResult();
	    
	    return $total;
    }

    // D1. Delete single item based on primary key
    public function delete_item($pk, $column = 'id')
    {        
        $conditions = array($column, '=', $pk);
        
        return $this->delete_items($conditions);
    }

    // D2. Delete multiple records based on conditions
    public function delete_items($conditions = [])
    {
        // Conditions should be present for deletion
        if (empty($conditions))
        {
            return;
        }

        $this->query = $this->db->getQuery(true);
        
		$this->query->delete($this->db->quoteName('#__' . $this->table));

        if ($conditions)
        {
            $this->set_conditions($conditions);
        }

	    $this->db->setQuery($this->query);
	    
        $this->db->execute();
	    
	    return $this->db->getAffectedRows();
    }

    // D3. Truncate table - Delete all records
    public function truncate_table()
    {
        $this->db->truncateTable('#__' . $this->table);
    }

    // E1. Get all tables in database
    public function get_all_tables($print = false)
    {
        $tables = $this->db->getTableList();

        if ($print)
        {
            $output = '<pre>';
                $output .= print_r($tables, true);
            $output .= '</pre>';

            return $output;
        }

        return $tables;
    }

    // E2. Get all columns in a table
    public function get_table_columns($print = false)
    {
        $cols = $this->db->getTableColumns('#__' . $this->table);

        if ($print)
        {
            $output = '<pre>';
                $output .= print_r($cols, true);
            $output .= '</pre>';

            return $output;
        }
        
        return $cols;
    }

    // E3. Get table create
    public function get_table_create($print = false)
    {
        $cols = $this->db->getTableCreate('#__' . $this->table);

        if ($print)
        {
            $output = '<pre>';
                $output .= print_r($cols, true);
            $output .= '</pre>';

            return $output;
        }
        
        return $cols;
    }

    // E4. Create table in database
  	public function create_table($columns = [])
    {
		$fields = [];

        foreach ($columns as $name => $definition)
        {
            $fields[] = $this->db->quoteName($name) . ' ' . strtoupper($definition);
        }

        $query = $this->db->getQuery(true);

        $query = 'CREATE TABLE IF NOT EXISTS ' . $this->db->quoteName('#__' . strtolower($this->table)) . ' (' . implode(', ', $fields);

		$query .= ', PRIMARY KEY (' . $this->db->quoteName('id') . '))';
		$query .= ' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci';

	    $this->db->setQuery($query);
	    
	    $this->db->execute();
    }
    
    // E5. Add column to database table
  	public function add_column($column, $definition, $constraints = '')
    {
        $query = $this->db->getQuery(true);
        
        $query = 'ALTER TABLE ' . $this->db->quoteName('#__' . $this->table);
		$query .= ' ADD COLUMN ' . $this->db->quoteName($column) . ' ' . $definition . ' ' . $constraints;

        $this->db->setQuery($query);
	    
        $this->db->execute();
    }

    // E6. Modify column
  	public function modify_column($column, $definition, $constraints = '')
    {
        $query = $this->db->getQuery(true);
        
        $query = 'ALTER TABLE ' . $this->db->quoteName('#__' . $this->table);
		$query .= ' MODIFY COLUMN ' . $this->db->quoteName($column) . ' ' . $definition . ' ' . $constraints;

        $this->db->setQuery($query);
	    
        $this->db->execute();
    }	
  
    // E7. Drop column in database table
  	public function drop_column($column)
    {        
        $query = $this->db->getQuery(true);
        
        $query = 'ALTER TABLE ' . $this->db->quoteName('#__' . $this->table);
        $query .= ' DROP COLUMN ' . $this->db->quoteName($column);
        
        $this->db->setQuery($query);
	    
        $this->db->execute();
    }	
  
  	// E8. Drop table
    public function drop_table()
    {
        if (!$this->table_exists())
        {
            return false;
        }
        
        $query = $this->db->getQuery(true);
        
        $query = 'DROP TABLE IF EXISTS ' . $this->db->quoteName('#__' . $this->table) . ';';
        
        $this->db->setQuery($query);
	    
	    $this->db->execute();
    }

    // F1. Check if database table exists
    public function table_exists()
    {
        $tables = $this->db->getTableList();
        $prefix = $this->db->getPrefix();
        
        if (\in_array($prefix . $this->table, $tables))
        {
            return true;
        }
        
        return false;
    }

    public function custom_query($q)
    {
        $this->query = $q;
        
        $this->db->setQuery($this->query);
	    
	    $this->db->execute();
    }

    public function replace_column($conditions, $column, $old_value, $new_value)
    {
        $this->query->update($this->db->quoteName('#__' . $this->table));

        $fields = array($this->db->quoteName($column) . ' = REPLACE(' . $this->db->quoteName($column) . ',' . $this->db->quote($old_value) . ',' . $this->db->quote($new_value) . ')');
        
        if ($conditions)
        {
            $this->set_conditions($conditions);
        }
        
        $this->query->set($fields);

        $this->db->setQuery($this->query);
	    
        $this->db->execute();
	    
	    return $this->db->getAffectedRows();
    }

    // Build where clause
    public function set_conditions($conditions = [])
    {
        // $conditions - string (single condition), 1-D array, 2-D array
        /*
        'id = 4'; ['id = 4']; ['id', '=', '4']

        */

        if (!$conditions)
        {
            return;
        }
        
        if (\is_string($conditions))
        {
            $this->conditions[] = $conditions;
        }
        
        if (\is_array($conditions) && !empty($conditions))
	    {
            foreach ($conditions as $key => $condition)
	        {
                if (\is_string($condition))
                {
                    $this->conditions[] = $condition;
                }
                elseif (\is_array($condition))
                {
                    $condition = array_values($condition);
                    
                    $field_type = $condition[3] ?? '';

                    if ($field_type == 'date')
                    {
                        $date = Factory::getDate()->modify($condition[2] . ' days');
                        $this->conditions[] = $this->db->quoteName($condition[0]) . ' ' . $condition[1] . ' ' . $this->db->quote($date);
                    }
                    elseif ($condition[1] == 'IS NULL' || $condition[1] == 'IS NOT NULL')
                    {
                        $this->conditions[] = $this->db->quoteName($condition[0]) . ' ' . $condition[1];
                    }
                    elseif (strtoupper($condition[1]) == 'IN')
                    {
                        $in = \is_array($condition[2]) ? $condition[2] : str_getcsv($condition[2]);
                        $this->in_conditions[] = array($condition[0], $in);
                    }
                    else
                    {
                        $this->conditions[] = $this->db->quoteName($condition[0]) . ' ' . $condition[1] . ' ' . $this->db->quote($condition[2]);
                    }
                }
	        }
	    }

        $this->query->where($this->conditions);

        foreach ($this->in_conditions as $in)
        {
            $this->query->whereIn($in[0], $in[1]);
        }
    }

    public function set_select($select = '*')
    {
        if (empty($select))
        {
            $select = '*';
        }

        if (\is_string($select))
        {
            $this->select = array_map('trim', explode(',', $select));
        }
        else
        {
            $this->select = $select;
        }
    }

    public function set_ordering($ordering = '')
    {
        // column, direction

        if ($ordering && \is_string($ordering))
        {
            $this->order = $ordering;
        }

        $this->query->order($this->order);
    }

    public function set_limit($limit = '', $offset = 0)
    {
        if ($limit)
        {
            $this->limit = $limit;
            $this->offset = $offset;

            $this->query->setLimit($this->limit, $this->offset);
        }
    }

    public function set_joins($joins)
    {
        $this->joins = $joins;
    }

    public function set_group($group = '')
    {
        if ($group)
        {
            $this->group = $group;

            $this->query->group($this->db->quoteName($this->group));
        }
    }

    public function set_having($having = '')
    {
        if ($having)
        {
            $this->having = $having;

            $this->query->having($this->having);
        }
    }

    public function print_query()
    {
        Factory::getApplication()->enqueueMessage($this->query->__toString());
    }
}