Пример #1
0
 public function __construct(RedBeanModel $model = null, $attributeName = null)
 {
     assert('$attributeName === null || is_string($attributeName)');
     assert('$model === null || $model->isAttribute($attributeName)');
     if ($model !== null) {
         $this->attributeName = $attributeName;
         $this->attributeLabels = $model->getAttributeLabelsForAllActiveLanguagesByAttributeName($attributeName);
         $this->attributePropertyToDesignerFormAdapter = new AttributePropertyToDesignerFormAdapter();
         $validators = $model->getValidators($attributeName);
         foreach ($validators as $validator) {
             if ($validator instanceof CDefaultValueValidator) {
                 $this->defaultValue = $validator->value;
             } elseif ($validator instanceof CRequiredValidator) {
                 $this->isRequired = true;
                 $modelAttributesAdapter = new ModelAttributesAdapter($model);
                 if ($modelAttributesAdapter->isStandardAttribute($attributeName) && $modelAttributesAdapter->isStandardAttributeRequiredByDefault($attributeName)) {
                     $this->attributePropertyToDesignerFormAdapter->setUpdateRequiredFieldStatus(false);
                 }
             }
         }
         if ($model instanceof Item && $attributeName != null) {
             $this->isAudited = $model->isAttributeAudited($attributeName);
         }
     }
 }
 /**
  * Copy the account from a related model to a activity items
  * @param RedBeanModel $model
  * @param RedBeanModel $relatedModel
  */
 protected function addRelatedModelAccountToModel(RedBeanModel $model, RedBeanModel $relatedModel)
 {
     $metadata = Activity::getMetadata();
     if ($relatedModel->isRelation('account') && isset($relatedModel->account) && $relatedModel->account->id > 0 && in_array(get_class($relatedModel->account), $metadata['Activity']['activityItemsModelClassNames'])) {
         $model->activityItems->add($relatedModel->account);
     }
 }
 public static function processAfterCopy(RedBeanModel $model, RedBeanModel $copyToModel)
 {
     foreach ($model->tasks as $task) {
         $copyToTask = new Task();
         TaskActivityCopyModelUtil::copy($task, $copyToTask);
         $copyToTask->status = Task::STATUS_NEW;
         $copyToModel->tasks->add($copyToTask);
     }
     $copyToModel->save();
 }
 /**
  *
  * Get model properties as array.
  * return array
  */
 public function getData()
 {
     $data = array();
     $data['id'] = $this->model->id;
     $retrievableAttributes = static::resolveRetrievableAttributesByModel($this->model);
     foreach ($this->model->getAttributes($retrievableAttributes) as $attributeName => $notUsed) {
         $type = ModelAttributeToMixedArrayTypeUtil::getType($this->model, $attributeName);
         $adapterClassName = $type . 'RedBeanModelAttributeValueToArrayValueAdapter';
         if ($type != null && @class_exists($adapterClassName) && !($this->model->isRelation($attributeName) && $this->model->getRelationType($attributeName) != RedBeanModel::HAS_ONE)) {
             $adapter = new $adapterClassName($this->model, $attributeName);
             $adapter->resolveData($data);
         } elseif ($this->model->isOwnedRelation($attributeName) && ($this->model->getRelationType($attributeName) == RedBeanModel::HAS_ONE || $this->model->getRelationType($attributeName) == RedBeanModel::HAS_MANY_BELONGS_TO)) {
             if ($this->model->{$attributeName}->id > 0) {
                 $util = new ModelToArrayAdapter($this->model->{$attributeName});
                 $relatedData = $util->getData();
                 $data[$attributeName] = $relatedData;
             } else {
                 $data[$attributeName] = null;
             }
         } elseif ($this->model->isRelation($attributeName) && $this->model->getRelationType($attributeName) == RedBeanModel::HAS_ONE) {
             if ($this->model->{$attributeName}->id > 0) {
                 $data[$attributeName] = array('id' => $this->model->{$attributeName}->id);
             } else {
                 $data[$attributeName] = null;
             }
         }
     }
     return $data;
 }
 /**
  * Given a model and attributeName, get the min length for that attribute as defined by the metadata rules.
  * @param object $model RedBeanModel
  * @param string $attributeName
  */
 public static function getMinLengthByModelAndAttributeName(RedBeanModel $model, $attributeName)
 {
     assert('is_string($attributeName)');
     $validators = $model->getValidators($attributeName);
     $minLength = null;
     foreach ($validators as $validator) {
         if ($validator instanceof CStringValidator) {
             if ($validator->min !== null) {
                 $minLength = $validator->min;
                 break;
             }
         }
     }
     return $minLength;
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     ZurmoDatabaseCompatibilityUtil::dropStoredFunctionsAndProcedures();
     SecurityTestHelper::createSuperAdmin();
     SecurityTestHelper::createUsers();
     SecurityTestHelper::createGroups();
     SecurityTestHelper::createRoles();
     RedBeanModel::forgetAll();
     //do the rebuild to ensure the tables get created properly.
     ReadPermissionsOptimizationUtil::rebuild();
     //Manually build the test model munge tables.
     ReadPermissionsOptimizationUtil::recreateTable(ReadPermissionsOptimizationUtil::getMungeTableName('OwnedSecurableTestItem'));
     ReadPermissionsOptimizationUtil::recreateTable(ReadPermissionsOptimizationUtil::getMungeTableName('OwnedSecurableTestItem2'));
     $benny = User::getByUsername('benny');
     $model = new OwnedSecurableTestItem();
     $model->member = 'test';
     assert($model->save());
     // Not Coding Standard
     $model = new OwnedSecurableTestItem();
     $model->member = 'test2';
     assert($model->save());
     // Not Coding Standard
     $model = new OwnedSecurableTestItem();
     $model->member = 'test3';
     $model->owner = $benny;
     assert($model->save());
     // Not Coding Standard
     assert(OwnedSecurableTestItem::getCount() == 3);
     // Not Coding Standard
     $model = new OwnedSecurableTestItem2();
     $model->member = 'test5';
     assert($model->save());
     // Not Coding Standard
 }
Пример #7
0
 protected static function generateCampaignItems($campaign, $pageSize)
 {
     if ($pageSize == null) {
         $pageSize = self::DEFAULT_CAMPAIGNITEMS_TO_CREATE_PAGE_SIZE;
     }
     $contacts = array();
     $quote = DatabaseCompatibilityUtil::getQuote();
     $marketingListMemberTableName = RedBeanModel::getTableName('MarketingListMember');
     $campaignItemTableName = RedBeanModel::getTableName('CampaignItem');
     $sql = "select {$quote}{$marketingListMemberTableName}{$quote}.{$quote}contact_id{$quote} from {$quote}{$marketingListMemberTableName}{$quote}";
     // Not Coding Standard
     $sql .= "left join {$quote}{$campaignItemTableName}{$quote} on ";
     $sql .= "{$quote}{$campaignItemTableName}{$quote}.{$quote}contact_id{$quote} ";
     $sql .= "= {$quote}{$marketingListMemberTableName}{$quote}.{$quote}contact_id{$quote}";
     $sql .= "AND {$quote}{$campaignItemTableName}{$quote}.{$quote}campaign_id{$quote} = " . $campaign->id . " ";
     $sql .= "where {$quote}{$marketingListMemberTableName}{$quote}.{$quote}marketinglist_id{$quote} = " . $campaign->marketingList->id;
     $sql .= " and {$quote}{$campaignItemTableName}{$quote}.{$quote}id{$quote} is null limit " . $pageSize;
     $ids = R::getCol($sql);
     foreach ($ids as $contactId) {
         $contacts[] = Contact::getById((int) $contactId);
     }
     if (!empty($contacts)) {
         //todo: if the return value is false, then we might need to catch that since it didn't go well.
         CampaignItem::registerCampaignItemsByCampaign($campaign, $contacts);
         if (count($ids) < $pageSize) {
             return true;
         }
     } else {
         return true;
     }
     return false;
 }
 /**
  * Adds a related model.
  */
 public function add(RedBeanModel $model)
 {
     assert("\$model instanceof {$this->modelClassName}");
     assert('!$this->contains($model)');
     assert('($oldCount = $this->count()) > -1');
     // To save the value only when asserts are enabled.
     $bean = $model->getClassBean($this->modelClassName);
     $this->deferredRelateBeans[] = $bean;
     if (in_array($bean, $this->deferredUnrelateBeans)) {
         self::array_remove_object($this->deferredUnrelateBeans, $bean);
     }
     $this->relatedBeansAndModels[] = $model;
     $this->modified = true;
     assert('$this->count() == $oldCount + 1');
     assert('$this->contains($model)');
 }
 /**
  * @param @modelClassName - the main 'from part' table is this model's table. This is considered the base table
  */
 public function __construct($modelClassName)
 {
     assert('is_string($modelClassName)');
     $tableName = RedBeanModel::getTableName($modelClassName);
     $quote = DatabaseCompatibilityUtil::getQuote();
     $this->baseFromTableName = $tableName;
     $this->addTableCount($tableName);
 }
Пример #10
0
 /**
  * Any changes to the model must be re-cached.
  * @see RedBeanModel::save()
  */
 public function save($runValidation = true, array $attributeNames = null)
 {
     $saved = parent::save($runValidation, $attributeNames);
     if ($saved) {
         GeneralCache::cacheEntry('CustomFieldData' . $this->name, $this);
     }
     return $saved;
 }
Пример #11
0
 public function setUp()
 {
     parent::setUp();
     RedBeanModel::forgetAll();
     $this->setupServerUrl();
     if (!$this->isApiTestUrlConfigured()) {
         $this->markTestSkipped(Zurmo::t('ApiModule', 'API test url is not configured in perInstanceTest.php file.'));
     }
 }
 /**
  * Constructs a new RedBeanModels which is a collection of classes extending model.
  * The models are created lazily.
  * Models are only constructed with beans by the model. Beans are
  * never used by the application directly.
  */
 public function __construct(RedBean_OODBBean $bean, $modelClassName)
 {
     assert('is_string($modelClassName)');
     assert('$modelClassName != ""');
     $this->modelClassName = $modelClassName;
     $tableName = RedBeanModel::getTableName($modelClassName);
     $this->bean = $bean;
     $this->relatedBeansAndModels = array_values(R::related($this->bean, $tableName));
 }
Пример #13
0
 /**
  * Copy attributes from one model to another. If the attributes are relations, then only copy when it is a
  * HAS_ONE variant.  In the case that the relation is an OwnedModel, take special consideration for CurrencyValue
  * CustomField, and MultipleValuesCustomField models. If it is owned and not one of those 3, then it should just
  * copy the OwnedModel nonRelation attributes. An example of that would be Address or Email
  * @param RedBeanModel $model
  * @param RedBeanModel $copyToModel - model to copy attribute values from $model to
  */
 public static function copy(RedBeanModel $model, RedBeanModel $copyToModel)
 {
     $copyToModel->setIsCopied();
     foreach ($model->attributeNames() as $attributeName) {
         if ($attributeName == 'owner') {
             continue;
         }
         $isReadOnly = $model->isAttributeReadOnly($attributeName);
         if (!$model->isRelation($attributeName) && !$isReadOnly) {
             static::copyNonRelation($model, $attributeName, $copyToModel);
         } elseif ($model->isRelation($attributeName) && !$isReadOnly && $model->isRelationTypeAHasOneVariant($attributeName)) {
             static::copyRelation($model, $attributeName, $copyToModel);
         }
     }
     if ($model instanceof OwnedSecurableItem) {
         static::copyRelation($model, 'owner', $copyToModel);
     }
     static::resolveExplicitPermissions($model, $copyToModel);
 }
 /**
  * Make an array of message strings by RedBeanModel errors
  * @param array $errors RedBeanModel errors
  */
 public static function makeMessagesByModel(RedBeanModel $model)
 {
     $messages = array();
     foreach ($model->getErrors() as $attributeName => $errors) {
         foreach ($errors as $relationAttributeName => $errorOrRelatedError) {
             if (is_array($errorOrRelatedError)) {
                 $relationModelClassName = $model->getRelationModelClassName($attributeName);
                 foreach ($errorOrRelatedError as $relatedError) {
                     if ($relatedError != '') {
                         $messages[] = LabelUtil::makeModelAndAttributeNameCombinationLabel(get_class($model), $attributeName) . ' - ' . $relatedError;
                     }
                 }
             } elseif ($errorOrRelatedError != '') {
                 $messages[] = LabelUtil::makeModelAndAttributeNameCombinationLabel(get_class($model), $attributeName) . ' - ' . $errorOrRelatedError;
             }
         }
     }
     return $messages;
 }
Пример #15
0
 /**
  * @param SavedWorkflow $savedWorkflow
  * @param RedBeanModel $model
  * @return ByTimeWorkflowInQueue
  * @throws NotSupportedException
  */
 public static function resolveByWorkflowIdAndModel(SavedWorkflow $savedWorkflow, RedBeanModel $model)
 {
     $searchAttributeData = array();
     $searchAttributeData['clauses'] = array(1 => array('attributeName' => 'modelItem', 'operatorType' => 'equals', 'value' => $model->getClassId('Item')), 2 => array('attributeName' => 'savedWorkflow', 'operatorType' => 'equals', 'value' => $savedWorkflow->id), 3 => array('attributeName' => 'modelClassName', 'operatorType' => 'equals', 'value' => get_class($model)));
     $searchAttributeData['structure'] = '1 and 2 and 3';
     $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('ByTimeWorkflowInQueue');
     $where = RedBeanModelDataProvider::makeWhere('ByTimeWorkflowInQueue', $searchAttributeData, $joinTablesAdapter);
     $models = self::getSubset($joinTablesAdapter, null, null, $where, null);
     if (count($models) > 1) {
         throw new NotSupportedException();
     } elseif (count($models) == 1) {
         return $models[0];
     } else {
         $byTimeWorkflowInQueue = new ByTimeWorkflowInQueue();
         $byTimeWorkflowInQueue->modelClassName = get_class($model);
         $byTimeWorkflowInQueue->modelItem = $model;
         $byTimeWorkflowInQueue->savedWorkflow = $savedWorkflow;
         return $byTimeWorkflowInQueue;
     }
 }
Пример #16
0
 /**
  * For a give User name, run a partial search by
  * full name and retrieve user models.
  *
  */
 public static function getUsersByPartialFullName($partialName, $pageSize)
 {
     assert('is_string($partialName)');
     assert('is_int($pageSize)');
     $personTableName = RedBeanModel::getTableName('Person');
     $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('User');
     $joinTablesAdapter->addFromTableAndGetAliasName($personTableName, "{$personTableName}_id");
     $fullNameSql = DatabaseCompatibilityUtil::concat(array('person.firstname', '\' \'', 'person.lastname'));
     $where = "      (person.firstname      like lower('{$partialName}%') or " . "       person.lastname       like lower('{$partialName}%') or " . "       {$fullNameSql} like lower('{$partialName}%')) ";
     return User::getSubset($joinTablesAdapter, null, $pageSize, $where, "person.firstname, person.lastname");
 }
Пример #17
0
 /**
  * Given an id of a currency model, determine if any currency values are using this currency.
  * @return true if at least one currency value model is using this currency.
  * @param integer $currencyId
  */
 public static function isCurrencyInUseById($currencyId)
 {
     assert('is_int($currencyId)');
     $columnName = RedBeanModel::getForeignKeyName('CurrencyValue', 'currency');
     $quote = DatabaseCompatibilityUtil::getQuote();
     $where = "{$quote}{$columnName}{$quote} = '{$currencyId}'";
     $count = CurrencyValue::getCount(null, $where);
     if ($count > 0) {
         return true;
     }
     return false;
 }
 /**
  * Given an external system id and model class name, try to find the associated model if it exists. If it is
  * not found, a NotFoundException will be thrown.  Otherwise the model will be made and returned.
  * @param string $id
  * @param string $modelClassName
  * @return RedBeanModel $model
  * @throws NotFoundException
  */
 public static function getModelByExternalSystemIdAndModelClassName($id, $modelClassName)
 {
     assert('$id != null && is_string($id)');
     assert('is_string($modelClassName)');
     $tableName = $modelClassName::getTableName();
     $beans = ZurmoRedBean::find($tableName, ExternalSystemIdUtil::EXTERNAL_SYSTEM_ID_COLUMN_NAME . " = '{$id}'");
     assert('count($beans) <= 1');
     if (count($beans) == 0) {
         throw new NotFoundException();
     }
     return RedBeanModel::makeModel(end($beans), $modelClassName);
 }
Пример #19
0
 public static function getModelsByFullName($modelClassName, $fullName)
 {
     assert('is_string($modelClassName)');
     assert('is_subclass_of($modelClassName, "Person") && $modelClassName != "Person" ||' . '$modelClassName == "User"');
     assert('is_string($fullName)');
     $personTableName = RedBeanModel::getTableName('Person');
     $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
     $joinTablesAdapter->addFromTableAndGetAliasName($personTableName, "{$personTableName}_id");
     $fullNameSql = DatabaseCompatibilityUtil::concat(array('person.firstname', '\' \'', 'person.lastname'));
     $where = "{$fullNameSql} = '{$fullName}'";
     return $modelClassName::getSubset($joinTablesAdapter, null, null, $where);
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     $super = SecurityTestHelper::createSuperAdmin();
     self::$emailMessage = EmailMessageTestHelper::createDraftSystemEmail('a test message', $super);
     SecurityTestHelper::createUsers();
     SecurityTestHelper::createGroups();
     SecurityTestHelper::createRoles();
     RedBeanModel::forgetAll();
     //do the rebuild to ensure the tables get created properly.
     ReadPermissionsOptimizationUtil::rebuild();
 }
 public function testAttributesTranslateToAllSupportedLanguagesCorrectly()
 {
     $this->assertEquals('en', Yii::app()->language);
     $account = new Account(false);
     $this->assertEquals('Office Phone', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('Billing Address', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'fr';
     $this->assertEquals('Téléphone de bureau', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('Adresse de facturation', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'it';
     $this->assertEquals('Telefono Ufficio', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('Indirizzo di Fatturazione', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'es';
     $this->assertEquals('Teléfono de la Oficina', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('Dirección de facturación', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'de';
     $this->assertEquals('Bürotelefon', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('Rechnungsadresse', $account->getAttributeLabel('billingAddress'));
     //Set language back to english.
     Yii::app()->language = 'en';
     //Now customize both labels for all supported languages.
     $metadata = Account::getMetadata();
     $metadata['Account']['labels']['officePhone'] = array('de' => 'GermanSomething', 'en' => 'EnglishSomething', 'es' => 'SpanishSomething', 'fr' => 'FrenchSomething', 'it' => 'ItalianSomething');
     $metadata['Account']['labels']['billingAddress'] = array('de' => 'GermanSomethingElse', 'en' => 'EnglishSomethingElse', 'es' => 'SpanishSomethingElse', 'fr' => 'FrenchSomethingElse', 'it' => 'ItalianSomethingElse');
     Account::setMetadata($metadata);
     RedBeanModel::forgetAll();
     //Set language back to english.
     Yii::app()->language = 'en';
     $this->assertEquals('EnglishSomething', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('EnglishSomethingElse', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'fr';
     $this->assertEquals('FrenchSomething', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('FrenchSomethingElse', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'it';
     $this->assertEquals('ItalianSomething', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('ItalianSomethingElse', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'es';
     $this->assertEquals('SpanishSomething', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('SpanishSomethingElse', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'de';
     $this->assertEquals('GermanSomething', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('GermanSomethingElse', $account->getAttributeLabel('billingAddress'));
     //Set language back to english.
     Yii::app()->language = 'en';
     //Retrieve all the language labels for a particular attribute.
     $officePhoneLabels = $account->getAttributeLabelsForAllActiveLanguagesByAttributeName('officePhone');
     $billingAddressLabels = $account->getAttributeLabelsForAllActiveLanguagesByAttributeName('billingAddress');
     $comparePhoneLabels = array('de' => 'GermanSomething', 'en' => 'EnglishSomething', 'es' => 'SpanishSomething', 'fr' => 'FrenchSomething', 'it' => 'ItalianSomething');
     $compareAddressLabels = array('de' => 'GermanSomethingElse', 'en' => 'EnglishSomethingElse', 'es' => 'SpanishSomethingElse', 'fr' => 'FrenchSomethingElse', 'it' => 'ItalianSomethingElse');
     $this->assertEquals($comparePhoneLabels, $officePhoneLabels);
     $this->assertEquals($compareAddressLabels, $compareAddressLabels);
 }
Пример #22
0
 public static function tearDownAfterClass()
 {
     if (RedBeanDatabase::isFrozen()) {
         TestDatabaseUtil::deleteRowsFromAllTablesExceptLog();
     } else {
         TestDatabaseUtil::deleteAllTablesExceptLog();
     }
     RedBeanModel::forgetAll();
     RedBeanDatabase::close();
     assert('!RedBeanDatabase::isSetup()');
     // Not Coding Standard
     GeneralCache::forgetAll();
 }
 public function testListContactStateAttributes()
 {
     RedBeanModel::forgetAll();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $authenticationData = $this->login();
     $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     $allAttributes = ApiRestTestHelper::getModelAttributes(new ContactState());
     $response = $this->createApiCallWithRelativeUrl('listAttributes/', 'GET', $headers);
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals($allAttributes, $response['data']['items']);
 }
 /**
  * Notice the use of $modelToForgetCache. This was needed to avoid a caching issue with the following example.
  * If an opportunity fires, and a related account's opportunity is created. This new opportunity had a cached
  * model for account that was null.  So this is fixed by forgetting the new model after it is added to the account.
  * @throws FailedToSaveModelException
  * @throws NotSupportedException
  */
 protected function processCreateRelatedAction()
 {
     if ($this->action->relationFilter != ActionForWorkflowForm::RELATION_FILTER_ALL) {
         throw new NotSupportedException();
     }
     $modelClassName = get_class($this->triggeredModel);
     if ($this->triggeredModel->isADerivedRelationViaCastedUpModel($this->action->relation) && $this->triggeredModel->getDerivedRelationType($this->action->relation) == RedBeanModel::MANY_MANY) {
         foreach (WorkflowUtil::resolveDerivedModels($this->triggeredModel, $this->action->relation) as $relatedModel) {
             if ($this->resolveCreateModel($relatedModel, $this->action->relatedModelRelation)) {
                 $saved = $relatedModel->save();
                 if (!$saved) {
                     throw new FailedToSaveModelException();
                 }
             }
         }
     } elseif ($this->triggeredModel->getInferredRelationModelClassNamesForRelation(ModelRelationsAndAttributesToWorkflowAdapter::resolveRealAttributeName($this->action->relation)) != null) {
         foreach (WorkflowUtil::getInferredModelsByAtrributeAndModel($this->action->relation, $this->triggeredModel) as $relatedModel) {
             if ($this->resolveCreateModel($relatedModel, $this->action->relatedModelRelation)) {
                 $saved = $relatedModel->save();
                 if (!$saved) {
                     throw new FailedToSaveModelException();
                 }
             }
         }
     } elseif ($this->triggeredModel->{$this->action->relation} instanceof RedBeanMutableRelatedModels) {
         foreach ($this->triggeredModel->{$this->action->relation} as $relatedModel) {
             if ($this->resolveCreateModel($relatedModel, $this->action->relatedModelRelation)) {
                 $saved = $relatedModel->save();
                 if (!$saved) {
                     throw new FailedToSaveModelException();
                 }
             }
         }
     } elseif ($modelClassName::isRelationTypeAHasOneVariant($this->action->relation) && !$modelClassName::isOwnedRelation($this->action->relation)) {
         $relatedModel = $this->triggeredModel->{$this->action->relation};
         $modelToForgetCache = null;
         if ($this->resolveCreateModel($relatedModel, $this->action->relatedModelRelation, $modelToForgetCache)) {
             $saved = $relatedModel->save();
             if (!$saved) {
                 throw new FailedToSaveModelException();
             }
             if ($modelToForgetCache instanceof RedBeanModel) {
                 $modelToForgetCache->forget();
             }
         }
     } else {
         throw new NotSupportedException();
     }
 }
Пример #25
0
 public static function tearDownAfterClass()
 {
     if (static::$activateDefaultLanguages) {
         Yii::app()->languageHelper->deactivateLanguagesForTesting();
     }
     TestDatabaseUtil::deleteRowsFromAllTablesExceptLog();
     PermissionsCache::forgetAll();
     AllPermissionsOptimizationCache::forgetAll();
     RedBeanModel::forgetAll();
     RedBeanDatabase::close();
     assert('!RedBeanDatabase::isSetup()');
     // Not Coding Standard
     GeneralCache::forgetAll();
     BeanModelCache::forgetAll();
 }
 protected function resolveIdAndNameByModel(RedBeanModel $model)
 {
     $existingContact = null;
     if (!isset($this->modelDerivationPathToItemFromContact)) {
         $this->modelDerivationPathToItemFromContact = RuntimeUtil::getModelDerivationPathToItem('Contact');
     }
     try {
         $contact = $model->castDown(array($this->modelDerivationPathToItemFromContact));
         if (get_class($contact) == 'Contact') {
             $existingContact = array('id' => Meeting::CONTACT_ATTENDEE_PREFIX . $contact->id, 'name' => self::renderHtmlContentLabelFromContactAndKeyword($contact, null));
         }
     } catch (NotFoundException $e) {
         //do nothing
     }
     return $existingContact;
 }
Пример #27
0
 public static function updateValueByDataIdAndOldValueAndNewValue($customFieldDataId, $oldValue, $newValue)
 {
     $quote = DatabaseCompatibilityUtil::getQuote();
     $customFieldTableName = RedBeanModel::getTableName('CustomField');
     $baseCustomFieldTableName = RedBeanModel::getTableName('BaseCustomField');
     $baseCustomFieldJoinColumnName = $baseCustomFieldTableName . '_id';
     $valueAttributeColumnName = 'value';
     $dataAttributeColumnName = RedBeanModel::getForeignKeyName('BaseCustomField', 'data');
     $sql = "update {$quote}{$customFieldTableName}{$quote}, {$quote}{$baseCustomFieldTableName}{$quote} ";
     $sql .= "set {$quote}{$valueAttributeColumnName}{$quote} = '{$newValue}' ";
     $sql .= "where {$quote}{$customFieldTableName}{$quote}.{$baseCustomFieldJoinColumnName} = ";
     // Not Coding Standard
     $sql .= "{$quote}{$baseCustomFieldTableName}{$quote}.id ";
     $sql .= "AND {$quote}{$dataAttributeColumnName}{$quote} = {$customFieldDataId} ";
     $sql .= "AND {$quote}{$valueAttributeColumnName}{$quote} = '{$oldValue}'";
     R::exec($sql);
 }
Пример #28
0
 public static function getByLayoutIdAndUser($layoutId, $user)
 {
     assert('is_integer($layoutId) && $layoutId >= 1');
     assert('$user instanceof User && $user->id > 0');
     $sql = 'select dashboard.id id ' . 'from dashboard, ownedsecurableitem ' . 'where ownedsecurableitem.owner__user_id = ' . $user->id . ' and dashboard.ownedsecurableitem_id = ownedsecurableitem.id ' . ' and layoutid = ' . $layoutId . ' order by layoutId;';
     $ids = R::getCol($sql);
     assert('count($ids) <= 1');
     if (count($ids) == 0) {
         if ($layoutId == Dashboard::DEFAULT_USER_LAYOUT_ID) {
             return Dashboard::setDefaultDashboardForUser($user);
         }
         throw new NotFoundException();
     }
     $bean = R::load(RedBeanModel::getTableName('Dashboard'), $ids[0]);
     assert('$bean === false || $bean instanceof RedBean_OODBBean');
     if ($bean === false) {
         throw new NotFoundException();
     }
     return self::makeModel($bean);
 }
Пример #29
0
 /**
  * Utilized for existing models, that were not originally saved with a new custom field.  This will be utilized
  * to ensure cached models properly generate information needed by the existing model. Construct incomplete does
  * not run on new models.  This only needs to run on custom fields that have been created after a model was
  * created, so the model does not have a  value for the linking id in the table.
  * (non-PHPdoc)
  * @see RedBeanModel::constructIncomplete()
  */
 protected function constructIncomplete($bean)
 {
     assert('$bean === null || $bean instanceof RedBean_OODBBean');
     parent::constructIncomplete($bean);
     $metadata = $this->getMetadata();
     foreach ($metadata as $unused => $classMetadata) {
         if (isset($classMetadata['customFields'])) {
             foreach ($classMetadata['customFields'] as $customFieldName => $customFieldDataName) {
                 $customFieldModelClassName = $this->getAttributeModelClassName($customFieldName);
                 $classBean = $this->getClassBean($customFieldModelClassName);
                 $columnName = static::getForeignKeyName($customFieldModelClassName, $customFieldName);
                 if ($classBean->{$columnName} == null) {
                     $customField = $this->unrestrictedGet($customFieldName);
                     $customFieldData = CustomFieldData::getByName($customFieldDataName);
                     $customField->data = $customFieldData;
                 }
             }
         }
     }
 }
Пример #30
0
 /**
  * For a give Contact name, run a partial search by
  * full name and retrieve contact models.
  *
  */
 public static function getContactsByPartialFullName($partialName, $pageSize, $stateMetadataAdapterClassName = null)
 {
     assert('is_string($partialName)');
     assert('is_int($pageSize)');
     assert('$stateMetadataAdapterClassName == null || is_string($stateMetadataAdapterClassName)');
     $personTableName = RedBeanModel::getTableName('Person');
     $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('Contact');
     if (!$joinTablesAdapter->isTableInFromTables('person')) {
         $joinTablesAdapter->addFromTableAndGetAliasName($personTableName, "{$personTableName}_id");
     }
     $metadata = array('clauses' => array(), 'structure' => '');
     if ($stateMetadataAdapterClassName != null) {
         $stateMetadataAdapter = new $stateMetadataAdapterClassName($metadata);
         $metadata = $stateMetadataAdapter->getAdaptedDataProviderMetadata();
         $metadata['structure'] = '(' . $metadata['structure'] . ')';
     }
     $where = RedBeanModelDataProvider::makeWhere('Contact', $metadata, $joinTablesAdapter);
     if ($where != null) {
         $where .= 'and';
     }
     $where .= self::getWherePartForPartialNameSearchByPartialName($partialName);
     return Contact::getSubset($joinTablesAdapter, null, $pageSize, $where, "person.firstname, person.lastname");
 }