public function getModelObject()
 {
     if (!$this->resourceIdentifier || !is_numeric($this->resourceIdentifier)) {
         throw new CollectionUrlException();
     }
     return SolutionSchema::getModel($this->modelName, $this->resourceIdentifier);
 }
 /**
  * Converts the comparison value used in the constructor to one which can be compared against that returned
  * by the relevant model.
  *
  * @param $rawComparisonValue
  * @param Collection $list
  * @return mixed
  */
 protected final function getTransformedComparisonValue($rawComparisonValue, Collection $list)
 {
     $exampleObject = SolutionSchema::getModel($list->getModelClassName());
     $columnSchema = $exampleObject->getColumnSchemaForColumnReference($this->columnName);
     if ($columnSchema != null) {
         $closure = $columnSchema->getTransformIntoModelData();
         if ($closure !== null) {
             $rawComparisonValue = $closure($rawComparisonValue);
         }
     }
     return $rawComparisonValue;
 }
 public function setFilterValuesOnModel(Model $model)
 {
     // Create a row in the intermediate collection so that if the filter was ran again the model
     // would now qualify.
     $relationships = SolutionSchema::getAllRelationshipsForModel("\\" . get_class($model));
     /**
      * @var OneToMany $relationship
      */
     $relationship = $relationships[$this->collectionProperty];
     $modelName = $relationship->getTargetModelName();
     $newModel = SolutionSchema::getModel($modelName);
     $newModel[$model->UniqueIdentifierColumnName] = $model->UniqueIdentifier;
     $newModel[$this->columnName] = $this->equalTo;
     $newModel->save();
     return $newModel;
 }
 protected static final function getTransformedComparisonValueForRepository($columnName, $rawComparisonValue, Repository $repository)
 {
     $exampleObject = SolutionSchema::getModel($repository->getModelClass());
     $columnSchema = $exampleObject->getColumnSchemaForColumnReference($columnName);
     if ($columnSchema != null) {
         // Transform the value first into model data. This function should sanitise the value as
         // the model data transforms expect inputs passed by unwary developers.
         $closure = $columnSchema->getTransformIntoModelData();
         if ($closure !== null) {
             $rawComparisonValue = $closure($rawComparisonValue);
         }
         $closure = $columnSchema->getTransformIntoRepository();
         if ($closure !== null) {
             $rawComparisonValue = $closure($rawComparisonValue);
         }
     }
     return $rawComparisonValue;
 }
 public function getModelObject()
 {
     try {
         return parent::getModelObject();
     } catch (CollectionUrlException $er) {
         // Normally you can't get a model with no identifier in the rest handler.
         // However we want to allow for retrieval of a fresh model ready to receive our post back
         // data. So we restore that behaviour here.
         if (!$this->isCollection) {
             $newModel = SolutionSchema::getModel($this->modelName);
             // If we have a parent handler - see if it can populate our model with some foreign keys.
             $parentHandler = $this->getParentHandler();
             if ($parentHandler !== null && $parentHandler instanceof ModelCollectionHandler) {
                 $parentHandler->populateNewModelWithRelationshipValues($newModel);
             }
             return $newModel;
         }
         throw $er;
     }
 }
Example #6
0
 public function fetchFor(Model $relatedTo)
 {
     $targetModel = SolutionSchema::getModel($this->targetModelName);
     $sourceValue = $relatedTo[$this->getSourceColumnName()];
     $targetColumnName = $this->getTargetColumnName();
     if ($targetColumnName == $targetModel->UniqueIdentifierColumnName) {
         if ($sourceValue === null) {
             return null;
         }
         try {
             return SolutionSchema::getModel($this->targetModelName, $sourceValue);
         } catch (RecordNotFoundException $er) {
             return null;
         }
     } else {
         $collection = new Collection($this->targetModelName);
         $collection->filter(new Equals($targetColumnName, $sourceValue));
         if (sizeof($collection) > 0) {
             return $collection[0];
         }
     }
     return null;
 }
Example #7
0
 /**
  * Get's the unique identifiers required for the matching filters and loads the data into
  * the cache for performance reasons.
  *
  * @param Collection $list
  * @param int $unfetchedRowCount
  * @param array $relationshipNavigationPropertiesToAutoHydrate
  * @return array
  */
 public function getUniqueIdentifiersForDataList(Collection $list, &$unfetchedRowCount = 0, $relationshipNavigationPropertiesToAutoHydrate = [])
 {
     $this->lastSortsUsed = [];
     $schema = $this->schema;
     $table = $schema->schemaName;
     $whereClause = "";
     $filter = $list->getFilter();
     $namedParams = [];
     $propertiesToAutoHydrate = $relationshipNavigationPropertiesToAutoHydrate;
     $filteredExclusivelyByRepository = true;
     if ($filter !== null) {
         $filterSql = $filter->filterWithRepository($this, $namedParams, $propertiesToAutoHydrate);
         if ($filterSql != "") {
             $whereClause .= " WHERE " . $filterSql;
         }
         $filteredExclusivelyByRepository = $filter->wasFilteredByRepository();
     }
     $relationships = SolutionSchema::getAllRelationshipsForModel($this->getModelClass());
     $aggregateColumnClause = "";
     $aggregateColumnClauses = [];
     $aggregateColumnAliases = [];
     $aggregateRelationshipPropertiesToAutoHydrate = [];
     foreach ($list->getAggregates() as $aggregate) {
         $clause = $aggregate->aggregateWithRepository($this, $aggregateRelationshipPropertiesToAutoHydrate);
         if ($clause != "") {
             $aggregateColumnClauses[] = $clause;
             $aggregateColumnAliases[] = $aggregate->getAlias();
         }
     }
     if (sizeof($aggregateColumnClauses) > 0) {
         $aggregateColumnClause = ", " . implode(", ", $aggregateColumnClauses);
     }
     $aggregateRelationshipPropertiesToAutoHydrate = array_unique($aggregateRelationshipPropertiesToAutoHydrate);
     $joins = [];
     $groups = [];
     foreach ($aggregateRelationshipPropertiesToAutoHydrate as $joinRelationship) {
         /**
          * @var OneToMany $relationship
          */
         $relationship = $relationships[$joinRelationship];
         $targetModelName = $relationship->getTargetModelName();
         $targetModelClass = SolutionSchema::getModelClass($targetModelName);
         /**
          * @var Model $targetModel
          */
         $targetModel = new $targetModelClass();
         $targetSchema = $targetModel->getSchema();
         $joins[] = "LEFT JOIN `{$targetSchema->schemaName}` AS `{$joinRelationship}` ON `{$this->schema->schemaName}`.`" . $relationship->getSourceColumnName() . "` = `{$joinRelationship}`.`" . $relationship->getTargetColumnName() . "`";
         $groups[] = "`{$table}`.`" . $relationship->getSourceColumnName() . '`';
     }
     $joinColumns = [];
     $joinOriginalToAliasLookup = [];
     $joinColumnsByModel = [];
     $sorts = $list->getSorts();
     $possibleSorts = [];
     $columns = $schema->getColumns();
     foreach ($sorts as $columnName => $ascending) {
         if (!isset($columns[$columnName])) {
             // If this is a one to one relationship we can still sort by using auto hydration.
             $parts = explode(".", $columnName);
             $relationshipProperty = $parts[0];
             $escapedColumnName = '`' . implode('`.`', $parts) . '`';
             if (isset($relationships[$relationshipProperty]) && $relationships[$relationshipProperty] instanceof OneToOne) {
                 $propertiesToAutoHydrate[] = $relationshipProperty;
                 $possibleSorts[] = $escapedColumnName . " " . ($ascending ? "ASC" : "DESC");
                 $this->lastSortsUsed[] = $columnName;
             } else {
                 // If the request sorts contain any that we can't sort by we must only sort by those
                 // after this column.
                 $possibleSorts = [];
                 $this->lastSortsUsed = [];
             }
         } else {
             $possibleSorts[] = '`' . str_replace('.', '`.`', $columnName) . "` " . ($ascending ? "ASC" : "DESC");
             $this->lastSortsUsed[] = $columnName;
         }
     }
     $propertiesToAutoHydrate = array_unique($propertiesToAutoHydrate);
     foreach ($propertiesToAutoHydrate as $joinRelationship) {
         /**
          * @var OneToMany $relationship
          */
         $relationship = $relationships[$joinRelationship];
         $targetModelName = $relationship->getTargetModelName();
         $targetModelClass = SolutionSchema::getModelClass($targetModelName);
         /**
          * @var Model $targetModel
          */
         $targetModel = new $targetModelClass();
         $targetSchema = $targetModel->getSchema();
         $columns = $targetSchema->getColumns();
         foreach ($columns as $columnName => $column) {
             $joinColumns[$targetModelName . $columnName] = "`{$joinRelationship}`.`{$columnName}`";
             $joinOriginalToAliasLookup[$targetModelName . "." . $columnName] = $targetModelName . $columnName;
             if (!isset($joinColumnsByModel[$targetModelName])) {
                 $joinColumnsByModel[$targetModelName] = [];
             }
             $joinColumnsByModel[$targetModelName][$targetModelName . $columnName] = $columnName;
         }
         $joins[] = "LEFT JOIN `{$targetSchema->schemaName}` AS `{$joinRelationship}` ON `{$this->schema->schemaName}`.`" . $relationship->getSourceColumnName() . "` = `{$joinRelationship}`.`" . $relationship->getTargetColumnName() . "`";
     }
     $joinString = "";
     $joinColumnClause = "";
     if (sizeof($joins)) {
         $joinString = " " . implode(" ", $joins);
         $joinClauses = [];
         foreach ($joinColumns as $aliasName => $columnName) {
             $joinClauses[] = "{$columnName} AS `{$aliasName}`";
         }
         if (sizeof($joinClauses)) {
             $joinColumnClause = ", " . implode(", ", $joinClauses);
         }
     }
     $groupClause = "";
     if (sizeof($groups)) {
         $groupClause = " GROUP BY " . implode(", ", $groups);
     }
     $orderBy = "";
     if (sizeof($possibleSorts)) {
         $orderBy .= " ORDER BY " . implode(", ", $possibleSorts);
     }
     $sql = "SELECT `{$table}`.*{$joinColumnClause}{$aggregateColumnClause} FROM `{$table}`" . $joinString . $whereClause . $groupClause . $orderBy;
     $ranged = false;
     if ($filteredExclusivelyByRepository && sizeof($possibleSorts) == sizeof($sorts)) {
         $range = $list->getRange();
         if ($range != false) {
             $ranged = true;
             $sql .= " LIMIT " . $range[0] . ", " . $range[1];
             $sql = preg_replace("/^SELECT /", "SELECT SQL_CALC_FOUND_ROWS ", $sql);
         }
     }
     $statement = self::executeStatement($sql, $namedParams);
     $results = $statement->fetchAll(\PDO::FETCH_ASSOC);
     $uniqueIdentifiers = [];
     if (sizeof($joinColumns)) {
         foreach ($joinColumnsByModel as $joinModel => $modelJoinedColumns) {
             $model = SolutionSchema::getModel($joinModel);
             $repository = $model->getRepository();
             foreach ($results as &$result) {
                 $aliasedUniqueIdentifierColumnName = $joinOriginalToAliasLookup[$joinModel . "." . $model->UniqueIdentifierColumnName];
                 if (isset($result[$aliasedUniqueIdentifierColumnName]) && !isset($repository->cachedObjectData[$result[$aliasedUniqueIdentifierColumnName]])) {
                     $joinedData = array_intersect_key($result, $modelJoinedColumns);
                     $modelData = array_combine($modelJoinedColumns, $joinedData);
                     $repository->cachedObjectData[$modelData[$model->UniqueIdentifierColumnName]] = $modelData;
                 }
                 $result = array_diff_key($result, $modelJoinedColumns);
             }
             unset($result);
         }
     }
     foreach ($results as $result) {
         $uniqueIdentifier = $result[$schema->uniqueIdentifierColumnName];
         $result = $this->transformDataFromRepository($result);
         // Store the data in the cache and add the unique identifier to our list.
         $this->cachedObjectData[$uniqueIdentifier] = $result;
         $uniqueIdentifiers[] = $uniqueIdentifier;
     }
     if ($ranged) {
         $foundRows = Mysql::returnSingleValue("SELECT FOUND_ROWS()");
         $unfetchedRowCount = $foundRows - sizeof($uniqueIdentifiers);
     }
     return $uniqueIdentifiers;
 }
 protected function getCollectionFilter($phrase)
 {
     $model = SolutionSchema::getModel($this->modelClassName);
     $filter = new Contains($model->getLabelColumnName(), $phrase);
     return $filter;
 }
Example #9
0
 /**
  * Returns the schema Column object for the matching column reference.
  *
  * A column reference might be a column name or a Relationship.ColumnName expressions.
  *
  * @param $columnReference
  * @return null|\Rhubarb\Stem\Schema\Columns\Column
  */
 public function getColumnSchemaForColumnReference($columnReference)
 {
     if (strpos($columnReference, ".") !== false) {
         $parts = explode(".", $columnReference);
         $relationshipName = $parts[0];
         $this->ensureRelationshipsArePopulated();
         if (isset(self::$relationships[$this->modelName][$relationshipName])) {
             $relationship = self::$relationships[$this->modelName][$relationshipName];
             $relatedModel = SolutionSchema::getModel($relationship->getTargetModelName());
             return $relatedModel->getColumnSchemaForColumnReference($parts[1]);
         }
     }
     $schema = $this->getSchema();
     $columns = $schema->getColumns();
     if (isset($columns[$columnReference])) {
         return $columns[$columnReference];
     }
     return null;
 }
 public function testModelCanBeRetrievedByName()
 {
     $company = SolutionSchema::getModel("Company");
     $this->assertInstanceOf("Rhubarb\\Stem\\Tests\\Fixtures\\Company", $company);
     $this->assertTrue($company->isNewRecord());
     $company->CompanyName = "Boyo";
     $company->save();
     $model2 = SolutionSchema::getModel("Company", $company->CompanyID);
     $this->assertEquals($company->CompanyID, $model2->UniqueIdentifier);
 }
 public static function draftPackage(CommunicationPackage $package)
 {
     $communication = SolutionSchema::getModel("Communication");
     $communication->Title = $package->title;
     if ($package->dateToSend) {
         $communication->DateToSend = $package->dateToSend;
     }
     $communication->save();
     foreach ($package->getSendables() as $sendable) {
         foreach ($sendable->getRecipients() as $recipient) {
             $clone = clone $sendable;
             $clone->clearRecipients();
             $clone->addRecipient($recipient);
             $item = SolutionSchema::getModel("CommunicationItem");
             $item->Recipient = (string) $recipient;
             $item->Text = $clone->getText();
             $item->Type = $clone->getSendableType();
             $item->SendableClassName = get_class($clone);
             $item->Data = $clone->toArray();
             $item->CommunicationID = $communication->CommunicationID;
             $item->save();
         }
     }
     return $communication;
 }
 /**
  * Returns the model object for the logged in user.
  *
  * @return \Rhubarb\Stem\Models\Model
  * @throws NotLoggedInException
  */
 public function getModel()
 {
     if (!$this->isLoggedIn()) {
         throw new NotLoggedInException();
     }
     if (isset($this->LoggedInUserIdentifier)) {
         try {
             return SolutionSchema::getModel($this->modelClassName, $this->LoggedInUserIdentifier);
         } catch (\Rhubarb\Stem\Exceptions\RecordNotFoundException $er) {
             throw new NotLoggedInException();
         }
     }
     throw new NotLoggedInException();
 }
Example #13
0
 /**
  * Get's the repository used by the associated data object.
  *
  * @return \Rhubarb\Stem\Repositories\Repository
  */
 protected function getRepository()
 {
     $emptyObject = SolutionSchema::getModel($this->modelClassName);
     $repository = $emptyObject->getRepository();
     return $repository;
 }