PHP code example of jced-artem / leak-safe-generator

1. Go to this page and download the library: Download jced-artem/leak-safe-generator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jced-artem / leak-safe-generator example snippets


function parsePages() {
    $ch = curl_init();
    // ... some options
    while ($condition) {
        yield curl_exec($ch);
    }
    curl_close($ch);
}

foreach (parsePages() as $page) {
    if ($someCondition) {
        break;
    }
    // ...
}

function parsePages() {
    $ch = curl_init();
    // ... some options
    try {
        $finished = false;
        while ($condition) {
            yield curl_exec($ch);
        }
        $finished = true;
    } finally {
        // close anyway
        curl_close($ch);
        if ($finished) {
            // do something if reached last element
        } else {
            // do something on break
        }
    }
}

$lsg = new LeakSafeGenerator();
$lsg
    ->init(function() {
        $this->ch = curl_init();
        // ... some options
        while ($condition) {
            yield curl_exec($this->ch);
        }
    })
    ->onInterrupt(function() {
        // do something on break
    })
    ->onComplete(function() {
        // do something if reached last element
    })
    ->onFinish(function() {
        curl_close($this->ch);
    })
;
foreach ($lsg->getGenerator() as $page) {
    if ($someCondition) {
        break;
    }
    // ...
}

$lsg = new LeakSafeGenerator(
    function() {
        $this->ch = curl_init();
        // ... some options
        while ($condition) {
            yield curl_exec($this->ch);
        }
    },
    function() {
        curl_close($this->ch);
    }
);