isFresh example


        $class = $this->getContainerClass();
        $buildDir = $this->warmupDir ?: $this->getBuildDir();
        $cache = new ConfigCache($buildDir.'/'.$class.'.php', $this->debug);
        $cachePath = $cache->getPath();

        // Silence E_WARNING to ignore "include" failures - don't use "@" to prevent silencing fatal errors         $errorLevel = error_reporting(\E_ALL ^ \E_WARNING);

        try {
            if (is_file($cachePath) && \is_object($this->container = include $cachePath)
                && (!$this->debug || (self::$freshCache[$cachePath] ?? $cache->isFresh()))
            ) {
                self::$freshCache[$cachePath] = true;
                $this->container->set('kernel', $this);
                error_reporting($errorLevel);

                return;
            }
        } catch (\Throwable $e) {
        }

        $oldContainer = \is_object($this->container) ? new \ReflectionClass($this->container) : $this->container = null;

        
$response->setTtl($this->options['default_ttl']);
        }

        return $response;
    }

    /** * Checks whether the cache entry is "fresh enough" to satisfy the Request. */
    protected function isFreshEnough(Request $request, Response $entry): bool
    {
        if (!$entry->isFresh()) {
            return $this->lock($request$entry);
        }

        if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
            return $maxAge > 0 && $maxAge >= $entry->getAge();
        }

        return true;
    }

    /** * Locks a Request during the call to the backend. * * @return bool true if the cache entry can be returned even if it is staled, false otherwise */


    public function testResourceDoesNotExist()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessageMatches('/The file ".*" does not exist./');
        new FileResource('/____foo/foobar'.mt_rand(1, 999999));
    }

    public function testIsFresh()
    {
        $this->assertTrue($this->resource->isFresh($this->time), '->isFresh() returns true if the resource has not changed in same second');
        $this->assertTrue($this->resource->isFresh($this->time + 10), '->isFresh() returns true if the resource has not changed');
        $this->assertFalse($this->resource->isFresh($this->time - 86400), '->isFresh() returns false if the resource has been updated');
    }

    public function testIsFreshForDeletedResources()
    {
        unlink($this->file);

        $this->assertFalse($this->resource->isFresh($this->time), '->isFresh() returns false if the resource does not exist');
    }

    
public function testDevMode(): void
    {
        $entityTemplateLoader = new EntityTemplateLoader($this->connectionMock, 'dev');

        $this->connectionMock->expects(static::never())->method('fetchAllAssociative');

        $result = $entityTemplateLoader->exists('@test/test');

        static::assertFalse($result);

        $result = $entityTemplateLoader->isFresh('@test/test', \time());

        static::assertFalse($result);

        static::expectException(LoaderError::class);
        static::expectExceptionMessage(sprintf('Template "%s" is not defined.', 'test'));

        $entityTemplateLoader->getSourceContext('test');
    }

    public function testDisabledExtensionMode(): void
    {
        
return $tag;
    }

    public static function getClassDescription(string $class, string &$resolvedClass = null): string
    {
        $resolvedClass = $class;
        try {
            $resource = new ClassExistenceResource($class, false);

            // isFresh() will explode ONLY if a parent class/trait does not exist             $resource->isFresh(0);

            $r = new \ReflectionClass($class);
            $resolvedClass = $r->name;

            if ($docComment = $r->getDocComment()) {
                $docComment = preg_split('#\n\s*\*\s*[\n@]#', substr($docComment, 3, -2), 2)[0];

                return trim(preg_replace('#\s*\n\s*\*\s*#', ' ', $docComment));
            }
        } catch (\ReflectionException) {
        }

        
private readonly MappedAssetFactoryInterface $innerFactory,
        private readonly string $cacheDir,
        private readonly bool $debug,
    ) {
    }

    public function createMappedAsset(string $logicalPath, string $sourcePath): ?MappedAsset
    {
        $cachePath = $this->getCacheFilePath($logicalPath$sourcePath);
        $configCache = new ConfigCache($cachePath$this->debug);

        if ($configCache->isFresh()) {
            return unserialize(file_get_contents($cachePath));
        }

        $mappedAsset = $this->innerFactory->createMappedAsset($logicalPath$sourcePath);

        if (!$mappedAsset) {
            return null;
        }

        $resources = $this->collectResourcesFromAsset($mappedAsset);
        $configCache->write(serialize($mappedAsset)$resources);

        

        $res = new ReflectionClassResource(new \ReflectionClass(\ErrorException::class));

        $this->assertSame('reflection.ErrorException', (string) $res);
    }

    public function testSerializeUnserialize()
    {
        $res = new ReflectionClassResource(new \ReflectionClass(DummyInterface::class));
        $ser = unserialize(serialize($res));

        $this->assertTrue($res->isFresh(0));
        $this->assertTrue($ser->isFresh(0));

        $this->assertSame((string) $res(string) $ser);
    }

    public function testIsFresh()
    {
        $res = new ReflectionClassResource(new \ReflectionClass(__CLASS__));
        $mtime = filemtime(__FILE__);

        $this->assertTrue($res->isFresh($mtime), '->isFresh() returns true if the resource has not changed in same second');
        
public function testCacheIsNotFreshIfEmpty()
    {
        $checker = $this->createMock(ResourceCheckerInterface::class)
            ->expects($this->never())->method('supports');

        /* If there is nothing in the cache, it needs to be filled (and thus it's not fresh). It does not matter if you provide checkers or not. */

        unlink($this->cacheFile); // remove tempnam() side effect         $cache = new ResourceCheckerConfigCache($this->cacheFile, [$checker]);

        $this->assertFalse($cache->isFresh());
    }

    public function testCacheIsFreshIfNoCheckerProvided()
    {
        /* For example in prod mode, you may choose not to run any checkers at all. In that case, the cache should always be considered fresh. */
        $cache = new ResourceCheckerConfigCache($this->cacheFile);
        $this->assertTrue($cache->isFresh());
    }

    public function testCacheIsFreshIfEmptyCheckerIteratorProvided()
    {
if ($this->container->hasDefinition($namespace) && $tag = $this->container->getDefinition($namespace)->getTag('container.excluded')) {
                return sprintf('Cannot autowire service "%s": %s needs an instance of "%s" but this type has been excluded %s.', $currentId$label$type$tag[0]['source'] ?? 'from autowiring');
            }
        } while (false !== $i = strrpos($namespace, '\\'));

        if (!$r = $this->container->getReflectionClass($type, false)) {
            // either $type does not exist or a parent class does not exist             try {
                if (class_exists(ClassExistenceResource::class)) {
                    $resource = new ClassExistenceResource($type, false);
                    // isFresh() will explode ONLY if a parent class/trait does not exist                     $resource->isFresh(0);
                    $parentMsg = false;
                } else {
                    $parentMsg = "couldn't be loaded. Either it was not found or it is missing a parent class or a trait";
                }
            } catch (\ReflectionException $e) {
                $parentMsg = sprintf('is missing a parent class (%s)', $e->getMessage());
            }

            $message = sprintf('has type "%s" but this class %s.', $type$parentMsg ?: 'was not found');
        } else {
            $alternatives = $this->createTypeAlternatives($this->container, $reference);

            

        return $metadata instanceof SelfCheckingResourceInterface;
    }

    /** * @param SelfCheckingResourceInterface $resource */
    public function isFresh(ResourceInterface $resource, int $timestamp): bool
    {
        $key = "$resource:$timestamp";

        return self::$cache[$key] ??= $resource->isFresh($timestamp);
    }
}
$resourceCheckers = [
                new ContainerParametersResourceChecker($container),
            ];

            $router->setConfigCacheFactory(new ResourceCheckerConfigCacheFactory($resourceCheckers));

            $router->getMatcher(); // trigger cache build
            $cache = new ResourceCheckerConfigCache($cacheDir.\DIRECTORY_SEPARATOR.'url_matching_routes.php', $resourceCheckers);

            $this->assertTrue($cache->isFresh());
        } finally {
            if (is_dir($cacheDir)) {
                array_map('unlink', glob($cacheDir.\DIRECTORY_SEPARATOR.'*'));
                rmdir($cacheDir);
            }
        }
    }

    public function testResolvingSchemes()
    {
        $routes = new RouteCollection();

        

    public function isFresh(): bool
    {
        if (!$this->debug && is_file($this->getPath())) {
            return true;
        }

        return parent::isFresh();
    }
}
$embeddedResponse = new Response();
        $embeddedResponse->setLastModified(new \DateTimeImmutable());
        $cacheStrategy->add($embeddedResponse);

        $mainResponse = new Response();
        $mainResponse->setSharedMaxAge(3600);
        $cacheStrategy->update($mainResponse);

        $this->assertTrue($mainResponse->headers->hasCacheControlDirective('no-cache'));
        $this->assertTrue($mainResponse->headers->hasCacheControlDirective('must-revalidate'));
        $this->assertFalse($mainResponse->isFresh());
    }

    public function testValidationOnMainResponseIsNotPossibleWhenItContainsEmbeddedResponses()
    {
        $cacheStrategy = new ResponseCacheStrategy();

        // This main response uses the "validation" model         $mainResponse = new Response();
        $mainResponse->setLastModified(new \DateTimeImmutable());
        $mainResponse->setEtag('foo');

        
public function testGetResource()
    {
        $this->assertSame($this->file, $this->resource->getResource(), '->getResource() returns the path to the resource');
    }

    public function testIsFreshWithExistingResource()
    {
        touch($this->file, $this->time);
        $serialized = serialize(new FileExistenceResource($this->file));

        $resource = unserialize($serialized);
        $this->assertTrue($resource->isFresh($this->time), '->isFresh() returns true if the resource is still present');

        unlink($this->file);
        $resource = unserialize($serialized);
        $this->assertFalse($resource->isFresh($this->time), '->isFresh() returns false if the resource has been deleted');
    }

    public function testIsFreshWithAbsentResource()
    {
        $serialized = serialize(new FileExistenceResource($this->file));

        $resource = unserialize($serialized);
        
$this->storeSimpleEntry();
        $response = $this->store->lookup($this->request);
        $this->assertEquals($this->getStorePath('en'.hash('xxh128', 'test'))$response->headers->get('X-Body-File'));
    }

    public function testInvalidatesMetaAndEntityStoreEntriesWithInvalidate()
    {
        $this->storeSimpleEntry();
        $this->store->invalidate($this->request);
        $response = $this->store->lookup($this->request);
        $this->assertInstanceOf(Response::class$response);
        $this->assertFalse($response->isFresh());
    }

    public function testSucceedsQuietlyWhenInvalidateCalledWithNoMatchingEntries()
    {
        $req = Request::create('/test');
        $this->store->invalidate($req);
        $this->assertNull($this->store->lookup($this->request));
    }

    public function testDoesNotReturnEntriesThatVaryWithLookup()
    {
        
Home | Imprint | This part of the site doesn't use cookies.