Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,8 @@ public function getSummit($summit_id)
return $this->processRequest(function () use ($summit_id) {

Log::debug(sprintf("OAuth2SummitApiController::getSummit %s", $summit_id));
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)->find($summit_id);
$summit = SummitFinderStrategyFactory::build($this->repository, $this->resource_server_context)
->find($summit_id, ['event_types','badge_features_types','badge_features_types.image','presentation_categories','ticket_types','locations','category_groups','badge_access_level_types']);
if (!$summit instanceof Summit || $summit->isDeleting()) return $this->error404();
$current_member = $this->resource_server_context->getCurrentUser();

Expand Down Expand Up @@ -1082,4 +1083,4 @@ public function validateBadge($summit_id, $badge) {
);
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,21 @@ public function __construct
}

/**
* @param mixed $summit_id
* @return null|Summit
* @param $summit_id
* @param array $relations
* @return mixed|Summit|\models\utils\IEntity|null
*/
public function find($summit_id)
public function find($summit_id, array $relations = [])
{
if(count($relations) > 0){
Copy link

Copilot AI Oct 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing space after 'if' keyword. Should be 'if (count($relations) > 0) {' to follow PHP coding standards.

Suggested change
if(count($relations) > 0){
if (count($relations) > 0){

Copilot uses AI. Check for mistakes.
$summit = $summit_id === 'current' ? $this->repository->getCurrentAndRelations($relations) : $this->repository->getByIdAndRelations(intval($summit_id), $relations);
if(is_null($summit))
Copy link

Copilot AI Oct 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing space after 'if' keyword. Should be 'if (is_null($summit))' to follow PHP coding standards.

Suggested change
if(is_null($summit))
if (is_null($summit))

Copilot uses AI. Check for mistakes.
$summit = $this->repository->getBySlugAndRelations(strval($summit_id), $relations);
return $summit;
}
$summit = $summit_id === 'current' ? $this->repository->getCurrent() : $this->repository->getById(intval($summit_id));
if(is_null($summit))
$summit = $this->repository->getBySlug(strval($summit_id));
return $summit;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@
interface ISummitFinderStrategy
{
/**
* @param mixed $summit_id
* @return null|Summit
* @param $summit_id
* @param array $relations
* @return mixed
*/
public function find($summit_id);
}
public function find($summit_id, array $relations = []);
}
13 changes: 12 additions & 1 deletion app/Models/Foundation/Summit/Repositories/ISummitRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,15 @@ public function getAllWithExternalRegistrationFeed():array;
* @return PagingResponse
*/
public function getRegistrationCompanies(Summit $summit, PagingInfo $paging_info, Filter $filter = null, Order $order = null):PagingResponse;
}

public function getBySlugAndRelations(string $slug, array $relations = []): ?Summit;

public function getByIdAndRelations(int $id, array $relations = []): ?Summit;

/**
* @param array $relations
* @return Summit|null
*/
public function getCurrentAndRelations(array $relations = []):?Summit;

}
59 changes: 58 additions & 1 deletion app/Repositories/Summit/DoctrineSummitRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
* limitations under the License.
**/

use App\libs\Utils\Doctrine\GraphLoaderTrait;
use Doctrine\ORM\Query\ResultSetMappingBuilder;
use Doctrine\ORM\QueryBuilder;
use Illuminate\Support\Facades\Log;
use models\summit\ISummitRepository;
use models\summit\Summit;
use App\Repositories\SilverStripeDoctrineRepository;
use utils\DoctrineFilterMapping;
use utils\DoctrineHavingFilterMapping;
use utils\Filter;
use utils\Order;
use utils\PagingInfo;
Expand All @@ -33,6 +33,8 @@ final class DoctrineSummitRepository
extends SilverStripeDoctrineRepository
implements ISummitRepository
{
use GraphLoaderTrait;


/**
* @return array
Expand Down Expand Up @@ -438,4 +440,59 @@ public function getRegistrationCompanies(Summit $summit, PagingInfo $paging_info

return new PagingResponse($total, $paging_info->getPerPage(), $paging_info->getCurrentPage(), $last_page, $companies);
}

public function getBySlugAndRelations(string $slug, array $relations = []): ?Summit
{
try {
return $this->loadGraphBy(
$this->getEntityManager(),
Summit::class,
$relations,
// WHERE configurator
function ($qb, string $rootAlias) use ($slug): void {
$qb->where("$rootAlias.slug = :slug")
->setParameter('slug', strtolower($slug));
}
);
} catch (\Throwable $e) {
Log::warning($e);
return null;
}
}

public function getByIdAndRelations(int $id, array $relations = []): ?Summit
{
try {
return $this->loadGraphBy(
$this->getEntityManager(),
Summit::class,
$relations,
function ($qb, string $rootAlias) use ($id): void {
$qb->where("$rootAlias.id = :id")
->setParameter('id', $id);
}
);
} catch (\Throwable $e) {
Log::warning($e);
return null;
}
}

public function getCurrentAndRelations(array $relations = []): ?Summit
{
try {
return $this->loadGraphBy(
$this->getEntityManager(),
Summit::class,
$relations,
function ($qb, string $rootAlias): void {
$qb->where('s.active = 1')
->orderBy('s.begin_date', 'DESC');
}
);
} catch (\Throwable $e) {
Log::warning($e);
return null;
}
}
}
208 changes: 208 additions & 0 deletions app/libs/Utils/Doctrine/GraphLoaderTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
<?php namespace App\libs\Utils\Doctrine;
/*
* Copyright 2025 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query;

/**
* Generic helpers to load a root entity plus a flexible set of relations.
* - Direct ToOne relations are joined in the root query.
* - Each requested top-level ToMany relation is loaded in a separate query.
* - Nested ToOne under a top-level collection (dot-notation) are joined in that same per-collection query.
*/
trait GraphLoaderTrait
{
/**
* Normalize user-provided relations (trim, unique, remove empties).
*/
protected function normalizeRelations(array $relations): array
{
return array_values(array_unique(array_filter(array_map(
static fn($r) => trim((string)$r),
$relations
))));
}

/**
* Partition requested relations into:
* - $toOneDirect: direct ToOne on the root entity
* - $topCollections: top-level ToMany relations on the root entity
* - $nestedByCollection: nested ToOne under a top-level collection (dot-notation)
*
* @return array{toOneDirect: string[], topCollections: string[], nestedByCollection: array<string, string[]>}
*/
protected function partitionRelations(ClassMetadata $meta, array $relations): array
{
$toOneDirect = [];
$topCollections = [];
$nestedByCollection = [];

foreach ($relations as $r) {
$parts = explode('.', $r);
$top = $parts[0];

if (!isset($meta->associationMappings[$top])) {
// Not a mapped association on the root entity; skip.
continue;
}

$type = $meta->associationMappings[$top]['type'] ?? null;

if (count($parts) === 1) {
// Direct relation on root
if (in_array($type, [ClassMetadata::MANY_TO_ONE, ClassMetadata::ONE_TO_ONE], true)) {
$toOneDirect[] = $top;
} else {
// ONE_TO_MANY or MANY_TO_MANY
$topCollections[] = $top;
}
} else {
// Dot-notation: top is a collection; the rest are assumed ToOne
$topCollections[] = $top;
$nestedByCollection[$top] = array_merge(
$nestedByCollection[$top] ?? [],
array_slice($parts, 1)
);
}
}

// De-duplicate
$toOneDirect = array_values(array_unique($toOneDirect));
$topCollections = array_values(array_unique($topCollections));
foreach ($nestedByCollection as $k => $arr) {
$nestedByCollection[$k] = array_values(array_unique($arr));
}

return compact('toOneDirect', 'topCollections', 'nestedByCollection');
}

/**
* Build and execute the root query:
* - SELECT root alias
* - LEFT JOIN + addSelect for each direct ToOne relation
*
* Returns the hydrated root entity or null.
*/
protected function loadRootWithToOne(
EntityManagerInterface $em,
string $entityClass,
array $toOneDirect,
callable $whereConfigurator // function(QueryBuilder $qb, string $rootAlias): void
): ?object {
$qb = $em->createQueryBuilder();
$qb->select('r')
->from($entityClass, 'r');

foreach ($toOneDirect as $rel) {
$alias = 'r_' . $rel;
$qb->leftJoin("r.$rel", $alias)->addSelect($alias);
}

// Let caller apply WHERE / params
$whereConfigurator($qb, 'r');

return $qb->getQuery()->getOneOrNullResult();
}

/**
* For a given root id, load exactly one top-level collection and optional nested ToOne under items of that collection.
* Example: root -> badgeFeatureTypes (collection) -> file (ToOne)
*
* This hydrates into the current UnitOfWork; no need to assign the result.
*/
protected function hydrateCollectionWithNestedToOne(
EntityManagerInterface $em,
string $entityClass,
string|int $rootId,
string $collection,
array $nestedToOne = []
): void {
$rootAlias = 'r2';
$colAlias = 'c2_' . $collection;

$selects = [$rootAlias, $colAlias];
$joins = ["LEFT JOIN $rootAlias.$collection $colAlias"];

foreach ($nestedToOne as $nestedRel) {
$nestedAlias = $colAlias . '_' . $nestedRel;
$joins[] = "LEFT JOIN $colAlias.$nestedRel $nestedAlias";
$selects[] = $nestedAlias;
}

$dql = sprintf(
'SELECT DISTINCT %s FROM %s %s %s WHERE %s.id = :id',
implode(', ', $selects),
$entityClass,
$rootAlias,
implode(' ', $joins),
$rootAlias
);

$em->createQuery($dql)
->setParameter('id', $rootId)
->getOneOrNullResult();
}

/**
* High-level convenience: load a root entity by an arbitrary field using a where configurator,
* plus a flexible graph (ToOne direct + one query per requested top-level collection).
*
* Returns the root entity or null.
*/
protected function loadGraphBy(
EntityManagerInterface $em,
string $entityClass,
array $relations,
callable $whereConfigurator // function(QueryBuilder $qb, string $rootAlias): void
): ?object {
$meta = $em->getClassMetadata($entityClass);
$relations = $this->normalizeRelations($relations);
$partitions = $this->partitionRelations($meta, $relations);

// 1) Root + direct ToOne
$root = $this->loadRootWithToOne(
$em,
$entityClass,
$partitions['toOneDirect'],
$whereConfigurator
);

if (!$root) {
return null;
}

// 2) Per collection query (+ optional nested ToOne)
$idField = $meta->getSingleIdentifierFieldName();
$getter = 'get' . ucfirst($idField);
$rootId = $root->$getter();

foreach ($partitions['topCollections'] as $collection) {
// Defensive: ensure mapping still exists
if (!isset($meta->associationMappings[$collection])) {
continue;
}

$nested = $partitions['nestedByCollection'][$collection] ?? [];
$this->hydrateCollectionWithNestedToOne(
$em,
$entityClass,
$rootId,
$collection,
$nested
);
}

return $root;
}
}
Loading