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
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;
abstract class Entity
{
const ACTION_ADD = 'add';
const ACTION_REMOVE = 'remove';
protected $row;
protected $mapper;
protected $entityFactory;
protected static $reflections = array();
private $currentReflection;
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];
}
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();
}
}
public function __get($name)
{
$reflection = $this->getCurrentReflection();
$nativeGetter = $reflection->getGetter('get' . ucfirst($name));
if ($nativeGetter !== null) {
try {
return $nativeGetter->invoke($this);
} 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();
}
return $this->get($property);
}
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);
}
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;
}
}
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') {
return $this->get(lcfirst(substr($name, 3)), $arguments);
} elseif (substr($name, 0, 3) === 'set') {
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) {
$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) {
$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) {
$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) {
$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;
}
}
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);
}
}
}
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;
}
public function getRowData()
{
return $this->row->getData();
}
public function getModifiedRowData()
{
return $this->row->getModifiedData();
}
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;
}
public function isModified()
{
return $this->row->isModified();
}
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()
);
}
}
}
public function detach()
{
$this->row->detach();
$this->entityFactory = null;
$this->mapper = null;
}
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()));
}
public function isDetached()
{
return $this->row->isDetached();
}
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() . '.');
}
}
public function __sleep()
{
return array('row', 'mapper', 'entityFactory');
}
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;
}
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);
}
$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;
}
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;
}
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;
}
$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()) {
throw new InvalidValueException("Detached entity cannot be assigned to property '{$property->getName()}' with relationship in entity " . get_called_class() . '.');
}
}
$this->assignEntityToProperty($value, $name);
return;
}
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);
}
protected function getCurrentReflection()
{
if ($this->currentReflection === null) {
$this->currentReflection = $this->getReflection($this->mapper);
}
return $this->currentReflection;
}
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);
}
}
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);
}
}
protected function createImplicitFilters($entityClass, Caller $caller = null)
{
$implicitFilters = $this->mapper->getImplicitFilters($entityClass, $caller);
return ($implicitFilters instanceof ImplicitFilters) ? $implicitFilters : new ImplicitFilters($implicitFilters);
}
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;
}
protected function initDefaults()
{
}
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;
}
}
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);
}
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;
}
}
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);
}
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) {
throw new InvalidStateException("Given mapper isn't same as mapper already present in entity " . get_called_class() . '.');
}
}
private function setEntityFactory(IEntityFactory $entityFactory)
{
if ($this->entityFactory === null) {
$this->entityFactory = $entityFactory;
} elseif ($this->entityFactory != $entityFactory) {
throw new InvalidStateException("Given entity factory isn't same as entity factory already present in entity " . get_called_class() . '.');
}
}
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.');
}
$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());
}
}
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.");
}
}
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' : '') . '.');
}
}
}
}