Overview

Namespaces

  • LeanMapper
    • Exception
    • Reflection
    • Relationship

Classes

  • LeanMapper\Entity
  • LeanMapper\Reflection\Aliases
  • LeanMapper\Reflection\AliasesBuilder
  • LeanMapper\Reflection\AliasesParser
  • LeanMapper\Reflection\AnnotationsParser
  • LeanMapper\Reflection\EntityReflection
  • LeanMapper\Reflection\Property
  • LeanMapper\Reflection\PropertyFactory
  • LeanMapper\Reflection\PropertyFilters
  • LeanMapper\Reflection\PropertyType
  • LeanMapper\Relationship\BelongsTo
  • LeanMapper\Relationship\BelongsToMany
  • LeanMapper\Relationship\BelongsToOne
  • LeanMapper\Relationship\HasMany
  • LeanMapper\Relationship\HasOne
  • LeanMapper\Repository
  • LeanMapper\Result
  • LeanMapper\Row

Exceptions

  • LeanMapper\Exception\InvalidAnnotationException
  • LeanMapper\Exception\InvalidArgumentException
  • LeanMapper\Exception\InvalidMethodCallException
  • LeanMapper\Exception\InvalidStateException
  • LeanMapper\Exception\InvalidValueException
  • LeanMapper\Exception\MemberAccessException
  • LeanMapper\Exception\RuntimeException
  • LeanMapper\Exception\UtilityClassException
  • Overview
  • Namespace
  • Class
  1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 
<?php

/**
 * This file is part of the Lean Mapper library (http://www.leanmapper.com)
 *
 * Copyright (c) 2013 Vojtěch Kohout (aka Tharos)
 *
 * For the full copyright and license information, please view the file
 * license-mit.txt that was distributed with this source code.
 */

namespace LeanMapper;

use dibi;
use DibiConnection;
use DibiRow;
use LeanMapper\Exception\InvalidStateException;
use LeanMapper\Reflection\AnnotationsParser;
use ReflectionClass;

/**
 * Base class for custom repositories
 *
 * @author Vojtěch Kohout
 */
abstract class Repository
{

    /** @varstring */
    public static $defaultEntityNamespace = 'Model\Entity';

    /** @var DibiConnection */
    protected $connection;

    /** @var string */
    protected $table;

    /** @var string */
    protected $entityClass;

    /** @var string */
    private $docComment;


    /**
     * @param DibiConnection $connection
     */
    public function __construct(DibiConnection $connection)
    {
        $this->connection = $connection;
    }

    /**
     * Stored modified fields of entity into database and creates new row in database when entity is in detached state
     *
     * @param Entity $entity
     * @return int
     */
    public function persist(Entity $entity)
    {
        if ($entity->isModified()) {
            $values = $entity->getModifiedData();
            if ($entity->isDetached()) {
                $this->connection->insert($this->getTable(), $values)
                        ->execute(); // dibi::IDENTIFIER would lead to exception when there is no column with AUTO_INCREMENT
                $id = isset($values['id']) ? $values['id'] : $this->connection->getInsertId();
                $entity->markAsCreated($id, $this->getTable(), $this->connection);
                return $id;
            } else {
                $result = $this->connection->update($this->getTable(), $values)
                        ->where('[id] = %i', $entity->id)
                        ->execute();
                $entity->markAsUpdated();
                return $result;
            }
        }
    }

    /**
     * Removes given entity (or entity with given id) from database
     *
     * @param Entity|int $arg
     * @throws InvalidStateException
     */
    public function delete($arg)
    {
        $id = $arg;
        if ($arg instanceof Entity) {
            if ($arg->isDetached()) {
                throw new InvalidStateException('Cannot delete detached entity.');
            }
            $id = $arg->id;
            $arg->detach();
        }
        $this->connection->delete($this->getTable())
                ->where('[id] = %i', $id)
                ->execute();
    }

    /**
     * Helps to create entity instance from given DibiRow instance
     *
     * @param DibiRow $row
     * @param string|null $entityClass
     * @param string|null $table
     * @return mixed
     */
    protected function createEntity(DibiRow $row, $entityClass = null, $table = null)
    {
        if ($entityClass === null) {
            $entityClass = $this->getEntityClass();
        }
        if ($table === null) {
            $table = $this->getTable();
        }
        $collection = Result::getInstance($row, $table, $this->connection);
        return new $entityClass($collection->getRow($row->id));
    }

    /**
     * Helps to create array of entites from given array of DibiRow instances
     *
     * @param array $rows
     * @param string|null $entityClass
     * @param string|null $table
     * @return array
     */
    protected function createEntities(array $rows, $entityClass = null, $table = null)
    {
        if ($entityClass === null) {
            $entityClass = $this->getEntityClass();
        }
        if ($table === null) {
            $table = $this->getTable();
        }
        $entities = array();
        $collection = Result::getInstance($rows, $table, $this->connection);
        foreach ($rows as $row) {
            $entities[$row->id] = new $entityClass($collection->getRow($row->id));
        }
        return $entities;
    }

    /**
     * Returns name of database table related to entity which repository can handle
     *
     * @return string
     * @throws InvalidStateException
     */
    protected function getTable()
    {
        if ($this->table === null) {
            $name = AnnotationsParser::parseSimpleAnnotationValue('table', $this->getDocComment());
            if ($name !== null) {
                $this->table = $name;
            } else {
                $matches = array();
                if (preg_match('#([a-z0-9]+)repository$#i', get_called_class(), $matches)) {
                    $this->table = strtolower($matches[1]);
                } else {
                    throw new InvalidStateException('Cannot determine table name.');
                }
            }
        }
        return $this->table;
    }

    /**
     * Returns fully qualified name of entity class which repository can handle
     *
     * @return string
     * @throws InvalidStateException
     */
    protected function getEntityClass()
    {
        if ($this->entityClass === null) {
            $name = AnnotationsParser::parseSimpleAnnotationValue('entity', $this->getDocComment());
            if ($name !== null) {
                $this->entityClass = $name;
            } else {
                $matches = array();
                if (preg_match('#([a-z0-9]+)repository$#i', get_called_class(), $matches)) {
                    $this->entityClass = self::$defaultEntityNamespace . '\\' . $matches[1];
                } else {
                    throw new InvalidStateException('Cannot determine entity class name.');
                }
            }
        }
        return $this->entityClass;
    }

    ////////////////////
    ////////////////////

    /**
     * @return string
     */
    private function getDocComment()
    {
        if ($this->docComment === null) {
            $reflection = new ReflectionClass(get_called_class());
            $this->docComment = $reflection->getDocComment();
        }
        return $this->docComment;
    }
    
}
tharos/leanmapper v1.3.0 API documentation API documentation generated by ApiGen