Skip to content

Commit

Permalink
Merge pull request #3 from 8fold/filenames
Browse files Browse the repository at this point in the history
add: Allow directory with no specified file name
  • Loading branch information
joshbruce authored Apr 13, 2023
2 parents bb97273 + 27763fb commit b0e196d
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/Errors/Environment.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ enum Environment: string
case AllowUrlFOpenNotEnabled = 'Tried to copy file from URL without allow_url_fopen in php_ini';
case CopyDestinationMustBeLocal = 'Tried to copy file to URL';
case FailedToCreateDestinationDirectory = 'Tried to copy file to directory that was not found';
case FailedToParseUrl = 'Tried to copy file from URL and could not parse url.';
case UrlPathNotFound = 'Tried to copy file from URL with no path.';
}
25 changes: 25 additions & 0 deletions src/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ public static function fromUrlToLocalPath(
string $url,
string $filename
): self|ImageError|EnvironmentError {
if (str_contains($filename, '.') === false) {
$file = self::filenameFromUrl($url);
if (is_string($file) === false) {
return $file;
}
$filename = $filename . '/' . $file;
}

$copied = self::copiedUrlToLocalpath($url, $filename);
if (is_bool($copied) === false) {
return $copied;
Expand Down Expand Up @@ -98,6 +106,23 @@ public static function copiedUrlToLocalPath(
return copy($from, $to);
}

public static function filenameFromUrl(string $url): string|EnvironmentError
{
$url = parse_url($url);
if ($url === false) {
return EnvironmentError::FailedToParseUrl;
}

if (array_key_exists('path', $url) === false) {
return EnvironmentError::UrlPathNotFound;
}

$path = $url['path'];
$parts = explode('/', $path);

return array_pop($parts);
}

private static function didMakeDirectoryFor(string $filename): bool
{
$dir = self::directoryFromFilename($filename);
Expand Down
17 changes: 17 additions & 0 deletions tests/ImageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,23 @@ public function tearDown(): void
parent::tearDown();
}

/**
* @test
*/
public function can_get_file_from_url(): void
{
$expected = 'image.png';

$result = Image::filenameFromUrl(
'https://ex.ample/some/path/image.png?query=1#text-fragment'
);

$this->assertSame(
$expected,
$result
);
}

/**
* @test
*/
Expand Down

0 comments on commit b0e196d

Please sign in to comment.