aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/Routes/Institutes/InstituteHierarchy.php
blob: a6a3fc331091edb6928eab19466d1b0108473cb4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
namespace JsonApi\Routes\Institutes;

use DI\NotFoundException;
use Institute;
use JsonApi\JsonApiController;
use Psr\Http\Message\{
    ResponseInterface as Response,
    ServerRequestInterface as Request
};

final class InstituteHierarchy extends JsonApiController
{
    public function __invoke(Request $request, Response $response, array $args): Response
    {
        $institute = Institute::find($args['id']);
        if (!$institute) {
            throw new NotFoundException();
        }

        $hierarchy = $this->getHierarchyUp($institute);

        return $this->getContentResponse($hierarchy);
    }

    private function getHierarchyUp(Institute $institute): array
    {
        $hierarchy = [];
        do {
            $hierarchy[] = $institute;

            $range_tree = \RangeTreeNode::findOneBySQL(
                "studip_object_id = ?",
                [$institute->id]
            );

            $institute = $range_tree?->parent->institute;
        } while ($institute);

        return array_reverse($hierarchy);
    }
}