<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property\hangar;

use hangar\api\HangarPropDef;
use hangar\api\PropSourceDef;
use n2n\util\type\attrs\Attributes;
use hangar\api\DbInfo;
use n2n\persistence\orm\property\EntityProperty;
use n2n\reflection\annotation\AnnotationSet;
use n2n\util\type\ArgUtils;
use n2n\io\orm\ManagedFileEntityProperty;
use n2n\impl\web\dispatch\mag\model\NumericMag;
use n2n\persistence\orm\annotation\AnnoManagedFile;
use n2n\io\managed\FileManager;
use n2n\impl\web\dispatch\mag\model\ClassNameMag;
use n2n\persistence\meta\structure\common\CommonStringColumn;
use hangar\api\CompatibilityLevel;
use n2n\io\managed\File;
use hangar\api\ColumnDefaults;
use phpbob\representation\PhpTypeDef;
use n2n\util\type\CastUtils;
use hangar\api\HuoContext;
use n2n\persistence\meta\structure\Column;
use n2n\web\dispatch\mag\MagCollection;
use n2n\util\StringUtils;

class ManagedFilePropDef implements HangarPropDef {
	const PROP_NAME_LENGTH = 'length';
	const PROP_NAME_FILE_MANAGER = 'fileManager';

	private $columnDefaults;

	public function setup(HuoContext $huoContext, ColumnDefaults $columnDefaults) {
		$this->columnDefaults = $columnDefaults;
	}

	public function getName(): string {
		return 'MangedFile';
	}

	public function createMagCollection(PropSourceDef $propSourceDef = null): MagCollection {
		$magCollection = new MagCollection();

		$size = $this->columnDefaults->getDefaultStringLength();
		$fileManagerLookupId = null;
		if (null !== $propSourceDef) {
			$size = $propSourceDef->getHangarData()->get(self::PROP_NAME_LENGTH, false, $size);

			$fileManagerLookupId = FileManager::TYPE_PUBLIC;
			if ($propSourceDef->hasPhpPropertyAnno(AnnoManagedFile::class)) {
				$phpAnno = $propSourceDef->getPhpPropertyAnno(AnnoManagedFile::class);

				if (null !== ($phpAnnoParam = $phpAnno->getPhpAnnoParam(1))) {
					$fileManagerLookupId = $propSourceDef->determineTypeName(self::determineFileManagerStr($phpAnnoParam));
				}
			}
		}

		$options = [FileManager::TYPE_PRIVATE => FileManager::TYPE_PRIVATE,
				FileManager::TYPE_PUBLIC => FileManager::TYPE_PUBLIC];

		$magCollection->addMag(self::PROP_NAME_LENGTH, new NumericMag('Length', $size, true));
		$magCollection->addMag(self::PROP_NAME_FILE_MANAGER, new ClassNameMag('FileManager (Lookup Id)',
				new \ReflectionClass(FileManager::class), $fileManagerLookupId, false, null, null,
				['class' => 'hangar-autocompletion', 'data-suggestions' => StringUtils::jsonEncode($options),
						'data-custom-allowed' => true]));

		return $magCollection;
	}

	/**
	 * {@inheritDoc}
	 * @see \hangar\api\HangarPropDef::resetPropSourceDef()
	 */
	public function resetPropSourceDef(PropSourceDef $propSourceDef) {
		if ($propSourceDef->hasPhpPropertyAnno(AnnoManagedFile::class)) {
			$phpAnno = $propSourceDef->getPhpPropertyAnno(AnnoManagedFile::class);

			if (null !== ($annoManagedFile = $phpAnno->determineAnnotation())) {
				CastUtils::assertTrue($annoManagedFile instanceof AnnoManagedFile);
				if (null !== ($fileLocator = $annoManagedFile->getFileLocator())) {
					$propSourceDef->removePhpUse(get_class($fileLocator));
				}
			}

			$propSourceDef->removePhpUse(AnnoManagedFile::class);
			$propSourceDef->removePhpPropertyAnno(AnnoManagedFile::class);
		}

		$propSourceDef->removePhpUse($this->determineFileManagerLookupId($propSourceDef));
	}

	private function determineFileManagerLookupId($propSourceDef) {
		$fileManagerLookupId = FileManager::TYPE_PUBLIC;
		if ($propSourceDef->hasPhpPropertyAnno(AnnoManagedFile::class)) {
			$phpAnno = $propSourceDef->getPhpPropertyAnno(AnnoManagedFile::class);
			if (null !== ($phpAnnoParam = $phpAnno->getPhpAnnoParam(1))) {
				$fileManagerLookupId = $propSourceDef->determineTypeName(self::determineFileManagerStr($phpAnnoParam));
			}
		}
		return $fileManagerLookupId;
	}

	public function updatePropSourceDef(Attributes $attributes, PropSourceDef $propSourceDef) {
		$propSourceDef->setPhpTypeDef(PhpTypeDef::fromTypeName(File::class));

		$annoManagedFile = $propSourceDef->getOrCreatePhpPropertyAnno(AnnoManagedFile::class);

		$fileManagerLookupId = $attributes->get(self::PROP_NAME_FILE_MANAGER);
		if ($fileManagerLookupId === FileManager::TYPE_PUBLIC) {
			$fileManagerLookupId = null;
		}

		if (null !== $fileManagerLookupId) {
			$phpTypeDef = PhpTypeDef::fromTypeName($fileManagerLookupId);
			$propSourceDef->createPhpUse($phpTypeDef->getTypeName());

			$annoManagedFile->getOrCreatePhpAnnoParam(1, $phpTypeDef->getLocalName() . '::class');
		} else if ($annoManagedFile->getNumPhpAnnoParams() > 1) {
			$annoManagedFile->getPhpAnnoParam(1)->setValue('null');
		} else {
			$annoManagedFile->resetPhpAnnoParams();
		}

		$propSourceDef->getHangarData()->setAll(array(
				self::PROP_NAME_LENGTH => $attributes->get(self::PROP_NAME_LENGTH)));
	}

	/**
	 * {@inheritDoc}
	 * @see \hangar\api\HangarPropDef::applyDbMeta()
	 */
	public function applyDbMeta(DbInfo $dbInfo, PropSourceDef $propSourceDef, EntityProperty $entityProperty,
			AnnotationSet $annotationSet) {

		ArgUtils::assertTrue($entityProperty instanceof ManagedFileEntityProperty);
		$columnName = $entityProperty->getColumnName();
		$dbInfo->removeColumn($columnName);

		$dbInfo->getTable()->createColumnFactory()
				->createStringColumn($columnName,
						$propSourceDef->getHangarData()->get(self::PROP_NAME_LENGTH,
								false, $this->columnDefaults->getDefaultStringLength()));
	}

	/**
	 * @param PropSourceDef $propSourceDef
	 * @return Column
	 */
	public function createMetaColumn(EntityProperty $entityProperty, PropSourceDef $propSourceDef): ?Column {
		ArgUtils::assertTrue($entityProperty instanceof ManagedFileEntityProperty);
		return new CommonStringColumn($entityProperty->getColumnName(),
				$propSourceDef->getHangarData()->get(self::PROP_NAME_LENGTH,
						false, $this->columnDefaults->getDefaultStringLength()));
	}

	/**
	 * {@inheritDoc}
	 * @see \hangar\api\HangarPropDef::testCompatibility()
	 */
	public function testCompatibility(PropSourceDef $propSourceDef): int {
		if ($propSourceDef->hasPhpPropertyAnno(AnnoManagedFile::class)) return CompatibilityLevel::COMMON;
		if (null !== ($phpTypeDef = $propSourceDef->getPhpTypeDef()) &&
				$phpTypeDef->getTypeName() === File::class) return CompatibilityLevel::COMMON;

		return CompatibilityLevel::NOT_COMPATIBLE;
	}

    public static function determineFileManagerStr(string $param) {
    	if ($param === 'null') return FileManager::TYPE_PUBLIC;

    	if (StringUtils::endsWith('::class', $param)) {
    		return mb_substr($param, 0, -7);
    	}

    	if (StringUtils::startsWith('\'', $param) && StringUtils::endsWith('\'', $param)) {
    		return mb_substr($param, 1, -1);
    	}

    	throw new \InvalidArgumentException('Invalid file manager param: ' . $param);
    }
}


<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property\relation;

use n2n\persistence\orm\criteria\compare\ComparisonStrategy;
use n2n\persistence\orm\query\QueryState;
use n2n\persistence\orm\query\from\MetaTreePoint;
use n2n\persistence\orm\FetchType;
use n2n\impl\persistence\orm\property\relation\selection\ToOneRelationSelection;
use n2n\impl\persistence\orm\property\relation\util\ToOneValueHasher;
use n2n\impl\persistence\orm\property\relation\compare\IdColumnComparableDecorator;
use n2n\persistence\orm\store\action\supply\SupplyJob;
use n2n\impl\persistence\orm\property\relation\util\ToOneUtils;
use n2n\persistence\orm\property\EntityProperty;
use n2n\persistence\orm\model\EntityModel;
use n2n\persistence\orm\EntityManager;
use n2n\persistence\orm\query\from\TreePath;
use n2n\persistence\orm\store\ValueHash;
use n2n\util\ex\IllegalStateException;

class PropertyMappedOneToOneRelation extends MappedRelation implements ToOneRelation  {
	private $toOneUtils;

	public function __construct(EntityProperty $entityProperty, EntityModel $targetEntityModel,
			EntityProperty $targetEntityProperty) {
		parent::__construct($entityProperty, $targetEntityModel, $targetEntityProperty);
		$this->toOneUtils = new ToOneUtils($this, false);
	}
	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\ToOneRelation::createRepresentingQueryItem()
	 */
	public function createRepresentingQueryItem(MetaTreePoint $metaTreePoint, QueryState $queryState) {
		return $metaTreePoint->requestPropertyRepresentableQueryItem($this->createTargetIdTreePath());
	}
	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\ToOneRelation::createColumnComparable()
	 */
	public function createColumnComparable(MetaTreePoint $metaTreePoint, QueryState $queryState) {
		$comparisonStrategy = $metaTreePoint->requestPropertyComparisonStrategy($this->createTargetIdTreePath());

		IllegalStateException::assertTrue($comparisonStrategy->getType() == ComparisonStrategy::TYPE_COLUMN);

		return new IdColumnComparableDecorator($comparisonStrategy->getColumnComparable(), $this->targetEntityModel);
	}
	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\Relation::createSelection()
	 */
	public function createSelection(MetaTreePoint $metaTreePoint, QueryState $queryState) {
		$targetTreePath = $this->createTargetIdTreePath();

		$idSelection = $metaTreePoint->requestCustomPropertyJoinTreePoint($this->entityProperty, false)
			->requestPropertySelection(new TreePath(array($this->targetEntityModel->getIdDef()
				->getPropertyName())));

		$entitySelection = new ToOneRelationSelection($this->targetEntityModel, $idSelection, $queryState);
		$entitySelection->setLazy($this->fetchType == FetchType::LAZY);
		return $entitySelection;
	}
	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\Relation::createValueHash()
	 */
	public function createValueHash($value, EntityManager $em): ValueHash {
		return ToOneValueHasher::createFromEntityModel($this->targetEntityModel)
			->createValueHash($value);
	}
	/**
	 * @param mixed $value
	 * @param ValueHash $oldValueHash
	 * @param SupplyJob $supplyJob
	 */
	public function prepareSupplyJob(SupplyJob $supplyJob, $value, ?ValueHash $oldValueHash) {
		$this->toOneUtils->prepareSupplyJob($supplyJob, $value, $oldValueHash);
	}
}


<?php
declare(strict_types = 1);

namespace Innmind\Http\Headers;

use Innmind\Http\{
    Headers as HeadersInterface,
    Header,
    Exception\HeaderNotFound
};
use Innmind\Immutable\{
    MapInterface,
    Pair,
    Str,
    Map,
    Sequence
};

final class Headers implements HeadersInterface
{
    private $headers;

    public function __construct(MapInterface $headers = null)
    {
        $headers = $headers ?? new Map('string', Header::class);

        if (
            (string) $headers->keyType() !== 'string' ||
            (string) $headers->valueType() !== Header::class
        ) {
            throw new \TypeError(sprintf(
                'Argument 1 must be of type MapInterface<string, %s>',
                Header::class
            ));
        }

        $this->headers = $headers->map(function(string $name, Header $header) {
            return new Pair(
                (string) (new Str($name))->toLower(),
                $header
            );
        });
    }

    public static function of(Header ...$headers): self
    {
        return new self(
            Sequence::of(...$headers)->reduce(
                new Map('string', Header::class),
                static function(MapInterface $headers, Header $header): MapInterface {
                    return $headers->put(
                        $header->name(),
                        $header
                    );
                }
            )
        );
    }

    /**
     * {@inheritdoc}
     */
    public function get(string $name): Header
    {
        if (!$this->has($name)) {
            throw new HeaderNotFound;
        }

        return $this->headers->get((string) (new Str($name))->toLower());
    }

    /**
     * {@inheritdoc}
     */
    public function has(string $name): bool
    {
        return $this->headers->contains((string) (new Str($name))->toLower());
    }

    /**
     * {@inheritdoc}
     */
    public function current()
    {
        return $this->headers->current();
    }

    /**
     * {@inheritdoc}
     */
    public function key()
    {
        return $this->headers->key();
    }

    /**
     * {@inheritdoc}
     */
    public function next()
    {
        $this->headers->next();
    }

    /**
     * {@inheritdoc}
     */
    public function rewind()
    {
        $this->headers->rewind();
    }

    /**
     * {@inheritdoc}
     */
    public function valid()
    {
        return $this->headers->valid();
    }

    /**
     * {@inheritdoc}
     */
    public function count()
    {
        return $this->headers->size();
    }
}


<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property;

use n2n\persistence\orm\property\EntityPropertyProvider;
use n2n\reflection\property\AccessProxy;
use n2n\persistence\orm\property\ClassSetup;
use n2n\persistence\orm\model\EntityModelManager;
use n2n\persistence\orm\annotation\AnnoOneToOne;
use n2n\persistence\orm\annotation\AnnoManyToOne;
use n2n\persistence\orm\annotation\AnnoOneToMany;
use n2n\impl\persistence\orm\property\relation\RelationFactory;
use n2n\persistence\orm\annotation\AnnoManyToMany;
use n2n\reflection\property\PropertiesAnalyzer;
use n2n\reflection\ReflectionUtils;
use n2n\persistence\orm\model\NamingStrategy;
use n2n\util\type\ArgUtils;
use n2n\persistence\orm\annotation\AnnoEmbedded;
use n2n\io\orm\FileEntityProperty;
use n2n\io\orm\ManagedFileEntityProperty;
use n2n\io\managed\impl\SimpleFileLocator;
use n2n\io\IoUtils;
use n2n\util\uri\Url;
use n2n\persistence\orm\annotation\AnnoBool;
use n2n\util\type\TypeName;

class CommonEntityPropertyProvider implements EntityPropertyProvider {
	const PROP_FILE_NAME_SUFFIX = '.originalName';
	/* (non-PHPdoc)
	 * @see \n2n\persistence\orm\property\EntityPropertyProvider::setupPropertyIfSuitable()
	 */
	public function setupPropertyIfSuitable(AccessProxy $propertyAccessProxy,
			ClassSetup $classSetup) {

		$annotationSet = $classSetup->getAnnotationSet();
		$propertyName = $propertyAccessProxy->getPropertyName();

		if (null !== ($annoDateTime = $annotationSet->getPropertyAnnotation($propertyName,
				'n2n\persistence\orm\annotation\AnnoDateTime'))) {
			$classSetup->provideEntityProperty(new DateTimeEntityProperty($propertyAccessProxy,
					$classSetup->requestColumn($propertyName), array($annoDateTime)));
			return;
		}

		if (null !== ($annoN2nLocale = $annotationSet->getPropertyAnnotation($propertyName,
				'n2n\persistence\orm\annotation\AnnoN2nLocale'))) {
			$classSetup->provideEntityProperty(new N2nLocaleEntityProperty($propertyAccessProxy,
					$classSetup->requestColumn($propertyName)), array($annoN2nLocale));
			return;
		}

		if (null !== ($annoUrl = $annotationSet->getPropertyAnnotation($propertyName,
				'n2n\persistence\orm\annotation\AnnoUrl'))) {
			$classSetup->provideEntityProperty(new UrlEntityProperty($propertyAccessProxy,
					$classSetup->requestColumn($propertyName)), array($annoUrl));
			return;
		}

		if (null !== ($annoLob = $annotationSet->getPropertyAnnotation($propertyName,
				'n2n\persistence\orm\annotation\AnnoLob'))) {
				$classSetup->provideEntityProperty(new LobEntityProperty($propertyAccessProxy,
								$classSetup->requestColumn($propertyName)),
						array($annoLob));
				return;
		}

		if (null !== ($annoFile = $annotationSet->getPropertyAnnotation($propertyName,
				'n2n\persistence\orm\annotation\AnnoFile'))) {
			$classSetup->provideEntityProperty(new FileEntityProperty($propertyAccessProxy,
							$classSetup->requestColumn($propertyName),
							$classSetup->requestColumn($propertyName . self::PROP_FILE_NAME_SUFFIX),
									$annoFile->getOriginalNameColumnName()),
					array($annoN2nLocale));
			return;
		}

		if (null !== ($annoManagedFile = $annotationSet->getPropertyAnnotation($propertyName,
				'n2n\persistence\orm\annotation\AnnoManagedFile'))) {
			$manageFileEntityProperty = new ManagedFileEntityProperty($propertyAccessProxy,
					$classSetup->requestColumn($propertyName), $annoManagedFile->getLookupId(),
					$annoManagedFile->isCascadeDelete());

			if (null !== ($fileLocator = $annoManagedFile->getFileLocator())) {
				$manageFileEntityProperty->setFileLocator($fileLocator);
			} else {
				$manageFileEntityProperty->setFileLocator(new SimpleFileLocator(
						mb_strtolower(IoUtils::stripSpecialChars($classSetup->getClass()->getShortName()))));
			}

			$classSetup->provideEntityProperty($manageFileEntityProperty, array($annoN2nLocale));
			return;
		}

		if (null !== ($annoBool = $annotationSet->getPropertyAnnotation($propertyName, AnnoBool::class))) {
			$classSetup->provideEntityProperty(new BoolEntityProperty($propertyAccessProxy,
					$classSetup->requestColumn($propertyName)), array($annoBool));
			return;
		}

		switch ($propertyAccessProxy->getConstraint()->getTypeName()) {
			case TypeName::BOOL:
				$classSetup->provideEntityProperty(new BoolEntityProperty($propertyAccessProxy,
						$classSetup->requestColumn($propertyName)));
				return;
			case TypeName::INT:
				$classSetup->provideEntityProperty(new IntEntityProperty($propertyAccessProxy,
						$classSetup->requestColumn($propertyName)));
				return;
			case TypeName::FLOAT:
				$classSetup->provideEntityProperty(new IntEntityProperty($propertyAccessProxy,
						$classSetup->requestColumn($propertyName)));
				return;
			case TypeName::STRING:
				$classSetup->provideEntityProperty(new IntEntityProperty($propertyAccessProxy,
						$classSetup->requestColumn($propertyName)));
				return;
		}

		if ($this->checkForRelations($propertyAccessProxy, $classSetup)) {
			return;
		}

		if ($this->checkForEmbedded($propertyAccessProxy, $classSetup)) {
			return;
		}

		$setterMethodName = PropertiesAnalyzer::buildSetterName($propertyName);
		$class = $classSetup->getClass();

		if (!$class->hasMethod($setterMethodName)) return;

		$setterMethod = $class->getMethod($setterMethodName);

		$parameters = $setterMethod->getParameters();
		if (count($parameters) == 0) return;
		$parameter = current($parameters);

		if (null !== ($paramClass = ReflectionUtils::extractParameterClass($parameter))) {
			switch ($paramClass->getName()) {
				case 'DateTime':
					$classSetup->provideEntityProperty(new DateTimeEntityProperty($propertyAccessProxy,
							$classSetup->requestColumn($propertyName)));
					break;
				case 'n2n\l10n\N2nLocale':
					$classSetup->provideEntityProperty(new N2nLocaleEntityProperty($propertyAccessProxy,
							$classSetup->requestColumn($propertyName)));
					break;
				case 'n2n\io\managed\File':
					$classSetup->provideEntityProperty(new FileEntityProperty($propertyAccessProxy,
							$classSetup->requestColumn($propertyName), null));
					break;
				case Url::class:
					$classSetup->provideEntityProperty(new UrlEntityProperty($propertyAccessProxy,
							$classSetup->requestColumn($propertyName)));
					break;
			}
		}

		if (null !== ($type = $parameter->getType())) {
			switch ($type->__toString()) {
				case TypeName::BOOL:
					$classSetup->provideEntityProperty(new BoolEntityProperty($propertyAccessProxy,
							$classSetup->requestColumn($propertyName)));
					break;
				case TypeName::INT:
					$classSetup->provideEntityProperty(new IntEntityProperty($propertyAccessProxy,
							$classSetup->requestColumn($propertyName)));
					break;
			}
		}
	}

	private function checkForEmbedded(AccessProxy $propertyAccessProxy,
			ClassSetup $classSetup) {
		$propertyName = $propertyAccessProxy->getPropertyName();
		$annotationSet = $classSetup->getAnnotationSet();
		$annoEmbedded = $annotationSet->getPropertyAnnotation($propertyName,
				'n2n\persistence\orm\annotation\AnnoEmbedded');
		if ($annoEmbedded === null) return false;

		ArgUtils::assertTrue($annoEmbedded instanceof AnnoEmbedded);

		$embeddedEntityProperty = new EmbeddedEntityProperty($propertyAccessProxy,
				$annoEmbedded->getTargetClass());

		$classSetup->provideEntityProperty($embeddedEntityProperty);

		$setupProcess = $classSetup->getSetupProcess();
		$targetClassSetup = new ClassSetup($setupProcess, $annoEmbedded->getTargetClass(),
				new EmbeddedNampingStrategy($classSetup->getNamingStrategy(), $annoEmbedded->getColumnPrefix(),
						$annoEmbedded->getColumnSuffix()),
				$classSetup, $propertyName);
		$setupProcess->getEntityPropertyAnalyzer()->analyzeClass($targetClassSetup);

		foreach ($targetClassSetup->getEntityProperties() as $property) {
			$embeddedEntityProperty->addEntityProperty($property);
		}

		return true;
	}

	private function checkForRelations(AccessProxy $propertyAccessProxy,
			ClassSetup $classSetup) {
		$propertyName = $propertyAccessProxy->getPropertyName();
		$annotationSet = $classSetup->getAnnotationSet();

		if (null !== ($annoOneToOne = $annotationSet->getPropertyAnnotation($propertyName,
				'n2n\persistence\orm\annotation\AnnoOneToOne'))) {
			$this->provideOneToOne($propertyAccessProxy, $annoOneToOne, $classSetup);
			return true;
		}

		if (null !== ($annoManyToOne = $annotationSet->getPropertyAnnotation($propertyName,
				'n2n\persistence\orm\annotation\AnnoManyToOne'))) {
			$this->provideManyToOne($propertyAccessProxy, $annoManyToOne, $classSetup);
			return true;
		}

		if (null !== ($annoOneToMany = $annotationSet->getPropertyAnnotation($propertyName,
				'n2n\persistence\orm\annotation\AnnoOneToMany'))) {
			$this->provideOneToMany($propertyAccessProxy, $annoOneToMany, $classSetup);
			return true;
		}

		if (null !== ($annoManyToMany = $annotationSet->getPropertyAnnotation($propertyName,
				'n2n\persistence\orm\annotation\AnnoManyToMany'))) {
			$this->provideManyToMany($propertyAccessProxy, $annoManyToMany, $classSetup);
			return true;
		}
	}

	private function provideOneToOne(AccessProxy $propertyAccessProxy,
			AnnoOneToOne $annoOneToOne, ClassSetup $classSetup) {
		$toOneProperty = new ToOneEntityProperty($propertyAccessProxy,
				$annoOneToOne->getMappedBy() === null, RelationEntityProperty::TYPE_ONE_TO_ONE);
		$classSetup->provideEntityProperty($toOneProperty);

		$relationFactory = new RelationFactory($classSetup, $toOneProperty, $annoOneToOne);

		$classSetup->onFinalize(function (EntityModelManager $entityModelManager)
				use ($toOneProperty, $annoOneToOne, $relationFactory) {
			if (null !== ($mappedBy = $annoOneToOne->getMappedBy())) {
				$toOneProperty->setRelation($relationFactory->createMappedOneToOneRelation(
						$mappedBy, $entityModelManager));
			} else {
				$toOneProperty->setRelation($relationFactory
						->createMasterToOneRelation($entityModelManager));
			}
		}, $toOneProperty->isMaster());
	}

	private function provideManyToOne(AccessProxy $propertyAccessProxy,
			AnnoManyToOne $annoManyToOne, ClassSetup $classSetup) {
		$toOneProperty = new ToOneEntityProperty($propertyAccessProxy, true,
				RelationEntityProperty::TYPE_MANY_TO_ONE);
		$classSetup->provideEntityProperty($toOneProperty);

		$relationFactory = new RelationFactory($classSetup, $toOneProperty, $annoManyToOne);

		$classSetup->onFinalize(function (EntityModelManager $entityModelManager)
				use ($toOneProperty, $relationFactory, $classSetup) {
			$toOneProperty->setRelation($relationFactory->createMasterToOneRelation($entityModelManager));
		}, true);
	}

	private function provideOneToMany(AccessProxy $propertyAccessProxy,
			AnnoOneToMany $annoOneToMany, ClassSetup $classSetup) {
		$toManyProperty = new ToManyEntityProperty($propertyAccessProxy,
				$annoOneToMany->getMappedBy() === null, RelationEntityProperty::TYPE_ONE_TO_MANY);
		$classSetup->provideEntityProperty($toManyProperty);

		$relationFactory = new RelationFactory($classSetup, $toManyProperty, $annoOneToMany);

		if (!$toManyProperty->isMaster()) {
			$classSetup->onFinalize(function (EntityModelManager $entityModelManager)
					use ($toManyProperty, $annoOneToMany, $relationFactory) {
						$entityModelManager->getEntityModelByClass($annoOneToMany->getTargetEntityClass());
			}, true);
		}

		$classSetup->onFinalize(function (EntityModelManager $entityModelManager)
				use ($toManyProperty, $annoOneToMany, $relationFactory) {
			if (null !== ($mappedBy = $annoOneToMany->getMappedBy())) {
				$toManyProperty->setRelation($relationFactory->createMappedOneToManyRelation(
						$mappedBy, $entityModelManager));
			} else {
				$toManyProperty->setRelation($relationFactory
						->createMasterToManyRelation($entityModelManager));
			}
		}, $toManyProperty->isMaster());
	}

	private function provideManyToMany(AccessProxy $propertyAccessProxy,
			AnnoManyToMany $annoManyToMany, ClassSetup $classSetup) {
		$manyToManyProperty = new ToManyEntityProperty($propertyAccessProxy,
				 $annoManyToMany->getMappedBy() === null, RelationEntityProperty::TYPE_MANY_TO_MANY);
		$classSetup->provideEntityProperty($manyToManyProperty);

		$relationFactory = new RelationFactory($classSetup, $manyToManyProperty, $annoManyToMany);

		$classSetup->onFinalize(function (EntityModelManager $entityModelManager)
				use ($manyToManyProperty, $annoManyToMany, $relationFactory) {
			if (null !== ($mappedBy = $annoManyToMany->getMappedBy())) {
				$manyToManyProperty->setRelation($relationFactory->createMappedManyToManyRelation(
						$mappedBy, $entityModelManager));
			} else {
				$manyToManyProperty->setRelation($relationFactory->createMasterToManyRelation(
						$entityModelManager));
			}
		}, $manyToManyProperty->isMaster());
	}
}

class EmbeddedNampingStrategy implements NamingStrategy {
	private $decoratedNamingStrategie;
	private $prefix;
	private $suffix;

	public function __construct(NamingStrategy $decoratedNamingStrategy, $prefix = null, $suffix = null) {
		$this->decoratedNamingStrategie = $decoratedNamingStrategy;
		$this->prefix = $prefix;
		$this->suffix = $suffix;
	}

	public function buildTableName(\ReflectionClass $class, string $tableName = null): string {
		return $this->prefix . $this->decoratedNamingStrategie->buildTableName($class, $tableName)
				. $this->suffix;
	}

	public function buildJunctionTableName(string $ownerTableName, string $propertyName, string $tableName = null): string {
		return $this->prefix . $this->decoratedNamingStrategie->buildJunctionTableName($ownerTableName,
				$propertyName, $tableName) . $this->suffix;
	}

	public function buildColumnName(string $propertyName, string $columnName = null): string {
		return $this->prefix . $this->decoratedNamingStrategie->buildColumnName($propertyName,
				$columnName) . $this->suffix;
	}

	public function buildJunctionJoinColumnName(\ReflectionClass $targetClass, string $targetIdPropertyName,
			string $joinColumnName = null): string {
		return $this->prefix . $this->decoratedNamingStrategie->buildJunctionJoinColumnName($targetClass,
				$targetIdPropertyName, $joinColumnName) . $this->suffix;
	}

	public function buildJoinColumnName(string $propertyName, string $targetIdPropertyName, string $joinColumnName = null): string {
		return $this->prefix . $this->decoratedNamingStrategie->buildJoinColumnName($propertyName,
				$targetIdPropertyName, $joinColumnName) . $this->suffix;
	}
}


<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property\relation;

use n2n\persistence\orm\query\from\MetaTreePoint;
use n2n\persistence\orm\query\QueryState;
use n2n\util\ex\IllegalStateException;
use n2n\persistence\orm\criteria\compare\ComparisonStrategy;
use n2n\persistence\orm\FetchType;
use n2n\impl\persistence\orm\property\relation\selection\ToOneRelationSelection;
use n2n\persistence\orm\store\action\PersistAction;
use n2n\impl\persistence\orm\property\relation\util\ToOneValueHasher;
use n2n\impl\persistence\orm\property\relation\compare\IdColumnComparableDecorator;
use n2n\persistence\orm\store\action\supply\SupplyJob;
use n2n\persistence\orm\property\EntityProperty;
use n2n\persistence\orm\model\EntityModel;
use n2n\impl\persistence\orm\property\relation\util\ToOneUtils;
use n2n\persistence\orm\store\ValueHash;
use n2n\util\type\ArgUtils;
use n2n\impl\persistence\orm\property\relation\util\ToOneValueHash;
use n2n\persistence\orm\EntityManager;

class JoinTableToOneRelation extends JoinTableRelation implements ToOneRelation {
	private $toOneUtils;

	public function __construct(EntityProperty $entityProperty, EntityModel $targetEntityModel) {
		parent::__construct($entityProperty, $targetEntityModel);
		$this->toOneUtils = new ToOneUtils($this, true);
	}

	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\ToOneRelation::createRepresentingQueryItem()
	 */
	public function createRepresentingQueryItem(MetaTreePoint $metaTreePoint, QueryState $queryState) {
		return $metaTreePoint->requestPropertyRepresentableQueryItem($this->createTargetIdTreePath());
	}

	public function createColumnComparable(MetaTreePoint $metaTreePoint, QueryState $queryState) {
		$comparisonStargegy = $metaTreePoint->requestPropertyComparisonStrategy($this->createTargetIdTreePath())
				->getColumnComparable();

		IllegalStateException::assertTrue($comparisonStargegy->getType() == ComparisonStrategy::TYPE_COLUMN);

		$meta = $metaTreePoint->getMeta();
		return new IdColumnComparableDecorator($comparisonStargegy->getColumnComparable(),
				$this->targetEntityModel);
	}
	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\Relation::createSelection()
	 */
	public function createSelection(MetaTreePoint $metaTreePoint, QueryState $queryState) {
		$idSelection = $metaTreePoint->requestPropertySelection($this->createTargetIdTreePath());

		$toOneRelationSelection = new ToOneRelationSelection($this->entityModel, $idSelection, $queryState);
		$toOneRelationSelection->setLazy($this->fetchType == FetchType::LAZY);
		return $toOneRelationSelection;
	}

	public function prepareSupplyJob(SupplyJob $supplyJob, $value, ?ValueHash $oldValueHash) {
		$this->toOneUtils->prepareSupplyJob($supplyJob, $value, $oldValueHash);
	}

	public function supplyPersistAction(PersistAction $persistAction, $value, ValueHash $valueHash, ?ValueHash $oldValueHash) {
		ArgUtils::assertTrue($oldValueHash === null || $oldValueHash instanceof ToOneValueHash);

		if ($value === null) {
			if ($oldValueHash === null || $oldValueHash->getEntityIdRep() === null) return;

			$this->createJoinTableActionFromPersistAction($persistAction);
			return;
		}

		$targetIdProperty = $this->targetEntityModel->getIdDef()->getEntityProperty();
		$actionQueue = $persistAction->getActionQueue();
		$targetPersistAction = $actionQueue->getPersistAction($value);

		if ($targetPersistAction->hasId()) {
			$targetIdRep = $targetIdProperty->valueToRep($targetPersistAction->getId());
			if ($oldValueHash !== null && $targetIdRep === $oldValueHash->getEntityIdRep()) return;

			$this->createJoinTableActionFromPersistAction($persistAction)->addInverseJoinIdRep($targetIdRep);
			return;
		}

		$joinTableAction = $this->createJoinTableActionFromPersistAction($persistAction);
		$joinTableAction->addDependent($targetPersistAction);
		$targetPersistAction->executeAtEnd(function () use ($joinTableAction, $targetPersistAction, $targetIdProperty) {
			$joinTableAction->addInverseJoinIdRep($targetIdProperty->valueToRep($targetPersistAction->getId()));

			$hasher = new ToOneValueHasher($this->getTargetIdEntityProperty());
			$hasher->reportId($targetId, $valueHash);
		});
	}

	public function createValueHash($value, EntityManager $em): ValueHash {
		return ToOneValueHasher::createFromEntityModel($this->targetEntityModel)
				->createValueHash($value);
	}
}


<?php
/**
 * YAWIK
 * Auth Module Bootstrap
 *
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
 * @license   MIT
 */

namespace Pdf;

use Zend\ServiceManager\ServiceManager;
use SplFileInfo;
use Zend\View\Resolver\ResolverInterface;
use Zend\View\Renderer\RendererInterface as Renderer;
use Zend\Mvc\MvcEvent;
use Zend\View\ViewEvent;
use Zend\EventManager\EventManagerInterface;
use Core\Html2Pdf\PdfInterface;
use Core\View\Helper\InsertFile\FileEvent;
use Core\Entity\FileEntity;
use Core\ModuleManager\ModuleConfigLoader;

/**
 * Make HTML to PDF
 *
 */
class Module implements PdfInterface, ResolverInterface
{
    const RENDER_FULL = 0;
    const RENDER_WITHOUT_PDF = 1;
    const RENDER_WITHOUT_ATTACHMENTS = 2;

    protected $serviceManager;

    protected $viewResolverAttached = false;

    protected $appendPDF = array();
    protected $appendImage = array();

    /**
    * Loads module specific configuration.
    *
    * @return array
    */
    public function getConfig()
    {
        return ModuleConfigLoader::load(__DIR__ . '/../config');
    }

    public static function factory(ServiceManager $serviceManager)
    {
        $module = new static();
        $module->serviceManager = $serviceManager;
        return $module;
    }

    public function onBootstrap(MvcEvent $e)
    {
        $eventManager = $e->getApplication()->getEventManager();
        $eventManager->getSharedManager()->attach(
            'Applications',
            'application.detail.actionbuttons',
            function ($event) {
                return 'pdf/application/details/button';
            }
        );
    }

    /**
     * hook into the rendering for transformation of HTML to PDF
     * @param \Zend\EventManager\EventManagerInterface $events
     */
    public function attach(EventManagerInterface $events)
    {
        $events->attach(ViewEvent::EVENT_RENDERER_POST, array($this, 'cleanLayout'), 1);
        $events->attach(ViewEvent::EVENT_RESPONSE, array($this, 'attachPDFtransformer'), 10);
    }

    /**
     * hook into the MVC
     * in here you could still decide, if you want to hook into the Rendering
     * @param \Zend\EventManager\EventManagerInterface $events
     */
    public function attachMvc(EventManagerInterface $events)
    {
        $events->attach(MvcEvent::EVENT_RENDER, array($this, 'initializeViewHelper'), 100);
    }

    /**
     * hook into the Rendering of files
     * the manager to hook in is the viewhelper 'insertfiles'
     *
     * @param \Zend\Mvc\MvcEvent $e
     */
    public function initializeViewHelper(MvcEvent $e)
    {
        $viewhelperManager = $this->serviceManager->get('ViewHelperManager');
        if ($viewhelperManager->has('InsertFile')) {
            $insertFile = $viewhelperManager->get('InsertFile');
            $insertFile->attach(FileEvent::GETFILE, array($this, 'getFile'));
            $insertFile->attach(FileEvent::RENDERFILE, array($this, 'renderFile'));
            $insertFile->attach(FileEvent::INSERTFILE, array($this, 'collectFiles'));
        }
    }

    /**
     * proxy, in case that you just got a name and have to find the associated file-entity
     * maybe this is redundant and can be deprecated
     *
     * @param \Core\View\Helper\InsertFile\FileEvent $e
     * @return null
     */
    public function getFile(FileEvent $e)
    {
        $lastFileName = $e->getLastFileName();
        if (is_string($lastFileName)) {
            $repository = $this->serviceManager->get('repositories')->get('Applications/Attachment');
            $file       = $repository->find($lastFileName);
            if (isset($file)) {
                $e->setFileObject($lastFileName, $file);
                $e->stopPropagation();
                return $file;
            }
            return null;
        }
        // if it is not a string i do presume it is already a file-Object
        return $lastFileName;
    }

    /**
     * here the inserted File is rendered,
     * there is a lot which still can be done like outsorcing the HTML to a template,
     * or distinguish between different File Types,
     * at the moment we assume the $file is always an (sub-)instance of \Core\File\Entity
     *
     * @param \Core\View\Helper\InsertFile\FileEvent $e
     * @return string
     */
    public function renderFile(FileEvent $e)
    {
        $file = $e->getLastFileObject();
        // assume it is of the class Core\Entity\FileEntity
        $return = '
getId() . '">' . $file->getName() . '
' . PHP_EOL
                . '
' . $file->getType() . '
'
                . '
' . $file->prettySize . '
';
        /*
         * this snippet was for direct inserting an image into the PDF
        if ($file && $file instanceOf FileEntity && 0 === strpos($file->getType(), 'image')) {
            //$content = $file->getContent();
            //$url = 'data:image/' . $file->getType() . ';base64,' . base64_encode ($content);
            //$html = '';
            $html = '' . $file->getName() . '';
            $e->stopPropagation();
            return $html;
        }
         */
        return $return;
    }

    /**
     * give a summary of all inserted Files,
     * this is for having access to those files in the post-process
     * @param \Core\View\Helper\InsertFile\FileEvent|\Zend\View\ViewEvent $e
     * @return NULL
     */
    public function collectFiles(FileEvent $e)
    {
        $this->appendPDF = array();
        $files = $e->getAllFiles();
        foreach ($files as $name => $file) {
            if (!empty($file) && $file instanceof FileEntity) {
                if (0 === strpos($file->getType(), 'image')) {
                    $this->appendImage[] = $file;
                }
                if (strtolower($file->getType()) == 'application/pdf') {
                    $this->appendPDF[] = $file;
                }
            }
        }
        return null;
    }

    /**
     * remove unwanted or layout related data
     *
     * basically you rake through the viewmodel for the data you want to use for your template,
     * this may not be optimal because you have to rely on the correct naming of the viewmodels
     *
     * if you get the data you want, you switch to the specific template by adding the conforming resolver
     *
     * @param \Zend\View\ViewEvent $e
     */
    public function cleanLayout(ViewEvent $e)
    {
        $result   = $e->getResult();
        $response = $e->getResponse();
        $model = $e->getModel();
        if ($model->hasChildren()) {
            $children = $model->getChildren();
            $content = null;
            foreach ($children as $child) {
                if ($child->captureTo() == 'content') {
                    $content = $child;
                    $this->attachViewResolver();
                }
            }
            if (!empty($content)) {
                $e->setModel($content);
            }
        } else {
            // attach the own resolver here too ?
            // ...
        }
    }

    /**
     * Attach an own ViewResolver
     */
    public function attachViewResolver()
    {
        if (!$this->viewResolverAttached) {
            $this->viewResolverAttached = true;
            $resolver = $this->serviceManager->get('ViewResolver');
            $resolver->attach($this, 100);
        }
    }

    /**
     * Transform the HTML to PDF,
     * this is a post-rendering-process
     *
     * put in here everything related to the transforming-process like options
     *
     * @param \Zend\View\ViewEvent $e
     */
    public function attachPDFtransformer(ViewEvent $e)
    {

        //$renderer = $e->getRenderer();
        $result   = $e->getResult();
        $response = $e->getResponse();

        // the handles are for temporary files
        error_reporting(0);
        foreach (array(self::RENDER_FULL, self::RENDER_WITHOUT_PDF, self::RENDER_WITHOUT_ATTACHMENTS ) as $render) {
            $handles = array();
            try {
                $pdf = new extern\mPDFderive();
                $pdf->SetImportUse();
                // create bookmark list in Acrobat Reader
                $pdf->h2bookmarks = array('H1' => 0, 'H2' => 1, 'H3' => 2);
                $pdf->WriteHTML($result);

                // Output of the Images
                if (self::RENDER_FULL == $render || self::RENDER_WITHOUT_PDF == $render) {
                    if (is_array($this->appendImage) && !empty($this->appendImage)) {
                        foreach ($this->appendImage as $imageAttachment) {
                            $content = $imageAttachment->getContent();
                            $url = 'data:image/' . $imageAttachment->getType() . ';base64,' . base64_encode($content);
                            $html = 'getId() . '">
';
                            $pdf->WriteHTML($html);
                        }
                    }
                }

                // Temp Files PDF
                if (self::RENDER_FULL == $render) {
                    if (is_array($this->appendPDF) && !empty($this->appendPDF)) {
                        foreach ($this->appendPDF as $pdfAttachment) {
                            $content = $pdfAttachment->getContent();
                            $tmpHandle = tmpfile();
                            $handles[] = $tmpHandle;
                            fwrite($tmpHandle, $content);
                            fseek($tmpHandle, 0);
                        }
                    }
                }

                // Output of the PDF
                foreach ($handles as $handle) {
                    $meta_data = stream_get_meta_data($handle);
                    $filename = $meta_data["uri"];
                    $pdf->WriteHTML($filename);
                    $pagecount = $pdf->SetSourceFile($filename);
                    for ($pages = 0; $pages < $pagecount; $pages++) {
                        $pdf->AddPage();
                        $pdf->WriteHTML(' pages: ' . $pagecount);
                        $tx = $pdf->ImportPage($pages + 1);
                        $pdf->UseTemplate($tx);
                    }
                }

                $pdf_result = $pdf->Output();
                $e->setResult($pdf_result);

                // delete all temporary Files again
                foreach ($handles as $handle) {
                    fclose($handle);
                }
                break;
            } catch (\Exception $e) {
            }
        }
        error_reporting(E_ALL);
    }

    /**
     * Look for a template with the Suffix ".pdf.phtml"
     *
     * @param string $name
     * @param \Zend\View\Renderer\RendererInterface $renderer
     * @return string|boolean
     */
    public function resolve($name, Renderer $renderer = null)
    {
        if ($this->serviceManager->has('ViewTemplatePathStack')) {
            // get all the Pases made up for the zend-provided resolver
            // we won't get any closer to ALL than that
            $viewTemplatePathStack = $this->serviceManager->get('ViewTemplatePathStack');
            $paths = $viewTemplatePathStack->getPaths();
            $defaultSuffix = $viewTemplatePathStack->getDefaultSuffix();
            if (pathinfo($name, PATHINFO_EXTENSION) != $defaultSuffix) {
                ;
                $name .= '.pdf.' . $defaultSuffix;
            } else {
                // TODO: replace Filename by Filename for PDF
            }

            foreach ($paths as $path) {
                $file = new SplFileInfo($path . $name);
                if ($file->isReadable()) {
                    // Found! Return it.
                    if (($filePath = $file->getRealPath()) === false && substr($path, 0, 7) === 'phar://') {
                        // Do not try to expand phar paths (realpath + phars == fail)
                        $filePath = $path . $name;
                        if (!file_exists($filePath)) {
                            break;
                        }
                    }
                    //if ($this->useStreamWrapper()) {
                    //    // If using a stream wrapper, prepend the spec to the path
                    //    $filePath = 'zend.view://' . $filePath;
                    //}
                    return $filePath;
                }
            }
        }
        // TODO: Resolving to an PDF has failed, this could have implications for the transformer
        return false;
    }
}


<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property;

use n2n\persistence\orm\query\select\SelectionGroup;
use n2n\persistence\orm\query\from\MetaTreePoint;
use n2n\persistence\PdoStatement;
use n2n\persistence\orm\query\select\ValueBuilder;
use n2n\reflection\ReflectionUtils;
use n2n\util\ex\IllegalStateException;
use n2n\persistence\orm\query\select\Selection;

class EmbeddedSelection implements Selection {
	private $embeddedEntityProperty;
	private $selectionGroup;

	public function __construct(EmbeddedEntityProperty $embeddedEntityProperty, MetaTreePoint $metaTreePoint) {
		$this->embeddedEntityProperty = $embeddedEntityProperty;

		$this->selectionGroup = new SelectionGroup();
		foreach ($embeddedEntityProperty->getEntityProperties() as $entityProperty) {
			$this->selectionGroup->addSelection($entityProperty->toPropertyString(),
					$metaTreePoint->requestCustomPropertySelection($entityProperty));
		}
	}

	// 	private function buildKey(EntityProperty $entityProperty) {
	// 		return $entityProperty->getEntityModel()->getClass()->getName()
	// 				. '::$' . $entityProperty->getName();
	// 	}
	/**
	 * @return \n2n\persistence\meta\data\QueryItem[]
	 */
	public function getSelectQueryItems() {
		return $this->selectionGroup->getSelectQueryItems();
	}
	/* (non-PHPdoc)
	 * @see \n2n\persistence\orm\query\select\Selection::bindColumns()
	*/
	public function bindColumns(PdoStatement $stmt, array $columnAliases) {
		$this->selectionGroup->bindColumns($stmt, $columnAliases);
	}

	public function createValueBuilder() {
		$propertyValueBuilders = array();
		foreach ($this->embeddedEntityProperty->getEntityProperties() as $entityProperty) {
			$propertyString = $entityProperty->toPropertyString();
			$selection = $this->selectionGroup->getSelectionByKey($propertyString);
			$propertyValueBuilders[$propertyString] = $selection->createValueBuilder();
		}

		return new EmbeddedValueBuilder($this->embeddedEntityProperty, $propertyValueBuilders);
	}
}

class EmbeddedValueBuilder implements ValueBuilder {
	private $embeddedEntityProperty;
	private $propertyValueBuilders;

	public function __construct(EmbeddedEntityProperty $embeddedEntityProperty, array $propertyValueBuilders) {
		$this->embeddedEntityProperty = $embeddedEntityProperty;
		$this->propertyValueBuilders = $propertyValueBuilders;
	}
	/* (non-PHPdoc)
	 * @see \n2n\persistence\orm\query\select\ValueBuilder::buildValue()
	 */
	public function buildValue() {
		$propertyValues = array();
		$notNull = false;
		foreach ($this->propertyValueBuilders as $propertyString => $propertyValueBuilder) {
			if (null !== ($propertyValues[$propertyString] = $propertyValueBuilder->buildValue())) {
				$notNull = true;
			}
		}

		if (!$notNull) return null;

		$object = ReflectionUtils::createObject($this->embeddedEntityProperty->getTargetClass());
		foreach ($this->embeddedEntityProperty->getEntityProperties() as $entityProperty) {
			$propertyString = $entityProperty->toPropertyString();
			IllegalStateException::assertTrue(array_key_exists($propertyString, $propertyValues));
			$entityProperty->writeValue($object, $propertyValues[$propertyString]);
		}
		return $object;
	}

}


<?php

/*
 * This file is part of the Wid'op package.
 *
 * (c) Wid'op <contact@widop.com>
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code.
 */

namespace Widop\Twitter\Options;

/**
 * Option bag.
 *
 * @author GeLo <geloen.eric@gmail.com>
 */
class OptionBag implements \ArrayAccess, \IteratorAggregate
{
    /** @var \Widop\Twitter\Options\OptionFactory */
    private $factory;

    /** @var array */
    private $options;

    /**
     * Creates an option bag.
     *
     * @param \Widop\Twitter\Options\OptionFactory|null $factory The option factory.
     */
    public function __construct(OptionFactory $factory = null)
    {
        $this->factory = $factory ?: new OptionFactory();
        $this->options = array();
    }

    /**
     * Registers an option.
     *
     * @param string|\Widop\Twitter\Options\OptionInterface $option The option.
     * @param string                                        $type   The option type.
     *
     * @throws \InvalidArgumentException If the option is not valid.
     *
     * @return \Widop\Twitter\Options\OptionBag The option bag.
     */
    public function register($option, $type = OptionInterface::TYPE_GET)
    {
        if (is_string($option)) {
            $option = $this->factory->create($option, $type);
        }

        if (!$option instanceof OptionInterface) {
            throw new \InvalidArgumentException(
                'The option should be either a string or a "Widop\Twitter\Options\OptionInterface".'
            );
        }

        $this->options[$option->getName()] = $option;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function offsetExists($offset)
    {
        return $this->getOption($offset)->hasValue();
    }

    /**
     * {@inheritdoc}
     */
    public function offsetGet($offset)
    {
        return $this->getOption($offset)->getValue();
    }

    /**
     * {@inheritdoc}
     */
    public function offsetSet($offset, $value)
    {
        $this->getOption($offset)->setValue($value);
    }

    /**
     * {@inheritdoc}
     */
    public function offsetUnset($offset)
    {
        $this->offsetSet($offset, null);
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->options);
    }

    /**
     * Gets an option.
     *
     * @param string $name The option name.
     *
     * @throws \InvalidArgumentException If the option does not exist.
     *
     * @return \Widop\Twitter\Options\OptionInterface The option.
     */
    private function getOption($name)
    {
        if (!isset($this->options[$name])) {
            throw new \InvalidArgumentException(sprintf('The option "%s" does not exist.', $name));
        }

        return $this->options[$name];
    }
}


<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property\hangar;

use hangar\api\HangarPropDef;
use hangar\api\PropSourceDef;
use n2n\util\type\attrs\Attributes;
use n2n\web\dispatch\mag\MagCollection;
use hangar\api\DbInfo;
use n2n\persistence\orm\property\EntityProperty;
use n2n\reflection\annotation\AnnotationSet;
use n2n\l10n\N2nLocale;
use n2n\util\type\ArgUtils;
use hangar\api\ColumnDefaults;
use n2n\persistence\meta\structure\common\CommonStringColumn;
use hangar\api\CompatibilityLevel;
use phpbob\representation\PhpTypeDef;
use hangar\api\HuoContext;
use n2n\persistence\meta\structure\Column;
use n2n\persistence\orm\annotation\AnnoN2nLocale;
use n2n\util\uri\Url;
use n2n\persistence\orm\annotation\AnnoUrl;
use n2n\impl\persistence\orm\property\UrlEntityProperty;

class UrlPropDef implements HangarPropDef {
	const DEFAULT_URL_COLUMN_LENGTH = '255';

	protected $columnDefaults;

	public function setup(HuoContext $huoContext, ColumnDefaults $columnDefaults) {
		$this->columnDefaults = $columnDefaults;
	}

	public function getName(): string {
		return 'URL';
	}

	public function createMagCollection(PropSourceDef $propSourceDef = null): MagCollection {
		return new MagCollection();
	}

	/**
	 * {@inheritDoc}
	 * @see \hangar\api\HangarPropDef::resetPropSourceDef()
	 */
	public function resetPropSourceDef(PropSourceDef $propSourceDef) {
	    $propSourceDef->removePhpPropertyAnno(Url::class);
	    $propSourceDef->removePhpUse(AnnoUrl::class);
	    $propSourceDef->removePhpUse(Url::class);
	}

	public function updatePropSourceDef(Attributes $attributes, PropSourceDef $propSourceDef) {
		$propSourceDef->setPhpTypeDef(PhpTypeDef::fromTypeName(Url::class));
	}

	/**
	 * {@inheritDoc}
	 * @see \hangar\api\HangarPropDef::applyDbMeta()
	 */
	public function applyDbMeta(DbInfo $dbInfo, PropSourceDef $propSourceDef, EntityProperty $entityProperty,
			AnnotationSet $annotationSet) {
		ArgUtils::assertTrue($entityProperty instanceof UrlEntityProperty);
		$columnName = $entityProperty->getColumnName();
		$dbInfo->removeColumn($columnName);

		$dbInfo->getTable()->createColumnFactory()->createStringColumn($columnName, self::DEFAULT_URL_COLUMN_LENGTH);
	}

	/**
	 * @param PropSourceDef $propSourceDef
	 * @return Column
	 */
	public function createMetaColumn(EntityProperty $entityProperty, PropSourceDef $propSourceDef): ?Column {
		ArgUtils::assertTrue($entityProperty instanceof UrlEntityProperty);
		return new CommonStringColumn($entityProperty->getColumnName(), self::DEFAULT_URL_COLUMN_LENGTH);
	}

	/**
	 * {@inheritDoc}
	 * @see \hangar\api\HangarPropDef::testCompatibility()
	 */
	public function testCompatibility(PropSourceDef $propSourceDef): int {
		if ($propSourceDef->hasPhpPropertyAnno(AnnoN2nLocale::class)) return CompatibilityLevel::COMMON;
		if (null !== ($phpTypeDef = $propSourceDef->getPhpTypeDef()) &&
				$phpTypeDef->getTypeName() === N2nLocale::class) return CompatibilityLevel::COMMON;

		return CompatibilityLevel::NOT_COMPATIBLE;
	}
}


<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property;

use n2n\util\type\TypeConstraint;
use n2n\reflection\property\AccessProxy;
use n2n\persistence\orm\property\BasicEntityProperty;
use n2n\persistence\orm\query\from\MetaTreePoint;
use n2n\persistence\orm\query\QueryState;
use n2n\persistence\meta\data\QueryItem;
use n2n\util\type\ArgUtils;
use n2n\persistence\orm\store\action\PersistAction;
use n2n\persistence\orm\store\operation\MergeOperation;
use n2n\persistence\Pdo;
use n2n\persistence\orm\store\action\RemoveAction;
use n2n\persistence\orm\EntityManager;
use n2n\persistence\orm\store\ValueHash;
use n2n\persistence\orm\store\CommonValueHash;
use n2n\persistence\orm\criteria\compare\ScalarColumnComparable;
use n2n\persistence\orm\query\select\SimpleSelection;

class BoolEntityProperty extends ColumnPropertyAdapter implements BasicEntityProperty {
	/**
	 * @param AccessProxy $accessProxy
	 * @param string $columnName
	 */
	public function __construct(AccessProxy $accessProxy, $columnName) {
		$accessProxy->setConstraint(TypeConstraint::createSimple('bool', true, true));

		parent::__construct($accessProxy, $columnName);
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\persistence\orm\property\ColumnComparableEntityProperty::createColumnComparable()
	 */
	public function createColumnComparable(MetaTreePoint $metaTreePoint, QueryState $queryState) {
		return new ScalarColumnComparable($this->createQueryColumn($metaTreePoint->getMeta()), $queryState, 'bool');
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\persistence\orm\property\BasicEntityProperty::createColumnComparableFromQueryItem()
	 */
	public function createColumnComparableFromQueryItem(QueryItem $queryItem, QueryState $queryState) {
		return new ScalarColumnComparable($queryItem, $queryState, 'bool');
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\persistence\orm\property\EntityProperty::createSelection()
	 */
	public function createSelection(MetaTreePoint $metaTreePoint, QueryState $queryState) {
		return new SimpleSelection($this->createQueryColumn($metaTreePoint->getMeta()), 'bool');
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\persistence\orm\property\BasicEntityProperty::valueToRep()
	 */
	public function valueToRep($value): string {
		ArgUtils::assertTrue(is_bool($value));

		return (string) (int) $value;
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\persistence\orm\property\BasicEntityProperty::repToValue()
	 */
	public function repToValue(string $rep) {
		ArgUtils::assertTrue(is_numeric($rep));
		return (bool) $rep;
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\persistence\orm\property\EntityProperty::supplyPersistAction()
	 */
	public function supplyPersistAction(PersistAction $persistAction, $value, ValueHash $valueHash, ?ValueHash $oldValueHash) {
		$persistAction->getMeta()->setRawValue($this->getEntityModel(), $this->getColumnName(), $value, \PDO::PARAM_BOOL);
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\persistence\orm\property\EntityProperty::createValueHash()
	 */
	public function createValueHash($value, EntityManager $em): ValueHash {
		if ($value === null) return new CommonValueHash(null);
		return new CommonValueHash($this->valueToRep($value));
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\persistence\orm\property\EntityProperty::mergeValue()
	 */
	public function mergeValue($value, $sameEntity, MergeOperation $mergeOperation) {
		return $value;
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\persistence\orm\property\EntityProperty::supplyRemoveAction()
	 */
	public function supplyRemoveAction(RemoveAction $removeAction, $value, ValueHash $valueHash = null) {
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\persistence\orm\property\BasicEntityProperty::parseValue()
	 */
	public function parseValue($raw, Pdo $pdo) {
		if ($raw === null) return null;

		return (bool) $raw;
	}

	public function buildRaw($value, Pdo $pdo) {
		ArgUtils::valType($value, 'bool', true);
		return $value;
	}

	public function createSelectionFromQueryItem(QueryItem $queryItem, QueryState $queryState) {
		return new SimpleSelection($queryItem, 'bool');
	}
}


<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property\hangar\scalar;

use n2n\util\type\attrs\Attributes;
use hangar\api\DbInfo;
use n2n\persistence\meta\structure\ColumnFactory;
use n2n\impl\web\dispatch\mag\model\NumericMag;
use hangar\api\PropSourceDef;
use n2n\persistence\meta\structure\common\CommonBinaryColumn;
use n2n\persistence\orm\property\EntityProperty;
use n2n\util\type\ArgUtils;
use n2n\impl\persistence\orm\property\ScalarEntityProperty;
use phpbob\representation\PhpTypeDef;
use n2n\web\dispatch\mag\MagCollection;
use n2n\persistence\meta\structure\Column;
use hangar\api\CompatibilityLevel;

class BinaryPropDef extends ScalarPropDefAdapter {
	const PROP_NAME_SIZE = 'size';

	/**
	 * {@inheritDoc}
	 * @see \hangar\api\HangarPropDef::getName()
	 */
	public function getName(): string {
		return 'Binary';
	}

	protected function createColumn(EntityProperty $entityProperty, DbInfo $dbInfo, ColumnFactory $columnFactory, $columnName,
			Attributes $attributes) {
		$columnFactory->createBinaryColumn($columnName,
				$attributes->get(self::PROP_NAME_SIZE, false, $this->columnDefaults->getDefaultBinarySize()));
	}

	/**
	 * {@inheritDoc}
	 * @see \hangar\api\HangarPropDef::createMagCollection()
	 * @return MagCollection
	 */
	public function createMagCollection(PropSourceDef $propSourceDef = null): MagCollection {
		$optionCollection = new MagCollection();

		$size = $this->columnDefaults->getDefaultBinarySize();
		if (null !== $propSourceDef) {
			$size = $propSourceDef->getHangarData()->get(self::PROP_NAME_SIZE, false, $size);
		}

		$optionCollection->addMag(self::PROP_NAME_SIZE, new NumericMag('Size', $size, true));

		return $optionCollection;
	}

	/**
	 * {@inheritDoc}
	 * @see \hangar\api\HangarPropDef::updatePropSourceDef()
	 */
	public function updatePropSourceDef(Attributes $attributes, PropSourceDef $propSourceDef) {
		$propSourceDef->getHangarData()->setAll(array(self::PROP_NAME_SIZE =>
				$attributes->get(self::PROP_NAME_SIZE)));
		$propSourceDef->setPhpTypeDef(new PhpTypeDef('string'));
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\impl\persistence\orm\property\hangar\scalar\ScalarPropDefAdapter::testSourceCompatibility()
	 */
	public function testSourceCompatibility(PropSourceDef $propSourceDef): int {
		if (null === $propSourceDef->getPhpTypeDef() || $propSourceDef->getPhpTypeDef()->isString()) {
			return CompatibilityLevel::COMPATIBLE;
		}

		return CompatibilityLevel::NOT_COMPATIBLE;
	}

	/**
	 * @param PropSourceDef $propSourceDef
	 * @return Column
	 */
	public function createMetaColumn(EntityProperty $entityProperty, PropSourceDef $propSourceDef): ?Column {
		ArgUtils::assertTrue($entityProperty instanceof ScalarEntityProperty);

		return new CommonBinaryColumn($entityProperty->getColumnName(),
				$this->determineSize($propSourceDef->getHangarData()));
	}

	private function determineSize(Attributes $attributes) {
		return $attributes->get(self::PROP_NAME_SIZE, false,
				$this->columnDefaults->getDefaultBinarySize());
	}
}


<?php

namespace Igorwanbarros\Php2Html;

/**
 * Class Helpers
 * @package Igorwanbarros\Php2Html
 */
class Helpers
{

    /**
     * @param string $string
     * @param string $character
     *
     * @return string
     */
    public static function camelCase($string, $character = '-')
    {
        $string = preg_replace('/[A-Z]/', $character . '$0', $string);
        $string = strtolower($string);

        return ltrim($string, $character);
    }

    /**
     * @param string $string
     *
     * @return string
     */
    public static function normalize($string)
    {
        $tableCharacters = [
            'Š' => 'S', 'š' => 's', 'Đ' => 'Dj', 'đ' => 'dj', 'Ž' => 'Z',
            'ž' => 'z', 'Č' => 'C', 'č' => 'c', 'Ć' => 'C', 'ć' => 'c',
            'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A',
            'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E',
            'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I',
            'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O',
            'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U',
            'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss',
            'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a',
            'å' => 'a', 'æ' => 'a', 'ç' => 'c', 'è' => 'e', 'é' => 'e',
            'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i',
            'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o',
            'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o', 'ù' => 'u',
            'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'þ' => 'b', 'ÿ' => 'y',
            'Ŕ' => 'R', 'ŕ' => 'r',
        ];

        return strtr($string, $tableCharacters);
    }
}


<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property\hangar\scalar;

use n2n\util\type\attrs\Attributes;
use n2n\persistence\meta\structure\ColumnFactory;
use hangar\api\DbInfo;
use hangar\api\PropSourceDef;
use n2n\persistence\orm\property\EntityProperty;
use n2n\util\type\ArgUtils;
use n2n\impl\persistence\orm\property\ScalarEntityProperty;
use n2n\persistence\meta\structure\common\CommonIntegerColumn;
use hangar\api\CompatibilityLevel;
use phpbob\representation\PhpTypeDef;
use n2n\impl\persistence\orm\property\BoolEntityProperty;
use n2n\reflection\annotation\AnnotationSet;
use n2n\web\dispatch\mag\MagCollection;
use n2n\persistence\meta\structure\Column;

class BooleanPropDef extends ScalarPropDefAdapter {

	/**
	 * {@inheritDoc}
	 * @see \hangar\api\HangarPropDef::getName()
	 */
	public function getName(): string {
		return 'Boolean';
	}

	/**
	 * {@inheritDoc}
	 * @see \hangar\api\HangarPropDef::createMagCollection()
	 * @return MagCollection
	 */
	public function createMagCollection(PropSourceDef $propSourceDef = null): MagCollection {
		return new MagCollection();
	}

	/**
	 * {@inheritDoc}
	 * @see \hangar\api\HangarPropDef::updatePropSourceDef()
	 */
	public function updatePropSourceDef(Attributes $attributes, PropSourceDef $propSourceDef) {
		$propSourceDef->setPhpTypeDef(new PhpTypeDef('bool'));
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\impl\persistence\orm\property\hangar\scalar\ScalarPropDefAdapter::applyDbMeta()
	 */
	public function applyDbMeta(DbInfo $dbInfo, PropSourceDef $propSourceDef, EntityProperty $entityProperty,
			AnnotationSet $annotationSet) {

		ArgUtils::assertTrue($entityProperty instanceof BoolEntityProperty || $entityProperty instanceof ScalarEntityProperty);

		$columnName = $entityProperty->getColumnName();
		$dbInfo->removeColumn($columnName);
		$columnFactory = $dbInfo->getTable()->createColumnFactory();
		$attributes = $propSourceDef->getHangarData();

		$this->createColumn($entityProperty, $dbInfo, $columnFactory, $columnName, $attributes);
	}
	/**
	 * @param PropSourceDef $propSourceDef
	 * @return Column
	 */
	public function createMetaColumn(EntityProperty $entityProperty, PropSourceDef $propSourceDef): Column {
		ArgUtils::assertTrue($entityProperty instanceof BoolEntityProperty || $entityProperty instanceof ScalarEntityProperty);

		return new CommonIntegerColumn($entityProperty->getColumnName(), 1, false);
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\impl\persistence\orm\property\hangar\scalar\ScalarPropDefAdapter::testSourceCompatibility()
	 */
	public function testCompatibility(PropSourceDef $propSourceDef): int {
		if (null === $propSourceDef->getPhpTypeDef() || $propSourceDef->getPhpTypeDef()->isBool()) {
			if (null === $propSourceDef || $propSourceDef->getPropertyName() === 'online') {
				return CompatibilityLevel::COMMON;
			}

			return parent::testCompatibility($propSourceDef);
		}

		return CompatibilityLevel::NOT_COMPATIBLE;
	}

	protected function createColumn(EntityProperty $entityProperty, DbInfo $dbInfo,
			ColumnFactory $columnFactory, $columnName, Attributes $attributes) {
		$columnFactory->createIntegerColumn($columnName, 1, false);
	}
}


<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property\relation;

use n2n\persistence\orm\query\from\MetaTreePoint;
use n2n\persistence\orm\query\QueryState;
use n2n\impl\persistence\orm\property\relation\selection\JoinTableToManyLoader;
use n2n\persistence\orm\store\SimpleLoaderUtils;
use n2n\persistence\orm\FetchType;
use n2n\impl\persistence\orm\property\relation\selection\ToManyRelationSelection;
use n2n\persistence\orm\store\action\PersistAction;
use n2n\impl\persistence\orm\property\relation\util\ToManyValueHasher;
use n2n\impl\persistence\orm\property\relation\util\ToManyAnalyzer;
use n2n\impl\persistence\orm\property\relation\compare\JoinTableToManyQueryItemFactory;
use n2n\impl\persistence\orm\property\relation\compare\ToManyCustomComparable;
use n2n\persistence\orm\store\action\supply\SupplyJob;
use n2n\persistence\orm\property\EntityProperty;
use n2n\persistence\orm\model\EntityModel;
use n2n\impl\persistence\orm\property\relation\util\ToManyUtils;
use n2n\persistence\orm\EntityManager;
use n2n\persistence\orm\store\ValueHash;
use n2n\util\type\ArgUtils;
use n2n\impl\persistence\orm\property\relation\util\ToManyValueHash;

class JoinTableToManyRelation extends JoinTableRelation implements ToManyRelation {
	private $toManyUtils;
	private $orderDirectives = array();

	public function __construct(EntityProperty $entityProperty, EntityModel $targetEntityModel) {
		parent::__construct($entityProperty, $targetEntityModel);
		$this->toManyUtils = new ToManyUtils($this, true);
	}

	public function getOrderDirectives() {
		return $this->orderDirectives;
	}

	public function setOrderDirectives(array $orderDirectives) {
		$this->orderDirectives = $orderDirectives;
	}

	public function createCustomComparable(MetaTreePoint $metaTreePoint, QueryState $queryState) {
		$toManyQueryItemFactory = new JoinTableToManyQueryItemFactory($this->joinTableName,
				$this->joinColumnName, $this->inverseJoinColumnName);

		return new ToManyCustomComparable($metaTreePoint, $this->targetEntityModel,
				$this->createTargetIdTreePath(), $toManyQueryItemFactory, $queryState);
	}

	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\Relation::createSelection()
	 */
	public function createSelection(MetaTreePoint $metaTreePoint, QueryState $queryState) {
		$idSelection = $metaTreePoint->requestPropertySelection($this->createIdTreePath());

		$toManyLoader = new JoinTableToManyLoader(
				new SimpleLoaderUtils($queryState->getEntityManager(), $this->targetEntityModel),
				$this->entityModel->getIdDef()->getEntityProperty(), $this->joinTableName,
				$this->inverseJoinColumnName, $this->joinColumnName);
		$toManyLoader->setOrderDirectives($this->orderDirectives);

		$toManySelection = new ToManyRelationSelection($idSelection, $toManyLoader,
				$this->getTargetIdEntityProperty());
		$toManySelection->setLazy($this->fetchType == FetchType::LAZY);
		return $toManySelection;
	}
	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\Relation::prepareSupplyJob()
	 */
	public function prepareSupplyJob(SupplyJob $supplyJob, $value, ?ValueHash $oldValueHash) {
		$this->toManyUtils->prepareSupplyJob($supplyJob, $value, $oldValueHash);
	}
	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\Relation::supplyPersistAction()
	 */
	public function supplyPersistAction(PersistAction $persistAction, $value, ValueHash $valueHash,
			?ValueHash $oldValueHash) {
		ArgUtils::assertTrue($oldValueHash === null || $oldValueHash instanceof ToManyValueHash);
		if ($oldValueHash !== null && $oldValueHash->checkForUntouchedProxy($value)) return;

		$targetIdProperty = $this->targetEntityModel->getIdDef()->getEntityProperty();

		$toManyAnalyzer = new ToManyAnalyzer($persistAction->getActionQueue());
		$toManyAnalyzer->analyze($value);

		$hasher = new ToManyValueHasher($targetIdProperty);

		if ($oldValueHash !== null && !$toManyAnalyzer->hasPendingPersistActions()
				&& $hasher->matches($toManyAnalyzer->getEntityIds(), $oldValueHash)) {
			return;
		}

		$joinTableAction = $this->createJoinTableActionFromPersistAction($persistAction);

		foreach ($toManyAnalyzer->getEntityIds() as $targetEntityId) {
			$joinTableAction->addInverseJoinIdRaw($targetIdProperty->buildRaw($targetEntityId, $joinTableAction->getPdo()));
		}

		foreach ($toManyAnalyzer->getPendingPersistActions() as $key => $targetPersistAction) {
			$joinTableAction->addDependent($targetPersistAction);
			$targetPersistAction->executeAtEnd(function () use ($joinTableAction, $targetPersistAction, $targetIdProperty, $hasher, $key, $valueHash) {
				$targetId = $targetPersistAction->getId();
				$joinTableAction->addInverseJoinIdRaw($targetIdProperty->buildRaw($targetId, $joinTableAction->getPdo()));
				$hasher->reportId($key, $targetId, $valueHash);
			});
		}
	}

	public function createValueHash($value, EntityManager $em): ValueHash {
		$analyzer = new ToManyValueHasher($this->targetEntityModel->getIdDef()->getEntityProperty());
		return $analyzer->createValueHash($value);
	}
}


<?php

namespace Igorwanbarros\Php2Html\Table;

/**
 * Class RowTableView
 * @package Igorwanbarros\Php2Html\Table
 */
class RowTableView
{

    /**
     * @var array
     */
    protected $headers;

    /**
     * @var array
     */
    protected $attributes;

    /**
     * @var mixed
     */
    protected $data;

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

    /**
     * @param array $headers
     * @param mixed $data
     */
    public function __construct(array $headers, $data)
    {
        $this->headers  = $headers;
        $this->setData($data);
    }

    /**
     * @param $header
     *
     * @return string
     */
    public function getDataValue($header)
    {
        if (strpos($header, '.') !== false) {
            $fields = explode('.', $header);
            $value = $this->data;

            foreach ($fields as $campo) {
                if (isset($value->{$campo})) {
                    $value = $value->{$campo};
                } else {
                    $value = '';
                }
            }

            return $value;
        }

        return isset($this->data->{$header}) ? $this->data->{$header} : '';
    }

    /**
     * @return array
     */
    public function getHeaders()
    {
        return $this->headers;
    }

    /**
     * @param $headers
     *
     * @return $this
     */
    public function setHeaders(array $headers)
    {
        $this->headers = $headers;

        return $this;
    }

    /**
     * @return array
     */
    public function getAttributes()
    {
        return $this->attributes;
    }

    /**
     * @param $key
     * @param $value
     *
     * @return $this
     */
    public function addAttributes($key, $value)
    {
        $this->attributes .= "{$key}=\"{$value}\" ";

        return $this;
    }

    /**
     * @return mixed
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @param mixed $data
     *
     * @return $this
     */
    public function setData($data)
    {
        $this->data = is_array($data) ? (object) $data : $data;

        return $this;
    }

    /**
     * @return string
     */
    public function getLineLink()
    {
        return strpos($this->lineLink, '%s') !== false
            ? sprintf($this->lineLink, isset($this->data->id) ? $this->data->id : '')
            : $this->lineLink;
    }

    /**
     * @param string $lineLink
     *
     * @return $this
     */
    public function setLineLink($lineLink)
    {
        $this->lineLink = $lineLink;

        return $this;
    }

    public function getValueKey($key)
    {
        $value = $this->data->{$key};

        if (strpos($key, '.') !== false) {
            $fields = explode('.', $key);
            $value = $this->data;

            foreach ($fields as $campo) {
                $value = $value->{$campo};
            }
        }

        return $value;
    }
}


<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property\relation;

use n2n\persistence\orm\query\QueryState;
use n2n\persistence\orm\query\from\MetaTreePoint;
use n2n\impl\persistence\orm\property\relation\tree\JoinColumnTreePoint;
use n2n\util\ex\IllegalStateException;
use n2n\persistence\orm\criteria\compare\ComparisonStrategy;
use n2n\persistence\orm\store\action\PersistAction;
use n2n\impl\persistence\orm\property\relation\selection\JoinColumnToManyLoader;
use n2n\impl\persistence\orm\property\relation\selection\ToManyRelationSelection;
use n2n\persistence\orm\store\SimpleLoaderUtils;
use n2n\persistence\orm\FetchType;
use n2n\util\ex\UnsupportedOperationException;
use n2n\persistence\orm\query\from\meta\TreePointMeta;
use n2n\impl\persistence\orm\property\relation\util\OrphanRemover;
use n2n\impl\persistence\orm\property\relation\util\ToManyValueHasher;
use n2n\impl\persistence\orm\property\relation\util\ToManyAnalyzer;
use n2n\impl\persistence\orm\property\relation\compare\IdColumnComparableDecorator;
use n2n\persistence\orm\store\action\supply\SupplyJob;
use n2n\util\type\ArgUtils;
use n2n\util\col\ArrayUtils;
use n2n\persistence\orm\model\EntityModel;
use n2n\persistence\orm\EntityManager;
use n2n\persistence\orm\store\ValueHash;
use n2n\impl\persistence\orm\property\relation\util\ToManyValueHash;

class InverseJoinColumnOneToManyRelation extends MasterRelation implements ToManyRelation {
	private $inverseJoinColumnName;
	private $orderDirectives = array();

	public function getInverseJoinColumnName() {
		return $this->inverseJoinColumnName;
	}

	public function setInverseJoinColumnName($inverseJoinColumnName) {
		$this->inverseJoinColumnName = $inverseJoinColumnName;
	}

	public function getOrderDirectives() {
		return $this->orderDirectives;
	}

	public function setOrderDirectives(array $orderDirectives) {
		$this->orderDirectives = $orderDirectives;
	}

	public function createJoinTreePoint(TreePointMeta $treePointMeta, QueryState $queryState) {
		$idQueryColumn = $this->entityModel->getIdDef()->getEntityProperty()
				->createQueryColumn($treePointMeta);

		$targetTreePointMeta = $this->targetEntityModel->createTreePointMeta($queryState);
		$targetJoinQueryColumn = $targetTreePointMeta->registerColumn($this->targetEntityModel,
				$this->inverseJoinColumnName);

		$treePoint = new JoinColumnTreePoint($queryState, $targetTreePointMeta);
		$treePoint->setJoinColumn($idQueryColumn);
		$treePoint->setTargetJoinColumn($targetJoinQueryColumn);
		return $treePoint;
	}
	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\MasterRelation::createInverseJoinTreePoint()
	 */
	public function createInverseJoinTreePoint(EntityModel $entityModel, TreePointMeta $targetTreePointMeta, QueryState $queryState) {
		$targetJoinQueryColumn = $targetTreePointMeta->registerColumn($this->targetEntityModel,
				$this->inverseJoinColumnName);

		$treePointMeta = $entityModel->createTreePointMeta($queryState);
		$idQueryColumn = $this->targetEntityModel->getIdDef()->getEntityProperty()
				->createColumn($treePointMeta);

		$treePoint = new JoinColumnTreePoint($queryState, $treePointMeta);
		$treePoint->setJoinColumn($targetJoinQueryColumn);
		$treePoint->setTargetJoinColumn($idQueryColumn);
		return $treePoint;
	}
	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\Relation::createColumnComparable()
	 */
	public function createCustomComparable(MetaTreePoint $metaTreePoint, QueryState $queryState) {
		$comparisonStargegy = $metaTreePoint->requestPropertyComparisonStrategy($this->createTargetIdTreePath())
				->getColumnComparable();

		IllegalStateException::assertTrue($comparisonStargegy->getType() == ComparisonStrategy::TYPE_COLUMN);

		return new IdColumnComparableDecorator($comparisonStargegy->getColumnComparable(),
				$this->targetEntityModel);
	}

	public function createInverseJoinTableToManyQueryItemFactory(EntityModel $entityModel) {
		throw new UnsupportedOperationException();
	}

	public function prepareSupplyJob(SupplyJob $supplyJob, $value, ?ValueHash $oldValueHash) {
		if (!$this->orphanRemoval || $oldValueHash === null || $supplyJob->isInsert()) return;

		ArgUtils::assertTrue($oldValueHash instanceof ToManyValueHash);
		if ($oldValueHash->checkForUntouchedProxy($value)) return;

		$orphanRemover = new OrphanRemover($supplyJob, $this->targetEntityModel, $this->actionMarker);

		if (!$supplyJob->isRemove()) {
			ArgUtils::assertTrue(ArrayUtils::isArrayLike($value));
			foreach ($value as $entity) {
				$orphanRemover->releaseCandiate($entity);
			}
		}

		$orphanRemover->reportCandidateByIdReps($oldValueHash->getIdReps(true));
	}

	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\Relation::supplyPersistAction()
	 */
	public function supplyPersistAction(PersistAction $persistAction, $value, ValueHash $valueHash,
			?ValueHash $oldValueHash) {
		ArgUtils::assertTrue($oldValueHash === null || $oldValueHash instanceof ToManyValueHash);
		if ($oldValueHash !== null && $oldValueHash->checkForUntouchedProxy($value)) return;

		$toManyAnalyzer = new ToManyAnalyzer($persistAction->getActionQueue());
		$toManyAnalyzer->analyze($value);

		$hasher = new ToManyValueHasher($this->targetEntityModel->getIdDef()->getEntityProperty());

		if ($oldValueHash !== null && !$toManyAnalyzer->hasPendingPersistActions()
				&& $hasher->matches($toManyAnalyzer->getEntityIds(), $oldValueHash)) {
			return;
		}

		$this->checkValueHash($toManyAnalyzer, $hasher, $valueHash);

		$targetPersistActions = $toManyAnalyzer->getAllPersistActions();

		if ($persistAction->hasId()) {
			$this->applyPersistId($persistAction, $targetPersistActions);
			return;
		}

		foreach ($targetPersistActions as $targetPersistAction) {
			$targetPersistAction->addDependent($persistAction);
		}

		$persistAction->executeAtEnd(function () use ($persistAction, $targetPersistActions) {
			$this->applyPersistId($persistAction, $targetPersistActions);
		});
	}

	/**
	 * @param PersistAction[] $targetPersistActions
	 * @param ToManyValueHasher $hasher
	 * @param ToManyValueHash $valueHash
	 */
	private function checkValueHash(ToManyAnalyzer $toManyAnalyzer, ToManyValueHasher $hasher, ToManyValueHash $valueHash) {
		foreach ($toManyAnalyzer->getPendingPersistActions() as $key => $targetPersistAction) {
			$targetPersistAction->executeAtEnd(function () use ($targetPersistAction, $hasher, $key, $valueHash) {
				$hasher->reportId($key, $targetPersistAction->getId(), $valueHash);
			});
		}
	}

	private function applyPersistId(PersistAction $persistAction, array $targetPersistActions) {
		$idProperty = $this->entityModel->getIdDef()->getEntityProperty();
		$idRaw = $idProperty->valueToRep($persistAction->getId());
		foreach ($targetPersistActions as $targetPersistAction) {
			$targetPersistAction->getMeta()->setRawValue($this->targetEntityModel,
					$this->inverseJoinColumnName, $idRaw);
		}
	}
// 	/* (non-PHPdoc)
// 	 * @see \n2n\impl\persistence\orm\property\relation\Relation::supplyInverseToManyRemoveAction()
// 	 */
// 	public function supplyInverseToManyRemoveAction($targetValue, $targetValueHash, RemoveAction $targetRemoveAction) {
// 		throw new UnsupportedOperationException();
// 	}
// 	/* (non-PHPdoc)
// 	 * @see \n2n\impl\persistence\orm\property\relation\Relation::supplyInverseToOneRemoveAction()
// 	 */
// 	public function supplyInverseToOneRemoveAction($targetValue, $targetValueHash, RemoveAction $targetRemoveAction) {
// 	}

	public function createValueHash($value, EntityManager $em): ValueHash {
		$analyzer = new ToManyValueHasher($this->targetEntityModel->getIdDef()
				->getEntityProperty());
		return $analyzer->createValueHash($value);
	}

	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\Relation::createSelection()
	 */
	public function createSelection(MetaTreePoint $metaTreePoint, QueryState $queryState) {
		$idSelection = $metaTreePoint->requestPropertySelection($this->createIdTreePath());
		$idProperty = $this->entityModel->getIdDef()->getEntityProperty();

		$toManyLoader = new JoinColumnToManyLoader(
				new SimpleLoaderUtils($queryState->getEntityManager(), $this->targetEntityModel),
				$idProperty, $this->inverseJoinColumnName);
		$toManyLoader->setOrderDirectives($this->orderDirectives);

		$toManySelection = new ToManyRelationSelection($idSelection, $toManyLoader,
				$this->getTargetIdEntityProperty());
		$toManySelection->setLazy($this->fetchType == FetchType::LAZY);
		return $toManySelection;
	}
	/* (non-PHPdoc)
	 * @see \n2n\impl\persistence\orm\property\relation\MasterRelation::createInverseToManyLoader()
	 */
	public function createInverseToManyLoader(EntityModel $entityModel, QueryState $queryState) {
		throw new UnsupportedOperationException();
	}
}


<?php

/*
 * This file is part of the xAPI package.
 *
 * (c) Christian Flothmann <christian.flothmann@xabbuh.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Xabbuh\XApi\DataFixtures;

use Xabbuh\XApi\Model\Activity;
use Xabbuh\XApi\Model\ActivityProfile;
use Xabbuh\XApi\Model\ActivityProfileDocument;
use Xabbuh\XApi\Model\Agent;
use Xabbuh\XApi\Model\AgentProfile;
use Xabbuh\XApi\Model\AgentProfileDocument;
use Xabbuh\XApi\Model\DocumentData;
use Xabbuh\XApi\Model\InverseFunctionalIdentifier;
use Xabbuh\XApi\Model\IRI;
use Xabbuh\XApi\Model\State;
use Xabbuh\XApi\Model\StateDocument;

/**
 * Document fixtures.
 *
 * @author Christian Flothmann <christian.flothmann@xabbuh.de>
 */
class DocumentFixtures
{
    /**
     * Loads empty document data.
     *
     * @return DocumentData
     */
    public static function getEmptyDocumentData()
    {
        return new DocumentData();
    }

    /**
     * Loads document data.
     *
     * @return DocumentData
     */
    public static function getDocumentData()
    {
        return new DocumentData(array('x' => 'foo', 'y' => 'bar'));
    }

    /**
     * Loads an activity profile document.
     *
     * @param DocumentData $documentData The document data, by default, a some
     *                                   default data will be used
     *
     * @return ActivityProfileDocument
     */
    public static function getActivityProfileDocument(DocumentData $documentData = null)
    {
        if (null === $documentData) {
            $documentData = static::getDocumentData();
        }

        $activityProfile = new ActivityProfile('profile-id', new Activity(IRI::fromString('activity-id')));

        return new ActivityProfileDocument($activityProfile, $documentData);
    }

    /**
     * Loads an agent profile document.
     *
     * @param DocumentData $documentData The document data, by default, a some
     *                                   default data will be used
     *
     * @return AgentProfileDocument
     */
    public static function getAgentProfileDocument(DocumentData $documentData = null)
    {
        if (null === $documentData) {
            $documentData = static::getDocumentData();
        }

        return new AgentProfileDocument(new AgentProfile('profile-id', new Agent(InverseFunctionalIdentifier::withMbox(IRI::fromString('mailto:christian@example.com')))), $documentData);
    }

    /**
     * Loads a state document.
     *
     * @param DocumentData $documentData The document data, by default, a some
     *                                   default data will be used
     *
     * @return StateDocument
     */
    public static function getStateDocument(DocumentData $documentData = null)
    {
        if (null === $documentData) {
            $documentData = static::getDocumentData();
        }

        $agent = new Agent(InverseFunctionalIdentifier::withMbox(IRI::fromString('mailto:alice@example.com')));
        $activity = new Activity(IRI::fromString('activity-id'));

        return new StateDocument(new State($activity, $agent, 'state-id'), $documentData);
    }
}


<?php
declare(strict_types = 1);

namespace Innmind\Http\Message\Cookies;

use Innmind\Http\{
    Message\Cookies as CookiesInterface,
    Exception\CookieNotFound
};
use Innmind\Immutable\{
    MapInterface,
    Map
};

final class Cookies implements CookiesInterface
{
    private $cookies;

    public function __construct(MapInterface $cookies = null)
    {
        $cookies = $cookies ?? new Map('string', 'scalar');

        if (
            (string) $cookies->keyType() !== 'string' ||
            (string) $cookies->valueType() !== 'scalar'
        ) {
            throw new \TypeError(
                'Argument 1 must be of type MapInterface<string, scalar>'
            );
        }

        $this->cookies = $cookies;
    }

    /**
     * {@inheritdoc}
     */
    public function get(string $name)
    {
        if (!$this->has($name)) {
            throw new CookieNotFound;
        }

        return $this->cookies->get($name);
    }

    /**
     * {@inheritdoc}
     */
    public function has(string $name): bool
    {
        return $this->cookies->contains($name);
    }

    /**
     * {@inheritdoc}
     */
    public function current()
    {
        return $this->cookies->current();
    }

    /**
     * {@inheritdoc}
     */
    public function key()
    {
        return $this->cookies->key();
    }

    /**
     * {@inheritdoc}
     */
    public function next()
    {
        $this->cookies->next();
    }

    /**
     * {@inheritdoc}
     */
    public function rewind()
    {
        $this->cookies->rewind();
    }

    /**
     * {@inheritdoc}
     */
    public function valid()
    {
        return $this->cookies->valid();
    }

    /**
     * {@inheritdoc}
     */
    public function count()
    {
        return $this->cookies->size();
    }
}


<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property\relation\util;

use n2n\util\type\ArgUtils;
use n2n\persistence\orm\property\BasicEntityProperty;
use n2n\persistence\orm\model\EntityModel;
use n2n\persistence\orm\store\ValueHash;
use n2n\util\ex\IllegalStateException;

class ToOneValueHasher {
	private $idEntityProperty;

	public function __construct(BasicEntityProperty $idEntityProperty) {
		$this->idEntityProperty = $idEntityProperty;
	}

	public function createValueHash($value) {
		if ($value === null) return new ToOneValueHash(false, null);
		ArgUtils::assertTrue(is_object($value));

		$id = $this->idEntityProperty->readValue($value);
		if ($id === null) return new ToOneValueHash(true, null);

		return new ToOneValueHash(true, $this->idEntityProperty->valueToRep($id));
	}

	public function reportId($id, ToOneValueHash $toOneValueHash) {
		$toOneValueHash->reportIdRep($this->idEntityProperty->valueToRep($id));
	}

	public static function createFromEntityModel(EntityModel $entityModel) {
		return new ToOneValueHasher($entityModel->getIdDef()->getEntityProperty());
	}
}

class ToOneValueHash implements ValueHash {
	/**
	 * @var bool
	 */
	private $objectExisting;
	/**
	 * @var string|null
	 */
	private $idRep;

	/**
	 * @param string|null $idRep
	 */
	public function __construct(bool $objectExisting, ?string $idRep) {
		$this->objectExisting = $objectExisting;
		$this->idRep = $idRep;
	}

	/**
	 * @param string $idRep
	 */
	public function reportIdRep(string $idRep) {
		IllegalStateException::assertTrue($this->objectExisting, 'Hash is for non-existing object.');
		IllegalStateException::assertTrue($this->idRep === null, 'IdRep already known.');
		$this->idRep = $idRep;
	}

	/**
	 * @return boolean
	 */
	public function isObjectExisting() {
		return $this->objectExisting;
	}

	/**
	 * @return string|null
	 */
	public function getIdRep() {
		return $this->idRep;
	}

	/**
	 * {@inheritDoc}
	 * @see \n2n\persistence\orm\store\ValueHash::matches()
	 */
	public function matches(ValueHash $valueHash): bool {
		ArgUtils::assertTrue($valueHash instanceof ToOneValueHash);

		return $this->objectExisting === $valueHash->isObjectExisting()
				&& $this->idRep === $valueHash->getIdRep();
	}

// 	public function checkForUntouchedProxy($entityObj) {
// 		if ($entityObj instanceof EntityProxy) {

// 		}
// 	}
}