11<?php
22
33// Example: custom finder function that finds files in ftp by using a custom function instead of scanning the file system
4- // Example: custom prune function that deletes files from ftp
4+ // Example: custom prune function that deletes files from ftp (use xlight ftp server for quick testing)
55
66use PhpRetention \FileInfo ;
77use PhpRetention \Retention ;
88
99require_once __DIR__ . "/../vendor/autoload.php " ;
1010
11- $ ftpConnection = ftp_connect ("ftp.example.com " );
11+ $ ftpConnection = ftp_connect ("localhost " );
1212if (!$ ftpConnection ) {
1313 die ('Could not connect to the FTP server ' );
1414}
15- $ loginResult = ftp_login ($ ftpConnection , "ftp-user " , "ftp-pass " );
15+ $ loginResult = ftp_login ($ ftpConnection , "test " , "123456 " );
1616if (!$ loginResult ) {
1717 die ('FTP login failed ' );
1818}
1919
2020$ ret = new Retention ([
21- 'keep-last ' => 2
21+ 'keep-daily ' => 3 ,
22+ 'keep-weekly ' => 2
2223]);
2324$ ret ->setFindHandler (function (string $ targetDir ) use ($ ftpConnection ) {
2425 $ files = [];
2526 $ fileList = ftp_mlsd ($ ftpConnection , $ targetDir ) ?: [];
2627 foreach ($ fileList as $ file ) {
2728 $ filename = $ file ['name ' ];
28- $ time = (int ) $ file ['modify ' ];
29-
30- if (preg_match ('/^backup_\w+\.zip$/ ' , $ filename )) {
31- $ date = new DateTimeImmutable ('now ' , new DateTimeZone ('UTC ' ));
32- $ date ->setTimestamp ($ time );
33-
34- $ filepath = "$ targetDir/ $ filename " ;
35-
36- $ files [] = new FileInfo (
37- date: $ date ,
38- path: $ filepath ,
39- isDirectory: false
40- );
29+ if (preg_match ('/^backup\-\w+$/ ' , $ filename )) {
30+ if (preg_match ('/([0-9]{4})([0-9]{2})([0-9]{2})/ ' , $ file ['modify ' ], $ matches )) {
31+ $ year = intval ($ matches [1 ]);
32+ $ month = intval ($ matches [2 ]);
33+ $ day = intval ($ matches [3 ]);
34+
35+ $ date = new DateTimeImmutable ('now ' , new DateTimeZone ('UTC ' ));
36+ $ date = $ date ->setDate ($ year , $ month , $ day )->setTime (0 , 0 , 0 );
37+
38+ $ filepath = "$ targetDir/ $ filename " ;
39+ $ files [] = new FileInfo (
40+ date: $ date ,
41+ path: $ filepath ,
42+ isDirectory: false
43+ );
44+ }
4145 }
4246 }
4347
4448 return $ files ;
4549});
4650$ ret ->setPruneHandler (function (FileInfo $ fileInfo ) use ($ ftpConnection ) {
47- ftp_delete ($ ftpConnection , $ fileInfo ->path );
51+ return ftp_delete ($ ftpConnection , $ fileInfo ->path );
4852});
49- $ ret ->apply ("/path/to/dir " );
53+ $ keptFiles = $ ret ->apply ("/backup " );
54+
55+ print_r ($ keptFiles );
5056
5157ftp_close ($ ftpConnection );
0 commit comments