Skip to content

Instantly share code, notes, and snippets.

@geekish
Last active October 13, 2017 15:34
Show Gist options
  • Save geekish/fd6b2093cf73716d7a7c to your computer and use it in GitHub Desktop.
Save geekish/fd6b2093cf73716d7a7c to your computer and use it in GitHub Desktop.
Useful PHP functions

Useful PHP functions

Mostly for debugging. Useful enough to remember them but not enough to create a Composer package (yet).

If you want to use any of these, they are provided under the MIT license (see LICENSE.md). Some of the code here was adapted from answers found on Stack Overflow, and credit is given where due.

<?php
/**
* Removes an item from the array and returns its value.
*
* @see http://stackoverflow.com/q/10898699
* @param array $arr The input array
* @param $key The key pointing to the desired value
* @return The value mapped to $key or null if none
*/
function arrayUnsetGet(array &$arr, $key) {
if (array_key_exists($key, $arr)) {
$val = $arr[$key];
unset($arr[$key]);
return $val;
}
return null;
}
<?php
/**
* Makes an associative array of class name => methods
* Useful for classes with methods via inheritance
* @example $methods = listClassMethods(new ReflectionClass(Foo::class));
*/
function listClassMethods(ReflectionClass $reflection) {
$methods = [];
foreach ($reflection->getMethods() as $method) {
$methods[$method->class][] = $method->name;
}
return $methods;
}
<?php
/**
* Return an array of request headers
* Used for debugging; when not using PSR7
* Apparently getallheaders() is available when using Apache?
*
* @see http://stackoverflow.com/q/13224615
*/
if (!function_exists('getallheaders')) {
function getallheaders() : array {
if (!is_array($_SERVER)) {
return array();
}
$normalize = function ($value) {
return str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($value, 5)))));
};
$headers = [];
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[$normalize($name)] = $value;
}
}
return $headers;
}
}
/**
* Get an array of header lines from a PSR-7 message
*/
function getHeaderLines(\Psr\Http\Message\MessageInterface $message) {
$lines = [];
foreach (array_keys($message->getHeaders()) as $key) {
$lines[$key] = $message->getHeaderLine($key);
}
return $lines;
}
/**
* Convert //link.com to http(s)://link.com
*/
function fullUrl(string $url, $https = false) : string {
if (substr($url, 0, 2) == "//") {
return $https ? sprintf("https:%s", $url) : sprintf("http:%s", $url);
}
return $url;
}
/**
* Remove http(s):// and www. from url
*/
function urlNoScheme(string $url) : string {
return preg_replace("#^(https?:)?//(www\.)?#", "", $url);
}
/**
* Return PSR-7 Response body contents, decodes json
* If only getParsedBody() was on MessageInterface and not just ServerRequestInterface
*
* @return string|array|object
*/
function decodeResponse(\Psr\Http\Message\ResponseInterface $response, $assoc = false, $depth = 512, int $options = 0) {
$parts = explode(';', $response->getHeaderLine('Content-Type'));
$mime = strtolower(trim(array_shift($parts)));
$body = $response->getBody()->getContents();
if (preg_match('~^application/([a-z.]+\+)?json($|;)~', $mime)) {
$body = json_decode($body, $assoc, $depth, $options);
}
return $body;
}

The MIT License (MIT)

Copyright (c) 2016 Hannah Warmbier hannahwarmbier@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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