public static function dispatchModelEvent($event, Model $model) { $event = SolutionSchema::getModelNameFromClass(get_class($model)) . ":" . $event; if (!isset(self::$eventHandlers[$event])) { return null; } $args = func_get_args(); $args = array_slice($args, 1); // Check if the last argument is a callback. $count = count($args); $callBack = false; if ($count > 0 && is_object($args[$count - 1]) && is_callable($args[$count - 1])) { $callBack = $args[$count - 1]; $args = array_slice($args, 0, -1); } $result = null; foreach (self::$eventHandlers[$event] as $delegate) { $answer = call_user_func_array($delegate, $args); if ($result === null) { $result = $answer; } } if ($callBack !== false) { call_user_func($callBack, $result); } return $result; }
protected static function canAggregateInMySql(Repository $repository, $columnName, &$relationshipsToAutoHydrate) { $schema = $repository->getSchema(); $columns = $schema->getColumns(); if (isset($columns[$columnName])) { return true; } if (strpos($columnName, ".") !== false) { // If the column name contains a dot, the part before the dot is the name of a relationship to another model list($relationship, $columnName) = explode(".", $columnName, 2); $relationships = SolutionSchema::getAllRelationshipsForModel($repository->getModelClass()); // Check for the name being that of a relationship if (isset($relationships[$relationship]) && $relationships[$relationship] instanceof OneToMany) { $targetModelName = $relationships[$relationship]->getTargetModelName(); $targetSchema = SolutionSchema::getModelSchema($targetModelName); $targetColumns = $targetSchema->getColumns(); // Check for the column name in the schema of the related model if (isset($targetColumns[$columnName])) { $relationshipsToAutoHydrate[] = $relationship; return true; } } } return false; }
protected function initialise() { parent::initialise(); Repository::SetDefaultRepositoryClassName(MySql::class); include_once "settings/site.config.php"; SolutionSchema::registerSchema('Default', DefaultSolutionSchema::class); }
public function testOneToMany() { SolutionSchema::registerSchema("MySchema", "Rhubarb\\Stem\\Tests\\Fixtures\\UnitTestingSolutionSchema"); $company = new Company(); $company->getRepository()->clearObjectCache(); $company->CompanyName = "Test Company"; $company->save(); $user = new User(); $user->getRepository()->clearObjectCache(); $user->Username = "******"; $user->Password = "******"; $user->Active = 1; $user->CompanyID = $company->CompanyID; $user->save(); $user = new User(); $user->Username = "******"; $user->Password = ""; $user->Active = 1; $user->CompanyID = $company->CompanyID; $user->save(); $user = new User(); $user->Username = "******"; $user->Password = ""; $user->Active = 0; $user->CompanyID = $company->CompanyID; $user->save(); $oneToMany = new OneToMany("Unused", "Company", "CompanyID", "UnitTestUser"); $list = $oneToMany->fetchFor($company); $this->assertCount(2, $list); $this->assertEquals("msmith", $list[1]->Username); }
public function __construct($version = 2) { parent::__construct($version); $this->addModel('Image', Image::class); $this->addModel('Comment', Comment::class); $this->addModel('Gallery', Gallery::class); $this->addModel('CustomUser', CustomUser::class); }
/** * @return mixed */ public function getSourceColumnName() { $sourceColumnName = $this->sourceColumnName; if ($sourceColumnName == "") { $sourceSchema = SolutionSchema::getModelSchema($this->sourceModelName); $sourceColumnName = $sourceSchema->uniqueIdentifierColumnName; } return $sourceColumnName; }
public function __construct() { parent::__construct(); $this->addModel("Company", "Rhubarb\\Stem\\Tests\\Fixtures\\Company"); $this->addModel("Category", "Rhubarb\\Stem\\Tests\\Fixtures\\Category"); $this->addModel("CompanyCategory", "Rhubarb\\Stem\\Tests\\Fixtures\\CompanyCategory"); $this->addModel("Example", "Rhubarb\\Stem\\Tests\\Fixtures\\Example"); $this->addModel("UnitTestUser", "Rhubarb\\Stem\\Tests\\Fixtures\\User"); }
protected function populateNewModelWithRelationshipValues(Model $model) { $schema = SolutionSchema::getModelSchema($this->modelName); $model[$schema->uniqueIdentifierColumnName] = $this->resourceIdentifier; // 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($model); } }
/** * 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 generateResponse($request = null) { if (class_exists("Rhubarb\\Crown\\Layout\\LayoutModule")) { LayoutModule::disableLayout(); } $schemas = SolutionSchema::getAllSchemas(); foreach ($schemas as $schema) { $schema->checkModelSchemas(); } $response = new HtmlResponse(); $response->setContent("Done"); return $response; }
protected static function doFilterWithRepository(Repository $repository, Filter $originalFilter, &$params, &$relationshipsToAutoHydrate) { $relationshipsToAutoHydrate[] = $originalFilter->collectionProperty; // Get the relationship $relationships = SolutionSchema::getAllRelationshipsForModel($repository->getModelClass()); /** * @var OneToMany $relationship */ $relationship = $relationships[$originalFilter->collectionProperty]; $columnName = $relationship->getNavigationPropertyName() . "`.`" . $originalFilter->columnName; $paramName = uniqid() . str_replace("`.`", "", $columnName); $params[$paramName] = $originalFilter->equalTo; $originalFilter->filteredByRepository = true; return "`{$columnName}` = :{$paramName}"; }
public function testOneToOne() { SolutionSchema::registerSchema("MySchema", "Rhubarb\\Stem\\Tests\\Fixtures\\UnitTestingSolutionSchema"); $company = new Company(); $company->CompanyName = "Test Company"; $company->save(); $user = new User(); $user->Username = "******"; $user->Password = "******"; $user->Active = 1; $user->CompanyID = $company->CompanyID; $user->save(); $oneToOne = new OneToOne("Unused", "User", "CompanyID", "Company", "CompanyID"); $result = $oneToOne->fetchFor($user); $this->assertEquals("Test Company", $result->CompanyName); }
protected function getTitle() { if ($this->restModel !== null) { if ($this->restModel->isNewRecord()) { return "Adding a new " . strtolower(StringTools::wordifyStringByUpperCase(SolutionSchema::getModelNameFromClass(get_class($this->restModel)))) . " entry"; } else { return ucfirst(strtolower(StringTools::wordifyStringByUpperCase(SolutionSchema::getModelNameFromClass(get_class($this->restModel)))) . " '" . $this->restModel->GetLabel() . "'"); } } else { if ($this->restCollection !== null) { return StringTools::wordifyStringByUpperCase(StringTools::makePlural(SolutionSchema::getModelNameFromClass($this->restCollection->getModelClassName()))); } else { return "Untitled"; } } }
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; } }
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; }
public function __construct($version = 0) { parent::__construct($version); $this->addModel("TestModel", __NAMESPACE__ . "\\ModelB"); }
public function testRelationships() { SolutionSchema::registerSchema("MySchema", "Rhubarb\\Stem\\Tests\\Fixtures\\UnitTestingSolutionSchema"); $company = new Company(); $company->CompanyName = "Test Company"; $company->save(); $user = new User(); $user->Username = "******"; $user->Password = "******"; $user->Active = 1; $user->CompanyID = $company->CompanyID; $user->save(); $user = new User(); $user->Username = "******"; $user->Password = ""; $user->Active = 1; $user->CompanyID = $company->CompanyID; $user->save(); $company = $user->Company; $this->assertInstanceOf("\\Rhubarb\\Stem\\Tests\\Fixtures\\Company", $company); $this->assertEquals("Test Company", $company->CompanyName); $users = $company->Users; $this->assertCount(2, $users); $this->assertEquals("msmith", $users[1]->Username); }
protected function defineRelationships() { parent::defineRelationships(); $this->declareOneToManyRelationships(["Communication" => ["Items" => "CommunicationItem.CommunicationID"]]); }
protected function initialise() { parent::initialise(); SolutionSchema::registerSchema("RepositoryLog", Model\RepositoryLogSchema::class); }
/** * Finds the schema of the specified model and returns the values for the specified enum field * * @param $modelName * @param $enumFieldName * * @return array */ public static function GetEnumValues($modelName, $enumFieldName) { $schema = SolutionSchema::getModelSchema($modelName); $enum = $schema->getColumns()[$enumFieldName]; return $enum->enumValues; }
/** * 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(); }
protected function getCollectionFilter($phrase) { $model = SolutionSchema::getModel($this->modelClassName); $filter = new Contains($model->getLabelColumnName(), $phrase); return $filter; }
private function applyTypeDefinitionsToColumns() { if (!isset(self::$columnTypeFormatters[$this->modelClass])) { self::$columnTypeFormatters[$this->modelClass] = []; self::$columnTypeDecorators[$this->modelClass] = []; $schema = SolutionSchema::getModelSchema($this->modelClass); $columns = $schema->getColumns(); foreach ($this->typeFormatters as $type => $formatter) { foreach ($columns as $columnName => $column) { if ($column instanceof $type) { self::$columnTypeFormatters[$this->modelClass][$columnName] = $formatter; } } } foreach ($this->typeDecorators as $type => $decorator) { foreach ($columns as $columnName => $column) { if ($column instanceof $type) { self::$columnTypeDecorators[$this->modelClass][$columnName] = $decorator; } } } } foreach (self::$columnTypeDecorators[$this->modelClass] as $columnName => $decorator) { $this->columnDecorators[$columnName] = $decorator; } foreach (self::$columnTypeFormatters[$this->modelClass] as $columnName => $formatter) { $this->columnFormatters[$columnName] = $formatter; } }
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; }
public function __construct($version = 0.4) { parent::__construct($version); $this->addModel('Contact', Contact::class); }
public function __construct() { parent::__construct(0.3); $this->addModel("RhubarbLogEntry", RhubarbLogEntry::class); }
/** * Computes the given aggregates and returns an array of answers * * An answer will be null if the repository is unable to answer it. * * @param \Rhubarb\Stem\Aggregates\Aggregate[] $aggregates * @param \Rhubarb\Stem\Collections\Collection $collection * * @return array */ public function calculateAggregates($aggregates, Collection $collection) { $propertiesToAutoHydrate = []; if (!$this->canFilterExclusivelyByRepository($collection, $namedParams, $propertiesToAutoHydrate)) { return null; } $relationships = SolutionSchema::getAllRelationshipsForModel($this->getModelClass()); $propertiesToAutoHydrate = array_unique($propertiesToAutoHydrate); $joins = []; $joinColumns = []; 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 = ""; if (sizeof($joins)) { $joinString = " " . implode(" ", $joins); $joinClauses = []; foreach ($joinColumns as $aliasName => $columnName) { $joinClauses[] = "`" . str_replace('.', '`.`', $columnName) . "` AS `" . $aliasName . "`"; } } $clauses = []; $clausePositions = []; $results = []; $i = -1; $c = -1; $relationships = []; foreach ($aggregates as $aggregate) { $i++; $clause = $aggregate->aggregateWithRepository($this, $relationships); if ($clause != "") { $c++; $clauses[] = str_replace('.', '`.`', $clause); $clausePositions[$c] = $i; } else { $results[$i] = null; } } if (sizeof($clauses)) { $schema = $this->getSchema(); $namedParams = []; $propertiesToAutoHydrate = []; $groupClause = ""; if ($joinString) { $groupClause = " GROUP BY `{$schema->schemaName}`.`{$schema->uniqueIdentifierColumnName}`"; } $sql = "SELECT " . implode(", ", $clauses) . " FROM `{$schema->schemaName}`" . $joinString; $filter = $collection->getFilter(); if ($filter !== null) { $filterSql = $filter->filterWithRepository($this, $namedParams, $propertiesToAutoHydrate); if ($filterSql != "") { $sql .= " WHERE " . $filterSql; } } $sql .= $groupClause; $row = array_values(self::returnFirstRow($sql, $namedParams)); foreach ($clausePositions as $rowPosition => $resultPosition) { $results[$resultPosition] = $row[$rowPosition]; } } return $results; }
/** * 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; }