/** * Set properties of an object/array in cobj->LOAD_REGISTER which can then * be used to be loaded via TS with register:name * * @param string $properties comma separated list of properties * @param mixed $object object or array to get the properties * @param string $prefix optional prefix * @return void */ public static function setRegisterProperties($properties, $object, $prefix = 'news') { if (!empty($properties) && !is_null($object)) { $cObj = t3lib_div::makeInstance('tslib_cObj'); $items = t3lib_div::trimExplode(',', $properties, TRUE); $register = array(); foreach ($items as $item) { $key = $prefix . ucfirst($item); try { $register[$key] = Tx_Extbase_Reflection_ObjectAccess::getProperty($object, $item); } catch (Exception $e) { t3lib_div::devLog($e->getMessage(), 'news', t3lib_div::SYSLOG_SEVERITY_WARNING); } } $cObj->LOAD_REGISTER($register, ''); } }
/** * Gets a property path from a given object or array. * * If propertyPath is "bla.blubb", then we first call getProperty($object, 'bla'), * and on the resulting object we call getProperty(..., 'blubb'). * * For arrays the keys are checked likewise. * * @param mixed $subject An object or array * @param string $propertyPath * @return mixed Value of the property */ protected function getPropertyPath($subject, $propertyPath, Tx_Fluid_Core_Rendering_RenderingContextInterface $renderingContext) { $propertyPathSegments = explode('.', $propertyPath); foreach ($propertyPathSegments as $pathSegment) { if (is_object($subject) && Tx_Extbase_Reflection_ObjectAccess::isPropertyGettable($subject, $pathSegment)) { $subject = Tx_Extbase_Reflection_ObjectAccess::getProperty($subject, $pathSegment); } elseif ((is_array($subject) || $subject instanceof ArrayAccess) && isset($subject[$pathSegment])) { $subject = $subject[$pathSegment]; } else { return NULL; } if ($subject instanceof Tx_Fluid_Core_Parser_SyntaxTree_RenderingContextAwareInterface) { $subject->setRenderingContext($renderingContext); } } return $subject; }
/** * @param string $term * @return string */ public function autocompleteAction($term) { $searchProperty = $this->widgetConfiguration['searchProperty']; $query = $this->widgetConfiguration['objects']->getQuery(); $constraint = $query->getConstraint(); if ($constraint !== NULL) { $query->matching($query->logicalAnd($constraint, $query->like($searchProperty, '%' . $term . '%', FALSE))); } else { $query->matching($query->like($searchProperty, '%' . $term . '%', FALSE)); } $results = $query->execute(); $output = array(); foreach ($results as $singleResult) { $val = Tx_Extbase_Reflection_ObjectAccess::getProperty($singleResult, $searchProperty); $output[] = array('id' => $val, 'label' => $val, 'value' => $val); } return json_encode($output); }
/** * Retrieves the selected value(s) * * @return mixed value string or an array of strings * @author Bastian Waidelich <*****@*****.**> */ protected function getSelectedValue() { $value = $this->getValue(); if (!$this->arguments->hasArgument('optionValueField')) { return $value; } if (!is_array($value) && !$value instanceof Iterator) { if (is_object($value)) { return Tx_Extbase_Reflection_ObjectAccess::getProperty($value, $this->arguments['optionValueField']); } else { return $value; } } $selectedValues = array(); foreach ($value as $selectedValueElement) { if (is_object($selectedValueElement)) { $selectedValues[] = Tx_Extbase_Reflection_ObjectAccess::getProperty($selectedValueElement, $this->arguments['optionValueField']); } else { $selectedValues[] = $selectedValueElement; } } return $selectedValues; }
/** * Gets the value to use as sorting value from $object * * @param mixed $object * @return mixed */ protected function getSortValue($object) { $field = $this->arguments['sortBy']; $value = Tx_Extbase_Reflection_ObjectAccess::getProperty($object, $field); if ($value instanceof DateTime) { $value = $value->format('U'); } elseif ($value instanceof Tx_Extbase_Persistence_ObjectStorage) { $value = $value->count(); } elseif (is_array($value)) { $value = count($value); } return $value; }
/** * Checks if the specified property of the given object is valid. * * If at least one error occurred, the result is FALSE. * * @param object $object The object containing the property to validate * @param string $propertyName Name of the property to validate * @return boolean TRUE if the property value is valid, FALSE if an error occured * @api */ public function isPropertyValid($object, $propertyName) { if (!is_object($object)) { throw new InvalidArgumentException('Object expected, ' . gettype($object) . ' given.', 1241099149); } if (!isset($this->propertyValidators[$propertyName])) { return TRUE; } $result = TRUE; foreach ($this->propertyValidators[$propertyName] as $validator) { if ($validator->isValid(Tx_Extbase_Reflection_ObjectAccess::getProperty($object, $propertyName)) === FALSE) { $this->addErrorsForProperty($validator->getErrors(), $propertyName); $result = FALSE; } } return $result; }
/** * @test */ public function getPropertyCanAccessPropertiesOfAnArray() { $array = array('key' => 'value'); $expected = Tx_Extbase_Reflection_ObjectAccess::getProperty($array, 'key'); $this->assertEquals($expected, 'value', 'getProperty does not work with Array property.'); }
/** * Gets files uploaded through field name $name * * @param Tx_Extbase_DomainObject_DomainObjectInterface $domainObject * @param string $propertyName Index name of the files in $_FILES * @param string $objectType Optional class name to use for uploaded file resources * @return Tx_Tool_Resource_FileResourceObjectStorage * @api */ public function getUploadedFiles(Tx_Extbase_DomainObject_DomainObjectInterface &$domainObject, $propertyName, $objectType = NULL) { if ($objectType === NULL) { $objectType = 'Tx_Tool_Resource_FileResource'; } $namespace = $this->domainService->getPluginNamespace($domainObject); $fileObjectStorage = $this->objectManager->create('Tx_Tool_Resource_FileResourceObjectStorage'); $postFiles = Tx_Extbase_Reflection_ObjectAccess::getProperty($_FILES[$namespace]['tmp_name'], $propertyName); if (is_array($postFiles) === FALSE) { $filename = $postFiles; $targetFilename = Tx_Extbase_Reflection_ObjectAccess::getProperty($_FILES[$namespace]['name'], $propertyName); if ($targetFilename && $targetFilename != '') { $object = $this->objectManager->create($objectType, $filename); $object->setTargetFilename($targetFilename); $fileObjectStorage->attach($object); return $fileObjectStorage; } } $numFiles = count($postFiles); for ($i = 0; $i < $numFiles; $i++) { $filename = Tx_Extbase_Reflection_ObjectAccess::getProperty($_FILES[$namespace]['tmp_name'], $propertyName . '.' . $i); $targetFilename = Tx_Extbase_Reflection_ObjectAccess::getProperty($_FILES[$namespace]['name'], $propertyName . '.' . $i); if ($targetFilename && $targetFilename != '') { if (is_file($filename)) { $object = $this->objectManager->get($objectType, $filename); $object->setTargetFilename($targetFilename); $fileObjectStorage->attach($object); } } } return $fileObjectStorage; }
/** * Groups the given array by the specified groupBy property. * * @param array $elements The array / traversable object to be grouped * @param string $groupBy Group by this property * @return array The grouped array in the form array('keys' => array('key1' => [key1value], 'key2' => [key2value], ...), 'values' => array('key1' => array([key1value] => [element1]), ...), ...) * @author Bastian Waidelich <*****@*****.**> */ protected function groupElements(array $elements, $groupBy) { $groups = array('keys' => array(), 'values' => array()); foreach ($elements as $key => $value) { if (is_array($value)) { $currentGroupIndex = isset($value[$groupBy]) ? $value[$groupBy] : NULL; } elseif (is_object($value)) { $currentGroupIndex = Tx_Extbase_Reflection_ObjectAccess::getProperty($value, $groupBy); } else { throw new Tx_Fluid_Core_ViewHelper_Exception('GroupedForViewHelper only supports multi-dimensional arrays and objects', 1253120365); } $currentGroupKeyValue = $currentGroupIndex; if (is_object($currentGroupIndex)) { $currentGroupIndex = spl_object_hash($currentGroupIndex); } $groups['keys'][$currentGroupIndex] = $currentGroupKeyValue; $groups['values'][$currentGroupIndex][$key] = $value; } return $groups; }
/** * Traverses the given object structure in order to transform it into an * array structure. * * @param object $object Object to traverse * @param mixed $configuration Configuration for transforming the given object or NULL * @return array Object structure as an aray * @author Christopher Hlubek <*****@*****.**> * @author Dennis Ahrens <*****@*****.**> */ protected function transformObject($object, $configuration) { // hand over DateTime as ISO formatted string if ($object instanceof DateTime) { return $object->format('c'); } // load LayzyLoadingProxy instances if ($object instanceof Tx_Extbase_Persistence_LazyLoadingProxy) { $object = $object->_loadRealInstance(); } $propertyNames = Tx_Extbase_Reflection_ObjectAccess::getGettablePropertyNames($object); $propertiesToRender = array(); foreach ($propertyNames as $propertyName) { if (isset($configuration['_only']) && is_array($configuration['_only']) && !in_array($propertyName, $configuration['_only'])) { continue; } if (isset($configuration['_exclude']) && is_array($configuration['_exclude']) && in_array($propertyName, $configuration['_exclude'])) { continue; } $propertyValue = Tx_Extbase_Reflection_ObjectAccess::getProperty($object, $propertyName); if (!is_array($propertyValue) && !is_object($propertyValue)) { $propertiesToRender[$propertyName] = $propertyValue; } elseif (isset($configuration['_descend']) && array_key_exists($propertyName, $configuration['_descend'])) { $propertiesToRender[$propertyName] = $this->transformValue($propertyValue, $configuration['_descend'][$propertyName]); } else { } } if (isset($configuration['_exposeObjectIdentifier']) && $configuration['_exposeObjectIdentifier'] === TRUE) { // we don't use the IdentityMap like its done in FLOW3 because there are some cases objects are not registered there. // TODO: rethink this solution - it is really quick and dirty... $propertiesToRender['__identity'] = $object->getUid(); } return $propertiesToRender; }
/** * Maps the given properties to the target object WITHOUT VALIDATING THE RESULT. * If the properties could be set, this method returns TRUE, otherwise FALSE. * Returning TRUE does not mean that the target object is valid and secure! * * Only use this method if you're sure that you don't need validation! * * @param array $propertyNames Names of the properties to map. * @param mixed $source Source containing the properties to map to the target object. Must either be an array, ArrayObject or any other object. * @param object $target The target object * @param array $optionalPropertyNames Names of optional properties. If a property is specified here and it doesn't exist in the source, no error is issued. * @return boolean TRUE if the properties could be mapped, otherwise FALSE * @see mapAndValidate() * @api */ public function map(array $propertyNames, $source, $target, $optionalPropertyNames = array()) { if (!is_object($source) && !is_array($source)) { throw new Tx_Extbase_Property_Exception_InvalidSource('The source object must be a valid object or array, ' . gettype($target) . ' given.', 1187807099); } if (is_string($target) && strpos($target, '_') !== FALSE) { return $this->transformToObject($source, $target, '--none--'); } if (!is_object($target) && !is_array($target)) { throw new Tx_Extbase_Property_Exception_InvalidTarget('The target object must be a valid object or array, ' . gettype($target) . ' given.', 1187807099); } $this->mappingResults = new Tx_Extbase_Property_MappingResults(); if (is_object($target)) { $targetClassSchema = $this->reflectionService->getClassSchema(get_class($target)); } else { $targetClassSchema = NULL; } foreach ($propertyNames as $propertyName) { $propertyValue = NULL; if (is_array($source) || $source instanceof ArrayAccess) { if (isset($source[$propertyName])) { $propertyValue = $source[$propertyName]; } } else { $propertyValue = Tx_Extbase_Reflection_ObjectAccess::getProperty($source, $propertyName); } if ($propertyValue === NULL && !in_array($propertyName, $optionalPropertyNames)) { $this->mappingResults->addError(new Tx_Extbase_Error_Error("Required property '{$propertyName}' does not exist.", 1236785359), $propertyName); } else { if ($targetClassSchema !== NULL && $targetClassSchema->hasProperty($propertyName)) { $propertyMetaData = $targetClassSchema->getProperty($propertyName); if (in_array($propertyMetaData['type'], array('array', 'ArrayObject', 'Tx_Extbase_Persistence_ObjectStorage')) && (strpos($propertyMetaData['elementType'], '_') !== FALSE || $propertyValue === '')) { $objects = array(); if (is_array($propertyValue)) { foreach ($propertyValue as $value) { $objects[] = $this->transformToObject($value, $propertyMetaData['elementType'], $propertyName); } } // make sure we hand out what is expected if ($propertyMetaData['type'] === 'ArrayObject') { $propertyValue = new ArrayObject($objects); } elseif ($propertyMetaData['type'] === 'Tx_Extbase_Persistence_ObjectStorage') { $propertyValue = new Tx_Extbase_Persistence_ObjectStorage(); foreach ($objects as $object) { $propertyValue->attach($object); } } else { $propertyValue = $objects; } } elseif ($propertyMetaData['type'] === 'DateTime' || strpos($propertyMetaData['type'], '_') !== FALSE) { $propertyValue = $this->transformToObject($propertyValue, $propertyMetaData['type'], $propertyName); if ($propertyValue === NULL) { continue; } } } elseif ($targetClassSchema !== NULL) { $this->mappingResults->addError(new Tx_Extbase_Error_Error("Property '{$propertyName}' does not exist in target class schema.", 1251813614), $propertyName); } if (is_array($target)) { $target[$propertyName] = $propertyValue; } elseif (Tx_Extbase_Reflection_ObjectAccess::setProperty($target, $propertyName, $propertyValue) === FALSE) { $this->mappingResults->addError(new Tx_Extbase_Error_Error("Property '{$propertyName}' could not be set.", 1236783102), $propertyName); } } } return !$this->mappingResults->hasErrors(); }
protected function getObjectProperty($object) { $current = $object; reset($this->propertyPathParts); foreach ($this->propertyPathParts as $part) { $current = Tx_Extbase_Reflection_ObjectAccess::getProperty($current, $part); } return $current; }
/** * Does $propertyName on $instance contain a data type which supports deflation? * * @param object $instance Instance of an object, DomainObject included * @param string $propertyName String name of property on DomainObject instance which is up for assertion * @return boolean * @throws RuntimeException */ protected function assertSupportsDeflation($instance, $propertyName) { $className = get_class($instance); $gettableProperties = $this->reflectionService->getClassPropertyNames($className); if (FALSE === in_array($propertyName, $gettableProperties)) { return FALSE; } try { $value = Tx_Extbase_Reflection_ObjectAccess::getProperty($instance, $propertyName, TRUE); } catch (RuneimeException $error) { $getter = 'get' . ucfirst($propertyName); if (FALSE === method_exists($instance, $getter)) { return FALSE; } t3lib_div::sysLog('MarshallService encountered an error while attempting to retrieve the value of ' . $className . '::$' . $propertyName . ' - assuming safe deflation is possible', 'site', t3lib_div::SYSLOG_SEVERITY_NOTICE); return TRUE; } return FALSE === $value instanceof Closure; }
/** * action beCopy * * @param Tx_WoehrlSeminare_Domain_Model_Event $event * @ignorevalidation $event * @return void */ public function beCopyAction($event) { $availableProperties = Tx_Extbase_Reflection_ObjectAccess::getGettablePropertyNames($event); $newEvent = $this->objectManager->create('Tx_WoehrlSeminare_Domain_Model_Event'); foreach ($availableProperties as $propertyName) { if (Tx_Extbase_Reflection_ObjectAccess::isPropertySettable($newEvent, $propertyName) && !in_array($propertyName, array('uid', 'pid', 'subscribers', 'cancelled', 'subEndDateTime', 'subEndDateInfoSent', 'categories', 'discipline'))) { $propertyValue = Tx_Extbase_Reflection_ObjectAccess::getProperty($event, $propertyName); Tx_Extbase_Reflection_ObjectAccess::setProperty($newEvent, $propertyName, $propertyValue); } } foreach ($event->getCategories() as $cat) { $newEvent->addCategory($cat); } foreach ($event->getDiscipline() as $discipline) { $newEvent->addDiscipline($discipline); } if ($event->getGeniusBar()) { $newEvent->setTitle('Wissensbar ' . $newEvent->getContact()->getName()); } else { $newEvent->setTitle($newEvent->getTitle()); } $newEvent->setHidden(TRUE); $this->eventRepository->add($newEvent); $this->flashMessageContainer->add('Die Veranstaltung ' . $newEvent->getTitle() . ' wurde kopiert.'); $this->redirect('beList'); }