|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Helpers\Mocks; |
| 4 | + |
| 5 | +use App\Helpers\MetaFormats\FormatCache; |
| 6 | +use App\Helpers\MetaFormats\MetaFormatHelper; |
| 7 | +use App\Helpers\Mocks\MockUserStorage; |
| 8 | +use App\V1Module\Presenters\BasePresenter; |
| 9 | +use Nette\Application\Application; |
| 10 | +use Nette\Application\PresenterFactory; |
| 11 | +use Nette\Application\Routers\RouteList; |
| 12 | +use Nette\Http\Response; |
| 13 | +use Nette\Http\UrlScript; |
| 14 | +use Nette\Security\User; |
| 15 | +use Nette; |
| 16 | +use ReflectionProperty; |
| 17 | + |
| 18 | +class MockHelper |
| 19 | +{ |
| 20 | + /** |
| 21 | + * Initializes a presenter object with empty http request, response, and user objects. |
| 22 | + * This is intended to be called right after presenter instantiation and before calling the Presenter::run method. |
| 23 | + * @param BasePresenter $presenter The presenter to be initialized. |
| 24 | + */ |
| 25 | + public static function initPresenter(BasePresenter $presenter) |
| 26 | + { |
| 27 | + $httpRequest = new \Nette\Http\Request(new UrlScript()); |
| 28 | + $httpResponse = new Response(); |
| 29 | + $user = new User(new MockUserStorage()); |
| 30 | + |
| 31 | + $application = new Application(new PresenterFactory(), new RouteList("V1"), $httpRequest, $httpResponse); |
| 32 | + $presenter->application = $application; |
| 33 | + |
| 34 | + $factory = new MockTemplateFactory(); |
| 35 | + |
| 36 | + $presenter->injectPrimary($httpRequest, $httpResponse, user: $user, templateFactory: $factory); |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Injects a Format class to the FormatCache. |
| 41 | + * This method must not be used outside of testing, normal Format classes are discovered automatically. |
| 42 | + * @param string $format The Format class name. |
| 43 | + */ |
| 44 | + public static function injectFormat(string $format) |
| 45 | + { |
| 46 | + // make sure the cache is initialized (it uses lazy loading) |
| 47 | + FormatCache::getFormatToFieldDefinitionsMap(); |
| 48 | + FormatCache::getFormatNamesHashSet(); |
| 49 | + |
| 50 | + // inject the format name |
| 51 | + $hashSetReflector = new ReflectionProperty(FormatCache::class, "formatNamesHashSet"); |
| 52 | + $hashSetReflector->setAccessible(true); |
| 53 | + $formatNamesHashSet = $hashSetReflector->getValue(); |
| 54 | + $formatNamesHashSet[$format] = true; |
| 55 | + $hashSetReflector->setValue(null, $formatNamesHashSet); |
| 56 | + |
| 57 | + // inject the format definitions |
| 58 | + $formatMapReflector = new ReflectionProperty(FormatCache::class, "formatToFieldFormatsMap"); |
| 59 | + $formatMapReflector->setAccessible(true); |
| 60 | + $formatToFieldFormatsMap = $formatMapReflector->getValue(); |
| 61 | + $formatToFieldFormatsMap[$format] = MetaFormatHelper::createNameToFieldDefinitionsMap($format); |
| 62 | + $formatMapReflector->setValue(null, $formatToFieldFormatsMap); |
| 63 | + } |
| 64 | +} |
0 commit comments