11#!/usr/bin/env php
22<?php
3+
4+ use wapmorgan \Threadable \DownloadWorker ;
35use wapmorgan \Threadable \Worker ;
46use wapmorgan \Threadable \WorkersPool ;
57require_once __DIR__ .'/../vendor/autoload.php ' ;
68
7- class DownloadWorker extends Worker
8- {
9- public function onPayload (array $ data )
10- {
11- echo 'Started ' .$ data [0 ].' into ' .$ data [2 ].PHP_EOL ;
12- copy ($ data [0 ], $ data [2 ]);
13- }
14- }
15-
16- function remote_filesize ($ path )
17- {
18- $ fp = fopen ($ path , 'r ' );
19- $ inf = stream_get_meta_data ($ fp );
20- fclose ($ fp );
21-
22- foreach ($ inf ["wrapper_data " ] as $ v ) {
23- if (stristr ($ v ,"content-length " )) {
24- $ v = explode (": " ,$ v );
25- return (int )trim ($ v [1 ]);
26- }
27- }
28- }
29-
309function show_status (&$ files )
3110{
3211 foreach ($ files as $ i => $ file ) {
33- if (file_exists ($ file [2 ])) {
34- clearstatcache (true , $ file [2 ]);
35- $ downloaded_size = filesize ($ file [2 ]);
36- if ($ downloaded_size == $ file [1 ]) {
37- echo $ file [0 ].' downloaded ' .PHP_EOL ;
12+ if (file_exists ($ file [' target ' ])) {
13+ clearstatcache (true , $ file [' target ' ]);
14+ $ downloaded_size = filesize ($ file [' target ' ]);
15+ if ($ downloaded_size == $ file [' size ' ]) {
16+ echo $ file [' source ' ].' downloaded ' .PHP_EOL ;
3817 unset($ files [$ i ]);
39- unlink ($ file [2 ]);
18+ unlink ($ file [' target ' ]);
4019 } else if ($ downloaded_size === 0 ) {
4120 // echo $file[0].' in queue'.PHP_EOL;
4221 } else {
43- echo $ file [0 ].' downloading ' .round ($ downloaded_size * 100 / $ file [1 ], 2 ).'% ' .PHP_EOL ;
22+ echo $ file [' source ' ].' downloading ' .round ($ downloaded_size * 100 / $ file [' size ' ], 2 ).'% ' .PHP_EOL ;
4423 }
4524 }
4625 }
@@ -49,16 +28,20 @@ function show_status(&$files)
4928$ file_sources = [/*'https://yandex.ru/images/today?size=1920x1080', */ 'http://hosting-obzo-ru.1gb.ru/hosting-obzor.ru.zip ' , 'http://soft.eurodir.ru/test-speed-100Mb.bin ' ];
5029$ files = [];
5130foreach ($ file_sources as $ file_to_download ) {
52- $ file_size = remote_filesize ($ file_to_download );
31+ $ file_size = DownloadWorker:: getRemoteFileSize ($ file_to_download );
5332 $ output = tempnam (sys_get_temp_dir (), 'thrd_test ' );
54- $ files [] = [$ file_to_download , $ file_size , $ output ];
33+ $ files [] = [
34+ 'source ' => $ file_to_download ,
35+ 'size ' => $ file_size ,
36+ 'target ' => $ output ,
37+ ];
5538}
5639
57- $ pool = new WorkersPool ('DownloadWorker ' );
40+ $ pool = new WorkersPool ('wapmorgan\Threadable\ DownloadWorker ' );
5841$ pool ->setPoolSize (3 );
5942foreach ($ files as $ file ) {
60- echo 'Enqueuing ' .$ file [0 ].' with size ' .$ file [1 ].PHP_EOL ;
61- $ pool ->sendData ([ $ file] );
43+ echo 'Enqueuing ' .$ file [' source ' ].' with size ' .$ file [' size ' ].PHP_EOL ;
44+ $ pool ->sendData ($ file );
6245}
6346
6447$ pool ->waitToFinish ([
0 commit comments