Skip to content

Commit

Permalink
Merge pull request #2 from borislihk/SM-633
Browse files Browse the repository at this point in the history
SM-633: Upload to s3 obeying wordpress behaviour
  • Loading branch information
hoandang authored Aug 28, 2019
2 parents 6c5266d + bf28169 commit d920971
Showing 1 changed file with 26 additions and 9 deletions.
35 changes: 26 additions & 9 deletions wordpress-s3-uploads-drop-in.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,19 @@ public function filterUploadDir($dirs)

public function onUpdatedAttachment($attachmentData, $attachmentId)
{
$attachmentMainPath = $this->attachmentMainPath($attachmentId);
$sizes = $attachmentData['sizes'] ?? [];
$paths = array_filter(array_map([$this, 'attachmentPath'], $sizes));
$paths = [];
foreach($sizes as $size)
{
if ($path = $this->attachmentPath($size, $attachmentMainPath))
{
$paths[] = $path;
}
}

$attachments = array_values(array_merge(
[$this->attachmentMainPath($attachmentId)],
[$attachmentMainPath],
$paths
));

Expand Down Expand Up @@ -109,7 +117,8 @@ public function uploadToS3($path)
{
$source = fopen($path, 'rb');
$filename = basename($path);
$key = getenv('AWS_S3_PATH') . wp_get_upload_dir()['subdir'] . "/$filename";
$time = $this->attachmentTime($path);
$key = getenv('AWS_S3_PATH') . "/$time/$filename";
$uploader = new ObjectUploader(
$this->s3Client,
getenv('AWS_S3_BUCKET'),
Expand All @@ -119,14 +128,20 @@ public function uploadToS3($path)
$uploader->upload();
}

private function attachmentLocation($attachmentId)
private function attachmentTime($path)
{
$attachmentMainPath = $this->attachmentMainPath($attachmentId);
$pathInfo = pathinfo($attachmentMainPath);
$pathInfo = pathinfo($path);
$dirname = explode('/', $pathInfo['dirname']);
$year = $dirname[count($dirname) - 2];
$month = $dirname[count($dirname) - 1];
return "uploads/$year/$month";
return "$year/$month";
}

private function attachmentLocation($attachmentId)
{
$attachmentMainPath = $this->attachmentMainPath($attachmentId);
$time = $this->attachmentTime($attachmentMainPath);
return "uploads/$time";
}

private function attachmentMainPath($attachmentId)
Expand All @@ -144,9 +159,11 @@ private function attachmentOtherPaths($attachmentId)
}, $this->sizes($attachmentId)));
}

private function attachmentPath($sizeInfo)
private function attachmentPath($sizeInfo, $mainPath)
{
return isset($sizeInfo['file']) ? wp_get_upload_dir()['path'] . '/' . $sizeInfo['file'] : null;
$basedir = wp_get_upload_dir()['basedir'];
$time = $this->attachmentTime($mainPath);
return isset($sizeInfo['file']) ? "$basedir/$time/" . $sizeInfo['file'] : null;
}

private function sizes($attachmentId)
Expand Down

0 comments on commit d920971

Please sign in to comment.