44
55namespace Rector \Jack \Composer ;
66
7+ use Nette \Utils \DateTime ;
78use Nette \Utils \FileSystem ;
89use Symfony \Component \Process \Process ;
910
1011final class ComposerOutdatedResponseProvider
1112{
1213 public function provide (): string
1314 {
14- // load from cache, temporarily - @todo cache on json hash + week timeout
15- $ outdatedFilename = __DIR__ . '/../../dumped-outdated.json ' ;
16- if (is_file ($ outdatedFilename )) {
17- return FileSystem::read ($ outdatedFilename );
15+ $ composerOutdatedFilePath = $ this ->resolveComposerOutdatedFilePath ();
16+
17+ // let's use cache
18+ if ($ this ->shouldLoadCacheFile ($ composerOutdatedFilePath )) {
19+ /** @var string $composerOutdatedFilePath */
20+ return FileSystem::read ($ composerOutdatedFilePath );
1821 }
1922
2023 $ composerOutdatedProcess = Process::fromShellCommandline (
@@ -23,9 +26,60 @@ public function provide(): string
2326 );
2427
2528 $ composerOutdatedProcess ->mustRun ();
29+
2630 $ processResult = $ composerOutdatedProcess ->getOutput ();
2731
28- FileSystem::write ($ outdatedFilename , $ processResult );
32+ if (is_string ($ composerOutdatedFilePath )) {
33+ FileSystem::write ($ composerOutdatedFilePath , $ processResult );
34+ }
35+
2936 return $ processResult ;
3037 }
38+
39+ private function resolveProjectComposerHash (): ?string
40+ {
41+ if (file_exists (getcwd () . '/composer.lock ' )) {
42+ return sha1 (getcwd () . '/composer.lock ' );
43+ }
44+
45+ if (file_exists (getcwd () . '/composer.json ' )) {
46+ return getcwd () . '/composer.json ' ;
47+ }
48+
49+ return null ;
50+ }
51+
52+ private function resolveComposerOutdatedFilePath (): ?string
53+ {
54+ $ projectComposerHash = $ this ->resolveProjectComposerHash ();
55+ if ($ projectComposerHash ) {
56+ // load from cache, temporarily - @todo cache on json hash + week timeout
57+ return sys_get_temp_dir () . '/jack/composer-outdated- ' . $ projectComposerHash . '.json ' ;
58+ }
59+
60+ return null ;
61+ }
62+
63+ private function isFileYoungerThanWeek (string $ filePath ): bool
64+ {
65+ $ fileTime = filemtime ($ filePath );
66+ if ($ fileTime === false ) {
67+ return false ;
68+ }
69+
70+ return (time () - $ fileTime ) < DateTime::WEEK ;
71+ }
72+
73+ private function shouldLoadCacheFile (?string $ cacheFilePath ): bool
74+ {
75+ if (! is_string ($ cacheFilePath )) {
76+ return false ;
77+ }
78+
79+ if (! file_exists ($ cacheFilePath )) {
80+ return false ;
81+ }
82+
83+ return $ this ->isFileYoungerThanWeek ($ cacheFilePath );
84+ }
3185}
0 commit comments