Overview

Namespaces

  • LeanMapper
    • Bridges
      • Nette
        • DI
    • Exception
    • Reflection
    • Relationship

Classes

  • LeanMapper\Bridges\Nette\DI\LeanMapperExtension
  • LeanMapper\Caller
  • LeanMapper\Connection
  • LeanMapper\DataDifference
  • LeanMapper\DefaultEntityFactory
  • LeanMapper\DefaultMapper
  • LeanMapper\Entity
  • LeanMapper\EntityDataDecoder
  • 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: 
<?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.md that was distributed with this source code.
 */

namespace LeanMapper\Reflection;

use LeanMapper\Exception\InvalidAnnotationException;
use LeanMapper\Exception\UtilityClassException;
use LeanMapper\IMapper;
use LeanMapper\Relationship;
use LeanMapper\Result;

/**
 * @author Vojtěch Kohout
 */
class PropertyFactory
{

    /**
     * @throws UtilityClassException
     */
    public function __construct()
    {
        throw new UtilityClassException('Cannot instantiate utility class ' . get_called_class() . '.');
    }



    /**
     * Creates new Property instance from given annotation
     *
     * @param string $annotationType
     * @param string $annotation
     * @param EntityReflection $entityReflection
     * @param IMapper|null $mapper
     * @return Property
     * @throws InvalidAnnotationException
     */
    public static function createFromAnnotation($annotationType, $annotation, EntityReflection $entityReflection, IMapper $mapper = null)
    {
        $aliases = $entityReflection->getAliases();

        $matches = [];
        $matched = preg_match(
            '~
            ^(null\|)?
            ((?:\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+)
            (\[\])?
            (\|null)?\s+
            (\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)
            (?:\s+=\s*(?:
                "((?:\\\\"|[^"])+)" |  # double quoted string
                \'((?:\\\\\'|[^\'])+)\' |  # single quoted string
                ([^ ]*))  # unquoted value
            )?
            (?:\s*\(([^)]+)\))?
            (?:\s+(.*)\s*)?
        ~xi',
            $annotation,
            $matches
        );

        if (!$matched) {
            throw new InvalidAnnotationException(
                "Invalid property definition given: @$annotationType $annotation in entity {$entityReflection->getName()}."
            );
        }

        $propertyType = new PropertyType($matches[2], $aliases);
        $isWritable = $annotationType === 'property';
        $containsCollection = $matches[3] !== '';
        if ($propertyType->isBasicType() and $containsCollection) {
            throw new InvalidAnnotationException(
                "Invalid property type definition given: @$annotationType $annotation in entity {$entityReflection->getName()}. Lean Mapper doesn't support <type>[] notation for basic types."
            );
        }
        $isNullable = ($matches[1] !== '' or $matches[4] !== '');
        $name = substr($matches[5], 1);

        $hasDefaultValue = false;
        $defaultValue = null;
        if (isset($matches[6]) and $matches[6] !== '') {
            $defaultValue = str_replace('\"', '"', $matches[6]);
        } elseif (isset($matches[7]) and $matches[7] !== '') {
            $defaultValue = str_replace("\\'", "'", $matches[7]);
        } elseif (isset($matches[8]) and $matches[8] !== '') {
            $defaultValue = $matches[8];
        }
        if ($defaultValue !== null) {
            $hasDefaultValue = true;
            try {
                $defaultValue = self::fixDefaultValue($defaultValue, $propertyType, $isNullable);
            } catch (InvalidAnnotationException $e) {
                throw new InvalidAnnotationException(
                    "Invalid property definition given: @$annotationType $annotation in entity {$entityReflection->getName()}, " . lcfirst(
                        $e->getMessage()
                    )
                );
            }
        }
        $column = $mapper !== null ? $mapper->getColumn($entityReflection->getName(), $name) : $name;
        if (isset($matches[9]) and $matches[9] !== '') {
            $column = $matches[9];
        }

        $relationship = null;
        $propertyMethods = null;
        $propertyFilters = null;
        $propertyPasses = null;
        $propertyValuesEnum = null;
        $customFlags = [];
        $customColumn = null;
        $customDefault = null;

        if (isset($matches[10])) {
            $flagMatches = [];
            preg_match_all('~m:([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*(?:\(([^)]*)\))?~', $matches[10], $flagMatches, PREG_SET_ORDER);
            foreach ($flagMatches as $match) {
                $flag = $match[1];
                $flagArgument = (isset($match[2]) and $match[2] !== '') ? $match[2] : null;

                switch ($flag) {
                    case 'hasOne':
                    case 'hasMany':
                    case 'belongsToOne':
                    case 'belongsToMany':
                        if ($relationship !== null) {
                            throw new InvalidAnnotationException(
                                "It doesn't make sense to have multiple relationship definitions in property definition: @$annotationType $annotation in entity {$entityReflection->getName()}."
                            );
                        }
                        $relationship = self::createRelationship(
                            $entityReflection->getName(),
                            $propertyType,
                            $flag,
                            $flagArgument,
                            $mapper
                        );

                        $column = null;
                        if ($relationship instanceof Relationship\HasOne) {
                            $column = $relationship->getColumnReferencingTargetTable();
                        }
                        break;
                    case 'useMethods':
                        if ($propertyMethods !== null) {
                            throw new InvalidAnnotationException(
                                "Multiple m:useMethods flags found in property definition: @$annotationType $annotation in entity {$entityReflection->getName()}."
                            );
                        }
                        $propertyMethods = new PropertyMethods($name, $isWritable, $flagArgument);
                        break;
                    case 'filter':
                        if ($propertyFilters !== null) {
                            throw new InvalidAnnotationException(
                                "Multiple m:filter flags found in property definition: @$annotationType $annotation in entity {$entityReflection->getName()}."
                            );
                        }
                        $propertyFilters = new PropertyFilters($flagArgument);
                        break;
                    case 'passThru':
                        if ($propertyPasses !== null) {
                            throw new InvalidAnnotationException(
                                "Multiple m:passThru flags found in property definition: @$annotationType $annotation in entity {$entityReflection->getName()}."
                            );
                        }
                        $propertyPasses = new PropertyPasses($flagArgument);
                        break;
                    case 'enum':
                        if ($propertyValuesEnum !== null) {
                            throw new InvalidAnnotationException(
                                "Multiple values enumerations found in property definition: @$annotationType $annotation in entity {$entityReflection->getName()}."
                            );
                        }
                        if ($flagArgument === null) {
                            throw new InvalidAnnotationException(
                                "Parameter of m:enum flag was not found in property definition: @$annotationType $annotation in entity {$entityReflection->getName()}."
                            );
                        }
                        $propertyValuesEnum = new PropertyValuesEnum($flagArgument, $entityReflection);
                        break;
                    case 'column':
                        if ($customColumn !== null) {
                            throw new InvalidAnnotationException(
                                "Multiple column name settings found in property definition: @$annotationType $annotation in entity {$entityReflection->getName()}."
                            );
                        }
                        if ($flagArgument === null) {
                            throw new InvalidAnnotationException(
                                "Parameter of m:column flag was not found in property definition: @$annotationType $annotation in entity {$entityReflection->getName()}."
                            );
                        }
                        $customColumn = $flagArgument;
                        break;
                    case 'default':
                        if ($customDefault !== null) {
                            throw new InvalidAnnotationException(
                                "Multiple default value settings found in property definition: @$annotationType $annotation in entity {$entityReflection->getName()}."
                            );
                        }
                        if ($flagArgument === null) {
                            throw new InvalidAnnotationException(
                                "Parameter of m:default flag was not found in property definition: @$annotationType $annotation in entity {$entityReflection->getName()}."
                            );
                        }
                        $matched = preg_match(
                            '~
                            ^\s*(?:
                                "((?:\\\\"|[^"])+)" |      # double quoted string
                                \'((?:\\\\\'|[^\'])+)\' |  # single quoted string
                                ([^ ]*)                    # unquoted value
                            )
                        ~xi',
                            $flagArgument,
                            $matches
                        );
                        if (!$matched) {
                            throw new \Exception;
                        }
                        if (isset($matches[1]) and $matches[1] !== '') {
                            $customDefault = str_replace('\"', '"', $matches[1]);
                        } elseif (isset($matches[2]) and $matches[2] !== '') {
                            $customDefault = str_replace("\\'", "'", $matches[2]);
                        } elseif (isset($matches[3]) and $matches[3] !== '') {
                            $customDefault = $matches[3];
                        }
                        break;
                    default:
                        if (array_key_exists($flag, $customFlags)) {
                            throw new InvalidAnnotationException(
                                "Multiple m:$flag flags found in property definition: @$annotationType $annotation in entity {$entityReflection->getName()}."
                            );
                        }
                        $customFlags[$flag] = $flagArgument;
                }
            }
        }

        $column = $customColumn ?: $column;
        $defaultValue = $customDefault ?: $defaultValue;

        return new Property(
            $name,
            $entityReflection,
            $column,
            $propertyType,
            $isWritable,
            $isNullable,
            $containsCollection,
            $hasDefaultValue,
            $defaultValue,
            $relationship,
            $propertyMethods,
            $propertyFilters,
            $propertyPasses,
            $propertyValuesEnum,
            $customFlags
        );
    }

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

    /**
     * @param string $sourceClass
     * @param PropertyType $propertyType
     * @param string $relationshipType
     * @param string|null $definition
     * @param IMapper|null $mapper
     * @return mixed
     * @throws InvalidAnnotationException
     */
    private static function createRelationship(
        $sourceClass,
        PropertyType $propertyType,
        $relationshipType,
        $definition = null,
        IMapper $mapper = null
    ) {
        if ($relationshipType !== 'hasOne') {
            $strategy = Result::STRATEGY_IN; // default strategy
            if ($definition !== null and substr($definition, -6) === '#union') {
                $strategy = Result::STRATEGY_UNION;
                $definition = substr($definition, 0, -6);
            }
        }
        $pieces = array_replace(array_fill(0, 6, ''), $definition !== null ? explode(':', $definition) : []);

        $sourceTable = ($mapper !== null ? $mapper->getTable($sourceClass) : null);
        $targetTable = ($mapper !== null ? $mapper->getTable($propertyType->getType()) : null);

        switch ($relationshipType) {
            case 'hasOne':
                $relationshipColumn = ($mapper !== null ? $mapper->getRelationshipColumn(
                    $sourceTable,
                    $targetTable
                ) : self::getSurrogateRelationshipColumn($propertyType));
                return new Relationship\HasOne($pieces[0] ?: $relationshipColumn, $pieces[1] ?: $targetTable);
            case 'hasMany':
                return new Relationship\HasMany(
                    $pieces[0] ?: ($mapper !== null ? $mapper->getRelationshipColumn(
                        $mapper->getRelationshipTable($sourceTable, $targetTable),
                        $sourceTable
                    ) : null),
                    $pieces[1] ?: ($mapper !== null ? $mapper->getRelationshipTable($sourceTable, $targetTable) : null),
                    $pieces[2] ?: ($mapper !== null ? $mapper->getRelationshipColumn(
                        $mapper->getRelationshipTable($sourceTable, $targetTable),
                        $targetTable
                    ) : null),
                    $pieces[3] ?: $targetTable,
                    $strategy
                );
            case 'belongsToOne':
                $relationshipColumn = ($mapper !== null ? $mapper->getRelationshipColumn($targetTable, $sourceTable) : $sourceTable);
                return new Relationship\BelongsToOne($pieces[0] ?: $relationshipColumn, $pieces[1] ?: $targetTable, $strategy);
            case 'belongsToMany':
                $relationshipColumn = ($mapper !== null ? $mapper->getRelationshipColumn($targetTable, $sourceTable) : $sourceTable);
                return new Relationship\BelongsToMany($pieces[0] ?: $relationshipColumn, $pieces[1] ?: $targetTable, $strategy);
        }
        return null;
    }



    /**
     * @param PropertyType $propertyType
     * @return string
     */
    private static function getSurrogateRelationshipColumn(PropertyType $propertyType)
    {
        return strtolower(self::trimNamespace($propertyType->getType())) . '{hasOne:' . self::generateRandomString(10) . '}';
    }



    /**
     * @param string $class
     * @return string
     */
    private static function trimNamespace($class)
    {
        $class = explode('\\', $class);
        return end($class);
    }



    /**
     * @param int $length
     * @return string
     */
    private static function generateRandomString($length)
    {
        return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
    }



    /**
     * @param mixed $value
     * @param PropertyType $propertyType
     * @param bool $isNullable
     * @return mixed
     * @throws InvalidAnnotationException
     */
    private static function fixDefaultValue($value, PropertyType $propertyType, $isNullable)
    {
        if ($isNullable and strtolower($value) === 'null') {
            return null;
        } elseif (!$propertyType->isBasicType()) {
            throw new InvalidAnnotationException('Only properties of basic types may have default values specified.');
        }
        switch ($propertyType->getType()) {
            case 'boolean':
                $lower = strtolower($value);
                if ($lower !== 'true' and $lower !== 'false') {
                    throw new InvalidAnnotationException("Property of type boolean cannot have default value '$value'.");
                }
                return $lower === 'true';
            case 'integer':
                if (!is_numeric($value) && !preg_match('~0x[0-9a-f]+~', $value)) {
                    throw new InvalidAnnotationException("Property of type integer cannot have default value '$value'.");
                }
                return intval($value, 0);
            case 'float':
                if (!is_numeric($value)) {
                    throw new InvalidAnnotationException("Property of type float cannot have default value '$value'.");
                }
                return floatval($value);
            case 'array':
                if (strtolower($value) !== 'array()' and $value !== '[]') {
                    throw new InvalidAnnotationException("Property of type array cannot have default value '$value'.");
                }
                return [];
            case 'string':
                if ($value === '\'\'' or $value === '""') {
                    return '';
                }
                return $value;
            default:
                return $value;
        }
    }

}
tharos/leanmapper v3.1.0 API documentation API documentation generated by ApiGen