PHP Classes

File: src/Field.php

Recommend this page to a friend!
  Classes of Vitaly   Queasy DB   src/Field.php   Download  
File: src/Field.php
Role: Class source
Content type: text/plain
Description: Class source
Class: Queasy DB
Execute queries by accessing class variables
Author: By
Last change: #48 fixed
#48 fixed
Date: 2 years ago
Size: 2,214 bytes
 

Contents

Class file image Download
<?php

namespace queasy\db;

use
PDO;
use
ArrayAccess;

use
Psr\Log\NullLogger;
use
Psr\Log\LoggerInterface;
use
Psr\Log\LoggerAwareInterface;

use
queasy\db\query\CountQuery;
use
queasy\db\query\SelectQuery;

class
Field implements ArrayAccess, LoggerAwareInterface
{
    protected
$pdo;

    protected
$table;

    protected
$name;

    protected
$logger;

    public function
__construct(PDO $pdo, Table $table, $name)
    {
       
$this->logger = new NullLogger();

       
$this->pdo = $pdo;
       
$this->table = $table;
       
$this->name = $name;
    }

    public function
update($offset, $value, array $options = array())
    {
        if (
null === $value) {
            return
$this->delete($offset);
        }

        return
$this->table->update($value, $this->name, $offset, $options);
    }

    public function
delete($offset, array $options = array())
    {
        return
$this->table->delete($this->name, $offset, $options);
    }

    public function
select($value, array $options = array())
    {
       
$query = new SelectQuery($this->pdo, $this->table->getName());
       
$query->setLogger($this->logger);

       
$statement = $query(array($this->name => $value), $options);

        return
$statement->fetchAll();
    }

    public function
offsetExists($offset)
    {
       
$query = new CountQuery($this->pdo, $this->table->getName());
       
$query->setLogger($this->logger);

       
$statement = $query(array($this->name => $offset));

       
$row = $statement->fetch();

       
$count = array_shift($row);

        return
$count > 0;
    }

    public function
offsetGet($offset)
    {
       
$rows = $this->select($offset);

        if (
is_array($offset)) {
            return
$rows;
        } else {
            return
array_shift($rows);
        }
    }

    public function
offsetSet($offset, $value)
    {
       
$this->update($offset, $value);
    }

    public function
offsetUnset($offset)
    {
       
$this->delete($offset);
    }

    public function
__invoke($value, array $options = array())
    {
        return
$this->select([$value], $options);
    }

    public function
setLogger(LoggerInterface $logger)
    {
       
$this->logger = $logger;
    }
}