Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Math Laravel Package

phpoffice/math

Pure-PHP library for building and converting math formulas in MathML and Office MathML (OMML). Provides classes for elements like identifiers, operators, numbers, fractions, superscripts, rows, and semantics. Requires PHP 7.1+ and XML/XMLWriter.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require phpoffice/math
    

    Verify PHP 8.1+ and extensions (dom, libxml, xmlwriter) are enabled.

  2. First Use Case: Render a basic equation in a Laravel Blade template:

    use PHPOffice\Math\Math;
    
    $math = new Math();
    $math->writeToString('<math><mi>x</mi><mo>+</mo><mn>2</mn></math>');
    echo $math->getLastError(); // Check for issues
    
  3. Key Classes:

    • Math: Core class for reading/writing MathML.
    • MathML: Namespace for MathML-specific operations (e.g., MathML::writeSemantics()).
  4. Where to Look First:

    • API Documentation (class methods, parameters).
    • Examples in the repo.
    • tests/ directory for usage patterns (e.g., MathMLReaderTest.php).

Implementation Patterns

Core Workflows

1. MathML Generation (Blade Templates)

// app/Helpers/MathHelper.php
use PHPOffice\Math\Math;

function renderMath($expression) {
    $math = new Math();
    $math->writeToString($expression);
    return $math->output();
}

Usage in Blade:

@verbatim
    {{ renderMath('<math><msup><mi>x</mi><mn>2</mn></msup></math>') }}
@endverbatim

2. Dynamic Equation Building

Use MathML namespace for structured elements:

use PHPOffice\Math\MathML;

$math = new Math();
$math->writeToString(
    MathML::writeFraction(
        MathML::writeIdentifier('a'),
        MathML::writeNumber('3')
    )
);

3. Image Output (APIs/Reports)

$math = new Math();
$math->writeToString('<math><mi>E</mi><mo>=</mo><msup><mi>mc</mi><mn>2</mn></msup></math>');
$math->renderToImage('png');
$imageData = $math->output();
return response($imageData, 200, ['Content-Type' => 'image/png']);

4. Queue Jobs for Heavy Rendering

// app/Jobs/RenderMathJob.php
use PHPOffice\Math\Math;

class RenderMathJob implements ShouldQueue {
    public function handle() {
        $math = new Math();
        $math->writeToString('<math><mfrac><mi>a</mi><mn>b</mn></mfrac></math>');
        $math->renderToImage('svg');
        Storage::put('math_cache/' . uniqid() . '.svg', $math->output());
    }
}

Dispatch:

RenderMathJob::dispatch();

5. Semantics for Accessibility

use PHPOffice\Math\MathML;

$math = new Math();
$math->writeToString(
    MathML::writeSemantics(
        'equation',
        '<math><mi>F</mi><mo>=</mo><mi>ma</mi></math>'
    )
);

Integration Tips

Laravel-Specific

  • Service Provider: Bind Math to the container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->singleton(Math::class, function () {
            return new Math();
        });
    }
    

    Usage:

    use Illuminate\Support\Facades\App;
    
    $math = App::make(Math::class);
    
  • Caching Rendered Equations:

    $cacheKey = 'math_' . md5($expression);
    $cached = Cache::get($cacheKey);
    if (!$cached) {
        $math = new Math();
        $math->writeToString($expression);
        Cache::put($cacheKey, $math->output(), now()->addHours(1));
    }
    
  • Validation: Use Laravel’s FormRequest to validate MathML input:

    public function rules() {
        return [
            'mathml' => 'required|string|max:10000',
        ];
    }
    

Performance

  • Lazy-Load Heavy Operations: Defer image rendering until needed:

    $math = new Math();
    $math->writeToString($expression);
    // Store MathML string in DB/cache, render only when requested.
    
  • Batch Processing: Use Laravel’s collect() to process multiple equations:

    $equations = ['<math>...</math>', '<math>...</math>'];
    $results = collect($equations)->map(function ($eq) {
        $math = new Math();
        $math->writeToString($eq);
        return $math->renderToImage('svg');
    });
    

Gotchas and Tips

Pitfalls

  1. XXE Vulnerability (Critical):

    • Risk: User-supplied MathML can trigger XML External Entity attacks.
    • Fix:
      • Always sanitize input:
        $dom = new DOMDocument();
        $dom->loadXML($mathml, LIBXML_NOENT | LIBXML_DTDLOAD); // Disable DTD
        
      • Use Math::setDebug(true) to log suspicious input.
    • Mitigation: Reject MathML with external entities (e.g., &entity;).
  2. MathML Complexity:

    • Issue: Nested structures (e.g., fractions in superscripts) may break.
    • Debugging:
  3. Image Generation Failures:

    • Common Causes:
      • Missing gd/imagick extensions.
      • Unsupported image format (e.g., webp may not work).
    • Fix:
      if (!extension_loaded('gd')) {
          throw new \RuntimeException('GD extension required for image output.');
      }
      
  4. PHP 8.4+ Changes:

    • Breaking: Some MathML methods may have stricter type hints.
    • Action: Update to ^0.3.0 and test edge cases.
  5. Memory Limits:

    • Issue: Complex equations (e.g., matrices) may hit PHP’s memory_limit.
    • Workaround:
      • Increase limit: ini_set('memory_limit', '256M').
      • Use Math::setMemoryLimit(50) (if supported).

Debugging Tips

  1. Enable Debug Mode:

    $math = new Math();
    $math->setDebug(true);
    $math->writeToString($expression);
    // Check logs for warnings/errors.
    
  2. Validate MathML:

    $math = new Math();
    $math->writeToString($expression);
    if ($math->getLastError()) {
        Log::error('MathML Error: ' . $math->getLastError());
        abort(500);
    }
    
  3. Inspect Output:

    • For MathML: Use a browser extension like MathJax to preview.
    • For images: Verify MIME type (image/png vs. image/svg+xml).
  4. Common Errors:

    Error Cause Solution
    Unsupported tag: <mrow> Invalid MathML syntax Use MathML::writeRow() helper.
    Failed to load XML Malformed input Validate with DOMDocument::loadXML().
    ImageMagick not installed Missing imagick extension Install via pecl install imagick.

Extension Points

  1. Custom MathML Elements: Extend PHPOffice\Math\MathML to add domain-specific tags:

    namespace App\Extensions;
    
    use PHPOffice\Math\MathML;
    
    class CustomMathML extends MathML {
        public static function writeVector($elements) {
            return '<mrow>' . implode('', $elements) . '</mrow>';
        }
    }
    
  2. Alternative Output Formats: Wrap Math in a facade to support multiple formats:

    // app/Facades/MathRenderer.php
    use Illuminate\Support\Facades\Facade;
    
    class MathRendererFacade extends Facade
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode