public function onKernelException(GetResponseForExceptionEvent $event) { if ($this->container->get('jarves.page_stack')->isAdmin()) { $exception = $event->getException(); $statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500; $view = ['status' => $statusCode, 'error' => get_class($event->getException()), 'message' => $event->getException()->getMessage()]; if ($exception instanceof RestException) { $view['data'] = $exception->getData(); } $previous = $exception; while ($previous = $previous->getPrevious()) { $prev = array('error' => get_class($previous), 'message' => $previous->getMessage()); if ($this->container->get('kernel')->isDebug()) { $trace = Tools::getArrayTrace($previous); $prev['file'] = $previous->getFile(); $prev['line'] = $previous->getLine(); $prev['trace'] = $trace; } $view['previous'][] = $prev; } if ($this->container->get('kernel')->isDebug()) { $trace = Tools::getArrayTrace($event->getException()); $view['file'] = $event->getException()->getFile(); $view['line'] = $event->getException()->getLine(); $view['trace'] = $trace; } $response = new Response(json_encode($view, JSON_PRETTY_PRINT)); $response->headers->set('Content-Type', 'application/json'); $event->setResponse($response); //why does the kernel send a 500 statusCode ? } }
/** * @param array $defaultData * @param null|string[] $filterFields * * @return array * @throws ValidationFailedException */ public function mapData($defaultData = [], $filterFields = null) { $data = $this->getData(); if ($filterFields) { $filterFields = array_flip($filterFields); } $values = []; foreach ($this->getFields() as $field) { $key = lcfirst($field->getId()); if (isset($data[$key])) { $value = $data[$key]; } else { $value = Tools::getArrayPath($data, $key); } if (null === $value && $defaultData) { $value = isset($defaultData[$key]) ? $defaultData[$key] : null; } if (null === $value && $field->getDefault()) { $value = $field->getDefault(); } if ($field['customValue'] && method_exists($this, $method = $field['customValue'])) { $value = $this->{$method}($field, $key); } $field->setValue($value); } foreach ($this->getFields() as $field) { $key = $field->getId(); if ($field['noSave']) { continue; } if ($field->getSaveOnlyFilled() && ($field->getValue() === '' || $field->getValue() === null)) { continue; } if ($field->getCustomSave() && method_exists($this, $method = $field->getCustomSave())) { $this->{$method}($values, $values, $field); continue; } $startKey = explode('.', $key)[0]; if (!$filterFields || isset($filterFields[$startKey])) { if (!($errors = $field->validate())) { $field->mapValues($values); } else { $restException = new ValidationFailedException(sprintf('Field `%s` has a invalid value. [%s]', $key, json_encode($errors)), 420); $restException->setData(['fields' => [$field->getId() => $errors]]); throw $restException; } } } return $values; }
/** * This is a try to increase initial loading performance, but I wasn't lucky. * * @ApiDoc( * section="Backend", * description="Prints all typscript modules combined" * ) * * @Rest\Get("/admin/backend/typescript-modules.ts") * * @return string CCS */ public function loadTypescriptModules() { $newestMTime = 0; $jsContent = ''; foreach ($this->jarves->getConfigs() as $bundleConfig) { $path = $bundleConfig->getBundleClass()->getPath(); $assetInfos = $bundleConfig->getAdminPreloadTypescriptModulesInfo(); foreach ($assetInfos as $assetInfo) { $localPath = $this->jarves->resolveInternalPublicPath($assetInfo->getPath()); $mtime = filemtime($localPath); $newestMTime = max($newestMTime, $mtime); $content = file_get_contents($localPath); $moduleName = sprintf('./bundles/%s/%s', $bundleConfig->getName(), Tools::getRelativePath($localPath, $path . '/Resources/public/')); $jsContent .= "\n/* ts file {$moduleName} */\ndeclare module \"{$moduleName}\" {\n{$content}\n};\n"; } } $ifModifiedSince = $this->pageStack->getRequest()->headers->get('If-Modified-Since'); if (isset($ifModifiedSince) && strtotime($ifModifiedSince) == $newestMTime) { // Client's cache IS current, so we just respond '304 Not Modified'. $response = new Response(); $response->setStatusCode(304); $response->headers->set('Last-Modified', gmdate('D, d M Y H:i:s', $newestMTime) . ' GMT'); return $response; } $expires = 60 * 60 * 24 * 14; //2 weeks $response = new Response(); $response->headers->set('Content-Type', 'application/javascript'); $response->headers->set('Pragma', 'public'); $response->headers->set('Cache-Control', 'max-age=' . $expires); $response->headers->set('Expires', gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT'); // $content = implode($files); $response->setContent($jsContent); return $response; }
public function mapValues(array &$data) { Tools::setArrayPath($data, $this->getFieldDefinition()->getId(), $this->getValue()); }
/** * @param \DOMNode $node * @param string $file */ public function import(\DOMNode $node, $file = null) { if ('bundle' === $node->nodeName) { $imported = $this->importNode($node); $root = realpath($this->getJarves()->getRootDir() . '/../'); foreach ($imported as $property) { $this->imported[$property] = Tools::getRelativePath($file, $root); } } }
/** * Converts given primary values from type string into proper normalized array definition. * This builds the array for the $pk for all of these methods inside this class. * * The primaryKey comes primarily from the REST API. * * admin/object/news/1 * admin/objects?uri=news/1/2 * where * admin/object/news/<id> * admin/objects?uri=news/<id> * * is this ID. * * 1/2/3 => array( array(id =>1),array(id =>2),array(id =>3) ) * 1 => array(array(id => 1)) * idFooBar => array( id => "idFooBar") * idFoo/Bar => array(array(id => idFoo), array(id2 => "Bar")) * 1,45/2,45 => array(array(id => 1, pid = 45), array(id => 2, pid=>45)) * * @param string $pk * * @return array Always a array with primary keys as arrays too. So $return[0] is the first primary key array. Example array(array('id' => 4)) */ public function primaryStringToArray($pk) { if ($pk === '') { return false; } $groups = explode('/', $pk); $result = array(); foreach ($groups as $group) { $item = array(); if ('' === $group) { continue; } $primaryGroups = explode(',', $group); foreach ($primaryGroups as $pos => $value) { if ($ePos = strpos($value, '=')) { $key = substr($value, 0, $ePos); $value = substr($value, $ePos + 1); if (!in_array($key, $this->primaryKeys)) { continue; } } elseif (!$this->primaryKeys[$pos]) { continue; } $key = $this->primaryKeys[$pos]; $item[$key] = Tools::urlDecode($value); } if (count($this->primaryKeys) > count($item)) { foreach ($this->primaryKeys as $pk2) { if (!@$item[$pk2]) { $item[$pk2] = null; } } } if (count($item) > 0) { $result[] = $item; } } return $result; }
public function setValue($value) { parent::setValue(Tools::urlDecode($value)); }
/** * @param $item propel object * @param array $values * @param bool $ignoreNotExistingValues */ public function mapValues(&$item, &$values, $ignoreNotExistingValues = false) { $setted = []; $applyColumn = function ($name) use(&$item, &$values, &$setted, &$ignoreNotExistingValues) { $fieldName = lcfirst($name); $setted[] = $fieldName; $fieldValue = @$values[$fieldName]; if (!isset($values[$fieldName]) && $ignoreNotExistingValues) { return; } $fieldName = ucfirst($fieldName); $set = 'set' . $fieldName; $methodExist = method_exists($item, $set); if ($methodExist) { $item->{$set}($fieldValue); } }; $pluralizer = new StandardEnglishPluralizer(); $self = $this; /** * @param RelationDefinition $relation * * @throws ObjectNotFoundException * @throws \Exception */ $applyRelation = function ($relation) use($self, $pluralizer, &$item, &$values, &$setted, &$ignoreNotExistingValues) { $fieldName = lcfirst($relation->getName()); $fieldValue = isset($values[$fieldName]) ? $values[$fieldName] : null; if (!isset($values[$fieldName]) && $ignoreNotExistingValues) { return; } if ($relation->getType() == AbstractStorage::MANY_TO_MANY || $relation->getType() == AbstractStorage::ONE_TO_MANY) { $name = $pluralizer->getPluralForm($pluralizer->getSingularForm(Tools::underscore2Camelcase($fieldName))); $setItems = 'set' . $name; $clearItems = 'clear' . $name; if (is_array($fieldValue)) { $foreignQuery = $self->getQueryClass($relation->getForeignObjectKey()); $foreignClass = $self->getPhpName($relation->getForeignObjectKey()); $foreignObjClass = $self->objects->getStorageController($relation->getForeignObjectKey()); if ($relation->getType() == AbstractStorage::ONE_TO_MANY) { $coll = new ObjectCollection(); $coll->setModel(ucfirst($foreignClass)); if (!is_array($fieldValue)) { throw new \LogicException(sprintf('Relation `%s` on object %s requires array value, not %s', $relation->getName(), $this->getObjectKey(), gettype($fieldValue))); } foreach ($fieldValue as $foreignItem) { $pk = $self->objects->getObjectPk($relation->getForeignObjectKey(), $foreignItem); $item2 = null; if ($pk) { $propelPk = $self->getPropelPk($pk, $relation->getForeignObjectKey()); $item2 = $foreignQuery->findPk($propelPk); } if (!$item2) { $item2 = new $foreignClass(); } $item2->fromArray($foreignItem, TableMap::TYPE_CAMELNAME); $coll[] = $item2; } $item->{$setItems}($coll); } else { $primaryKeys = array(); if (is_array($fieldValue)) { foreach ($fieldValue as $value) { $primaryKeys[] = $foreignObjClass->normalizePrimaryKey($value); } } $propelPks = array(); foreach ($primaryKeys as $primaryKey) { $propelPks[] = $self->getPropelPk($primaryKey, $relation->getForeignObjectKey()); } $collItems = $foreignQuery->findPks($propelPks); $item->{$setItems}($collItems); } } elseif ($ignoreNotExistingValues) { $item->{$clearItems}(); } } if ($relation->getType() == AbstractStorage::MANY_TO_ONE || $relation->getType() == AbstractStorage::ONE_TO_ONE) { if (!$self->tableMap->hasRelation(ucfirst($fieldName))) { throw new \Exception(sprintf('Relation %s not found in propel object %s (%s)', ucfirst($fieldName), $self->getObjectKey(), $self->getPhpName())); } //try to set the local column of the relation directly, when we get only primary keys $propelRelation = $self->tableMap->getRelation(ucfirst($fieldName)); $localColumns = $propelRelation->getLocalColumns(); $firstColumn = current($localColumns); $hasPrimaryKey = false; if (is_array($fieldValue)) { $foreignColumns = $propelRelation->getForeignColumns(); $firstForeignColumn = current($foreignColumns); $key = lcfirst($firstForeignColumn->getPhpName()); if (isset($fieldValue[$key])) { $fieldValue = $fieldValue[$key]; $hasPrimaryKey = true; } } else { $hasPrimaryKey = true; } if ($hasPrimaryKey) { //set local column of foreign key directly $setter = 'set' . ucfirst($firstColumn->getPhpName()); $item->{$setter}($fieldValue); } else { //we got no primary key, so set values at the object directly $getter = 'get' . ucfirst($relation->getName()); $relatedItem = $item->{$getter}(); if (!$relatedItem) { $class = $propelRelation->getForeignTable()->getClassName(); $relatedItem = new $class(); $setter = 'set' . ucfirst($relation->getName()); $item->{$setter}($relatedItem); } foreach ($fieldValue as $k => $v) { $relatedItem->{'set' . ucfirst($k)}($v); } } } }; foreach ($this->getDefinition()->getFields(true) as $field) { if ($field->isPrimaryKey() && $field->isAutoIncrement()) { continue; } foreach ($field->getFieldType()->getColumns() as $column) { $applyColumn($column->getName()); } } foreach ($this->getDefinition()->getRelations() as $relation) { $applyRelation($relation); } // /* // * all virtual fields which are not present in the object. // * Virtual fields are all methods in the model which have a setter. // * Examples: // * // * setPassword => 'password' // */ // foreach ($values as $fieldName => $fieldValue) { // $fieldName = lcfirst($fieldName); // if (in_array($fieldName, $setted)) { // continue; // } // // $fieldName = ucfirst($fieldName); // $set = 'set' . $fieldName; // $methodExist = method_exists($item, $set); // // if ($methodExist) { // $item->$set($fieldValue); // } // } }
/** * ('@JarvesBundle/Resources/public/test.png') => /var/www/jarves/src/Jarves/Resources/public/test.png * ('@JarvesBundle/Resources/public/test.png', '', true) => src/Jarves/Resources/public/test.png * * ('@JarvesBundle/test.png', 'Resources/public/') => /var/www/jarves/src/Jarves/Resources/public/test.png * ('@JarvesBundle/test.png') => /var/www/jarves/src/Jarves/test.png * * ('images/test.png') => /var/www/jarves/images/webtest.png * * @param string $path * @param string $suffix * @param bool $relativePath * * @return string without trailing slash when relative * * @throws Exceptions\BundleNotFoundException */ public function resolvePath($path, $suffix = '', $relativePath = false) { $path = preg_replace('/:+/', '/', $path); $root = realpath($this->rootDir . '/../'); if ($bundle = $this->getBundleFromPath($path, $bundleName)) { $path = substr($path, strlen($bundleName) + 1); $bundlePath = $bundle->getPath(); $suffix = trim($suffix, '/'); $path = trim($path, '/'); $bundlePath = '/' . trim($bundlePath, '/'); $path = $bundlePath . ($suffix ? '/' . $suffix : '') . '/' . $path; } else { $path = $root . $path; } if ($relativePath) { return Tools::getRelativePath($path, $root); } return $path; }
/** * Converts given object key and the object item to the internal url. * * @static * * @param string $objectKey * @param mixed $primaryValues * * @return string */ public function toUrl($objectKey, $primaryValues) { $url = 'object://' . $objectKey . '/'; if (is_array($primaryValues)) { foreach ($primaryValues as $key => $val) { $url .= Tools::urlEncode($val) . ','; } } else { return $url . Tools::urlEncode($primaryValues); } return substr($url, 0, -1); }
/** * @param resource $image * @param string $path * @param int $quality between 0 and 10 * * @return bool */ public function writeImage($image, $path, $quality = 8) { ob_start(); switch (Tools::getFileExtension($path)) { case 'png': imagepng($image, null, $quality); break; case 'jpeg': case 'jpg': imagejpeg($image, null, $quality * 100); break; case 'gif': imagegif($image); break; } $imageBuffer = ob_get_clean(); return $this->write($path, $imageBuffer); }
/** * @param Request|array $requestData * *@return array */ public function collectData($requestData) { if ($requestData instanceof Request) { $requestData = $requestData->request->all(); } $fields = $this->_fields; $values = []; foreach ($fields as $field) { $key = lcfirst($field->getId()); if (isset($requestData[$key])) { $value = $requestData[$key]; } else { $value = Tools::getArrayPath($requestData, $key); } $values[$key] = $value; } return $values; }
/** * @param Request $request * * @return array */ protected function extractPrimaryKey(Request $request) { $primaryKey = []; foreach ($this->getPrimary() as $pk) { $primaryKey[$pk] = Tools::urlDecode($request->attributes->get($pk)); } return $primaryKey; }
/** * @ApiDoc( * section="Object Browser", * description="General object item list output" * ) * * @Rest\QueryParam(name="url", requirements=".+", strict=true, description="The object url") * @Rest\QueryParam(name="fields", requirements=".+", description="Comma separated list of field names") * @Rest\QueryParam(name="returnKey", requirements=".+", description="If the result should be indexed by the pk") * @Rest\QueryParam(name="returnKeyAsRequested", requirements=".+", description="If the result should be indexed by the pk as requested") * * @Rest\Get("/admin/objects") * * @param ParamFetcher $paramFetcher * * @return array * @throws \Exception * @throws ClassNotFoundException * @throws ObjectNotFoundException */ public function getItemsByUrlAction(ParamFetcher $paramFetcher) { $url = $paramFetcher->get('url'); $fields = $paramFetcher->get('fields'); $returnKey = filter_var($paramFetcher->get('returnKey'), FILTER_VALIDATE_BOOLEAN); $returnKeyAsRequested = filter_var($paramFetcher->get('returnKeyAsRequested'), FILTER_VALIDATE_BOOLEAN); list($objectKey, $objectIds, ) = $this->getObjects()->parseUrl($url); //check if we got a id if ($objectIds[0] === '') { throw new \Exception(sprintf('No id given in uri %s.', $url)); } $definition = $this->getObjects()->getDefinition($objectKey); if (!$definition) { throw new ObjectNotFoundException(sprintf('Object %s can not be found.', $objectKey)); } if ($definition->getExcludeFromREST()) { return null; } $options['extraFields'] = $fields; $options['permissionCheck'] = true; $options['fields'][] = $definition->getLabelField(); if ($definition->getSingleItemLabelField()) { $options['fields'][] = $definition->getSingleItemLabelField(); } $items = array(); if (count($objectIds) == 1) { if ($item = $this->getObjects()->get($objectKey, $objectIds[0], $options)) { $items[] = $item; } } else { foreach ($objectIds as $primaryKey) { if ($item = $this->getObjects()->get($objectKey, $primaryKey, $options)) { $items[] = $item; } } } if ($returnKey || $returnKeyAsRequested) { $res = array(); if ($returnKeyAsRequested) { //map requested id to real ids $requestedIds = explode('/', $this->getObjects()->getCroppedObjectId($url)); $map = array(); foreach ($requestedIds as $id) { $pk = $this->getObjects()->normalizePkString($objectKey, $id); if ($pk) { $map[$this->getObjects()->getObjectUrlId($objectKey, $pk) . ''] = $id; } } if (is_array($items)) { foreach ($items as &$item) { $pk = $this->getObjects()->getObjectUrlId($objectKey, $item); $res[$map[$pk . '']] = $item; } } } else { $primaryKeys = $this->getObjects()->getPrimaries($objectKey); $c = count($primaryKeys); $firstPK = key($primaryKeys); if (is_array($items)) { foreach ($items as &$item) { if ($c > 1) { $keys = array(); foreach ($primaryKeys as $key => $field) { $keys[] = Tools::urlEncode($item[$key]); } $res[implode(',', $keys)] = $item; } else { $res[$item[$firstPK]] = $item; } } } } return $res; } else { return $items; } }
/** * @param string $from scss path * @param string $to css path * @param string $content * @return string */ protected function replaceRelativePaths($from, $to, $content) { $relative = Tools::getRelativePath(dirname($from), dirname($to)) . '/'; $content = preg_replace('/@import \'(?!.*:\\/\\/)([^\\/].*)\'/', '@import \'' . $relative . '$1\'', $content); $content = preg_replace('/@import "(?!.*:\\/\\/)([^\\/].*)"/', '@import "' . $relative . '$1"', $content); $content = preg_replace('/url\\(\'(?!.*:\\/\\/)([^\\/][^\\)]*)\'\\)/', 'url(\'' . $relative . '$1\')', $content); $content = preg_replace('/url\\(\\"(?!.*:\\/\\/)([^\\/][^\\)]*)\\"\\)/', 'url(\\"' . $relative . '$1\\")', $content); $content = preg_replace('/url\\((?!.*data:image)(?!.*:\\/\\/)([^\\/\'].*)\\)/', 'url(' . $relative . '$1)', $content); return $content; }
/** * {@inheritDoc} * * Same as parent method, except: * If we get the PK as path we convert it to internal ID. */ public function primaryStringToArray($primaryKey) { if (is_array($primaryKey)) { return $primaryKey; } if ($primaryKey === '') { return false; } $groups = explode('/', $primaryKey); $result = array(); foreach ($groups as $group) { $item = array(); if ('' === $group) { continue; } $primaryGroups = explode(',', $group); foreach ($primaryGroups as $pos => $value) { if ($ePos = strpos($value, '=')) { $key = substr($value, 0, $ePos); $value = substr($value, $ePos + 1); if (!in_array($key, $this->primaryKeys)) { continue; } } elseif (!$this->primaryKeys[$pos]) { continue; } if (is_numeric($value)) { $value = $this->webFilesystem->getPath($value); } else { $value = Tools::urlDecode($value); } $item['path'] = $value; } if (count($item) > 0) { $result[] = $item; } } return $result; }
public function bootRunTime(Object $object, Configs $configs) { $contentsObjectName = $object->getId() . ucfirst($this->getFieldDefinition()->getId()); $contentsObject = $object->getBundle()->getObject($contentsObjectName); if (!$contentsObject) { $contentsObject = new Object(); $contentsObject->setId($contentsObjectName); if ($object->getWorkspace()) { $contentsObject->setWorkspace(true); } $contentsObject->setAutoCrud(false); $contentsObject->setSearchable(false); $contentsObject->setExcludeFromREST(true); $contentsObject->setNested(true); $contentsObject->setNestedRootAsObject(true); $contentsObject->setNestedRootObject($object->getKey()); $contentsObject->setNestedRootObjectField('foreignId'); $contentsObject->setTable($object->getTable() . '_' . Tools::camelcase2Underscore($this->getFieldDefinition()->getId())); $contentsObject->setStorageService($object->getStorageService()); } $fields = ['id' => ['type' => 'number', 'autoIncrement' => true, 'primaryKey' => true], 'foreignId' => ['type' => 'number'], 'slotId' => ['type' => 'number'], 'sort' => ['type' => 'number'], 'content' => ['type' => 'textarea'], 'template' => ['type' => 'view'], 'type' => ['type' => 'text'], 'hide' => ['type' => 'checkbox'], 'unsearchable' => ['type' => 'checkbox'], 'access_from' => ['type' => 'datetime'], 'access_to' => ['type' => 'datetime'], 'access_from_groups' => ['type' => 'text']]; foreach ($fields as $k => $def) { if (!$contentsObject->getField($k)) { $def['id'] = $k; $field = new Field($def, $object->getJarves()); $contentsObject->addField($field); $configs->addReboot(sprintf('[ContentElements] Added field %s to %s', $k, $contentsObject->getKey())); } } if (!$contentsObject->hasRelation('ForeignObject')) { $relation = new RelationDefinition(); $relation->setName('ForeignObject'); $relation->setType(AbstractStorage::MANY_TO_ONE); $relation->setForeignObjectKey($object->getKey()); $relation->setRefName(ucfirst($this->getFieldDefinition()->getId())); $reference = new RelationReferenceDefinition(); $primaryFields = $object->getPrimaryKeys(); if (1 < count($primaryFields)) { throw new ModelBuildException(sprintf('FieldType `ContentElements` can not be used on the object `%s` with composite PrimaryKey', $object->getId())); } if (0 === count($primaryFields)) { throw new ModelBuildException(sprintf('FieldType `ContentElements` can not be used on the object `%s` with no PrimaryKey', $object->getId())); } $columns = $primaryFields[0]->getFieldType()->getColumns(); if (1 < count($columns)) { throw new ModelBuildException(sprintf('FieldType `ContentElements` can not be used on the object `%s` with composite PrimaryKey', $object->getId())); } $reference->setForeignColumn($columns[0]); $field = $contentsObject->getField('foreignId'); $columns = $field->getFieldType()->getColumns(); $reference->setLocalColumn($columns[0]); $relation->setReferences([$reference]); $contentsObject->addRelation($relation); $configs->addReboot(sprintf('[ContentElements] Added relation ForeignObject to %s', $contentsObject->getKey())); } if (!$contentsObject->getBundle()) { $object->getBundle()->addObject($contentsObject); } if (!$object->hasRelation($this->getFieldDefinition()->getId())) { $relation = new RelationDefinition(); $relation->setName(ucfirst($this->getFieldDefinition()->getId())); $relation->setType(AbstractStorage::ONE_TO_MANY); $relation->setForeignObjectKey($contentsObject->getKey()); $relation->setRefName('ForeignObject'); $reference = new RelationReferenceDefinition(); $primaryFields = $object->getPrimaryKeys(); $columns = $primaryFields[0]->getFieldType()->getColumns(); $reference->setLocalColumn($columns[0]); $field = $contentsObject->getField('foreignId'); $columns = $field->getFieldType()->getColumns(); $reference->setForeignColumn($columns[0]); $relation->setReferences([$reference]); $object->addRelation($relation); $configs->addReboot(sprintf('[ContentElements] Added relation %s to %s', ucfirst($this->getFieldDefinition()->getId()), $object->getKey())); } }
/** * @param \Jarves\Configuration\Object $objectDefinition * @param Configs $configs * @return bool */ protected function defineCrossObject(Object $objectDefinition, Configs $configs) { $changed = false; $bundle = $objectDefinition->getBundle(); $foreignObjectDefinition = $configs->getObject($this->getFieldDefinition()->getObject()); $possibleObjectName = ucfirst($objectDefinition->getId()) . ucfirst($foreignObjectDefinition->getId()); $possibleObjectKey = $bundle->getName() . '/' . $possibleObjectName; if (!($crossObjectKey = $this->getFieldDefinition()->getObjectRelationCrossObjectKey())) { $crossObjectKey = $possibleObjectKey; } $crossObject = $configs->getObject($crossObjectKey); if (!$crossObject) { if (!($crossObject = $configs->getObject($possibleObjectKey))) { $crossObject = new Object(null, $objectDefinition->getJarves()); $crossObject->setId($possibleObjectName); $crossObject->setSearchable(false); $crossObject->setAutoCrud(false); $crossObject->setExcludeFromREST(true); $crossObject->setTable($objectDefinition->getTable() . '_' . Tools::camelcase2Underscore($foreignObjectDefinition->getId())); $changed = true; } } if (!$crossObject->isCrossRef()) { $crossObject->setCrossRef(true); $changed = true; } $leftFieldName = $this->getFieldDefinition()->getObjectRefRelationName() ?: $objectDefinition->getId(); if (!$crossObject->getField($leftFieldName)) { $leftObjectField = new Field(null, $objectDefinition->getJarves()); $leftObjectField->setId($leftFieldName); $leftObjectField->setType('object'); $leftObjectField->setObject($objectDefinition->getKey()); $leftObjectField->setObjectRelation(AbstractStorage::ONE_TO_ONE); $leftObjectField->setPrimaryKey(true); $crossObject->addField($leftObjectField); $changed = true; } if (!$crossObject->getField($this->getFieldDefinition()->getId())) { $rightObjectField = new Field(null, $objectDefinition->getJarves()); $rightObjectField->setId($this->getFieldDefinition()->getId()); $rightObjectField->setType('object'); $rightObjectField->setObject($foreignObjectDefinition->getKey()); $rightObjectField->setObjectRelation(AbstractStorage::ONE_TO_ONE); $rightObjectField->setPrimaryKey(true); $crossObject->addField($rightObjectField); $changed = true; } if (!$crossObject->getBundle()) { //we created a new object $bundle->addObject($crossObject); } return $changed; }
/** * Get a condition object for item listings. * * @param string $objectKey * * @return Condition */ public function getListingCondition($objectKey) { $objectKey = Objects::normalizeObjectKey($objectKey); $obj = $this->objects->getStorageController($objectKey); $rules = self::getRules($objectKey, static::MODE_LISTING); if (count($rules) === 0) { return null; } if ($this->getCaching()) { $cacheKey = md5($objectKey); $cached = $this->cacher->getDistributedCache('core/acl/listing/' . $cacheKey); if (null !== $cached) { return $cached; } } $condition = ''; $primaryList = $this->objects->getPrimaryList($objectKey); $primaryKey = current($primaryList); $denyList = array(); $conditionObject = new Condition(null, $this->jarves); foreach ($rules as $rule) { if ($rule['constraint_type'] === ACL::CONSTRAINT_EXACT) { //todo $rule['constraint_code'] can be a (urlencoded) composite pk //todo constraint_code is always urlencoded; $condition = Condition::create(array($primaryKey, '=', Tools::urlDecode($rule['constraint_code'])), $this->jarves); } if ($rule['constraint_type'] === ACL::CONSTRAINT_CONDITION) { $condition = Condition::create($rule['constraint_code'], $this->jarves); } if ($rule['constraint_type'] === ACL::CONSTRAINT_ALL) { $condition = array('1', '=', '1'); } elseif ($rule['sub']) { $subCondition = $obj->getNestedSubCondition($condition); if ($subCondition) { $condition = array($condition, 'OR', $subCondition); } } if ($rule['access'] === 1) { if ($denyList) { $condition = array($condition, 'AND NOT', $denyList); $conditionObject->addOr($condition); // $conditionObject->add('AND NOT', $denyList); } else { $conditionObject->addOr($condition); } } if ($rule['access'] !== 1) { if ($denyList) { $denyList[] = 'AND NOT'; } $denyList[] = $condition; } } if (!$conditionObject->hasRules()) { $conditionObject->addAnd(array('1', '!=', '1')); } if ($this->getCaching()) { $cacheKey = md5($objectKey); $this->cacher->setDistributedCache('core/acl/listing/' . $cacheKey, $conditionObject); } return $conditionObject; }
/** * @param $fieldId * * @return Field */ public function getField($fieldId) { if (null !== $this->fields) { $id = Tools::camelcase2Underscore($fieldId); return isset($this->fields[$id]) ? $this->fields[$id] : null; } }
protected function setupColumnAttributes(ColumnDefinitionInterface $column, $xmlColumn) { $xmlColumn['name'] = Tools::camelcase2Underscore($column->getName()); $type = $column->getSqlDataType(); $size = null; if (false !== ($pos = strpos($type, '('))) { $size = trim(str_replace(['(', ')'], '', substr($type, $pos))); $type = substr($type, 0, $pos); } $propelType = $this->getPropelColumnType($type); $xmlColumn['type'] = strtoupper($propelType); if ($size) { $xmlColumn['size'] = $size; } }
/** * Appends the xm structure with the given values. * * @param string $key * @param mixed $value * @param \DOMNode $node * @param boolean $arrayType * @param boolean $printDefaults * * @param bool $printComments * @return \DOMNode * @throws \Exception */ public function appendXmlValue($key, $value, \DOMNode $node, $arrayType = false, $printDefaults = false, $printComments = false) { $doc = $node instanceof \DOMDocument ? $node : $node->ownerDocument; $append = function ($el) use($node) { return $node->appendChild($el); }; if ($printComments && property_exists(get_called_class(), $key) && ($comment = $this->getPropertyDescription($key))) { if (in_array($key, $this->attributes)) { $comment = Tools::indentString($comment, 4); $comment = sprintf("\n\n Attribute %s:\n\n%s", $key, $comment); $this->lastRootElementComment->appendData($comment); } else { $comment = "\n" . Tools::indentString($comment, 2); $comment = $doc->createComment($comment); $append($comment); } } if (null !== $this->nodeValueVar && $key == $this->nodeValueVar) { $textNode = $doc->createTextNode($value); $result = $append($textNode); } else { if (is_scalar($value) || null === $value) { $value = is_bool($value) ? $value ? 'true' : 'false' : (string) $value; if ($arrayType) { $element = $doc->createElement(@$this->arrayIndexNames[$arrayType] ?: 'item'); if (!is_integer($key)) { $element->setAttribute('key', (string) $key); } $element->nodeValue = $value; $result = $append($element); } else { if (in_array($key, $this->attributes)) { // $key = Tools::camelcase2Char($key, '-'); $result = $node->setAttribute($key, $value); } else { $elementName = is_integer($key) ? $this->arrayIndexNames[$arrayType] ?: 'item' : $key; // $elementName = Tools::camelcase2Char($elementName, '-'); $element = $doc->createElement($elementName); $element->nodeValue = $value; $result = $append($element); } } } else { if (is_array($value)) { if ($arrayName = $this->getElementArrayName($key)) { $element = $node; } else { $elementName = is_integer($key) ? $this->arrayIndexNames[$arrayType] ?: 'item' : $key; // $elementName = Tools::camelcase2Char($elementName, '-'); $element = $doc->createElement($elementName); } foreach ($value as $k => $v) { $this->appendXmlValue($k, $v, $element, $key, $printDefaults, $printComments); } if (!$arrayName) { $result = $append($element); } else { $result = $element; } } else { if ($value instanceof Model) { $result = $value->appendXml($node, $printDefaults, $printComments); } } } } return $result; }
/** * Returns the column name for database access. * * @return string */ public function getColumnName() { return Tools::camelcase2Underscore($this->getId()); }
/** * {@inheritDoc} */ public function getBranch($pk = null, Condition $condition = null, $depth = 1, $scope = null, $options = null) { $result = null; $path = $pk['path']; if ($depth === null) { $depth = 1; } if ($path) { $path = '@' . trim($path, '/@'); $path = str_replace(':', '/', $path); } $c = 0; $offset = $options['offset']; $limit = $options['limit']; $result = array(); if (!$path) { $result = array(); $bundles = array_keys($this->jarves->getBundles()); foreach ($bundles as $bundleName) { $directory = $this->jarves->resolvePath('@' . $bundleName, 'Resources/views', true); if (!$this->localFilesystem->has($directory)) { continue; } $file = $this->localFilesystem->getFile($directory); if (!$file) { $result[] = $directory; continue; } $file = $file->toArray(); $file['name'] = $bundleName; $file['path'] = $bundleName; if ($offset && $offset > $c) { continue; } if ($limit && $limit < $c) { continue; } if ($condition && $condition->hasRules() && !$this->conditionOperator->satisfy($condition, $file)) { $result[] = $directory; continue; } $c++; if ($depth > 0) { $children = self::getBranch(array('path' => $bundleName), $condition, $depth - 1); $file['_childrenCount'] = count($children); if ($depth > 1 && $file['type'] == 'dir') { $file['_children'] = $children; } } } } else { if (!($bundleName = $this->jarves->getBundleFromPath($path))) { return []; } $directory = $this->jarves->resolvePath($path, 'Resources/views', true) . '/'; if (!$this->localFilesystem->has($directory)) { return []; } $files = $this->localFilesystem->getFiles($directory); foreach ($files as $file) { $item = $file->toArray(); if ($condition && $condition->hasRules() && !$this->conditionOperator->satisfy($condition, $item, 'jarves/file')) { continue; } $c++; if ($offset && $offset >= $c) { continue; } if ($limit && $limit < $c) { continue; } $item = array('name' => $this->buildPath($path . '/' . Tools::getRelativePath($item['path'], $directory)), 'path' => $this->buildPath($path . '/' . Tools::getRelativePath($item['path'], $directory))); if ($file->isDir()) { $children = self::getBranch(array('path' => $item['path']), $condition, $depth - 1); foreach ($children as $child) { // $child['name'] = $item['name'] . '/' . $child['name']; $result[] = $child; } } if ($file->isFile()) { $result[] = $item; } } } return $result; }
public function testUrlEncode() { $encoded = Tools::urlEncode('path/to/test'); $this->assertEquals('path%252Fto%252Ftest', $encoded); }
/** * @param array $conditionRule * @param array $params * @param string $objectKey * @param array $usedFieldNames * @return string */ public function singleConditionToSql(Condition $condition, $conditionRule, &$params, $objectKey, &$usedFieldNames = null) { if ($conditionRule[0] === null) { return ''; } $tableName = ''; if ($condition->isTableNameSet()) { //custom tableName overwrites the tableName from the object definition (for alias use cases for example) $tableName = $condition->getTableName(); } $def = $this->objects->getDefinition($objectKey); if ($def && !$tableName) { $tableName = $def->getTable(); } $columnName = $fieldName = $conditionRule[0]; if (false !== ($pos = strpos($fieldName, '.'))) { $tableName = substr($fieldName, 0, $pos); $columnName = $fieldName = substr($fieldName, $pos + 1); } if ($def) { $field = $def->getField($fieldName); if ($field) { $columns = $field->getFieldType()->getColumns(); if (!$columns) { throw new \RuntimeException("Field {$fieldName} ({$field->getType()}) does not have columns"); } $columnName = Tools::camelcase2Underscore($columns[0]->getName()); } } else { $columnName = Tools::camelcase2Underscore($fieldName); } if (null !== $usedFieldNames) { $usedFieldNames[] = $fieldName; } if (!is_numeric($conditionRule[0])) { $result = ($tableName ? Tools::dbQuote($tableName) . '.' : '') . Tools::dbQuote($columnName) . ' '; } else { $result = $conditionRule[0]; } if (strtolower($conditionRule[1]) == 'regexp') { $result .= strtolower($this->jarvesConfig->getSystemConfig()->getDatabase()->getMainConnection()->getType()) == 'mysql' ? 'REGEXP' : '~'; } else { $result .= $conditionRule[1]; } if (!is_numeric($conditionRule[0])) { if (isset($conditionRule[2]) && $conditionRule[2] !== null) { if ($conditionRule[2] instanceof ConditionSubSelect) { $result .= ' (' . $this->subSelectConditionToSql($conditionRule[2], $params, $objectKey, $usedFieldNames) . ') '; } else { $params[':p' . (count($params) + 1)] = $conditionRule[2]; $p = ':p' . count($params); if (strtolower($conditionRule[1]) == 'in' || strtolower($conditionRule[1]) == 'not in') { $result .= " ({$p})"; } else { $result .= ' ' . $p; } } } } else { $result .= ' ' . ($conditionRule[0] + 0); } return $result; }