the browser-facing portion of osu!
at master 1.9 kB view raw
1<?php 2 3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. 4// See the LICENCE file in the repository root for full licence text. 5 6declare(strict_types=1); 7 8namespace App\Libraries; 9 10use Carbon\Carbon; 11use Exception; 12use GuzzleHttp\Client; 13 14class MenuContent 15{ 16 /** 17 * Get all active menu content images. 18 * 19 * @return array<string, mixed>[] 20 */ 21 public static function activeImages(): array 22 { 23 return cache_remember_mutexed('menu-content-active-images', 60, [], function () { 24 $images = self::parse(self::fetch()); 25 $now = Carbon::now(); 26 27 return array_values(array_filter($images, fn ($image) => ( 28 ($image['started_at']?->lessThanOrEqualTo($now) ?? true) 29 && ($image['ended_at']?->greaterThan($now) ?? true) 30 ))); 31 }); 32 } 33 34 private static function fetch(): array 35 { 36 $response = (new Client()) 37 ->get(osu_url('menu_content')) 38 ->getBody() 39 ->getContents(); 40 41 return json_decode($response, true); 42 } 43 44 private static function parse(array $data): array 45 { 46 if (!is_array($data['images'] ?? null)) { 47 throw new Exception('Invalid "images" key in menu-content response'); 48 } 49 50 $parsedImages = []; 51 52 foreach ($data['images'] as $image) { 53 if (!is_string($image['image']) || !is_string($image['url'])) { 54 throw new Exception('Invalid "image" or "url" key in menu-content image'); 55 } 56 57 $parsedImages[] = [ 58 'ended_at' => parse_time_to_carbon($image['expires']), 59 'image_url' => $image['image'], 60 'started_at' => parse_time_to_carbon($image['begins']), 61 'url' => $image['url'], 62 ]; 63 } 64 65 return $parsedImages; 66 } 67}