{"id":29651291,"url":"https://github.com/arraypress/wp-math-utils","last_synced_at":"2025-07-22T05:06:32.498Z","repository":{"id":303300024,"uuid":"1014514171","full_name":"arraypress/wp-math-utils","owner":"arraypress","description":"A lean WordPress library for mathematical calculations, e-commerce operations, and number utilities.","archived":false,"fork":false,"pushed_at":"2025-07-06T21:14:03.000Z","size":6,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-06T22:24:49.416Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/arraypress.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-05T21:55:17.000Z","updated_at":"2025-07-06T21:14:06.000Z","dependencies_parsed_at":"2025-07-06T22:25:06.453Z","dependency_job_id":null,"html_url":"https://github.com/arraypress/wp-math-utils","commit_stats":null,"previous_names":["arraypress/wp-math-utils"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/arraypress/wp-math-utils","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arraypress%2Fwp-math-utils","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arraypress%2Fwp-math-utils/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arraypress%2Fwp-math-utils/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arraypress%2Fwp-math-utils/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/arraypress","download_url":"https://codeload.github.com/arraypress/wp-math-utils/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arraypress%2Fwp-math-utils/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266430668,"owners_count":23927169,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-22T02:00:09.085Z","response_time":66,"last_error":null,"robots_txt_status":null,"robots_txt_updated_at":null,"robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-07-22T05:06:31.979Z","updated_at":"2025-07-22T05:06:32.485Z","avatar_url":"https://github.com/arraypress.png","language":"PHP","readme":"# WordPress Math Utils\n\nA lean WordPress library for mathematical calculations, e-commerce operations, number utilities, and safe expression evaluation.\n\n## Installation\n\n```bash\ncomposer require arraypress/wp-math-utils\n```\n\n## Quick Start\n\n```php\nuse ArrayPress\\MathUtils\\Math;\nuse ArrayPress\\MathUtils\\Number;\n\n// E-commerce calculations\n$discount = Math::discount(100, 20, true);        // 20% off: ['discount' =\u003e 20, 'final_price' =\u003e 80]\n$tax = Math::tax(100, 8.25, false);               // Add tax: ['tax' =\u003e 8.25, 'price_with_tax' =\u003e 108.25]\n\n// Business metrics\n$margin = Math::profit_margin(120, 100);          // 16.67% profit margin\n$change = Math::percentage_change(100, 120);      // 20% increase\n\n// Number formatting\n$formatted = Number::format(1234.56);             // \"1,234.56\"\n$ordinal = Number::ordinal(23);                   // \"23rd\"\n$abbreviated = Number::abbreviate(1500000);       // \"1.5M\"\n\n// Safe expression evaluation\n$result = wp_evaluate_expression('2 + 3 * 4');    // 14\n$user_calc = wp_safe_eval($_POST['formula']);      // Safe alternative to eval()\n```\n\n## Math Class\n\n### `percentage(float $value, float $percentage, int $precision = 2): float`\nCalculate percentage of a value.\n\n```php\n$result = Math::percentage( 100, 25 ); // 25.00 (25% of 100)\n$result = Math::percentage( 200, 15 ); // 30.00 (15% of 200)\n```\n\n### `discount(float $price, float $discount, bool $is_percentage = true, int $precision = 2): array`\nApply discount (percentage or flat amount).\n\n```php\n// Percentage discount\n$result = Math::discount( 100, 20, true );\n// Returns: ['discount' =\u003e 20.00, 'final_price' =\u003e 80.00]\n\n// Flat discount  \n$result = Math::discount( 100, 15, false );\n// Returns: ['discount' =\u003e 15.00, 'final_price' =\u003e 85.00]\n```\n\n### `tax(float $price, float $rate, bool $inclusive = false, int $precision = 2): array`\nCalculate tax (inclusive or exclusive).\n\n```php\n// Exclusive tax (add to price)\n$result = Math::tax( 100, 8.25, false );\n// Returns: ['tax' =\u003e 8.25, 'price_with_tax' =\u003e 108.25]\n\n// Inclusive tax (extract from price)\n$result = Math::tax( 108.25, 8.25, true );\n// Returns: ['tax' =\u003e 8.25, 'price_without_tax' =\u003e 100.00]\n```\n\n### `profit_margin(float $revenue, float $cost, int $precision = 2): float`\nCalculate profit margin as percentage.\n\n```php\n$margin = Math::profit_margin( 120, 100 ); // 16.67% margin\n$margin = Math::profit_margin( 150, 100 ); // 33.33% margin\n```\n\n### `percentage_change(float $old_value, float $new_value, int $precision = 2): float`\nCalculate percentage change between values.\n\n```php\n$change = Math::percentage_change( 100, 120 ); // 20.00 (20% increase)\n$change = Math::percentage_change( 120, 100 ); // -16.67 (16.67% decrease)\n```\n\n### `conversion_rate(float $conversions, float $total, int $precision = 2): float`\nCalculate conversion rate as percentage.\n\n```php\n$rate = Math::conversion_rate( 25, 1000 ); // 2.5% conversion rate\n$rate = Math::conversion_rate( 5, 100 );   // 5% conversion rate\n```\n\n### `average(array $values, int $precision = 2): float`\nCalculate average of array values.\n\n```php\n$avg = Math::average( [10, 20, 30] );      // 20.00\n$avg = Math::average( [100, 150, 200] );   // 150.00\n```\n\n### Currency Precision\n```php\n// Convert to/from cents for precise calculations\n$cents  = Math::to_cents( 19.99 );  // 1999\n$amount = Math::from_cents( 1999 );  // 19.99\n```\n\n### Utility Functions\n```php\n// Ensure non-negative values\n$positive = Math::positive( -5 );      // 0.00\n\n// Clamp to range\n$clamped = Math::clamp( 150, 0, 100 );  // 100.00\n```\n\n## Number Class\n\n### Validation\n```php\nNumber::is_even( 4 );               // true\nNumber::is_odd( 5 );                // true\nNumber::is_positive( 10 );          // true\nNumber::is_negative( -5 );          // true\nNumber::in_range( 5, 1, 10 );       // true\n```\n\n### Formatting\n```php\n// Format with thousands separator\nNumber::format( 1234.56 );         // \"1,234.56\"\nNumber::format( 1234.56, 1 );      // \"1,234.6\"\n\n// Ordinal numbers\nNumber::ordinal( 1 );               // \"1st\"\nNumber::ordinal( 22 );              // \"22nd\" \nNumber::ordinal( 103 );             // \"103rd\"\n\n// Zero padding\nNumber::zero_pad( 5, 3 );           // \"005\"\nNumber::zero_pad( 42, 6 );          // \"000042\"\n\n// Abbreviate large numbers\nNumber::abbreviate( 1500 );         // \"1.5K\"\nNumber::abbreviate( 2500000 );      // \"2.5M\"\nNumber::abbreviate( 1200000000 );   // \"1.2B\"\n```\n\n### Advanced\n```php\n// Round to step\nNumber::round_to_step( 23.7, 5 );   // 25.0 (nearest 5)\nNumber::round_to_step( 12.3, 0.5 ); // 12.5 (nearest 0.5)\n\n// Convert values with constraints\nNumber::to_numeric( '42', 'int', 0, 100 );  // 42 (integer, clamped to 0-100)\nNumber::to_numeric( '3.14159', 'float' );   // 3.14159\n```\n\n## Expression Parser\n\nSafe evaluation of mathematical expressions - a secure alternative to `eval()`.\n\n### Basic Usage\n```php\nuse ArrayPress\\MathUtils\\ExpressionParser;\n\n$parser = new ExpressionParser( 2 ); // 2 decimal places\n\n// Basic arithmetic\n$result = $parser-\u003eevaluate( '2 + 3 * 4' );        // 14\n$result = $parser-\u003eevaluate( '(10 + 5) / 3' );     // 5\n$result = $parser-\u003eevaluate( '2 ^ 3 ^ 2' );        // 512 (right associative)\n\n// Decimal numbers\n$result = $parser-\u003eevaluate( '3.14 * 2' );         // 6.28\n$result = $parser-\u003eevaluate( '10.5 / 2.1' );       // 5\n```\n\n### Helper Functions\n```php\n// Simple evaluation\n$result = wp_evaluate_expression( '100 * 1.25 + 50' );     // 175\n$result = wp_evaluate_expression( '15.99 * 0.85', 4 );     // 13.5915 (4 decimal places)\n\n// Safe eval alternative\n$user_formula = $_POST['calculation']; // User input: \"price * quantity + shipping\"\n$result = wp_safe_eval( $user_formula );\n\n// Error handling\n$result = wp_evaluate_expression( 'invalid expression' );\nif ( $result === null ) {\n    echo 'Invalid mathematical expression';\n}\n```\n\n### Security Features\n- **No code execution** - Only mathematical operations allowed\n- **Input validation** - Rejects invalid characters and syntax\n- **Safe operators** - Only `+`, `-`, `*`, `/`, `^`, `(`, `)` and numbers\n- **Error handling** - Graceful failure instead of PHP errors\n\n## Real-World Examples\n\n### Dynamic Pricing Formulas\n```php\n// Admin sets pricing formula\n$formula = get_option( 'pricing_formula' ); // \"(base_price * quantity) + shipping_cost\"\n\n// Calculate price based on user input\n$base_price = 25.99;\n$quantity = 3;\n$shipping = 5.99;\n\n$expression = str_replace( \n    ['base_price', 'quantity', 'shipping_cost'], \n    [$base_price, $quantity, $shipping], \n    $formula \n);\n\n$total = wp_evaluate_expression( $expression ); // 83.96\n```\n\n### User Calculator Widget\n```php\n// Safe user calculator\nif ( isset( $_POST['calculation'] ) ) {\n    $result = wp_safe_eval( sanitize_text_field( $_POST['calculation'] ) );\n    \n    if ( $result !== null ) {\n        echo \"Result: \" . Number::format( $result );\n    } else {\n        echo \"Invalid expression. Please use only numbers and +, -, *, /, ^ operators.\";\n    }\n}\n```\n\n### E-commerce Checkout\n```php\n$item_price = 99.99;\n\n// Apply 20% off coupon\n$discount_result  = Math::discount( $item_price, 20, true );\n$discounted_price = $discount_result['final_price']; // 79.99\n\n// Add 8.25% tax\n$tax_result  = Math::tax( $discounted_price, 8.25, false );\n$final_total = $tax_result['price_with_tax']; // 86.59\n\n// Display formatted\necho \"Original: $\" . Number::format( $item_price );                   // $99.99\necho \"Discount: -$\" . Number::format( $discount_result['discount'] ); // -$20.00\necho \"Tax: $\" . Number::format( $tax_result['tax'] );                 // $6.60\necho \"Total: $\" . Number::format( $final_total );                    // $86.59\n```\n\n### Business Analytics\n```php\n// Monthly revenue analysis\n$last_month = 45000;\n$this_month = 52000;\n\n$change           = Math::percentage_change( $last_month, $this_month );\n$formatted_change = Number::format( $change, 1 ) . '%';\n\necho \"Revenue growth: \" . $formatted_change; // \"Revenue growth: 15.6%\"\n\n// Commission calculations using expressions\n$sales_data = [\n    ['amount' =\u003e 1200, 'rate' =\u003e 5],\n    ['amount' =\u003e 850, 'rate' =\u003e 7.5],\n    ['amount' =\u003e 2100, 'rate' =\u003e 10]\n];\n\nforeach ( $sales_data as $sale ) {\n    $commission = wp_evaluate_expression( \"{$sale['amount']} * {$sale['rate']} / 100\" );\n    echo \"Sale: $\" . Number::format( $sale['amount'] ) . \" - Commission: $\" . Number::format( $commission );\n}\n```\n\n### Configuration-Driven Calculations\n```php\n// Configurable tax calculation\n$tax_formula = get_option( 'tax_calculation_formula', 'price * rate / 100' );\n$price = 100.00;\n$rate = 8.25;\n\n$formula = str_replace( ['price', 'rate'], [$price, $rate], $tax_formula );\n$tax = wp_evaluate_expression( $formula ); // 8.25\n\n// Complex shipping calculation\n$shipping_formula = get_option( 'shipping_formula', '(weight * 0.5) + (distance / 100) + base_fee' );\n$weight = 2.5;\n$distance = 150;\n$base_fee = 5.99;\n\n$expression = str_replace( \n    ['weight', 'distance', 'base_fee'], \n    [$weight, $distance, $base_fee], \n    $shipping_formula \n);\n$shipping = wp_evaluate_expression( $expression ); // 8.74\n```\n\n## Available Classes\n\n- **`Math`** - E-commerce calculations, percentages, and business metrics\n- **`Number`** - Number formatting, validation, and manipulation\n- **`ExpressionParser`** - Safe mathematical expression evaluation\n\n## Available Functions\n\n- **`wp_evaluate_expression()`** - Evaluate mathematical expressions safely\n- **`wp_safe_eval()`** - Safe alternative to PHP's `eval()` function\n\n## Requirements\n\n- PHP 7.4+\n- WordPress 5.0+\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## License\n\nThis project is licensed under the GPL-2.0-or-later License.\n\n## Support\n\n- [Documentation](https://github.com/arraypress/wp-math-utils)\n- [Issue Tracker](https://github.com/arraypress/wp-math-utils/issues)","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farraypress%2Fwp-math-utils","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Farraypress%2Fwp-math-utils","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farraypress%2Fwp-math-utils/lists"}