#34 - Functions for some sort of build script

Date: 2018-11-10 12:00 - PHP

Copy files based on a pattern and merge multiple javascript files into one with guard.

<?php

function copy_files($dst, $src, $pattern) {
    foreach (glob($src . $pattern) as $file) {
        if (substr($file, 0, strlen($src)) === $src) {
            $destfile = $dst . substr($file, strlen($src));
            copy($file, $destfile);
        } else {
            echo "$file doesn't have $src prefix\n";
        }
    }
}

function merge_scripts($resultFile, $files) {
    $check = FALSE;
    if (file_exists($resultFile)) {
        $check = sha1_file($resultFile);
    }

    $scriptContent = array("(function(){\n");
    foreach ($files as $file) {
        $scriptContent[] = file_get_contents($file);
    }
    $scriptContent[] = "\n})()";
    $newContents = implode("\n", $scriptContent);
    if (sha1($newContents) !== $check) {
        file_put_contents($resultFile, $newContents);
    }
}

Previous snippet | Next snippet