Skip to content

Instantly share code, notes, and snippets.

View caendesilva's full-sized avatar
🎩
HydePHP.com

Caen De Silva caendesilva

🎩
HydePHP.com
View GitHub Profile
<?php
// PHP has a number of built-in functions that allow you to perform
// linguistic operations on strings with knowledge of phonetics,
// as well as the English language rules and pronunciations.
// Calculate the metaphone key of a string
echo metaphone('test'); // TST
// Calculate the soundex key of a string
<?php
use App\Helpers\TextFormatter;
$array = ['Apple', 'Banana', 'Orange'];
// Awesome! Very readable and concise
array_map([TextFormatter::class, 'capitalize'], $array);
// Verbose, but classic, also adds cognitive load by introducing a new function
@caendesilva
caendesilva / capture-composer-output.php
Last active April 18, 2024 17:53
Capture Composer output
<?php
// As Composer writes to stderr, we need to capture the output manually
$command = 'composer global require hyde/cli';
// read from the stderr stream
$descriptorspec = [
2 => ['pipe', 'w'],
];
<?php
// Set the user agent as required by the GitHub API
ini_set('user_agent', 'github.com/your-username');
// Now you can make requests to the GitHub API
$response = file_get_contents('https://api.github.com/zen');
die($response); // Speak like a human.
<?php
/** @return array{major: int, minor: int, patch: int} */
function parseSemver(string $semver): array
{
return array_combine(['major', 'minor', 'patch'],
array_map('intval', explode('.', $semver))
);
}
<?php
function printSerializedArray(array $data): string
{
$string = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
// Convert JSON to PHP array syntax
$string = str_replace(['{', '}'], ['[', ']'], $string);
$string = str_replace('": "', "' => '", $string);
$string = str_replace('": [', "' => [", $string);
<?php
/**
* Get all of the given array without the specified array of values.
*
* @param array $array
* @param array|string|int|float $values
* @return array
*/
public static function without($array, $values)
@caendesilva
caendesilva / weighted-element.php
Created April 6, 2024 12:37
PHP weighted array selection
<?php
function weightedElement(array $array, float $factor = 1.5): mixed {
$totalWeight = 0;
$weightedArray = [];
// Reverse the array
$array = array_reverse($array);
// Calculate the total weight of the elements
@caendesilva
caendesilva / build.yml
Created March 8, 2024 10:24
Basic Laravel Vite GitHub Actions CI Workflow
name: Build Laravel Vite assets for production
on:
push:
branches: [ "master" ]
permissions:
contents: write
@caendesilva
caendesilva / scaffold-posts-inverted.bash
Last active February 11, 2024 21:11
Scaffold a bunch of Markdown blog posts
#!/bin/bash
for i in {1..25}
do
# Calculate the date in reverse order
reversed_date="2024-01-01 12:$(printf "%02d" $((25 - i)))"
# Create the file with the specified content
echo "---" > "_posts/post-$i.md"
echo "title: 'Post $i'" >> "_posts/post-$i.md"