MarjovanLier / XhprofTrace

MIT License
0 stars 0 forks source link

(Added) Addition of Trace class and related tests #5

Closed MarjovanLier closed 4 months ago

MarjovanLier commented 4 months ago

User description

Summary

This MR introduces a new Trace class to enhance the application's profiling capabilities by leveraging XHProf. It includes functionalities for enabling/disabling profiling, aggregating and displaying profiling data, and filtering out specific class prefixes during profiling. The MR encompasses updates to PHPUnit configurations, Dockerfile additions for PHP 8.1 to 8.3, and updates to the GitHub Actions workflow to streamline CI/CD processes. Notable changes include updating PHP and PHPUnit version requirements, refining the Docker environment setup for testing, and introducing a local testing script to automate build and test processes across different PHP versions.

Context and Background

The need for more precise profiling in the application was identified, emphasising the exclusion of non-relevant class prefixes from the profiling data. Including Dockerfiles and a local testing script aims to facilitate a consistent testing environment across different PHP versions, thereby enhancing the development workflow.

Problem Description

Before this MR, the application lacked an integrated approach for profiling, particularly one that could exclude specific prefixes, potentially cluttering the profiling data with irrelevant information.

Solution Description

The solution comprises the Trace class with methods for enabling/disabling XHProf profiling and processing the profiling data. The class supports excluding specified class prefixes from the profiling data. Additionally, the testing and CI/CD infrastructure have been updated to support these changes effectively.

List of Changes


Type

enhancement, tests, documentation


Description


Changes walkthrough

Relevant files
Configuration changes
4 files
php.yml
Enhance GitHub Actions Workflow for PHP CI and Automated Release
Process

.github/workflows/php.yml
  • Updated GitHub Actions workflow for PHP CI, including renaming the
    job, updating PHP versions, and adding steps for Go setup, osv-scanner
    installation, and vulnerability scanning.
  • Added steps for running PHPUnit tests and creating a new release with
    automated tagging and release notes generation.
  • +123/-31
    Dockerfile81
    Add Docker Environment for PHP 8.1                                             

    docker/Dockerfile81
  • Added a Dockerfile for setting up a PHP 8.1 environment with necessary
    extensions and Composer.
  • +16/-0   
    Dockerfile82
    Add Docker Environment for PHP 8.2                                             

    docker/Dockerfile82
  • Added a Dockerfile for setting up a PHP 8.2 environment with necessary
    extensions and Composer.
  • +16/-0   
    Dockerfile83
    Add Docker Environment for PHP 8.3                                             

    docker/Dockerfile83
  • Added a Dockerfile for setting up a PHP 8.3 environment with necessary
    extensions and Composer.
  • +16/-0   
    Dependencies
    1 files
    composer.json
    Update Composer Configuration for PHP and PHPUnit Versions

    composer.json
  • Updated PHP version requirements to "^8.1|^8.2|^8.3" and added
    "phpunit/php-code-coverage" and "phpunit/phpunit" to require-dev.
  • Introduced new scripts for running PHPUnit tests.
  • +7/-3     
    Enhancement
    2 files
    localTest.sh
    Automate Local Testing Across PHP Versions with Docker     

    localTest.sh
  • Introduced a local testing script to automate the build and test
    process across PHP versions 8.1 to 8.3 using Docker.
  • +21/-0   
    Trace.php
    Implement Trace Class for Enhanced Profiling with XHProf 

    src/Trace.php
  • Introduced the Trace class with methods for enabling/disabling XHProf
    profiling, generating reports, and filtering out specific class
    prefixes.
  • +298/-0 
    Tests
    2 files
    phpunit.xml
    Add PHPUnit Configuration for Organized Testing                   

    phpunit.xml
  • Added a PHPUnit configuration file to organize tests and configure
    environment variables and coverage reports.
  • +40/-0   
    IsExcludedClassTest.php
    Add Unit Tests for isExcludedClass Method in Trace Class 

    tests/Unit/IsExcludedClassTest.php
  • Added unit tests for the isExcludedClass method in the Trace class to
    ensure correct filtering of class prefixes.
  • +89/-0   

    ✨ PR-Agent usage: Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    Summary by CodeRabbit

    coderabbitai[bot] commented 4 months ago
    Walkthrough ## Walkthrough The project has undergone significant enhancements focusing on modernizing the PHP environment, improving code quality, and automating testing and deployment processes. Updates include advancing to PHP versions 8.1 to 8.3, refining the GitHub Actions workflow for better CI/CD practices, incorporating Docker for consistent development environments, adding PHPUnit for unit testing, and introducing new functionalities for code profiling and vulnerability scanning. These changes aim to elevate the project's maintainability, security, and performance. ## Changes | File(s) | Change Summary | |---------------------------------------|--------------------------------------------------------------------------------------------------------------------------| | `.github/workflows/php.yml` | Updated PHP versions, modified actions, added Go setup, vulnerability scanning, and PHPUnit tests; renamed job to `build`| | `.gitignore` | Added exclusion for `*.cache` files | | `composer.json` | Updated PHP version requirement, namespace, dependencies, and scripts for unit testing | | `docker/Dockerfile81`, `Dockerfile82`, `Dockerfile83` | Set up PHP CLI environments for PHP 8.1 to 8.3, including system dependencies and Composer | | `localTest.sh` | Automated Docker image building and testing across PHP versions 8.0 to 8.3 | | `phpunit.xml` | Configured PHPUnit settings | | `src/Trace.php` | Introduced `Trace` class for PHP code profiling and analysis using XHProf | | `tests/Unit/IsExcludedClassTest.php` | Added unit tests for `isExcludedClass` method in `Trace` class |

    Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

    Share - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

    Tips ### Chat There are 3 ways to chat with CodeRabbit: - Review comments: Directly reply to a review comment made by CodeRabbit. Example: - `I pushed a fix in commit .` - `Generate unit-tests for this file.` - Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples: - `@coderabbitai generate unit tests for this file.` - `@coderabbitai modularize this function.` - PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples: - `@coderabbitai generate interesting stats about this repository from git and render them as a table.` - `@coderabbitai show all the console.log statements in this repository.` - `@coderabbitai read src/utils.ts and generate unit tests.` - `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.` Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. ### CodeRabbit Commands (invoked as PR comments) - `@coderabbitai pause` to pause the reviews on a PR. - `@coderabbitai resume` to resume the paused reviews. - `@coderabbitai review` to trigger a review. This is useful when automatic reviews are disabled for the repository. - `@coderabbitai resolve` resolve all the CodeRabbit review comments. - `@coderabbitai help` to get help. Additionally, you can add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed. ### CodeRabbit Configration File (`.coderabbit.yaml`) - You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository. - The JSON schema for the configuration file is available [here](https://coderabbit.ai/integrations/coderabbit-overrides.v2.json). - If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json` ### CodeRabbit Discord Community Join our [Discord Community](https://discord.com/invite/GsXnASn26c) to get help, request features, and share feedback.
    guardrails[bot] commented 4 months ago

    :warning: We detected 3 security issues in this pull request:

    Insecure Access Control (3)
    Severity | Details | Docs :-: | :-- | :-: High | Title: **Missing User Instruction**
    https://github.com/MarjovanLier/XhprofTrace/blob/90c189d353b390586f7a22229afb427dc96dd0e1/docker/Dockerfile81#L1 | [:books:](https://docs.guardrails.io/docs/en/vulnerabilities/dockerfile/insecure_access_control.html?utm_source=ghpr#fd54f200-402c-4333-a5a4-36ef6709af2f) High | Title: **Missing User Instruction**
    https://github.com/MarjovanLier/XhprofTrace/blob/90c189d353b390586f7a22229afb427dc96dd0e1/docker/Dockerfile83#L1 | [:books:](https://docs.guardrails.io/docs/en/vulnerabilities/dockerfile/insecure_access_control.html?utm_source=ghpr#fd54f200-402c-4333-a5a4-36ef6709af2f) High | Title: **Missing User Instruction**
    https://github.com/MarjovanLier/XhprofTrace/blob/90c189d353b390586f7a22229afb427dc96dd0e1/docker/Dockerfile82#L1 | [:books:](https://docs.guardrails.io/docs/en/vulnerabilities/dockerfile/insecure_access_control.html?utm_source=ghpr#fd54f200-402c-4333-a5a4-36ef6709af2f) More info on how to fix Insecure Access Control in [Dockerfile](https://docs.guardrails.io/docs/en/vulnerabilities/dockerfile/insecure_access_control.html?utm_source=ghpr).

    πŸ‘‰ Go to the dashboard for detailed results.

    πŸ“₯ Happy? Share your feedback with us.

    codiumai-pr-agent-pro[bot] commented 4 months ago

    PR Description updated to latest commit (https://github.com/MarjovanLier/XhprofTrace/commit/90c189d353b390586f7a22229afb427dc96dd0e1)

    codiumai-pr-agent-pro[bot] commented 4 months ago

    Changelog updates:

    2024-02-24

    Added

    Changed

    to commit the new content to the CHANGELOG.md file, please type: '/update_changelog --pr_update_changelog.push_changelog_changes=true'

    codiumai-pr-agent-pro[bot] commented 4 months ago

    PR Code Suggestions

    Suggestions                                                                                                                                                     
    enhancement
    Use a configurable path for PROFILES_DIR.                        ___ **Consider using a configurable path for PROFILES_DIR instead of hardcoding it. This can be
    achieved by using environment variables or a configuration file. This change will make the
    code more flexible and easier to adapt to different environments.** [src/Trace.php [20]](https://github.com/MarjovanLier/XhprofTrace/pull/5/files#diff-15329b36f4764bd79867bdc947704d9b2afcb82fd7627bd305ae5865be6fb833R20-R20) ```diff -private const PROFILES_DIR = '/var/www/html/profiles/'; +private const PROFILES_DIR = getenv('PROFILES_DIR') ?: '/var/www/html/profiles/'; ```
    Use data providers for test methods to enhance readability and maintainability. ___ **Consider using a data provider for the test methods
    testIsExcludedClassReturnsTrueForExcludedPrefixes and
    testIsExcludedClassReturnsFalseForNonExcludedPrefixes to simplify the tests and make them
    more readable.** [tests/Unit/IsExcludedClassTest.php [51-65]](https://github.com/MarjovanLier/XhprofTrace/pull/5/files#diff-695aa0f2247ae4d4b8d76563739fb5190e87f9527d2fe1ca160a40bb2fa81dd0R51-R65) ```diff -public function testIsExcludedClassReturnsTrueForExcludedPrefixes(): void +/** + * @dataProvider excludedPrefixProvider + */ +public function testIsExcludedClassReturnsTrueForExcludedPrefixes(string $functionName): void { - foreach (self::EXCLUDED_PREFIXES as $excludedPrefix) { - $functionName = $excludedPrefix . 'SomeFunctionName'; - self::assertTrue($this->callIsExcludedClass($functionName)); - } + self::assertTrue($this->callIsExcludedClass($functionName)); } -public function testIsExcludedClassReturnsFalseForNonExcludedPrefixes(): void +public function excludedPrefixProvider(): array { - foreach (self::NON_EXCLUDED_FUNCTION_NAMES as $functionName) { - self::assertFalse($this->callIsExcludedClass($functionName)); - } + return array_map(function($prefix) { + return [$prefix . 'SomeFunctionName']; + }, self::EXCLUDED_PREFIXES); } +/** + * @dataProvider nonExcludedFunctionNameProvider + */ +public function testIsExcludedClassReturnsFalseForNonExcludedPrefixes(string $functionName): void +{ + self::assertFalse($this->callIsExcludedClass($functionName)); +} + +public function nonExcludedFunctionNameProvider(): array +{ + return array_map(function($functionName) { + return [$functionName]; + }, self::NON_EXCLUDED_FUNCTION_NAMES); +} + ```
    Add error handling for each command within the loop for better debugging.     ___ **Consider adding error handling for each command within the loop to ensure that the script
    stops executing further commands if any command fails, providing a clear error message for
    easier debugging.** [localTest.sh [12-18]](https://github.com/MarjovanLier/XhprofTrace/pull/5/files#diff-ee3cef051df5421a0c1f313c0666b6c8c80b8ec26be919fdfe65992736b6091aR12-R18) ```diff for version in 80 81 82 83; do DOCKER_CMD="docker run -it --rm -v $(pwd):/var/www -v $HOME/.composer/docker-cache:/root/.composer php-xprof-trace-composer-$version" - rm -f composer.lock && \ - $DOCKER_CMD composer --version && \ - $DOCKER_CMD composer install && \ - $DOCKER_CMD composer test:vulnerabilities-check && \ - $DOCKER_CMD composer test:phpunit + if ! rm -f composer.lock; then + echo "Failed to remove composer.lock" >&2 + exit 1 + fi + if ! $DOCKER_CMD composer --version; then + echo "Composer version command failed" >&2 + exit 1 + fi + if ! $DOCKER_CMD composer install; then + echo "Composer install failed" >&2 + exit 1 + fi + if ! $DOCKER_CMD composer test:vulnerabilities-check; then + echo "Vulnerability check failed" >&2 + exit 1 + fi + if ! $DOCKER_CMD composer test:phpunit; then + echo "PHPUnit tests failed" >&2 + exit 1 + fi done ```
    performance
    Use DirectoryIterator for retrieving profile files.              ___ **Replace the glob function with DirectoryIterator for better performance and more reliable
    error handling when retrieving profile files.** [src/Trace.php [85]](https://github.com/MarjovanLier/XhprofTrace/pull/5/files#diff-15329b36f4764bd79867bdc947704d9b2afcb82fd7627bd305ae5865be6fb833R85-R85) ```diff -$files = glob(self::PROFILES_DIR . '*.json', GLOB_NOSORT); +$files = []; +foreach (new DirectoryIterator(self::PROFILES_DIR) as $file) { + if ($file->isFile() && $file->getExtension() === 'json') { + $files[] = $file->getPathname(); + } +} ```
    maintainability
    Use a dedicated library for CLI output in displayReportCLI.      ___ **To improve the accuracy and maintainability of the displayReportCLI method, consider using
    a dedicated library for CLI output instead of manually managing table headers and rows.** [src/Trace.php [64-66]](https://github.com/MarjovanLier/XhprofTrace/pull/5/files#diff-15329b36f4764bd79867bdc947704d9b2afcb82fd7627bd305ae5865be6fb833R64-R66) ```diff +// Assuming the use of Symfony Console component $consoleOutput = new ConsoleOutput(); $table = new Table($consoleOutput); $table->setHeaders(['Function', 'Score', 'Occurrences']); +// Populate the table with data in a more maintainable way ```
    best practice
    Use conservative versioning for go-version in GitHub Actions workflow. ___ **For better reliability and to avoid potential future deprecations, specify the go-version
    using a more conservative versioning approach, such as ^1.22 to automatically use the
    latest patch version of Go 1.22.** [.github/workflows/php.yml [62]](https://github.com/MarjovanLier/XhprofTrace/pull/5/files#diff-a73bb6555480a5ee79ae276a3f5d71a08fa316e09a4a8da7b643cf1e92c97df9R62-R62) ```diff -go-version: "1.22" +go-version: "^1.22" ```

    ✨ Improve tool usage guide:
    **Overview:** The `improve` tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered [automatically](https://github.com/Codium-ai/pr-agent/blob/main/Usage.md#github-app-automatic-tools) every time a new PR is opened, or can be invoked manually by commenting on a PR. When commenting, to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L69) related to the improve tool (`pr_code_suggestions` section), use the following template: ``` /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=... ``` With a [configuration file](https://github.com/Codium-ai/pr-agent/blob/main/Usage.md#working-with-github-app), use the following template: ``` [pr_code_suggestions] some_config1=... some_config2=... ```
    Enabling\disabling automation
    When you first install the app, the [default mode](https://github.com/Codium-ai/pr-agent/blob/main/Usage.md#github-app-automatic-tools) for the improve tool is: ``` pr_commands = ["/improve --pr_code_suggestions.summarize=true", ...] ``` meaning the `improve` tool will run automatically on every PR, with summarization enabled. Delete this line to disable the tool from running automatically.
    Utilizing extra instructions
    Extra instructions are very important for the `improve` tool, since they enable to guide the model to suggestions that are more relevant to the specific needs of the project. Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify relevant aspects that you want the model to focus on. Examples for extra instructions: ``` [pr_code_suggestions] # /improve # extra_instructions=""" Emphasize the following aspects: - Does the code logic cover relevant edge cases? - Is the code logic clear and easy to understand? - Is the code logic efficient? ... """ ``` Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.
    A note on code suggestions quality
    - While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically. - Suggestions are not meant to be simplistic. Instead, they aim to give deep feedback and raise questions, ideas and thoughts to the user, who can then use his judgment, experience, and understanding of the code base. - Recommended to use the 'extra_instructions' field to guide the model to suggestions that are more relevant to the specific needs of the project, or use the [custom suggestions :gem:](https://github.com/Codium-ai/pr-agent/blob/main/docs/CUSTOM_SUGGESTIONS.md) tool - With large PRs, best quality will be obtained by using 'improve --extended' mode.
    More PR-Agent commands
    > To invoke the PR-Agent, add a comment using one of the following commands: > - **/review**: Request a review of your Pull Request. > - **/describe**: Update the PR title and description based on the contents of the PR. > - **/improve [--extended]**: Suggest code improvements. Extended mode provides a higher quality feedback. > - **/ask \**: Ask a question about the PR. > - **/update_changelog**: Update the changelog based on the PR's contents. > - **/add_docs** πŸ’Ž: Generate docstring for new components introduced in the PR. > - **/generate_labels** πŸ’Ž: Generate labels for the PR based on the PR's contents. > - **/analyze** πŸ’Ž: Automatically analyzes the PR, and presents changes walkthrough for each component. >See the [tools guide](https://github.com/Codium-ai/pr-agent/blob/main/docs/TOOLS_GUIDE.md) for more details. >To list the possible configuration parameters, add a **/config** comment.
    See the [improve usage](https://github.com/Codium-ai/pr-agent/blob/main/docs/IMPROVE.md) page for a more comprehensive guide on using this tool.
    codiumai-pr-agent-pro[bot] commented 4 months ago

    Auto-approved PR