Skip to content

Commit

Permalink
fix(attachment): update app_attachment_url_to_postid function
Browse files Browse the repository at this point in the history
  • Loading branch information
Jazz-Man committed May 30, 2024
1 parent 9f1a754 commit 76584e7
Showing 1 changed file with 27 additions and 9 deletions.
36 changes: 27 additions & 9 deletions src/helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,19 +150,36 @@ function app_get_attachment_image( int|string $attachmentId, array|string $size
* @return false|int
*/
function app_attachment_url_to_postid( string $url ): bool|int {
if ( ! app_is_current_host( $url ) ) {
global $wpdb;

if ( ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
return false;
}

global $wpdb;
$filetype = wp_check_filetype( $url );

if ( empty( $filetype['ext'] ) ) {

Check failure on line 161 in src/helper.php

View workflow job for this annotation

GitHub Actions / psalm

[psalm] src/helper.php#L161

RiskyTruthyFalsyComparison: Operand of type false|null|string contains type string, which can be falsy and truthy. This can cause possibly unexpected behavior. Use strict comparison instead.
Raw output
src/helper.php:161:14: error: RiskyTruthyFalsyComparison: Operand of type false|null|string contains type string, which can be falsy and truthy. This can cause possibly unexpected behavior. Use strict comparison instead. ()
return false;
}

$uploadDir = wp_upload_dir();
$relative_url = wp_make_link_relative( $url );

$siteUrl = (object) parse_url( $uploadDir['url'] );
$imagePath = (object) parse_url( $url );
$old_basename = basename( $url );

if ( (string) $imagePath->scheme !== (string) $siteUrl->scheme ) {
$url = str_replace( (string) $imagePath->scheme, (string) $siteUrl->scheme, $url );
/**
* removed image size from name.
*/
$new_basename = (string) preg_replace( "/-\\d+x\\d+\\.{$filetype['ext']}/", ".{$filetype['ext']}", $old_basename );

if ( empty( $new_basename ) ) {
return false;
}


$guid_url = str_replace( $old_basename, $new_basename, $relative_url );

if ( empty( $guid_url ) ) {
return false;
}

try {
Expand All @@ -180,11 +197,12 @@ function app_attachment_url_to_postid( string $url ): bool|int {
);

$pdoStatement->execute( [
'guid' => esc_url_raw( $url ),
'guid' => esc_url_raw( home_url( $guid_url ) ),
] );

return (int) $pdoStatement->fetchColumn();
} catch ( Exception ) {

} catch ( Exception $exception ) {
return false;
}
}
Expand Down

0 comments on commit 76584e7

Please sign in to comment.