/** * This is the description * * @param \EBT\ExtensionBuilder\Domain\Model\DomainObject $domainObject * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\TOOOL\Projects\Domain\Model\Calculation> $tests * @return \EBT\ExtensionBuilder\Domain\Model\DomainObject */ private static function testMethod(\EBT\ExtensionBuilder\Domain\Model\DomainObject $domainObject, \TYPO3\CMS\Extbase\Persistence\ObjectStorage $tests) { $number = 7; if ($number > $tests->count()) { return $domainObject; } else { $domainObject->setName('Foo'); } }
/** * @return array */ public function categoriesDataProvider() { $category1 = $this->getMock('Pws\\KesearchCategories\\Domain\\Model\\Category', array(), array(), '', false); $category1->expects($this->once())->method('getFilterOptionTag')->willReturn('onetitle'); $category2 = $this->getMock('Pws\\KesearchCategories\\Domain\\Model\\Category', array(), array(), '', false); $category2->expects($this->once())->method('getFilterOptionTag')->willReturn('secondtitle'); $objectStorage = new ObjectStorage(); $objectStorage->attach($category1); $objectStorage->attach($category2); return array(array($objectStorage)); }
/** * Returns a list generated from ObjectStorage * In best practice 'title' property should exist in target model. * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage * @param string $separator * @param string $property * * @return string */ public static function generateStringListFromObjectStorage(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage, $separator = ', ', $property = 'title') { $list = []; if ($objectStorage->count()) { /** @var \TYPO3\CMS\Extbase\DomainObject\AbstractDomainObject $object */ foreach ($objectStorage as $object) { $list[] = $object->_hasProperty($property) ? ucfirst($object->_getProperty($property)) : ''; } } return count($list) ? implode($separator, $list) : ''; }
/** * @return ObjectStorage */ public function constructObjectStorageContainingFrontendUsersWithUserGroups() { $storage = new ObjectStorage(); $userGroup1 = new FrontendUserGroup('my first group'); $userGroup2 = new FrontendUserGroup('my second group'); $user1 = new FrontendUser(); $user2 = new FrontendUser(); $user1->addUsergroup($userGroup1); $user2->addUsergroup($userGroup2); $storage->attach($user1); $storage->attach($user2); return $storage; }
/** * @return array */ public function getNegativeTestValues() { $bar = new Bar(); ObjectAccess::setProperty($bar, 'uid', 1, TRUE); $foo = new Foo(); ObjectAccess::setProperty($foo, 'uid', 2, TRUE); $objectStorage = new ObjectStorage(); $objectStorage->attach($bar); /** @var LazyObjectStorage $lazyObjectStorage */ $lazyObjectStorage = GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager')->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\LazyObjectStorage', $bar, 'foo', 0); ObjectAccess::setProperty($lazyObjectStorage, 'isInitialized', TRUE, TRUE); $lazyObjectStorage->attach($foo); return array(array(array('foo'), 'bar'), array('foo,baz', 'bar'), array($objectStorage, $foo), array($lazyObjectStorage, $bar)); }
/** * Validate object * * @param mixed $object * @throws \TYPO3\CMS\Extbase\Reflection\Exception\PropertyNotAccessibleException * @throws \InvalidArgumentException * @return boolean|\TYPO3\CMS\Extbase\Error\Result */ public function validate($object) { $messages = new \TYPO3\CMS\Extbase\Error\Result(); if (self::$instancesCurrentlyUnderValidation === NULL) { self::$instancesCurrentlyUnderValidation = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage(); } if ($object === NULL) { return $messages; } if (!$this->canValidate($object)) { $messages->addError(\TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('error_notvalidatable', 'StoreFinder'), 1301599551); return $messages; } if (self::$instancesCurrentlyUnderValidation->contains($object)) { return $messages; } else { self::$instancesCurrentlyUnderValidation->attach($object); } $this->model = $object; $propertyValidators = $this->getValidationRulesFromSettings(); foreach ($propertyValidators as $propertyName => $validatorsNames) { if (!property_exists($object, $propertyName)) { $messages->addError(\TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('error_notexists', 'StoreFinder'), 1301599575); } else { $this->currentPropertyName = $propertyName; $propertyValue = $this->getPropertyValue($object, $propertyName); $this->checkProperty($propertyValue, (array) $validatorsNames, $messages->forProperty($propertyName)); } } self::$instancesCurrentlyUnderValidation->detach($object); return $messages; }
/** * @param object $object * @param int $level * @param bool $plainText * @param bool $ansiColors * @return string The rendered body content of the Object(Storage) */ protected static function renderContent($object, $level, $plainText, $ansiColors) { $dump = ''; if ($object instanceof \TYPO3\CMS\Extbase\Persistence\ObjectStorage || $object instanceof \Iterator || $object instanceof \ArrayObject) { $dump .= self::renderCollection($object, $level, $plainText, $ansiColors); } else { self::$renderedObjects->attach($object); if (!$plainText) { $dump .= '<a name="' . spl_object_hash($object) . '" id="' . spl_object_hash($object) . '"></a>'; } if (get_class($object) === 'stdClass') { $objReflection = new \ReflectionObject($object); $properties = $objReflection->getProperties(); } else { $classReflection = new \ReflectionClass(get_class($object)); $properties = $classReflection->getProperties(); } foreach ($properties as $property) { if (self::isBlacklisted($property)) { continue; } $dump .= PHP_EOL . str_repeat(self::PLAINTEXT_INDENT, $level) . ($plainText ? '' : '<span class="extbase-debug-property">') . self::ansiEscapeWrap($property->getName(), '37', $ansiColors) . ($plainText ? '' : '</span>') . ' => '; $property->setAccessible(true); $dump .= self::renderDump($property->getValue($object), $level, $plainText, $ansiColors); if ($object instanceof \TYPO3\CMS\Extbase\DomainObject\AbstractDomainObject && !$object->_isNew() && $object->_isDirty($property->getName())) { if ($plainText) { $dump .= ' ' . self::ansiEscapeWrap('modified', '43;30', $ansiColors); } else { $dump .= '<span class="extbase-debug-dirty">modified</span>'; } } } } return $dump; }
/** * Update an object in the persistence. * * @param object $object The modified object * @return void * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException * @api */ public function update($object) { if ($this->isNewObject($object)) { throw new \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException('The object of type "' . get_class($object) . '" given to update must be persisted already, but is new.', 1249479819); } $this->changedObjects->attach($object); }
/** * Call the view helper associated with this object. * * First, it evaluates the arguments of the view helper. * * If the view helper implements \TYPO3\CMS\Fluid\Core\ViewHelper\Facets\ChildNodeAccessInterface, * it calls setChildNodes(array childNodes) on the view helper. * * Afterwards, checks that the view helper did not leave a variable lying around. * * @param \TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface $renderingContext * @return string evaluated node after the view helper has been called. */ public function evaluate(\TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface $renderingContext) { if ($this->viewHelpersByContext->contains($renderingContext)) { $viewHelper = $this->viewHelpersByContext[$renderingContext]; $viewHelper->resetState(); } else { $viewHelper = clone $this->uninitializedViewHelper; $this->viewHelpersByContext->attach($renderingContext, $viewHelper); } $evaluatedArguments = array(); if (count($viewHelper->prepareArguments())) { foreach ($viewHelper->prepareArguments() as $argumentName => $argumentDefinition) { if (isset($this->arguments[$argumentName])) { $argumentValue = $this->arguments[$argumentName]; $evaluatedArguments[$argumentName] = $argumentValue->evaluate($renderingContext); } else { $evaluatedArguments[$argumentName] = $argumentDefinition->getDefaultValue(); } } } $viewHelper->setArguments($evaluatedArguments); $viewHelper->setViewHelperNode($this); $viewHelper->setRenderingContext($renderingContext); if ($viewHelper instanceof \TYPO3\CMS\Fluid\Core\ViewHelper\Facets\ChildNodeAccessInterface) { $viewHelper->setChildNodes($this->childNodes); } $output = $viewHelper->initializeArgumentsAndRender(); return $output; }
/** * Deletes an object * * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object The object to be removed from the storage * @param boolean $markAsDeleted Wether to just flag the row deleted (default) or really delete it * @return void */ protected function removeEntity(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, $markAsDeleted = TRUE) { $this->signalSlotDispatcher->dispatch('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Backend', 'beforeRemoveObjectHijax', array('object' => $object)); // TODO: check if object is not already deleted parent::removeEntity($object, $markAsDeleted); // TODO: check if object is removed indeed $this->signalSlotDispatcher->dispatch('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Backend', 'afterRemoveObjectHijax', array('object' => $object)); $this->_removedObjects->attach($object); }
/** * @param $pages */ public function getEntriesFromPages($pages) { foreach ($pages as $page) { if (intval($page['doktype']) === 1) { $urlEntry = new UrlEntry(); $uri = $this->generatePageUrl($page['uid']); $urlEntry->setLoc($uri); $urlEntry->setLastmod(date('Y-m-d', $page['tstamp'])); if (isset($page['sitemap_priority'])) { $urlEntry->setPriority(number_format($page['sitemap_priority'] / 10, 1, '.', '')); } if (isset($page['sitemap_changefreq'])) { $urlEntry->setChangefreq($page['sitemap_changefreq']); } $this->entryStorage->attach($urlEntry); } } }
/** * [findDemanded description] * @param R3H6\LocallangTools\Domain\Model\Dto\TranslationDemand $demand [description] * @return TYPO3\CMS\Extbase\Persistence\ObjectStorage<R3H6\LocallangTools\Domain\Model\Translation> */ public function findDemanded(TranslationDemand $demand) { $demand->setLanguage('de'); $translations = new ObjectStorage(); $files = (array) $demand->getFiles(); if ($demand->getExtensions()) { $extensionPaths = []; foreach ($demand->getExtensions() as $extensionKey) { $extensionPaths[] = 'EXT:' . $extensionKey; } $files = $files + PathUtility::getLocallangPaths($extensionPaths); } elseif (empty($files)) { $files = PathUtility::getLocallangPaths(); } $language = $demand->getLanguage(); if (empty($language)) { $language = self::DEFAULT_LANGUAGE; } foreach ($files as $file) { $filePath = PathUtility::getAbsolutePath($file); $parsedData = $this->localizationFactory->getParsedData($filePath, $language, LocalizationFactory::CHARSET, LocalizationFactory::ERROR_MODE_EXCEPTION); foreach ($parsedData[self::DEFAULT_LANGUAGE] as $key => $value) { $default = $value[0]['source']; $source = isset($parsedData[$language][$key][0]['source']) ? $parsedData[$language][$key][0]['source'] : null; $target = isset($parsedData[$language][$key][0]['target']) ? $parsedData[$language][$key][0]['target'] : null; $translation = GeneralUtility::makeInstance(Translation::class, $file, $key, $language, $default, $source, $target); if ($demand->getState() && $demand->getState() !== $translation->getState()) { continue; } if ($demand->getKey() && stripos($translation->getKey(), $demand->getKey()) === false) { continue; } if ($demand->getSearch() && stripos($translation->getTarget(), $demand->getSearch()) === false && stripos($translation->getSource(), $demand->getSearch()) === false) { continue; } $translations->attach($translation); } } return $translations; }
/** * @test */ public function sortElementsAsDefinedInFlexFormsWithObjectStorage() { $records = new ObjectStorage(); $videoMock1 = $this->getMock(Video::class, ['getUid']); $videoMock1->expects($this->any())->method('getUid')->will($this->returnValue(1)); $videoMock2 = $this->getMock(Video::class, ['getUid']); $videoMock2->expects($this->any())->method('getUid')->will($this->returnValue(3)); $videoMock3 = $this->getMock(Video::class, ['getUid']); $videoMock3->expects($this->any())->method('getUid')->will($this->returnValue(4)); $videoMock4 = $this->getMock(Video::class, ['getUid']); $videoMock4->expects($this->any())->method('getUid')->will($this->returnValue(5)); $records->attach($videoMock1); $records->attach($videoMock2); $records->attach($videoMock3); $records->attach($videoMock4); self::assertSame([$videoMock2, $videoMock3, $videoMock1, $videoMock4], $this->subject->sortElementsAsDefinedInFlexForms('3,4,1,5', $records)); }
/** * @param int $itemsPerPage * @param int $offset * * @return array|QueryResultInterface * @throws \InvalidArgumentException */ protected function prepareObjectsSlice($itemsPerPage, $offset) { if ($this->objects instanceof QueryResultInterface) { $query = $this->objects->getQuery(); $query->setLimit($itemsPerPage); if ($offset > 0) { $query->setOffset($offset); } $modifiedObjects = $query->execute(); return $modifiedObjects; } elseif ($this->objects instanceof ObjectStorage) { $modifiedObjects = array(); $endOfRange = $offset + $itemsPerPage; for ($i = $offset; $i < $endOfRange; $i++) { $modifiedObjects[] = $this->objects->toArray()[$i]; } return $modifiedObjects; } elseif (is_array($this->objects)) { $modifiedObjects = array_slice($this->objects, $offset, $itemsPerPage); return $modifiedObjects; } else { throw new \InvalidArgumentException('The view helper "' . get_class($this) . '" accepts as argument "QueryResultInterface", "\\SplObjectStorage", "ObjectStorage" or an array. ' . 'given: ' . get_class($this->objects), 1385547291); } }
/** * Unregister an object * * @param object $object * @return void */ public function unregisterObject($object) { unset($this->identifierMap[strtolower(get_class($object))][$this->objectMap[$object]]); $this->objectMap->detach($object); }
/** * @param object $object * @param int $level * @param bool $plainText * @param bool $ansiColors * @return string The rendered body content of the Object(Storage) */ protected static function renderContent($object, $level, $plainText, $ansiColors) { $dump = ''; if ($object instanceof \TYPO3\CMS\Extbase\Persistence\ObjectStorage || $object instanceof \Iterator || $object instanceof \ArrayObject) { $dump .= self::renderCollection($object, $level, $plainText, $ansiColors); } else { self::$renderedObjects->attach($object); if (!$plainText) { $dump .= '<a name="' . spl_object_hash($object) . '" id="' . spl_object_hash($object) . '"></a>'; } if ($object instanceof \Closure) { $dump .= PHP_EOL . str_repeat(self::PLAINTEXT_INDENT, $level) . ($plainText ? '' : '<span class="extbase-debug-closure">') . self::ansiEscapeWrap('function (', '33', $ansiColors) . ($plainText ? '' : '</span>'); $reflectionFunction = new \ReflectionFunction($object); $params = []; foreach ($reflectionFunction->getParameters() as $parameter) { $parameterDump = ''; if ($parameter->isArray()) { if ($plainText) { $parameterDump .= self::ansiEscapeWrap('array ', '36', $ansiColors); } else { $parameterDump .= '<span class="extbase-debug-type">array </span>'; } } elseif ($parameter->getClass()) { if ($plainText) { $parameterDump .= self::ansiEscapeWrap($parameter->getClass()->name . ' ', '36', $ansiColors); } else { $parameterDump .= '<span class="extbase-debug-type">' . htmlspecialchars($parameter->getClass()->name) . '</span>'; } } if ($parameter->isPassedByReference()) { $parameterDump .= '&'; } if ($plainText) { $parameterDump .= self::ansiEscapeWrap('$' . $parameter->name, '37', $ansiColors); } else { $parameterDump .= '<span class="extbase-debug-property">' . htmlspecialchars('$' . $parameter->name) . '</span>'; } if ($parameter->isOptional()) { $parameterDump .= ' = '; if ($plainText) { $parameterDump .= self::ansiEscapeWrap(var_export($parameter->getDefaultValue(), true), '33', $ansiColors); } else { $parameterDump .= '<span class="extbase-debug-string">' . htmlspecialchars(var_export($parameter->getDefaultValue(), true)) . '</span>'; } } $params[] = $parameterDump; } $dump .= implode(', ', $params); if ($plainText) { $dump .= self::ansiEscapeWrap(') {' . PHP_EOL, '33', $ansiColors); } else { $dump .= '<span class="extbase-debug-closure">) {' . PHP_EOL . '</span>'; } $lines = file($reflectionFunction->getFileName()); for ($l = $reflectionFunction->getStartLine(); $l < $reflectionFunction->getEndLine() - 1; ++$l) { $dump .= $plainText ? $lines[$l] : htmlspecialchars($lines[$l]); } $dump .= str_repeat(self::PLAINTEXT_INDENT, $level); if ($plainText) { $dump .= self::ansiEscapeWrap('}' . PHP_EOL, '33', $ansiColors); } else { $dump .= '<span class="extbase-debug-closure">}</span>'; } } else { if (get_class($object) === 'stdClass') { $objReflection = new \ReflectionObject($object); $properties = $objReflection->getProperties(); } else { $classReflection = new \ReflectionClass(get_class($object)); $properties = $classReflection->getProperties(); } foreach ($properties as $property) { if (self::isBlacklisted($property)) { continue; } $dump .= PHP_EOL . str_repeat(self::PLAINTEXT_INDENT, $level); if ($plainText) { $dump .= self::ansiEscapeWrap($property->getName(), '37', $ansiColors); } else { $dump .= '<span class="extbase-debug-property">' . htmlspecialchars($property->getName()) . '</span>'; } $dump .= ' => '; $property->setAccessible(true); $visibility = $property->isProtected() ? 'protected' : ($property->isPrivate() ? 'private' : 'public'); if ($plainText) { $dump .= self::ansiEscapeWrap($visibility, '42;30', $ansiColors) . ' '; } else { $dump .= '<span class="extbase-debug-visibility">' . $visibility . '</span>'; } $dump .= self::renderDump($property->getValue($object), $level, $plainText, $ansiColors); if ($object instanceof \TYPO3\CMS\Extbase\DomainObject\AbstractDomainObject && !$object->_isNew() && $object->_isDirty($property->getName())) { if ($plainText) { $dump .= ' ' . self::ansiEscapeWrap('modified', '43;30', $ansiColors); } else { $dump .= '<span class="extbase-debug-dirty">modified</span>'; } } } } } return $dump; }
/** * @test */ public function setParticipantsUpdatesTotalPrice() { $this->subject = $this->getAccessibleMock(Reservation::class, ['getLesson']); $singlePrice = 123.45; $totalPrice = 2 * $singlePrice; $firstParticipant = new Person(); $secondParticipant = new Person(); $objectStorageContainingTwoParticipants = new ObjectStorage(); $objectStorageContainingTwoParticipants->attach($firstParticipant); $objectStorageContainingTwoParticipants->attach($secondParticipant); $lesson = $this->getMock(Schedule::class, ['getPrice']); $lesson->expects($this->any())->method('getPrice')->will($this->returnValue($singlePrice)); $this->subject->expects($this->any())->method('getLesson')->will($this->returnValue($lesson)); $this->subject->setParticipants($objectStorageContainingTwoParticipants); $this->assertSame($totalPrice, $this->subject->getTotalPrice()); }
/** * Get an existing items from the references that matches the file * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\GeorgRinger\News\Domain\Model\FileReference> $items * @param \TYPO3\CMS\Core\Resource\File $file * @return bool|FileReference */ protected function getIfFalRelationIfAlreadyExists(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $items, \TYPO3\CMS\Core\Resource\File $file) { $result = FALSE; if ($items->count() !== 0) { /** @var $item FileReference */ foreach ($items as $item) { // only check already persisted items if ($item->getFileUid() === (int) $file->getUid() || $item->getUid() && $item->getOriginalResource()->getName() === $file->getName() && $item->getOriginalResource()->getSize() === (int) $file->getSize()) { $result = $item; break; } } } return $result; }
/** * @test */ public function getModelDataRecursiveWithObjectStorageTest() { $testDate = new \DateTime(); $model = new MyNestedModelWithObjectStorage(); $model->setDate($testDate); $model->_setProperty('uid', 1); $childModel = new MyNestedModel(); $childModel->setDate($testDate); $childModel->_setProperty('uid', 2); $children = new ObjectStorage(); $children->attach($model); $children->attach($childModel); $model->setChildren($children); $expectedOutput = array('base' => 'Base', 'date' => $testDate, 'child' => array('uid' => null, 'pid' => null, '__class' => 'Cundd\\Rest\\Tests\\MyModel', 'name' => 'Initial value'), 'uid' => 1, 'pid' => null, '__class' => 'Cundd\\Rest\\Tests\\MyNestedModelWithObjectStorage', 'children' => array(0 => 'http:///rest/cundd-rest-tests-my_nested_model_with_object_storage/1/', 1 => array('base' => 'Base', 'date' => $testDate, 'uid' => 2, 'pid' => null, '__class' => 'Cundd\\Rest\\Tests\\MyNestedModel', 'child' => array('name' => 'Initial value', 'uid' => null, 'pid' => null, '__class' => 'Cundd\\Rest\\Tests\\MyModel')))); $this->assertEquals($expectedOutput, $this->fixture->getModelData($model)); // Make sure the same result is returned if getModelData() is invoked again $this->assertEquals($expectedOutput, $this->fixture->getModelData($model)); }
/** * Test for isValid() * * @param string $value * @param bool $expectedResult * @return void * @dataProvider validateIsValidReturnsBoolDataProvider * @test */ public function validateIsValidReturnsBool($value, $expectedResult) { $mail = new Mail(); $field = new Field(); $field->setType(1); $answer1 = new Answer(); $answer1->setValueType(3); $answer1->setValue($value); $answer1->setField($field); $objectStorage = new ObjectStorage(); $objectStorage->attach($answer1); $mail->setAnswers($objectStorage); if ($expectedResult === false) { $this->generalValidatorMock->expects($this->once())->method('setErrorAndMessage'); } else { $this->generalValidatorMock->expects($this->never())->method('setErrorAndMessage'); } $this->generalValidatorMock->_callRef('isValid', $mail); }
/** * hasFormAnUploadFieldReturnBool Test * * @return void * @test */ public function hasFormAnUploadFieldReturnBool() { $fieldObjectStorage = new ObjectStorage(); $field = new Field(); $field->setType('captcha'); $fieldObjectStorage->attach($field); $field2 = new Field(); $field2->setType('file'); $fieldObjectStorage->attach($field2); $pagesObjectStorage = new ObjectStorage(); $page = new Page(); $page->setFields($fieldObjectStorage); $pagesObjectStorage->attach($page); $form = new Form(); $form->setPages($pagesObjectStorage); $this->assertTrue(BasicFileUtility::hasFormAnUploadField($form)); $field2->setType('textarea'); $this->assertFalse(BasicFileUtility::hasFormAnUploadField($form)); }
/** * @test */ public function tansientObjectsWithObjectStorageAreConvertedToAnArrayOfProperties() { $mockValueObject = new ValueObjectFixture(); $objectStorage = new ObjectStorage(); $mockValueObject->name = 'foo'; $mockValueObject2 = new ValueObjectFixture(); $mockValueObject2->name = 'bar'; $objectStorage->attach($mockValueObject2); $mockValueObject->object = $objectStorage; $uriBuilder = new UriBuilder(); $actualResult = $uriBuilder->convertTransientObjectToArray($mockValueObject); $expectedResult = array('name' => 'foo', 'object' => array(array('name' => 'bar', 'uid' => null, 'pid' => null, 'object' => null)), 'uid' => null, 'pid' => null); $this->assertEquals($expectedResult, $actualResult); }
/** * @test */ public function prepareObjectsSliceReturnsCorrectPortionForObjectStorageAndSecondPage() { $this->controller->_set('currentPage', 2); $objects = new ObjectStorage(); for ($i = 0; $i <= 55; $i++) { $item = new \stdClass(); $objects->attach($item); } $this->controller->_set('objects', $objects); $expectedPortion = array(); for ($j = 10; $j <= 19; $j++) { $expectedPortion[] = $objects->toArray()[$j]; } $this->assertSame($expectedPortion, $this->controller->_call('prepareObjectsSlice', 10, 10)); }
/** * Adds given elements of an array to given object storage * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage * @param array $arrayToBeAdded */ protected function addObjectsToObjectStorageByArray(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage, $arrayToBeAdded) { foreach ($arrayToBeAdded as $key => $value) { $objectStorage->attach($value, $key); } }
/** * Returns the given result as property value of the specified property type. * * @param DomainObjectInterface $parentObject * @param string $propertyName * @param mixed $result The result * @return mixed */ public function mapResultToPropertyValue(DomainObjectInterface $parentObject, $propertyName, $result) { $propertyValue = null; if ($result instanceof Persistence\Generic\LoadingStrategyInterface) { $propertyValue = $result; } else { $propertyMetaData = $this->reflectionService->getClassSchema(get_class($parentObject))->getProperty($propertyName); if (in_array($propertyMetaData['type'], ['array', 'ArrayObject', 'SplObjectStorage', \TYPO3\CMS\Extbase\Persistence\ObjectStorage::class], true)) { $objects = []; foreach ($result as $value) { $objects[] = $value; } if ($propertyMetaData['type'] === 'ArrayObject') { $propertyValue = new \ArrayObject($objects); } elseif (in_array($propertyMetaData['type'], [\TYPO3\CMS\Extbase\Persistence\ObjectStorage::class], true)) { $propertyValue = new Persistence\ObjectStorage(); foreach ($objects as $object) { $propertyValue->attach($object); } $propertyValue->_memorizeCleanState(); } else { $propertyValue = $objects; } } elseif (strpbrk($propertyMetaData['type'], '_\\') !== false) { if (is_object($result) && $result instanceof Persistence\QueryResultInterface) { $propertyValue = $result->getFirst(); } else { $propertyValue = $result; } } } return $propertyValue; }
/** * * * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object * @param string $fieldname * @param \Iterator $fileReferences * @param string $key * @throws \Exception */ public function saveAll(\TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $object, $fieldname, \TYPO3\CMS\Extbase\Persistence\ObjectStorage $fileReferences, $key = '') { $someSavedAlready = FALSE; $savableReferences = array(); foreach ($fileReferences as $ref) { if (!$ref instanceof FileReference) { $fileReferences->detach($ref); continue; } $savableReferences[] = $ref; $uid = $ref->getUid(); if ($uid) { $someSavedAlready = TRUE; $keepers[] = $uid; } } // This is a new $object, unlikely to have any existing FileReferences for this field. if (!$object->getUid() || !$someSavedAlready) { $i = 0; foreach ($savableReferences as $ref) { $this->save($ref, $key); $this->limbo->clearHeld($key . '.' . $i++); } return; } // Remove FileReferences for this field, unless we're keeping them. $datamap = $this->dataMapper->getDataMap(get_class($object)); $this->removeFileReferences($object->getUid(), $datamap->getTableName(), $fieldname, $keepers); // Save any new ones $i = 0; foreach ($savableReferences as $ref) { $this->save($ref, $key); // We need to do this because, no matter which reference // is loaded, we need to clear the them all. And $this->save() // doesn't do that exactly. $this->limbo->clearHeld($key . '.' . $i++); } }
/** * @test */ public function returnsArrayForTypeObjectStorage() { $domainObject = new Foo(); $storage = new ObjectStorage(); $storage->attach($domainObject); $viewHelper = $this->getAccessibleMock('FluidTYPO3\\Vhs\\ViewHelpers\\Variable\\ConvertViewHelper', array('renderChildren')); $viewHelper->expects($this->once())->method('renderChildren')->will($this->returnValue($storage)); $viewHelper->setArguments(array('type' => 'array')); $converted = $viewHelper->render(); $this->assertInternalType('array', $converted); $this->assertEquals(1, count($converted)); }
/** * @param mixed $object * @return integer|NULL */ public function getPosition($object) { $this->initialize(); return parent::getPosition($object); }
/** * Persists an object storage. Objects of a 1:n or m:n relation are queued and processed with the parent object. A 1:1 relation * gets persisted immediately. Objects which were removed from the property were detached from the parent object. They will not be * deleted by default. You have to annotate the property with "@cascade remove" if you want them to be deleted as well. * * @param \TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage The object storage to be persisted. * @param \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject The parent object. One of the properties holds the object storage. * @param string $propertyName The name of the property holding the object storage. * @param array &$row The row array of the parent object to be persisted. It's passed by reference and gets filled with either a comma separated list of uids (csv) or the number of contained objects. * @return void */ protected function persistObjectStorage(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $objectStorage, \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface $parentObject, $propertyName, array &$row) { $className = get_class($parentObject); $columnMap = $this->dataMapper->getDataMap($className)->getColumnMap($propertyName); $propertyMetaData = $this->reflectionService->getClassSchema($className)->getProperty($propertyName); foreach ($this->getRemovedChildObjects($parentObject, $propertyName) as $removedObject) { $this->detachObjectFromParentObject($removedObject, $parentObject, $propertyName); if ($columnMap->getTypeOfRelation() === \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap::RELATION_HAS_MANY && $propertyMetaData['cascade'] === 'remove') { $this->removeEntity($removedObject); } } $currentUids = array(); $sortingPosition = 1; $updateSortingOfFollowing = false; foreach ($objectStorage as $object) { /** @var DomainObjectInterface $object */ if (empty($currentUids)) { $sortingPosition = 1; } else { $sortingPosition++; } $cleanProperty = $parentObject->_getCleanProperty($propertyName); if ($object->_isNew()) { $this->insertObject($object); $this->attachObjectToParentObject($object, $parentObject, $propertyName, $sortingPosition); // if a new object is inserted, all objects after this need to have their sorting updated $updateSortingOfFollowing = true; } elseif ($cleanProperty === null || $cleanProperty->getPosition($object) === null) { // if parent object is new then it doesn't have cleanProperty yet; before attaching object it's clean position is null $this->attachObjectToParentObject($object, $parentObject, $propertyName, $sortingPosition); // if a relation is dirty (speaking the same object is removed and added again at a different position), all objects after this needs to be updated the sorting $updateSortingOfFollowing = true; } elseif ($objectStorage->isRelationDirty($object) || $cleanProperty->getPosition($object) !== $objectStorage->getPosition($object)) { $this->updateRelationOfObjectToParentObject($object, $parentObject, $propertyName, $sortingPosition); $updateSortingOfFollowing = true; } elseif ($updateSortingOfFollowing) { if ($sortingPosition > $objectStorage->getPosition($object)) { $this->updateRelationOfObjectToParentObject($object, $parentObject, $propertyName, $sortingPosition); } else { $sortingPosition = $objectStorage->getPosition($object); } } $currentUids[] = $object->getUid(); } if ($columnMap->getParentKeyFieldName() === null) { $row[$columnMap->getColumnName()] = implode(',', $currentUids); } else { $row[$columnMap->getColumnName()] = $this->dataMapper->countRelated($parentObject, $propertyName); } }
/** * @test */ public function participantCanBeRemoved() { $participants = new ObjectStorage(); /** @var Person $mockParticipant */ $mockParticipant = $this->getMock(Person::class, [], [], '', false); $participants->attach($mockParticipant); $this->subject->setParticipants($participants); $this->subject->removeParticipant($mockParticipant); $this->assertFalse($this->subject->getParticipants()->contains($mockParticipant)); }