Overview

Namespaces

  • LeanMapper
    • Exception
    • Reflection
    • Relationship

Classes

  • LeanMapper\Caller
  • LeanMapper\Connection
  • LeanMapper\DataDifference
  • LeanMapper\DefaultEntityFactory
  • LeanMapper\DefaultMapper
  • LeanMapper\Entity
  • LeanMapper\Events
  • LeanMapper\Filtering
  • LeanMapper\FilteringResult
  • LeanMapper\FilteringResultDecorator
  • LeanMapper\Fluent
  • LeanMapper\ImplicitFilters
  • 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\PropertyMethods
  • LeanMapper\Reflection\PropertyPasses
  • LeanMapper\Reflection\PropertyType
  • LeanMapper\Reflection\PropertyValuesEnum
  • LeanMapper\Relationship\BelongsTo
  • LeanMapper\Relationship\BelongsToMany
  • LeanMapper\Relationship\BelongsToOne
  • LeanMapper\Relationship\HasMany
  • LeanMapper\Relationship\HasOne
  • LeanMapper\Repository
  • LeanMapper\Result
  • LeanMapper\ResultProxy
  • LeanMapper\Row

Interfaces

  • LeanMapper\IEntityFactory
  • LeanMapper\IMapper

Exceptions

  • LeanMapper\Exception\Exception
  • LeanMapper\Exception\InvalidAnnotationException
  • LeanMapper\Exception\InvalidArgumentException
  • LeanMapper\Exception\InvalidMethodCallException
  • LeanMapper\Exception\InvalidStateException
  • LeanMapper\Exception\InvalidValueException
  • LeanMapper\Exception\MemberAccessException
  • 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: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370: 371: 372: 373: 374: 375: 376: 377: 378: 379: 380: 381: 382: 383: 384: 385: 386: 387: 388: 389: 390: 391: 392: 393: 394: 395: 396: 397: 398: 399: 400: 401: 402: 403: 404: 405: 406: 407: 408: 409: 410: 411: 412: 413: 414: 415: 416: 417: 418: 419: 420: 421: 422: 423: 424: 425: 426: 427: 428: 429: 430: 431: 432: 433: 434: 435: 436: 437: 438: 439: 440: 441: 442: 443: 444: 445: 446: 447: 448: 449: 450: 451: 452: 453: 454: 455: 456: 457: 458: 459: 460: 461: 462: 463: 464: 465: 466: 467: 468: 469: 470: 471: 472: 473: 474: 475: 476: 477: 478: 479: 480: 481: 482: 483: 484: 485: 486: 487: 488: 489: 490: 491: 492: 493: 494: 495: 496: 497: 498: 499: 500: 501: 502: 503: 504: 505: 506: 507: 508: 509: 510: 511: 512: 513: 514: 515: 516: 517: 518: 519: 520: 521: 522: 523: 524: 525: 526: 527: 528: 529: 530: 531: 532: 533: 534: 535: 536: 537: 538: 539: 540: 541: 542: 543: 544: 545: 546: 547: 548: 549: 550: 551: 552: 553: 554: 555: 556: 557: 558: 559: 560: 561: 562: 563: 564: 565: 566: 567: 568: 569: 570: 571: 572: 573: 574: 575: 576: 577: 578: 579: 580: 581: 582: 583: 584: 585: 586: 587: 588: 589: 590: 591: 592: 593: 594: 595: 596: 597: 598: 599: 600: 601: 602: 603: 604: 605: 606: 607: 608: 609: 610: 611: 612: 613: 614: 615: 616: 617: 618: 619: 620: 621: 622: 623: 624: 625: 626: 627: 628: 629: 630: 631: 632: 633: 634: 635: 636: 637: 638: 639: 640: 641: 642: 643: 644: 645: 646: 647: 648: 649: 650: 651: 652: 653: 654: 655: 656: 657: 658: 659: 660: 661: 662: 663: 664: 665: 666: 667: 668: 669: 670: 671: 672: 673: 674: 675: 676: 677: 678: 679: 680: 681: 682: 683: 684: 685: 686: 687: 688: 689: 690: 691: 692: 693: 694: 695: 696: 697: 698: 699: 700: 701: 702: 703: 704: 705: 706: 707: 708: 709: 710: 711: 712: 713: 714: 715: 716: 717: 718: 719: 720: 721: 722: 723: 724: 725: 726: 727: 728: 729: 730: 731: 732: 733: 734: 735: 736: 737: 738: 739: 740: 741: 742: 743: 744: 745: 746: 747: 748: 749: 750: 751: 752: 753: 754: 755: 756: 757: 758: 759: 760: 761: 762: 763: 764: 765: 766: 767: 768: 769: 770: 771: 772: 773: 774: 775: 776: 777: 778: 779: 780: 781: 782: 783: 784: 785: 786: 787: 788: 789: 790: 791: 792: 793: 794: 795: 796: 797: 798: 799: 800: 801: 802: 803: 804: 805: 806: 807: 808: 809: 810: 811: 812: 813: 814: 815: 816: 817: 818: 819: 820: 821: 822: 823: 824: 825: 826: 827: 828: 829: 830: 831: 832: 833: 834: 835: 836: 837: 838: 839: 840: 841: 842: 843: 844: 845: 846: 847: 848: 849: 850: 851: 852: 853: 854: 855: 856: 857: 858: 859: 860: 861: 862: 863: 864: 865: 866: 867: 868: 869: 870: 871: 872: 873: 874: 875: 876: 877: 878: 879: 880: 881: 882: 883: 884: 885: 886: 887: 888: 889: 890: 891: 892: 893: 894: 895: 896: 897: 898: 899: 900: 901: 902: 903: 904: 905: 906: 907: 908: 909: 910: 911: 912: 913: 914: 915: 916: 917: 918: 919: 920: 921: 922: 923: 924: 925: 926: 927: 928: 929: 930: 931: 932: 933: 934: 935: 936: 937: 938: 939: 940: 941: 942: 943: 944: 945: 946: 947: 948: 949: 950: 951: 952: 953: 954: 955: 956: 957: 958: 959: 
<?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 Exception;
use LeanMapper\Exception\Exception as LeanMapperException;
use LeanMapper\Exception\InvalidArgumentException;
use LeanMapper\Exception\InvalidMethodCallException;
use LeanMapper\Exception\InvalidStateException;
use LeanMapper\Exception\InvalidValueException;
use LeanMapper\Exception\MemberAccessException;
use LeanMapper\Reflection\EntityReflection;
use LeanMapper\Reflection\Property;
use LeanMapper\Relationship;
use ReflectionException;
use Traversable;

/**
 * Base class for concrete entities
 *
 * @author Vojtěch Kohout
 */
abstract class Entity
{

    const ACTION_ADD = 'add';

    const ACTION_REMOVE = 'remove';

    /** @var Row */
    protected $row;

    /** @var IMapper */
    protected $mapper;

    /** @var IEntityFactory */
    protected $entityFactory;

    /** @var EntityReflection[] */
    protected static $reflections = array();

    /** @var EntityReflection */
    private $currentReflection;


    /**
     * Gets reflection of current entity
     *
     * @param IMapper|null $mapper
     * @return EntityReflection
     */
    public static function getReflection(IMapper $mapper = null)
    {
        $class = get_called_class();
        $mapperClass = $mapper !== null ? get_class($mapper) : '';
        if (!isset(static::$reflections[$class][$mapperClass])) {
            static::$reflections[$class][$mapperClass] = new EntityReflection($class, $mapper);
        }
        return static::$reflections[$class][$mapperClass];
    }

    /**
     * @param Row|Traversable|array|null $arg
     * @throws InvalidArgumentException
     */
    public function __construct($arg = null)
    {
        if ($arg instanceof Row) {
            if ($arg->isDetached()) {
                throw new InvalidArgumentException('It is not allowed to create entity ' . get_called_class() . ' from detached instance of LeanMapper\Row.');
            }
            $this->row = $arg;
            $this->mapper = $arg->getMapper();
        } else {
            $this->row = Result::createDetachedInstance()->getRow();
            foreach ($this->getCurrentReflection()->getEntityProperties() as $property) {
                if ($property->hasDefaultValue()) {
                    $propertyName = $property->getName();
                    $this->set($propertyName, $property->getDefaultValue());
                }
            }
            if ($arg !== null) {
                if (!is_array($arg) and !($arg instanceof Traversable)) {
                    $type = gettype($arg) !== 'object' ? gettype($arg) : 'instance of ' . get_class($arg);
                    throw new InvalidArgumentException("Argument \$arg in " . get_called_class() . "::__construct must contain either null, array, instance of LeanMapper\\Row or instance of Traversable, $type given.");
                }
                $this->assign($arg);
            }
            $this->initDefaults();
        }
    }

    /**
     * @param string $name
     * @return mixed
     * @throws InvalidMethodCallException
     * @throws MemberAccessException
     */
    public function __get($name)
    {
        $reflection = $this->getCurrentReflection();
        $nativeGetter = $reflection->getGetter('get' . ucfirst($name));
        if ($nativeGetter !== null) {
            try {
                return $nativeGetter->invoke($this); // filters arguments are not relevant here
            } catch (ReflectionException $e) {
                throw new MemberAccessException("Cannot invoke native getter of property '$name' in entity " . get_called_class() . '.');
            }
        }
        $property = $reflection->getEntityProperty($name);
        if ($property === null) {
            throw new MemberAccessException("Cannot access undefined property '$name' in entity " . get_called_class() . '.');
        }
        $customGetter = $property->getGetter();
        if ($customGetter !== null) {
            if (!method_exists($this, $customGetter)) {
                throw new InvalidMethodCallException("Missing getter method '$customGetter' in entity " . get_called_class() . '.');
            }
            return $this->$customGetter(); // filters arguments are not relevant here
        }
        return $this->get($property);
    }

    /**
     * @param string $name
     * @param mixed $value
     * @throws InvalidMethodCallException
     * @throws MemberAccessException
     */
    public function __set($name, $value)
    {
        $reflection = $this->getCurrentReflection();
        $nativeSetter = $reflection->getSetter('set' . ucfirst($name));
        if ($nativeSetter !== null) {
            try {
                $nativeSetter->invoke($this, $value);
                return;
            } catch (ReflectionException $e) {
                throw new MemberAccessException("Cannot invoke native setter of property '$name' in entity " . get_called_class() . '.');
            }
        }
        $property = $reflection->getEntityProperty($name);
        if ($property === null) {
            throw new MemberAccessException("Cannot access undefined property '$name' in entity " . get_called_class() . '.');
        }
        if (!$property->isWritable()) {
            throw new MemberAccessException("Cannot write to read-only property '$name' in entity " . get_called_class() . '.');
        }
        $customSetter = $property->getSetter();
        if ($customSetter !== null) {
            if (!method_exists($this, $customSetter)) {
                throw new InvalidMethodCallException("Missing setter method '$customSetter' in entity " . get_called_class() . '.');
            }
            $this->$customSetter($value);
            return;
        }
        $this->set($property, $value);
    }

    /**
     * Tells whether given property exists and is not null
     *
     * @param string $name
     * @throws LeanMapperException
     * @return bool
     */
    public function __isset($name)
    {
        try {
            return $this->$name !== null;
        } catch (MemberAccessException $e) {
            return false;
        } catch (LeanMapperException $e) {
            if ($this->isDetached() and $e->getCode() === Result::ERROR_MISSING_COLUMN) {
                return false;
            }
            throw $e;
        }
    }

    /**
     * @param string $name
     * @param array $arguments
     * @return mixed|void
     * @throws InvalidMethodCallException
     * @throws InvalidArgumentException
     */
    public function __call($name, array $arguments)
    {
        $e = new InvalidMethodCallException("Method $name in entity " . get_called_class() . ' is not callable.');
        if (strlen($name) < 4) {
            throw $e;
        }
        if (substr($name, 0, 3) === 'get') { // get<Name>
            return $this->get(lcfirst(substr($name, 3)), $arguments);

        } elseif (substr($name, 0, 3) === 'set') { // set<Name>
            if (count($arguments) !== 1) {
                throw new InvalidMethodCallException("Method $name in entity " . get_called_class() . ' expects exactly one argument.');
            }
            $property = $this->getCurrentReflection()->getEntityProperty(
                $propertyName = lcfirst(substr($name, 3))
            );
            if ($property === null) {
                throw new MemberAccessException("Cannot access undefined property '$propertyName' in entity " . get_called_class() . '.');
            }
            if (!$property->isWritable()) {
                throw new MemberAccessException("Cannot write to read-only property '$propertyName' in entity " . get_called_class() . '.');
            }
            $this->set($property, reset($arguments));

        } elseif (substr($name, 0, 5) === 'addTo' and strlen($name) > 5) { // addTo<Name>
            $this->checkMethodArgumentsCount(1, $arguments, $name);
            $this->addToOrRemoveFrom(self::ACTION_ADD, lcfirst(substr($name, 5)), reset($arguments));

        } elseif (substr($name, 0, 10) === 'removeFrom' and strlen($name) > 10) { // removeFrom<Name>
            $this->checkMethodArgumentsCount(1, $arguments, $name);
            $this->addToOrRemoveFrom(self::ACTION_REMOVE, lcfirst(substr($name, 10)), reset($arguments));

        } elseif (substr($name, 0, 9) === 'removeAll' and strlen($name) > 9) { // removeAll<Name>
            $this->checkMethodArgumentsCount(0, $arguments, $name);
            $property = lcfirst(substr($name, 9));
            foreach ($this->$property as $value) {
                $this->addToOrRemoveFrom(self::ACTION_REMOVE, $property, $value);
            }

        } elseif (substr($name, 0, 10) === 'replaceAll' and strlen($name) > 10) { // replaceAll<Name>
            $this->checkMethodArgumentsCount(1, $arguments, $name);
            $arg = reset($arguments);
            if (!is_array($arg) and (!($arg instanceof Traversable) or ($arg instanceof Entity))) {
                throw new InvalidArgumentException("Argument of method $name in entity " . get_called_class() . ' must contain either array or instance of Traversable which is not Entity.');
            }
            $property = lcfirst(substr($name, 10));
            foreach ($this->$property as $value) {
                $this->addToOrRemoveFrom(self::ACTION_REMOVE, $property, $value);
            }
            $this->addToOrRemoveFrom(self::ACTION_ADD, $property, reset($arguments));

        } else {
            throw $e;
        }
    }

    /**
     * Performs mass value assignment (using setters)
     *
     * @param array|Traversable $values
     * @param array|null $whitelist
     * @throws InvalidArgumentException
     */
    public function assign($values, array $whitelist = null)
    {
        if ($whitelist !== null) {
            $whitelist = array_flip($whitelist);
        }
        if (!is_array($values) and !($values instanceof Traversable)) {
            $givenType = gettype($values) !== 'object' ? gettype($values) : 'instance of ' . get_class($values);
            throw new InvalidArgumentException("Argument \$values in " . get_called_class() . "::assign must contain either array or instance of Traversable, $givenType given.");
        }
        foreach ($values as $property => $value) {
            if ($whitelist === null or isset($whitelist[$property])) {
                $this->__set($property, $value);
            }
        }
    }

    /**
     * Gets high-level values of properties
     *
     * @param array|null $whitelist
     * @return array
     */
    public function getData(array $whitelist = null)
    {
        $data = array();
        if ($whitelist !== null) {
            $whitelist = array_flip($whitelist);
        }
        $reflection = $this->getCurrentReflection();
        $usedGetters = array();
        foreach ($reflection->getEntityProperties() as $property) {
            $field = $property->getName();
            if ($whitelist !== null and !isset($whitelist[$field])) {
                continue;
            }
            $data[$field] = $this->__get($property->getName());
            $getter = $property->getGetter();
            if ($getter !== null) {
                $usedGetters[$getter] = true;
            }
        }
        foreach ($reflection->getGetters() as $name => $getter) {
            if (isset($usedGetters[$getter->getName()])) {
                continue;
            }
            $field = lcfirst(substr($name, 3));
            if ($whitelist !== null and !isset($whitelist[$field])) {
                continue;
            }
            if ($getter->getNumberOfRequiredParameters() === 0) {
                $data[$field] = $getter->invoke($this);
            }
        }
        return $data;
    }

    /**
     * Gets low-level values of underlying Row columns
     *
     * @return array
     */
    public function getRowData()
    {
        return $this->row->getData();
    }

    /**
     * Gets low-level values of underlying Row columns that were modified
     *
     * @return array
     */
    public function getModifiedRowData()
    {
        return $this->row->getModifiedData();
    }

    /**
     * Gets current M:N differences
     *
     * @return array
     */
    public function getHasManyRowDifferences()
    {
        $differences = array();
        foreach ($this->getCurrentReflection()->getEntityProperties() as $property) {
            if ($property->hasRelationship() and ($property->getRelationship() instanceof Relationship\HasMany)) {
                $relationship = $property->getRelationship();
                $difference = $this->row->createReferencingDataDifference(
                    $relationship->getRelationshipTable(),
                    $relationship->getColumnReferencingSourceTable(),
                    null,
                    $relationship->getStrategy()
                );
                if ($difference->mayHaveAny()) {
                    $differences[$relationship->getColumnReferencingSourceTable() . ':' . $relationship->getRelationshipTable() . ':' . $relationship->getColumnReferencingTargetTable()] = $difference->getByPivot($relationship->getColumnReferencingTargetTable());
                }
            }
        }
        return $differences;
    }

    /**
     * Tells whether entity was modified
     *
     * @return bool
     */
    public function isModified()
    {
        return $this->row->isModified();
    }

    /**
     * Marks entity as non-modified (isModified returns false right after this method call)
     */
    public function markAsUpdated()
    {
        $this->row->markAsUpdated();
        foreach ($this->getCurrentReflection()->getEntityProperties() as $property) {
            if ($property->hasRelationship() and ($property->getRelationship() instanceof Relationship\HasMany)) {
                $relationship = $property->getRelationship();
                $this->row->cleanReferencingAddedAndRemovedMeta(
                    $relationship->getRelationshipTable(),
                    $relationship->getColumnReferencingSourceTable(),
                    null,
                    $relationship->getStrategy()
                );
            }
        }
    }

    /**
     * Detaches entity
     */
    public function detach()
    {
        $this->row->detach();
        $this->entityFactory = null;
        $this->mapper = null;
    }

    /**
     * Attaches entity
     *
     * @param int $id
     * @throws InvalidStateException
     */
    public function attach($id)
    {
        if ($this->mapper === null) {
            throw new InvalidStateException('Missing mapper in ' . get_called_class() . '.');
        }
        $this->row->attach($id, $this->mapper->getTable(get_called_class()));
    }

    /**
     * Tells whether entity is in detached state (like newly created entity)
     *
     * @return bool
     */
    public function isDetached()
    {
        return $this->row->isDetached();
    }

    /**
     * Provides dependencies
     *
     * @param IEntityFactory|null $entityFactory
     * @param Connection|null $connection
     * @param IMapper|null $mapper
     * @throws InvalidArgumentException
     * @throws InvalidStateException
     */
    public function makeAlive(IEntityFactory $entityFactory = null, Connection $connection = null, IMapper $mapper = null)
    {
        $entityFactory === null or $this->setEntityFactory($entityFactory);
        $mapper === null or $this->useMapper($mapper);
        $connection === null or $this->row->setConnection($connection);

        if ($this->entityFactory === null) {
            throw new InvalidStateException('Missing entity factory in entity ' . get_called_class() . '.');
        }
        if ($this->mapper === null) {
            throw new InvalidStateException('Missing mapper in entity ' . get_called_class() . '.');
        }
        if (!$this->row->hasConnection()) {
            throw new InvalidStateException('Missing connection in Result in entity ' . get_called_class() . '.');
        }
    }

    /**
     * @return array
     */
    public function __sleep()
    {
        return array('row', 'mapper', 'entityFactory');
    }

    /**
     * @param $property
     * @param array $filterArgs
     * @throws InvalidValueException
     * @throws InvalidStateException
     * @throws MemberAccessException
     * @return mixed
     */
    protected function get($property, array $filterArgs = array())
    {
        if ($property instanceof Property) {
            $name = $property->getName();
        } else {
            $name = $property;
            $property = $this->getCurrentReflection()->getEntityProperty($name);
            if ($property === null) {
                throw new MemberAccessException("Cannot access undefined property '$name' in entity " . get_called_class() . '.');
            }
        }
        $pass = $property->getGetterPass();
        if ($property->isBasicType()) {
            $column = $property->getColumn();
            try {
                $value = $this->row->$column;
            } catch (LeanMapperException $e) {
                throw new LeanMapperException("Cannot get value of property '{$property->getName()}' in entity " . get_called_class() . ' due to low-level failure: ' . $e->getMessage(), $e->getCode(), $e);
            }
            if ($pass !== null) {
                $value = $this->$pass($value);
            }
            if ($value === null) {
                if (!$property->isNullable()) {
                    throw new InvalidValueException("Property $name in entity " . get_called_class() . ' cannot be null.');
                }
                return $value;
            }
            settype($value, $property->getType());
            if ($property->containsEnumeration() and !$property->isValueFromEnum($value)) {
                throw new InvalidValueException("Given value is not from possible values enumeration in property '{$property->getName()}' in entity " . get_called_class() . '.');
            }
            return $value;
        } // property doesn't contain basic type
        if ($property->hasRelationship()) {
            if ($this->entityFactory === null) {
                throw new InvalidStateException('Missing entity factory in ' . get_called_class() . '.');
            }
            $implicitFilters = $this->createImplicitFilters($property->getType(), new Caller($this, $property));
            $firstFilters = $property->getFilters(0) ?: array();

            $relationship = $property->getRelationship();
            if ($relationship instanceof Relationship\HasMany) {
                $secondFilters = $this->mergeFilters($property->getFilters(1) ?: array(), $implicitFilters->getFilters());
            } else {
                $firstFilters = $this->mergeFilters($firstFilters, $implicitFilters->getFilters());
            }
            if (!empty($firstFilters) or !empty($secondFilters)) {
                if ($relationship instanceof Relationship\HasMany) {
                    $relationshipTableFiltering = !empty($firstFilters) ? new Filtering($firstFilters, $filterArgs, $this, $property, (array) $property->getFiltersTargetedArgs(0)) : null;
                    $targetTableFiltering = new Filtering($secondFilters, $filterArgs, $this, $property, array_merge($implicitFilters->getTargetedArgs(), (array) $property->getFiltersTargetedArgs(1)));
                } else {
                    $targetTableFiltering = !empty($firstFilters) ? new Filtering($firstFilters, $filterArgs, $this, $property, array_merge($implicitFilters->getTargetedArgs(), (array) $property->getFiltersTargetedArgs(0))) : null;
                }
            }
            return $this->getValueByPropertyWithRelationship($property, isset($targetTableFiltering) ? $targetTableFiltering : null, isset($relationshipTableFiltering) ? $relationshipTableFiltering : null);
        } // property doesn't contain basic type and doesn't contain relationship
        $column = $property->getColumn();
        try {
            $value = $this->row->$column;
        } catch (LeanMapperException $e) {
            throw new LeanMapperException("Cannot get value of property '{$property->getName()}' in entity " . get_called_class() . ' due to low-level failure: ' . $e->getMessage(), $e->getCode(), $e);
        }
        if ($pass !== null) {
            $value = $this->$pass($value);
        }
        if ($value === null) {
            if (!$property->isNullable()) {
                throw new InvalidValueException("Property '$name' in entity " . get_called_class() . " cannot be null.");
            }
            return $value;
        } // property doesn't contain basic type, doesn't contain relationship and doesn't contain null
        if (!$property->containsCollection()) {
            $type = $property->getType();
            if (!($value instanceof $type)) {
                throw new InvalidValueException("Property '$name' in entity " . get_called_class() . " is expected to contain an instance of $type, " . (is_object($value) ? 'instance of ' . get_class($value) : gettype($value)) . " given.");
            }
            return $value;
        }
        if (!is_array($value)) {
            throw new InvalidValueException("Property '$name' in entity " . get_called_class() . " is expected to contain an array of {$property->getType()} instances.");
        }
        return $value;
    }

    /**
     * @param Property|string $property
     * @param mixed $value
     * @throws InvalidMethodCallException
     * @throws InvalidValueException
     * @throws MemberAccessException
     */
    protected function set($property, $value)
    {
        if ($property instanceof Property) {
            $name = $property->getName();
        } else {
            $name = $property;
            $property = $this->getCurrentReflection()->getEntityProperty($name);
            if ($property === null) {
                throw new MemberAccessException("Cannot access undefined property '$name' in entity " . get_called_class() . '.');
            }
        }
        if ($value === null and !$property->isNullable()) {
            throw new InvalidValueException("Property '$name' in entity " . get_called_class() . ' cannot be null.');
        }
        $pass = $property->getSetterPass();
        $column = $property->getColumn();

        if ($property->isBasicType()) {
            if ($value === null) {
                $this->row->$column = ($pass !== null ? $this->$pass($value) : $value);
                return;
            }
            settype($value, $property->getType());
            if ($property->containsEnumeration() and !$property->isValueFromEnum($value)) {
                throw new InvalidValueException("Given value is not from possible values enumeration in property '{$property->getName()}' in entity " . get_called_class() . '.');
            }
            $this->row->$column = ($pass !== null ? $this->$pass($value) : $value);
            return;
        }
        // property doesn't contain basic type
        $type = $property->getType();
        $givenType = gettype($value) !== 'object' ? gettype($value) : 'instance of ' . get_class($value);

        if ($property->hasRelationship()) {
            if ($value !== null) {
                if (!($value instanceof $type)) {
                    throw new InvalidValueException("Unexpected value type given in property '{$property->getName()}' in entity " . get_called_class() . ", {$property->getType()} expected, $givenType given.");
                }
                if ($value->isDetached()) { // the value should be entity
                    throw new InvalidValueException("Detached entity cannot be assigned to property '{$property->getName()}' with relationship in entity " . get_called_class() . '.');
                }
            }
            $this->assignEntityToProperty($value, $name); // $pass is irrelevant relevant here
            return;
        }
        //property doesn't contain basic type and property doesn't contain relationship
        if ($property->containsCollection()) {
            if (!is_array($value)) {
                throw new InvalidValueException("Unexpected value type given in property '{$property->getName()}' in entity " . get_called_class() . ", array of {$property->getType()} expected, $givenType given.");
            }
            $this->row->$column = ($pass !== null ? $this->$pass($value) : $value);
            return;
        }
        if ($value !== null and !($value instanceof $type)) {
            throw new InvalidValueException("Unexpected value type given in property '{$property->getName()}' in entity " . get_called_class() . ", {$property->getType()} expected, $givenType given.");
        }
        $this->row->$column = ($pass !== null ? $this->$pass($value) : $value);
    }

    /**
     * Gets current entity's reflection (cached in memory)
     *
     * @return EntityReflection
     */
    protected function getCurrentReflection()
    {
        if ($this->currentReflection === null) {
            $this->currentReflection = $this->getReflection($this->mapper);
        }
        return $this->currentReflection;
    }

    /**
     * @param Property|string $property micro-optimalization
     * @param Filtering|null $targetTableFiltering
     * @param Filtering|null $relationshipTableFiltering
     * @throws LeanMapperException
     * @return Entity|Entity[]
     */
    protected function getValueByPropertyWithRelationship($property, Filtering $targetTableFiltering = null, Filtering $relationshipTableFiltering = null)
    {
        if (is_string($property)) {
            $property = $this->getCurrentReflection()->getEntityProperty($property);
        }
        $relationship = $property->getRelationship();
        $method = explode('\\', get_class($relationship));
        $method = 'get' . end($method) . 'Value';
        try {
            return $this->$method($property, $relationship, $targetTableFiltering, $relationshipTableFiltering);
        } catch (Exception $e) {
            throw new LeanMapperException("Cannot get value of property '{$property->getName()}' in entity " . get_called_class() . ' due to low-level failure: ' . $e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * @param Entity|null $entity
     * @param Property|string $property micro-optimalization
     * @throws InvalidMethodCallException
     */
    protected function assignEntityToProperty(Entity $entity = null, $property)
    {
        if ($entity !== null) {
            $this->useMapper($entity->mapper);
            $this->setEntityFactory($entity->entityFactory);
        }
        if (is_string($property)) {
            $property = $this->getCurrentReflection()->getEntityProperty($property);
        }
        $relationship = $property->getRelationship();
        if (!($relationship instanceof Relationship\HasOne)) {
            throw new InvalidMethodCallException("Cannot assign value to property '{$property->getName()}' in entity " . get_called_class() . '. Only properties with m:hasOne relationship can be set via magic __set.');
        }
        $column = $relationship->getColumnReferencingTargetTable();

        if ($entity !== null) {
            $row = $entity->row;
            $pkColumn = $this->mapper->getPrimaryKey(
                $this->mapper->getTable(get_class($entity))
            );
            $this->row->$column = $row->$pkColumn;
            $this->row->setReferencedRow($row, $column);
        } else {
            $this->row->$column = null;
            $this->row->setReferencedRow(null, $column);
        }
    }

    /**
     * @param string $entityClass
     * @param Caller $caller
     * @return ImplicitFilters
     */
    protected function createImplicitFilters($entityClass, Caller $caller = null)
    {
        $implicitFilters = $this->mapper->getImplicitFilters($entityClass, $caller);
        return ($implicitFilters instanceof ImplicitFilters) ? $implicitFilters : new ImplicitFilters($implicitFilters);
    }

    /**
     * @param array $filters1
     * @param array $filters2
     * @return array
     */
    protected function mergeFilters(array $filters1, array $filters2)
    {
        if (!empty($filters2)) {
            foreach (array_reverse($filters2) as $filter) {
                if (!in_array($filter, $filters1)) {
                    array_unshift($filters1, $filter);
                }
            }
        }
        return $filters1;
    }

    /**
     * Allows initialize properties' default values
     */
    protected function initDefaults()
    {
    }

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

    /**
     * @param Property $property
     * @param Relationship\HasOne $relationship micro-optimalization
     * @param Filtering|null $filtering
     * @throws InvalidValueException
     * @return Entity
     */
    private function getHasOneValue(Property $property, Relationship\HasOne $relationship, Filtering $filtering = null)
    {
        $targetTable = $relationship->getTargetTable();
        $row = $this->row->referenced($targetTable, $relationship->getColumnReferencingTargetTable(), $filtering);
        if ($row === null) {
            if (!$property->isNullable()) {
                $name = $property->getName();
                throw new InvalidValueException("Property '$name' cannot be null in entity " . get_called_class() . '.');
            }
            return null;
        } else {
            $entityClass = $this->mapper->getEntityClass($targetTable, $row);

            $entity = $this->entityFactory->createEntity($entityClass, $row);
            $this->checkConsistency($property, $entityClass, $entity);
            $entity->makeAlive($this->entityFactory);
            return $entity;
        }
    }

    /**
     * @param Property $property
     * * @param Relationship\HasMany $relationship micro-optimalization
     * @param Filtering|null $targetTableFiltering
     * @param Filtering|null $relTableFiltering
     * @return Entity[]
     * @throws InvalidValueException
     */
    private function getHasManyValue(Property $property, Relationship\HasMany $relationship, Filtering $targetTableFiltering = null, Filtering $relTableFiltering = null)
    {
        $targetTable = $relationship->getTargetTable();
        $columnReferencingTargetTable = $relationship->getColumnReferencingTargetTable();
        $rows = $this->row->referencing($relationship->getRelationshipTable(), $relationship->getColumnReferencingSourceTable(), $relTableFiltering, $relationship->getStrategy());
        $value = array();
        foreach ($rows as $row) {
            $valueRow = $row->referenced($targetTable, $columnReferencingTargetTable, $targetTableFiltering);
            if ($valueRow !== null) {
                $entityClass = $this->mapper->getEntityClass($targetTable, $valueRow);
                $entity = $this->entityFactory->createEntity($entityClass, $valueRow);
                $this->checkConsistency($property, $entityClass, $entity);
                $entity->makeAlive($this->entityFactory);
                $value[] = $entity;
            }
        }
        return $this->entityFactory->createCollection($value);
    }

    /**
     * @param Property $property
     * @param Relationship\BelongsToOne $relationship micro-optimalization
     * @param Filtering|null $filtering
     * @return Entity
     * @throws InvalidValueException
     */
    private function getBelongsToOneValue(Property $property, Relationship\BelongsToOne $relationship, Filtering $filtering = null)
    {
        $targetTable = $relationship->getTargetTable();
        $rows = $this->row->referencing($targetTable, $relationship->getColumnReferencingSourceTable(), $filtering, $relationship->getStrategy());
        $count = count($rows);
        if ($count > 1) {
            throw new InvalidValueException('There cannot be more than one entity referencing to entity ' . get_called_class() . " in property '{$property->getName()}' with m:belongToOne relationship.");
        } elseif ($count === 0) {
            if (!$property->isNullable()) {
                $name = $property->getName();
                throw new InvalidValueException("Property '$name' cannot be null in entity " . get_called_class() . '.');
            }
            return null;
        } else {
            $row = reset($rows);
            $entityClass = $this->mapper->getEntityClass($targetTable, $row);
            $entity = $this->entityFactory->createEntity($entityClass, $row);
            $this->checkConsistency($property, $entityClass, $entity);
            $entity->makeAlive($this->entityFactory);
            return $entity;
        }
    }

    /**
     * @param Property $property
     * @param Relationship\BelongsToMany $relationship micro-optimalization
     * @param Filtering|null $filtering
     * @return Entity[]
     */
    private function getBelongsToManyValue(Property $property, Relationship\BelongsToMany $relationship, Filtering $filtering = null)
    {
        $targetTable = $relationship->getTargetTable();
        $rows = $this->row->referencing($targetTable, $relationship->getColumnReferencingSourceTable(), $filtering, $relationship->getStrategy());
        $value = array();
        foreach ($rows as $row) {
            $entityClass = $this->mapper->getEntityClass($targetTable, $row);
            $entity = $this->entityFactory->createEntity($entityClass, $row);
            $this->checkConsistency($property, $entityClass, $entity);
            $entity->makeAlive($this->entityFactory);
            $value[] = $entity;
        }
        return $this->entityFactory->createCollection($value);
    }

    /**
     * Provides an mapper for entity
     *
     * @param IMapper $mapper
     * @throws InvalidMethodCallException
     * @throws InvalidStateException
     */
    private function useMapper(IMapper $mapper)
    {
        if ($this->mapper === null) {
            $newProperties = $this->getReflection($mapper)->getEntityProperties();
            foreach ($this->getCurrentReflection()->getEntityProperties() as $oldProperty) {
                $oldColumn = $oldProperty->getColumn();
                if ($oldColumn !== null) {
                    $name = $oldProperty->getName();
                    if (!isset($newProperties[$name]) or $newProperties[$name]->getColumn() === null) {
                        throw new InvalidStateException('Inconsistent sets of properties detected in entity ' . get_called_class() . '.');
                    }
                    if ($this->row->hasColumn($oldColumn)) {
                        $newColumn = $newProperties[$name]->getColumn();
                        $value = $this->row->$oldColumn;
                        unset($this->row->$oldColumn);
                        $this->row->$newColumn = $value;
                    }
                }
            }
            $this->mapper = $mapper;
            $this->row->setMapper($mapper);
            $this->currentReflection = null;
        } elseif ($this->mapper != $mapper) { // intentionally !=, we want to ensure that types and states are same
            throw new InvalidStateException("Given mapper isn't same as mapper already present in entity " . get_called_class() . '.');
        }
    }

    /**
     * @param IEntityFactory $entityFactory
     * @throws InvalidStateException
     */
    private function setEntityFactory(IEntityFactory $entityFactory)
    {
        if ($this->entityFactory === null) {
            $this->entityFactory = $entityFactory;
        } elseif ($this->entityFactory != $entityFactory) { // intentionally !=, we want to ensure that types and states are same
            throw new InvalidStateException("Given entity factory isn't same as entity factory already present in entity " . get_called_class() . '.');
        }
    }

    /**
     * @param string $action
     * @param string $name
     * @param mixed $arg
     * @throws InvalidMethodCallException
     * @throws InvalidArgumentException
     * @throws InvalidValueException
     */
    private function addToOrRemoveFrom($action, $name, $arg)
    {
        if ($this->isDetached()) {
            throw new InvalidMethodCallException('Cannot add or remove related entity to detached entity.');
        }
        if ($arg === null) {
            throw new InvalidArgumentException('Invalid argument given in entity ' . get_called_class() . '.');
        }
        if (is_array($arg) or ($arg instanceof Traversable and !($arg instanceof Entity))) {
            foreach ($arg as $value) {
                $this->addToOrRemoveFrom($action, $name, $value);
            }
        } else {
            $method = $action === self::ACTION_ADD ? 'addTo' : 'removeFrom';
            $property = $this->getCurrentReflection()->getEntityProperty($name);
            if ($property === null or !$property->hasRelationship() or !($property->getRelationship() instanceof Relationship\HasMany)) {
                throw new InvalidMethodCallException("Cannot call $method method with '$name' property in entity " . get_called_class() . '. Only properties with m:hasMany relationship can be managed this way.');
            }
            if ($property->getFilters()) {
                throw new InvalidMethodCallException("Cannot call $method method with '$name' property in entity " . get_called_class() . '. Only properties without filters can be managed this way.'); // deliberate restriction
            }
            $relationship = $property->getRelationship();
            if ($arg instanceof Entity) {
                if ($arg->isDetached()) {
                    throw new InvalidArgumentException('Cannot add or remove detached entity ' . get_class($arg) . " to $name in entity " . get_called_class() . '.');
                }
                $type = $property->getType();
                if (!($arg instanceof $type)) {
                    $type = gettype($arg) !== 'object' ? gettype($arg) : 'instance of ' . get_class($arg);
                    throw new InvalidValueException("Unexpected value type given in property '{$property->getName()}' in entity " . get_called_class() . ", {$property->getType()} expected, $type given.");
                }
                $data = $arg->getRowData();
                $arg = $data[$this->mapper->getPrimaryKey($relationship->getTargetTable())];
            }
            $table = $this->mapper->getTable($this->getCurrentReflection()->getName());
            $values = array(
                $relationship->getColumnReferencingSourceTable() => $this->row->{$this->mapper->getPrimaryKey($table)},
                $relationship->getColumnReferencingTargetTable() => $arg,
            );
            $method .= 'Referencing';
            $this->row->$method($values, $relationship->getRelationshipTable(), $relationship->getColumnReferencingSourceTable(), null, $relationship->getStrategy());
        }
    }

    /**
     * @param Property $property
     * @param string $mapperClass
     * @param Entity $entity
     * @throws InvalidValueException
     */
    private function checkConsistency(Property $property, $mapperClass, Entity $entity)
    {
        $type = $property->getType();
        if (!($entity instanceof $type)) {
            throw new InvalidValueException("Inconsistency found: property '{$property->getName()}' in entity " . get_called_class() . " is supposed to contain an instance of '$type' (due to type hint), but mapper maps it to '$mapperClass'. Please fix getEntityClass method in mapper, property annotation or entities inheritance.");
        }
    }

    /**
     * @param int $expectedCount
     * @param array $arguments
     * @param string $methodName
     * @throws InvalidMethodCallException
     */
    private function checkMethodArgumentsCount($expectedCount, array $arguments, $methodName)
    {
        if (count($arguments) !== $expectedCount) {
            if ($expectedCount === 0) {
                throw new InvalidMethodCallException("Method '$methodName' in entity " . get_called_class() . " doesn't expect any arguments.");
            } else {
                throw new InvalidMethodCallException("Method '$methodName' in entity " . get_called_class() . " expects exactly $expectedCount argument" . ($expectedCount > 1 ? 's' : '') . '.');
            }
        }
    }

}
tharos/leanmapper v2.3.0 API documentation API documentation generated by ApiGen