App\services\Download::fromSong PHP Method

fromSong() protected method

Generate the downloadable path for a song.
protected fromSong ( Song $song ) : string
$song app\models\Song
return string
    protected function fromSong(Song $song)
    {
        if ($s3Params = $song->s3_params) {
            // The song is hosted on Amazon S3.
            // We download it back to our local server first.
            $localPath = rtrim(sys_get_temp_dir(), '/') . '/' . basename($s3Params['key']);
            $url = $song->getObjectStoragePublicUrl();
            abort_unless($url, 404);
            // The following function require allow_url_fopen to be ON.
            // We're just assuming that to be the case here.
            copy($url, $localPath);
        } else {
            // The song is hosted locally. Make sure the file exists.
            abort_unless(file_exists($song->path), 404);
            $localPath = $song->path;
        }
        // The BinaryFileResponse factory only accept ASCII-only file names.
        if (ctype_print($localPath)) {
            return $localPath;
        }
        // For those with high-byte characters in names, we copy it into a safe name
        // as a workaround.
        $newPath = rtrim(sys_get_temp_dir(), '/') . '/' . utf8_decode(basename($song->path));
        if ($s3Params) {
            // If the file is downloaded from S3, we rename it directly.
            // This will save us some disk space.
            rename($localPath, $newPath);
        } else {
            // Else we copy it to another file to not mess up the original one.
            copy($localPath, $newPath);
        }
        return $newPath;
    }