Skip to content

Instantly share code, notes, and snippets.

@donjajo
Last active October 2, 2018 18:14
Show Gist options
  • Save donjajo/bac592fbf63c0c4a4c1ca9462efe5dbc to your computer and use it in GitHub Desktop.
Save donjajo/bac592fbf63c0c4a4c1ca9462efe5dbc to your computer and use it in GitHub Desktop.
Get List of Directories in AWS S3 as array keys. Nested subfolders
<?php
require_once( __DIR__ . '/aws/aws-autoloader.php' );
use Aws\S3\S3Client;
define( 'AWS_S3', [
'key' => '',
'secret' => '',
'bucket' => ''
]);
function get_dirs() {
$s3 = S3Client::factory([
'credentials' => [
'key' => AWS_S3[ 'key' ],
'secret' => AWS_S3[ 'secret' ],
],
'region' => 'us-east-1',
'version' => 'latest'
]);
$objects = $s3->getIterator( 'ListObjects', [ 'Bucket' => AWS_S3[ 'bucket' ] ] );
$dirs = [];
foreach( $objects as $ob ) {
if( preg_match( '/^.*\/$/', $ob[ 'Key' ] ) ) {
$split = explode( '/', $ob[ 'Key' ] );
$dirs = nest_dir( $dirs, $split );
}
}
return $dirs;
}
function nest_dir( $ref, $dirs ) {
$dirs = array_filter( $dirs );
foreach( $dirs as $index => $dir ) {
$parent = @$dirs[ $index - 1 ];
if( $parent && isset( $ref[ $parent ] ) ) {
$ref[ $parent ][ $dir ] = nest_dir( [], array_slice( $dirs, $index + 1 ) );
continue;
}
if( !$parent || ( $parent && array_search( $parent, $dirs ) === 0 ) )
$ref[ $dir ] = [];
}
return $ref;
}
print_r( get_dirs() );
@donjajo
Copy link
Author

donjajo commented Oct 2, 2018

I use this jQuery to create unordered list elements, nested for subfolders

function show_dirs( ele, folders, prefix ) {
    jQuery.each( folders, function( key, value ) {
        prefix = ( prefix ? prefix + '/' + key : key )
        ele.append( '<li data-key="' + key + '" class="folder" data-prefix="' + prefix + '">' + key + '</li>' )
        if( Object.values( value ).length ) {
            var id = getRandomInt( 100, 999 )
            ele.find( 'li[data-key="' + key + '"]' ).append( '<ul id="folder_' + id + '" class="folders"></ul>' )
            show_dirs( ele.find( '#folder_' + id ), value, prefix )
        }
        prefix = ''
    })
}

@donjajo
Copy link
Author

donjajo commented Oct 2, 2018

<ul id="dirs"></ul>
show_dirs( $( '#dirs' ), json_object, '' )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment