Skip to content

Adds Misc helper for file information and formatting#474

Open
firestar300 wants to merge 3 commits intomasterfrom
feature/misc-helper
Open

Adds Misc helper for file information and formatting#474
firestar300 wants to merge 3 commits intomasterfrom
feature/misc-helper

Conversation

@firestar300
Copy link
Contributor

@firestar300 firestar300 commented Feb 25, 2026

Introduces a new helper to provide utility functions for handling file-related data.

This helper simplifies retrieving comprehensive attachment details and includes a dedicated function (get_accessible_file_size_label) to improve accessibility by transforming file size strings into pluralized, human-readable labels.

Summary by Sourcery

Introduce a miscellaneous helper module for file metadata retrieval and accessible file size formatting.

New Features:

  • Add a Misc helper that exposes a get_file_infos utility to return structured metadata for attachments, including name, URL, caption, and derived details.
  • Provide helpers to build human-readable file detail strings combining name, extension, and size.
  • Add an accessible file size label helper that converts raw size strings into localized, pluralized units for screen reader friendliness.

Enhancements:

  • Wire the new Misc helper into the theme bootstrap so its functions are available across the project.

Introduces a new helper to provide utility functions for handling file-related data.

This helper simplifies retrieving comprehensive attachment details and includes a dedicated function (`get_accessible_file_size_label`) to improve accessibility by transforming file size strings into pluralized, human-readable labels.
@sourcery-ai
Copy link

sourcery-ai bot commented Feb 25, 2026

Reviewer's Guide

Introduces a new Misc helper providing utilities to retrieve structured attachment metadata and generate accessible, human-readable file detail strings, and wires it into the theme bootstrap.

Sequence diagram for retrieving accessible file information

sequenceDiagram
  actor Caller
  participant Misc as MiscHelper
  participant WP_Attach as WordPress_Attachments
  participant WP_File as WordPress_FileSystem
  participant WP_Post as WordPress_Post

  Caller->>Misc: get_file_infos(file_id)
  Misc->>WP_Attach: wp_get_attachment_url(file_id)
  WP_Attach-->>Misc: file_href
  alt file_href empty
    Misc-->>Caller: default_file_infos_array
  else file_href present
    Misc->>WP_Attach: get_attached_file(file_id)
    WP_Attach-->>Misc: file_path
    alt file_path empty
      Misc-->>Caller: default_file_infos_array
    else file_path present
      Misc->>WP_Post: get_post_mime_type(file_id)
      WP_Post-->>Misc: mime_type
      Misc->>Misc: get_mime_type(file_id)
      alt mime_type empty
        Misc-->>Caller: default_file_infos_array
      else mime_type present
        Misc->>WP_File: wp_filesize(file_path)
        WP_File-->>Misc: bytes
        Misc->>WP_File: size_format(bytes)
        WP_File-->>Misc: file_size
        Misc->>WP_Post: get_the_title(file_id)
        WP_Post-->>Misc: file_name
        Misc->>Misc: get_file_detail(file_name, file_ext, file_size)
        Misc-->>Misc: details
        Misc->>Misc: get_accessible_file_size_label(file_size)
        Misc-->>Misc: accessible_size
        Misc->>Misc: get_file_detail(file_name, file_ext, accessible_size)
        Misc-->>Misc: details_accessible
        Misc->>WP_Post: wp_get_attachment_caption(file_id)
        WP_Post-->>Misc: caption
        Misc-->>Caller: file_infos_array
      end
    end
  end
Loading

Class diagram for new Misc helper functions

classDiagram
  class MiscHelper {
    <<namespace>>
    +array get_file_infos(int file_id)
    +string get_file_detail(string file_name, string file_ext, string file_size)
    +string get_mime_type(int file_id)
    +string get_accessible_file_size_label(string file_size)
  }

  class WordPress_Attachments {
    +string wp_get_attachment_url(int file_id)
    +string get_attached_file(int file_id)
  }

  class WordPress_Post {
    +string get_post_mime_type(int file_id)
    +string get_the_title(int file_id)
    +string wp_get_attachment_caption(int file_id)
  }

  class WordPress_FileSystem {
    +int wp_filesize(string file_path)
    +string size_format(int bytes)
  }

  class WordPress_I18n {
    +string _n(string singular, string plural, int count, string textdomain)
  }

  MiscHelper --> WordPress_Attach : uses
  MiscHelper --> WordPress_Post : uses
  MiscHelper --> WordPress_FileSystem : uses
  MiscHelper --> WordPress_I18n : uses
Loading

File-Level Changes

Change Details Files
Add a Misc helper module that centralizes file metadata retrieval and formatting, including accessible file size labels.
  • Include the new Misc helper file in the theme bootstrap so its functions are available globally.
  • Implement get_file_infos() to safely assemble attachment URL, name, caption, and formatted detail strings, with graceful fallbacks when data is missing.
  • Introduce get_file_detail() to build a human-readable summary string from name, extension, and size components.
  • Add get_mime_type() helper to extract the file extension part from a WordPress attachment MIME type.
  • Implement get_accessible_file_size_label() to parse compact size strings and return pluralized, localized, screen-reader-friendly size labels while falling back to the original input on unknown units.
functions.php
inc/Helpers/Misc.php

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues, and left some high level feedback:

  • In get_file_infos, the documented/initialized keys (path, size, ext) are no longer present in the returned array, which may break callers relying on that structure; either restore those keys or update usages and the docblock to reflect the new shape.
  • get_mime_type is documented as returning a string but lacks a return type declaration; adding : string would make the contract explicit and consistent with the other helpers.
  • get_accessible_file_size_label assumes the regex matches and will produce notices if $matches[1]/[2] are missing; consider returning $file_size immediately when preg_match fails to avoid undefined index issues.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `get_file_infos`, the documented/initialized keys (`path`, `size`, `ext`) are no longer present in the returned array, which may break callers relying on that structure; either restore those keys or update usages and the docblock to reflect the new shape.
- `get_mime_type` is documented as returning a string but lacks a return type declaration; adding `: string` would make the contract explicit and consistent with the other helpers.
- `get_accessible_file_size_label` assumes the regex matches and will produce notices if `$matches[1]`/`[2]` are missing; consider returning `$file_size` immediately when `preg_match` fails to avoid undefined index issues.

## Individual Comments

### Comment 1
<location path="inc/Helpers/Misc.php" line_range="14-23" />
<code_context>
+ */
+function get_file_infos( int $file_id ): array {
+	$file_href  = wp_get_attachment_url( $file_id );
+	$file_infos = [
+		'href'      => '',
+		'file_name' => '',
+		'path'      => '',
+		'size'      => '',
+		'ext'       => '',
+		'caption'   => '',
+	];
+
+	if ( empty( $file_href ) ) {
+		return $file_infos;
+	}
+
+	$file_path = get_attached_file( $file_id );
+
+	if ( empty( $file_path ) ) {
+		return $file_infos;
+	}
+
+	$file_ext = get_mime_type( $file_id );
+
+	if ( empty( $file_ext ) ) {
+		return $file_infos;
+	}
+
+	$file_size = (string) size_format( wp_filesize( $file_path ) );
+	$file_name = (string) ( get_the_title( $file_id ) ?? '' );
+
+	return [
</code_context>
<issue_to_address>
**issue (bug_risk):** Returned array shape from get_file_infos is inconsistent between early-return and success paths.

Early returns use the initialized `$file_infos` (with `path`, `size`, `ext`, etc.), but the final return omits some of these keys and adds others (`details`, `details_accessible`). This forces callers to handle multiple shapes and can break existing code expecting `path/size/ext` to always be present. Consider always returning a single, consistent structure (e.g., populate and return `$file_infos`).
</issue_to_address>

### Comment 2
<location path="inc/Helpers/Misc.php" line_range="47" />
<code_context>
+		'details'            => get_file_detail( $file_name, $file_ext, $file_size ),
+		'details_accessible' => get_file_detail( $file_name, $file_ext, get_accessible_file_size_label( $file_size ) ),
+		'href'               => $file_href,
+		'caption'            => wp_get_attachment_caption( $file_id ),
+	];
+}
</code_context>
<issue_to_address>
**suggestion (bug_risk):** Caption value might benefit from being normalized to a string.

Because `wp_get_attachment_caption()` may return `false` when no caption exists, consider normalizing it to a string (e.g., cast or map `false` to an empty string) so `get_file_infos()` consistently returns a string for `caption`.

```suggestion
		'caption'            => (string) wp_get_attachment_caption( $file_id ),
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
@cedric07
Copy link
Contributor

cedric07 commented Feb 25, 2026

Note

Note pour moi : regarder ce qui a été optimisé sur https://github.com/BeAPI/cnis/blob/refonte-2025/web/app/themes/cnis-2025/inc/Helpers/Misc.php afin de reporter ici si besoin

return $file_infos;
}

$file_ext = get_mime_type( $file_id );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

extension !== de mime_type, je ne suis pas sûr que ça fonctionne comme attendu pour tout type de fichier.

$int_value = (int) $value; // Cast to int for _n() pluralization.
$unit = strtolower( $matches[2] ?? '' );

switch ( $unit ) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dépendant de la traduction, est-ce que c'est fonctionnel toutes langues là ?

switch ( $unit ) {
case 'b':
case 'o':
$unit_label = _n( 'byte', 'bytes', $int_value, 'beapi-frontend-framework' );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Il faut ajouter le commentaire translators: lorsque l'export po/mo se fasse on ait les consignes de traduction.

$int_value = (int) $value; // Cast to int for _n() pluralization.
$unit = strtolower( $matches[2] ?? '' );

switch ( $unit ) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avecun match on est plus simple et morderne :

		'b', 'o'   => _n( 'byte', 'bytes', $int_value, 'beapi-frontend-framework' ),
		'kb', 'ko' => _n( 'kilobyte', 'kilobytes', $int_value, 'beapi-frontend-framework' ),
		'mb', 'mo' => _n( 'megabyte', 'megabytes', $int_value, 'beapi-frontend-framework' ),
		'gb', 'go' => _n( 'gigabyte', 'gigabytes', $int_value, 'beapi-frontend-framework' ),
		'tb', 'to' => _n( 'terabyte', 'terabytes', $int_value, 'beapi-frontend-framework' ),
		default    => null,
	};

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants