repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.Mul
public function Mul( $val ) { $value = $val instanceof DecimalValue ? $val : Convert::ToDecimal( $val ); return new DecimalValue( bcmul( $this->_value, $value->getValue(), $this->getScale() + $this->scale( $value ) ) ); }
php
public function Mul( $val ) { $value = $val instanceof DecimalValue ? $val : Convert::ToDecimal( $val ); return new DecimalValue( bcmul( $this->_value, $value->getValue(), $this->getScale() + $this->scale( $value ) ) ); }
Mul @param ValueProxy $val @return DecimalValue
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L335-L339
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.Div
public function Div( $denominator ) { $denominator = $denominator instanceof DecimalValue ? $denominator : Convert::ToDecimal( $denominator ); $denominator = $denominator->getValue(); if ( $denominator == 0 || is_nan( $denominator ) || ( is_string( $denominator ) && strtoupper( $denominator ) == "NAN" ) ) throw XPath2Exception::withErrorCode( "FOAR0001", Resources::FOAR0001 ); $numerator = $this->_value; if ( is_nan( $numerator ) || ( is_string( $numerator ) && in_array( strtoupper( $numerator ), array( "INF", "-INF", "NAN" ) ) ) ) throw XPath2Exception::withErrorCode( "FOAR0001", Resources::FOAR0001 ); return new DecimalValue( bcdiv( $numerator, $denominator, max( 21, strlen( $denominator ) + $this->getScale() ) ) ); }
php
public function Div( $denominator ) { $denominator = $denominator instanceof DecimalValue ? $denominator : Convert::ToDecimal( $denominator ); $denominator = $denominator->getValue(); if ( $denominator == 0 || is_nan( $denominator ) || ( is_string( $denominator ) && strtoupper( $denominator ) == "NAN" ) ) throw XPath2Exception::withErrorCode( "FOAR0001", Resources::FOAR0001 ); $numerator = $this->_value; if ( is_nan( $numerator ) || ( is_string( $numerator ) && in_array( strtoupper( $numerator ), array( "INF", "-INF", "NAN" ) ) ) ) throw XPath2Exception::withErrorCode( "FOAR0001", Resources::FOAR0001 ); return new DecimalValue( bcdiv( $numerator, $denominator, max( 21, strlen( $denominator ) + $this->getScale() ) ) ); }
Div @param ValueProxy $denominator @return DecimalValue
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L346-L359
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.Pow
public function Pow( $exponent ) { $exponent = $exponent instanceof DecimalValue ? $exponent : Convert::ToDecimal( $exponent ); return new DecimalValue( bcpow( $this->getValue(), $exponent->getValue(), 21 ) ); }
php
public function Pow( $exponent ) { $exponent = $exponent instanceof DecimalValue ? $exponent : Convert::ToDecimal( $exponent ); return new DecimalValue( bcpow( $this->getValue(), $exponent->getValue(), 21 ) ); }
Pow @param DecimalValue $exponent @return DecimalValue
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L366-L370
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.Mod
public function Mod( $denominator ) { $denominator = $denominator instanceof DecimalValue ? $denominator : Convert::ToDecimal( $denominator ); if ( $denominator->getIsZero() ) throw XPath2Exception::withErrorCode( "FOAR0001", Resources::FOAR0001 ); if ( $denominator->getIsNAN() ) throw XPath2Exception::withErrorCode( "FOAR0002", Resources::FOAR0002 ); if ( $this->getIsNAN() || $this->getIsInfinite() ) throw XPath2Exception::withErrorCode( "FOAR0002", Resources::FOAR0002 ); $power = 0; // bcmod does not handle decimals so if they exist the powers of the two numbers must be increased until there are no decimals if ( $this->getIsDecimal() ) { $power = strlen( $this->getIntegerPart() ); } if ( $denominator->getIsDecimal() ) { $power = max( strlen( $denominator->getIntegerPart() ), $power ); } $multiplier = new DecimalValue( 10 ); $multiplier = $multiplier->Pow( new DecimalValue( $power ) ); $numerator = $this->Mul( $multiplier ); $denominator = $denominator->Mul( $multiplier ); $mod = bcmod( $numerator->getIntegerPart(), $denominator->getIntegerPart() ); // Now need to divide by the multiplier to restore the correct power $mod = new DecimalValue( $mod ); $mod = $mod->Div( $multiplier ); return $mod; }
php
public function Mod( $denominator ) { $denominator = $denominator instanceof DecimalValue ? $denominator : Convert::ToDecimal( $denominator ); if ( $denominator->getIsZero() ) throw XPath2Exception::withErrorCode( "FOAR0001", Resources::FOAR0001 ); if ( $denominator->getIsNAN() ) throw XPath2Exception::withErrorCode( "FOAR0002", Resources::FOAR0002 ); if ( $this->getIsNAN() || $this->getIsInfinite() ) throw XPath2Exception::withErrorCode( "FOAR0002", Resources::FOAR0002 ); $power = 0; // bcmod does not handle decimals so if they exist the powers of the two numbers must be increased until there are no decimals if ( $this->getIsDecimal() ) { $power = strlen( $this->getIntegerPart() ); } if ( $denominator->getIsDecimal() ) { $power = max( strlen( $denominator->getIntegerPart() ), $power ); } $multiplier = new DecimalValue( 10 ); $multiplier = $multiplier->Pow( new DecimalValue( $power ) ); $numerator = $this->Mul( $multiplier ); $denominator = $denominator->Mul( $multiplier ); $mod = bcmod( $numerator->getIntegerPart(), $denominator->getIntegerPart() ); // Now need to divide by the multiplier to restore the correct power $mod = new DecimalValue( $mod ); $mod = $mod->Div( $multiplier ); return $mod; }
Mod @param DecimalValue|int|float|string $denominator @return DecimalValue
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L404-L439
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.normalize
private function normalize( $number = null ) { if ( is_null( $number ) ) $number =& $this->_value; // Handle the case of -0 if ( $this->_value == "-0" ) $this->_value = "0"; if ( strpos( $this->_value, '.' ) === false ) return; $number = trim( $number ); $number = rtrim( $number, '0'); $number = rtrim( $number, '.'); if ( $number == "" || $number == "-" ) $number .= "0"; // The leading zero may be missing if ( substr( $number, 0, 1 ) == "." ) $number = "0" . $number; if ( substr( $number, 0, 2 ) == "-." ) $number = str_replace( "-.", "-0.", $number ); if ( substr( $number, 0, 2 ) == "+." ) $number = str_replace( "+.", "0.", $number ); return $number; }
php
private function normalize( $number = null ) { if ( is_null( $number ) ) $number =& $this->_value; // Handle the case of -0 if ( $this->_value == "-0" ) $this->_value = "0"; if ( strpos( $this->_value, '.' ) === false ) return; $number = trim( $number ); $number = rtrim( $number, '0'); $number = rtrim( $number, '.'); if ( $number == "" || $number == "-" ) $number .= "0"; // The leading zero may be missing if ( substr( $number, 0, 1 ) == "." ) $number = "0" . $number; if ( substr( $number, 0, 2 ) == "-." ) $number = str_replace( "-.", "-0.", $number ); if ( substr( $number, 0, 2 ) == "+." ) $number = str_replace( "+.", "0.", $number ); return $number; }
Remove spaces and any trailing zeros @param string $number @return string
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L446-L466
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.getIsDecimal
public function getIsDecimal( $number = false ) { return strpos( $number === false ? $this->_value : $number, "." ) !== false && trim( substr( $number === false ? $this->_value : $number, strpos( $number === false ? $this->_value : $number, "." ) + 1 ), "0" ); }
php
public function getIsDecimal( $number = false ) { return strpos( $number === false ? $this->_value : $number, "." ) !== false && trim( substr( $number === false ? $this->_value : $number, strpos( $number === false ? $this->_value : $number, "." ) + 1 ), "0" ); }
True if the number has a fractional part and it is not zero @param double $number @return bool
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L482-L486
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.getCeil
public function getCeil() { if ( $this->getIsDecimal() === false ) { return $this; } if ( $this->getIsNegative() === true ) { return new DecimalValue( bcadd( $this->_value, '0', 0 ) ); } return new DecimalValue( bcadd( $this->_value, '1', 0 ) ); // Add one and truncate }
php
public function getCeil() { if ( $this->getIsDecimal() === false ) { return $this; } if ( $this->getIsNegative() === true ) { return new DecimalValue( bcadd( $this->_value, '0', 0 ) ); } return new DecimalValue( bcadd( $this->_value, '1', 0 ) ); // Add one and truncate }
Get the ceiling value of the decimal number @return DecimalValue
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L501-L514
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.getFloor
public function getFloor( $scale = false ) { if ( $this->getIsDecimal() === false ) { return $this; } if ( $this->getIsNegative() === true ) { return new DecimalValue( bcadd( $this->_value, '-1', 0 ) ); // Subtract 1 and truncate } return new DecimalValue( bcadd( $this->_value, '0', 0 ) ); }
php
public function getFloor( $scale = false ) { if ( $this->getIsDecimal() === false ) { return $this; } if ( $this->getIsNegative() === true ) { return new DecimalValue( bcadd( $this->_value, '-1', 0 ) ); // Subtract 1 and truncate } return new DecimalValue( bcadd( $this->_value, '0', 0 ) ); }
Get the number that is one @param int $scale @return DecimalValue
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L521-L534
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.getRound
public function getRound( $precision = 0, $mode = PHP_ROUND_HALF_UP ) { if ( $this->getIsDecimal() === false ) { // return $this; } if ( $precision === false ) $precision = $this->scale( $this->_value ); if ( is_null( $precision ) ) $precision = 0; // if( $precision < 0) $precision = 0; $factor = 1; // If the precision is negative create a factor if ( $precision < 0 ) { $precision = abs( $precision ); $factor = bcpow( 10, $precision, $precision ); $precision = 0; } // Create a new decimal on which to perform rounding $rounder = $this->Div( $factor ); $isHalf = false; $increment = "0"; $number = $rounder->_value; $sign = ""; if ( $mode == PHP_ROUND_HALF_EVEN || $mode == PHP_ROUND_HALF_ODD ) { // These are only relevant if the precision rounds the least significant digit and that digit is 5. if ( $rounder->getDecimalIsHalf( $precision ) ) { $isHalf = true; if ( $precision - 1 >= 0 ) // if ( $this->getIntegerPart() != 0 ) { if ( $rounder->getIsDecimalEven( $precision - 1) ) { if ( $mode == PHP_ROUND_HALF_ODD ) { $sign = $rounder->getIsNegative() ? "-" : ""; // The amount to add or substract is 1 at the digit position one above the $scale position // If the scale is zero then the value change is 1 or -1. If the scale is 1 then the // change is 0.1 or -0.1. $increment = $sign . bcpow( 10, "-$precision", $precision ); } } else { if ( $mode == PHP_ROUND_HALF_EVEN ) { $sign = $rounder->getIsNegative() ? "-" : ""; // The amount to add or substract is 1 at the digit position one above the $scale position // If the scale is zero then the value change is 1 or -1. If the scale is 1 then the // change is 0.1 or -0.1. $increment = $sign . bcpow( 10, "-$precision", $precision ); } } } else { if ( $rounder->getIsIntegerEven( $precision ) ) { if ( $mode == PHP_ROUND_HALF_ODD ) { $sign = $rounder->getIsNegative() ? -1 : 1; $increment = 1 * $sign; } } else { if ( $mode == PHP_ROUND_HALF_EVEN ) { $sign = $rounder->getIsNegative() ? -1 : 1; $increment = 1 * $sign; } } } } } if ( $rounder->getIsNegative() && $mode == PHP_ROUND_HALF_UP ) { $mode = PHP_ROUND_HALF_DOWN; // $mode = $mode == PHP_ROUND_HALF_UP // ? PHP_ROUND_HALF_DOWN // : PHP_ROUND_HALF_UP; } // Round half-up or half-down according to the $mode if ( ! $isHalf && $rounder->getIsCloserToNext( $precision, $mode ) ) { $decimalPart = $rounder->getDecimalPart(); if ( strlen( $decimalPart > $precision ) ) { $sign = $rounder->getIsNegative() ? "-" : ""; // The amount to add or substract is 1 at the digit position one above the $scale position // If the scale is zero then the value change is 1 or -1. If the scale is 1 then the // change is 0.1 or -0.1. $increment = $sign . bcpow( 10, "-$precision", $precision ); } } $rounder = DecimalValue::FromValue( bcadd( $rounder->getValue(), $increment, $precision ) ); if ( $factor > 1 ) { $rounder = $rounder->Mul( $factor ); } return $rounder; // return new DecimalValue( $number ); }
php
public function getRound( $precision = 0, $mode = PHP_ROUND_HALF_UP ) { if ( $this->getIsDecimal() === false ) { // return $this; } if ( $precision === false ) $precision = $this->scale( $this->_value ); if ( is_null( $precision ) ) $precision = 0; // if( $precision < 0) $precision = 0; $factor = 1; // If the precision is negative create a factor if ( $precision < 0 ) { $precision = abs( $precision ); $factor = bcpow( 10, $precision, $precision ); $precision = 0; } // Create a new decimal on which to perform rounding $rounder = $this->Div( $factor ); $isHalf = false; $increment = "0"; $number = $rounder->_value; $sign = ""; if ( $mode == PHP_ROUND_HALF_EVEN || $mode == PHP_ROUND_HALF_ODD ) { // These are only relevant if the precision rounds the least significant digit and that digit is 5. if ( $rounder->getDecimalIsHalf( $precision ) ) { $isHalf = true; if ( $precision - 1 >= 0 ) // if ( $this->getIntegerPart() != 0 ) { if ( $rounder->getIsDecimalEven( $precision - 1) ) { if ( $mode == PHP_ROUND_HALF_ODD ) { $sign = $rounder->getIsNegative() ? "-" : ""; // The amount to add or substract is 1 at the digit position one above the $scale position // If the scale is zero then the value change is 1 or -1. If the scale is 1 then the // change is 0.1 or -0.1. $increment = $sign . bcpow( 10, "-$precision", $precision ); } } else { if ( $mode == PHP_ROUND_HALF_EVEN ) { $sign = $rounder->getIsNegative() ? "-" : ""; // The amount to add or substract is 1 at the digit position one above the $scale position // If the scale is zero then the value change is 1 or -1. If the scale is 1 then the // change is 0.1 or -0.1. $increment = $sign . bcpow( 10, "-$precision", $precision ); } } } else { if ( $rounder->getIsIntegerEven( $precision ) ) { if ( $mode == PHP_ROUND_HALF_ODD ) { $sign = $rounder->getIsNegative() ? -1 : 1; $increment = 1 * $sign; } } else { if ( $mode == PHP_ROUND_HALF_EVEN ) { $sign = $rounder->getIsNegative() ? -1 : 1; $increment = 1 * $sign; } } } } } if ( $rounder->getIsNegative() && $mode == PHP_ROUND_HALF_UP ) { $mode = PHP_ROUND_HALF_DOWN; // $mode = $mode == PHP_ROUND_HALF_UP // ? PHP_ROUND_HALF_DOWN // : PHP_ROUND_HALF_UP; } // Round half-up or half-down according to the $mode if ( ! $isHalf && $rounder->getIsCloserToNext( $precision, $mode ) ) { $decimalPart = $rounder->getDecimalPart(); if ( strlen( $decimalPart > $precision ) ) { $sign = $rounder->getIsNegative() ? "-" : ""; // The amount to add or substract is 1 at the digit position one above the $scale position // If the scale is zero then the value change is 1 or -1. If the scale is 1 then the // change is 0.1 or -0.1. $increment = $sign . bcpow( 10, "-$precision", $precision ); } } $rounder = DecimalValue::FromValue( bcadd( $rounder->getValue(), $increment, $precision ) ); if ( $factor > 1 ) { $rounder = $rounder->Mul( $factor ); } return $rounder; // return new DecimalValue( $number ); }
getRound @param int $precision @param int $mode PHP_ROUND_HALF_UP (default), PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, PHP_ROUND_HALF_ODD @return DecimalValue
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L542-L658
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.roundDigit
private function roundDigit( $scale, $mode = PHP_ROUND_HALF_UP ) { if ( $this->getIsCloserToNext( $scale, $mode ) ) { return bcadd( $this->_value, $this->getIsNegative() ? -1 : 1, 0 ); } return bcadd( $this->_value, '0', 0 ); }
php
private function roundDigit( $scale, $mode = PHP_ROUND_HALF_UP ) { if ( $this->getIsCloserToNext( $scale, $mode ) ) { return bcadd( $this->_value, $this->getIsNegative() ? -1 : 1, 0 ); } return bcadd( $this->_value, '0', 0 ); }
Round the value to the required precision and using the required mode @param $scale The scale to use for rounding. The digit at this position will be rounded in the decimal part of the number will be rounded. @param int $mode PHP_ROUND_HALF_UP (default), PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, PHP_ROUND_HALF_ODD @return string
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L676-L684
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.getIntegerPart
public function getIntegerPart() { if ( ! $this->getIsDecimal() ) return $this->_value; return substr( $this->_value, 0, strpos( $this->_value, "." ) ); }
php
public function getIntegerPart() { if ( ! $this->getIsDecimal() ) return $this->_value; return substr( $this->_value, 0, strpos( $this->_value, "." ) ); }
Return the part of the number before the decimal point Does not taken into account the size of any fraction. @return string
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L712-L716
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.getDecimalIsHalf
public function getDecimalIsHalf( $scale = false ) { if ( ! $this->getIsDecimal() ) { return false; } if ( $scale === false ) $scale = $this->scale( $this->_value ); if ( $scale < 0 ) $scale = $scale = 0; $decimalPart = $this->getDecimalPart(); if ( $scale >= strlen( $decimalPart ) ) return false; // Get the portion of the decimal part affected by the scale value $decimalPart = substr( $decimalPart, $scale ); return strlen( $decimalPart ) == 1 && $decimalPart == "5"; }
php
public function getDecimalIsHalf( $scale = false ) { if ( ! $this->getIsDecimal() ) { return false; } if ( $scale === false ) $scale = $this->scale( $this->_value ); if ( $scale < 0 ) $scale = $scale = 0; $decimalPart = $this->getDecimalPart(); if ( $scale >= strlen( $decimalPart ) ) return false; // Get the portion of the decimal part affected by the scale value $decimalPart = substr( $decimalPart, $scale ); return strlen( $decimalPart ) == 1 && $decimalPart == "5"; }
Test to see if the digit at scale + 1 is a 5 @param int $scale @return bool
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L723-L738
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.getIsDecimalEven
public function getIsDecimalEven( $precision = false ) { if ( ! $this->getIsDecimal() ) { return false; } if ( $precision === false ) $precision = $this->scale( $this->_value ); if ( $precision < 0 ) $precision = $precision = 0; $decimalPart = $this->getDecimalPart(); if ( $precision >= strlen( $decimalPart ) ) return false; // Get the portion of the decimal part affected by the scale value $decimalPart = substr( $decimalPart, $precision ); return $decimalPart[0] % 2 === 0; }
php
public function getIsDecimalEven( $precision = false ) { if ( ! $this->getIsDecimal() ) { return false; } if ( $precision === false ) $precision = $this->scale( $this->_value ); if ( $precision < 0 ) $precision = $precision = 0; $decimalPart = $this->getDecimalPart(); if ( $precision >= strlen( $decimalPart ) ) return false; // Get the portion of the decimal part affected by the scale value $decimalPart = substr( $decimalPart, $precision ); return $decimalPart[0] % 2 === 0; }
Returns true if the digit at the required level of precision is even @param string $precision @return bool
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L764-L779
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.getIsCloserToNext
public function getIsCloserToNext( $precision = false, $mode = PHP_ROUND_HALF_UP ) { if ( ! $this->getIsDecimal() ) { return false; } if ( $precision === false ) $precision = $this->scale( $this->_value ); if ( $precision < 0 ) $precision = $precision = 0; $decimalPart = $this->getDecimalPart(); if ( $precision >= strlen( $decimalPart ) ) return false; // Get the portion of the decimal part affected by the scale value $decimalPart = substr( $decimalPart, $precision ); $result = bccomp( "0." . $decimalPart, "0.5", max( $this->scale( $decimalPart ), 1 ) ); return $mode == PHP_ROUND_HALF_DOWN ? $result == 1 : $result >= 0; }
php
public function getIsCloserToNext( $precision = false, $mode = PHP_ROUND_HALF_UP ) { if ( ! $this->getIsDecimal() ) { return false; } if ( $precision === false ) $precision = $this->scale( $this->_value ); if ( $precision < 0 ) $precision = $precision = 0; $decimalPart = $this->getDecimalPart(); if ( $precision >= strlen( $decimalPart ) ) return false; // Get the portion of the decimal part affected by the scale value $decimalPart = substr( $decimalPart, $precision ); $result = bccomp( "0." . $decimalPart, "0.5", max( $this->scale( $decimalPart ), 1 ) ); return $mode == PHP_ROUND_HALF_DOWN ? $result == 1 : $result >= 0; }
Returns true if the number at the scale position in the decimal part of the number is closer to the next power. @param int $precision @param int $mode PHP_ROUND_HALF_UP (default), PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, PHP_ROUND_HALF_ODD @return bool
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L787-L803
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.ToSingle
public function ToSingle( $provider ) { return floatval( $this->_value ); // Expand the number to a string return sprintf( "%.8G", $this->_value ); $matched = preg_match( DecimalValue::Pattern , $this->_value, $matches ); if ( ! $matched ) { throw new \InvalidArgumentException( "The number '{$this->_value}' cannot be parsed" ); } $sign = isset( $matches['sign'] ) && $matches['sign'] == '-' ? -1 : 1; $digits = isset( $matches['digits'] ) ? $matches['digits'] : ""; $decimals = isset( $matches['decimals'] ) ? $matches['decimals'] : ""; $exponent = isset( $matches['exponent'] ) ? $matches['exponent'] + 0 : false; $mantissa = $digits . $decimals; while ( strlen( decbin( $mantissa ) ) > 24 ) { $mantissa = round( $mantissa / 10 ); } $number = ""; $diff = strlen( $digits ) - strlen( $mantissa ); if ( $diff > 0 ) { $exponent += $diff; $number = $mantissa; } else if ( $diff == 0 ) { $number = $mantissa; } else { $number = $digits . "." . substr( $mantissa, strlen( $digits ) ); } if ( $exponent ) { $number .= "E{$exponent}"; } $number = $number + 0.0; if ( $number > 2**104 ) { $number = $sign == -1 ? -INF : INF; } else if ( $number < 2**-149 ) { $number = $sign == 1 ? 0 : -0; } $number = $number * $sign; return $number; }
php
public function ToSingle( $provider ) { return floatval( $this->_value ); // Expand the number to a string return sprintf( "%.8G", $this->_value ); $matched = preg_match( DecimalValue::Pattern , $this->_value, $matches ); if ( ! $matched ) { throw new \InvalidArgumentException( "The number '{$this->_value}' cannot be parsed" ); } $sign = isset( $matches['sign'] ) && $matches['sign'] == '-' ? -1 : 1; $digits = isset( $matches['digits'] ) ? $matches['digits'] : ""; $decimals = isset( $matches['decimals'] ) ? $matches['decimals'] : ""; $exponent = isset( $matches['exponent'] ) ? $matches['exponent'] + 0 : false; $mantissa = $digits . $decimals; while ( strlen( decbin( $mantissa ) ) > 24 ) { $mantissa = round( $mantissa / 10 ); } $number = ""; $diff = strlen( $digits ) - strlen( $mantissa ); if ( $diff > 0 ) { $exponent += $diff; $number = $mantissa; } else if ( $diff == 0 ) { $number = $mantissa; } else { $number = $digits . "." . substr( $mantissa, strlen( $digits ) ); } if ( $exponent ) { $number .= "E{$exponent}"; } $number = $number + 0.0; if ( $number > 2**104 ) { $number = $sign == -1 ? -INF : INF; } else if ( $number < 2**-149 ) { $number = $sign == 1 ? 0 : -0; } $number = $number * $sign; return $number; }
ToSingle @param IFormatProvider $provider @return float
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L924-L982
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.dec2bin
private function dec2bin( $decimal ) { bcscale(0); $binary = ''; do { $binary = bcmod( $decimal, '2' ) . $binary; $decimal = bcdiv( $decimal, '2' ); } while ( bccomp( $decimal, '0' ) ); return( $binary ); }
php
private function dec2bin( $decimal ) { bcscale(0); $binary = ''; do { $binary = bcmod( $decimal, '2' ) . $binary; $decimal = bcdiv( $decimal, '2' ); } while ( bccomp( $decimal, '0' ) ); return( $binary ); }
Create a binary representation of the current value @param string $decimal The number to be converted @return string
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L989-L1000
bseddon/XPath20
Value/DecimalValue.php
DecimalValue.ToDoubleString
public function ToDoubleString( $provider ) { $sign = $this->getIsNegative(); if ( bccomp( $this->_value, bcpow( 2, 204 ) ) > 0 ) { return $sign ? -INF : INF; } else if ( bccomp( $this->getAbs()->getValue(), bcpow( 2, -149, 149 ) ) < 0 ) { return $sign ? 0 : -0; } $abs = $this->getAbs(); $decimals = rtrim( $this->getDecimalPart(), "0" ); if ( bccomp( $abs->getValue(), 1 ) == -1 ) { // Are there enough bits available to store the number? if ( $this->dec2bin( $decimals ) > 56 ) { $exponent = 1; // First remove leading zeros which become part of the exponent while( $decimals[0] == 0 ) { $exponent++; $decimals = substr( $decimals, 1 ); } $number = $decimals[0] . "." . substr( $decimals, 1 ) . "E-" . $exponent; } else { return $this->_value; } } else { $digits = $this->getAbs()->getIntegerPart(); $mantissa = rtrim( $digits . $decimals, "0" ); $exponentRequired = strlen( $digits ) >= 20; while ( strlen( $this->dec2bin( $mantissa ) ) > 56 ) { $mantissa = bcdiv( $mantissa, 10, 0 ); $exponentRequired = true; } $number = $mantissa; if ( $exponentRequired ) { $number = $mantissa[0] . "." . substr( $mantissa, 1 ); $exponent = strlen( $digits ) -1; $number .= "E$exponent"; } else { $number = rtrim( $digits . "." . implode( "", explode( $digits, $mantissa, 2) ), "." ); } } if ( $sign ) { $number = "-" . $number; } return $number; }
php
public function ToDoubleString( $provider ) { $sign = $this->getIsNegative(); if ( bccomp( $this->_value, bcpow( 2, 204 ) ) > 0 ) { return $sign ? -INF : INF; } else if ( bccomp( $this->getAbs()->getValue(), bcpow( 2, -149, 149 ) ) < 0 ) { return $sign ? 0 : -0; } $abs = $this->getAbs(); $decimals = rtrim( $this->getDecimalPart(), "0" ); if ( bccomp( $abs->getValue(), 1 ) == -1 ) { // Are there enough bits available to store the number? if ( $this->dec2bin( $decimals ) > 56 ) { $exponent = 1; // First remove leading zeros which become part of the exponent while( $decimals[0] == 0 ) { $exponent++; $decimals = substr( $decimals, 1 ); } $number = $decimals[0] . "." . substr( $decimals, 1 ) . "E-" . $exponent; } else { return $this->_value; } } else { $digits = $this->getAbs()->getIntegerPart(); $mantissa = rtrim( $digits . $decimals, "0" ); $exponentRequired = strlen( $digits ) >= 20; while ( strlen( $this->dec2bin( $mantissa ) ) > 56 ) { $mantissa = bcdiv( $mantissa, 10, 0 ); $exponentRequired = true; } $number = $mantissa; if ( $exponentRequired ) { $number = $mantissa[0] . "." . substr( $mantissa, 1 ); $exponent = strlen( $digits ) -1; $number .= "E$exponent"; } else { $number = rtrim( $digits . "." . implode( "", explode( $digits, $mantissa, 2) ), "." ); } } if ( $sign ) { $number = "-" . $number; } return $number; }
ToSingle @param IFormatProvider $provider @return float
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/Value/DecimalValue.php#L1007-L1074
naucon/Utility
src/CollectionAbstract.php
CollectionAbstract.addAll
public function addAll(array $elements) { if (is_array($elements)) { foreach ($elements as $element) { $this->_items[] = $element; } $this->_iterator = null; } else { throw new CollectionException('Given array can not added to collection, because it is no array.', E_NOTICE); } }
php
public function addAll(array $elements) { if (is_array($elements)) { foreach ($elements as $element) { $this->_items[] = $element; } $this->_iterator = null; } else { throw new CollectionException('Given array can not added to collection, because it is no array.', E_NOTICE); } }
add elements to the end of the collection @param array $elements elements @return void @throws CollectionException
https://github.com/naucon/Utility/blob/d225bb5d09d82400917f710c9d502949a66442c4/src/CollectionAbstract.php#L51-L61
naucon/Utility
src/CollectionAbstract.php
CollectionAbstract.getIterator
public function getIterator() { if (is_null($this->_iterator)) { $this->_iterator = new Iterator($this->_items); } return $this->_iterator; }
php
public function getIterator() { if (is_null($this->_iterator)) { $this->_iterator = new Iterator($this->_items); } return $this->_iterator; }
return a iterator @return IteratorInterface
https://github.com/naucon/Utility/blob/d225bb5d09d82400917f710c9d502949a66442c4/src/CollectionAbstract.php#L100-L106
naucon/Utility
src/CollectionAbstract.php
CollectionAbstract.remove
public function remove($element) { $index = $this->indexOf($element); if ($index !== false) { unset($this->_items[$index]); $this->_items = array_values($this->_items); $this->_iterator = null; return true; } return false; }
php
public function remove($element) { $index = $this->indexOf($element); if ($index !== false) { unset($this->_items[$index]); $this->_items = array_values($this->_items); $this->_iterator = null; return true; } return false; }
remove a specified element from the collection @param mixed $element element @return bool
https://github.com/naucon/Utility/blob/d225bb5d09d82400917f710c9d502949a66442c4/src/CollectionAbstract.php#L124-L135
project-a/spryker-document
src/Pav/Zed/Document/DocumentDependencyProvider.php
DocumentDependencyProvider.provideBusinessLayerDependencies
public function provideBusinessLayerDependencies(Container $container) { $container[self::FACADE_PDF] = function (Container $container) { return new DocumentToPdfBridge($container->getLocator()->pdf()->facade()); }; $container[self::FACADE_FILE_UPLOAD] = function (Container $container) { return new DocumentToFileUploadBridge($container->getLocator()->fileUpload()->facade()); }; $container[self::PDF_CONVERTER_STACK] = function () { return $this->getPdfConverterStack(); }; return parent::provideBusinessLayerDependencies($container); }
php
public function provideBusinessLayerDependencies(Container $container) { $container[self::FACADE_PDF] = function (Container $container) { return new DocumentToPdfBridge($container->getLocator()->pdf()->facade()); }; $container[self::FACADE_FILE_UPLOAD] = function (Container $container) { return new DocumentToFileUploadBridge($container->getLocator()->fileUpload()->facade()); }; $container[self::PDF_CONVERTER_STACK] = function () { return $this->getPdfConverterStack(); }; return parent::provideBusinessLayerDependencies($container); }
@param \Spryker\Zed\Kernel\Container $container @return \Spryker\Zed\Kernel\Container
https://github.com/project-a/spryker-document/blob/878bbd412db9cb809e25980ab6fa8c14257578d6/src/Pav/Zed/Document/DocumentDependencyProvider.php#L23-L38
sndsgd/sndsgd-field
src/field/rule/FloatRule.php
FloatRule.validate
public function validate() { if (is_string($this->value)) { if (preg_match('~^([0-9\\.-]+)$~', $this->value)) { $this->value = floatval(Str::toNumber($this->value)); return true; } } else if ( is_bool($this->value) === false && ($newValue = filter_var($this->value, FILTER_VALIDATE_FLOAT)) !== false ) { $this->value = $newValue; return true; } return false; }
php
public function validate() { if (is_string($this->value)) { if (preg_match('~^([0-9\\.-]+)$~', $this->value)) { $this->value = floatval(Str::toNumber($this->value)); return true; } } else if ( is_bool($this->value) === false && ($newValue = filter_var($this->value, FILTER_VALIDATE_FLOAT)) !== false ) { $this->value = $newValue; return true; } return false; }
{@inheritdoc}
https://github.com/sndsgd/sndsgd-field/blob/34ac3aabfe031bd9b259b3b93e84964b04031334/src/field/rule/FloatRule.php#L24-L40
shampeak/GraceServer
src/Server/Server.php
Server.getInstance
public static function getInstance($Baseroot = '') { if (!(self::$_instance instanceof self)) { self::$_instance = new self($Baseroot); } return self::$_instance; }
php
public static function getInstance($Baseroot = '') { if (!(self::$_instance instanceof self)) { self::$_instance = new self($Baseroot); } return self::$_instance; }
@param string $Baseroot @return Server|null
https://github.com/shampeak/GraceServer/blob/e69891de3daae7d228c803c06213eb248fc88594/src/Server/Server.php#L74-L80
shampeak/GraceServer
src/Server/Server.php
Server.make
public function make($abstract, $parameters = []) { $abstract = ucfirst($abstract); if (isset($this->Instances[$abstract])) { return $this->Instances[$abstract]; } //未定义的服务类 返回空值; if (!isset($this->Providers[$abstract])) { return null; } // echo $abstract; $parameters = $parameters ?: isset($this->ObjectConfig[$abstract]) ? $this->ObjectConfig[$abstract] : []; $this->Instances[$abstract] = $this->build($abstract, $parameters); return $this->Instances[$abstract]; }
php
public function make($abstract, $parameters = []) { $abstract = ucfirst($abstract); if (isset($this->Instances[$abstract])) { return $this->Instances[$abstract]; } //未定义的服务类 返回空值; if (!isset($this->Providers[$abstract])) { return null; } // echo $abstract; $parameters = $parameters ?: isset($this->ObjectConfig[$abstract]) ? $this->ObjectConfig[$abstract] : []; $this->Instances[$abstract] = $this->build($abstract, $parameters); return $this->Instances[$abstract]; }
@param $abstract @param array $parameters @return mixed|null
https://github.com/shampeak/GraceServer/blob/e69891de3daae7d228c803c06213eb248fc88594/src/Server/Server.php#L107-L121
shampeak/GraceServer
src/Server/Server.php
Server.help
public function help() { //获取显示模板 $tpl = \Grace\Base\Help::getplframe(); //oblist $objectList = $this->objectList(); $chr = $title = $_GET['chr']; //计算左侧菜单 //<li class="active"><a href="/index.php?book=01-grace&lm=controller&ar=controller.md"> Controller </a></li> $nav = ''; foreach ($objectList as $key => $value) { if ($key == $chr) { $nav .= "<li class=\"active\"><a href=\"?chr=$key\"> $key </a></li>"; } else { $nav .= "<li><a href=\"?chr=$key\"> $key </a></li>"; } } $nr = ''; if ($objectList[$chr]) { //获取内容 $file = $objectList[$chr]; $nr = (new \Parsedown())->text(file_get_contents(__DIR__ . '/' . $file)); } else { $nr = ''; } $html = str_replace('##nav##', $nav, $tpl); $html = str_replace('##nr##', $nr, $html); $html = str_replace('##title##', $title, $html); echo $html; exit; }
php
public function help() { //获取显示模板 $tpl = \Grace\Base\Help::getplframe(); //oblist $objectList = $this->objectList(); $chr = $title = $_GET['chr']; //计算左侧菜单 //<li class="active"><a href="/index.php?book=01-grace&lm=controller&ar=controller.md"> Controller </a></li> $nav = ''; foreach ($objectList as $key => $value) { if ($key == $chr) { $nav .= "<li class=\"active\"><a href=\"?chr=$key\"> $key </a></li>"; } else { $nav .= "<li><a href=\"?chr=$key\"> $key </a></li>"; } } $nr = ''; if ($objectList[$chr]) { //获取内容 $file = $objectList[$chr]; $nr = (new \Parsedown())->text(file_get_contents(__DIR__ . '/' . $file)); } else { $nr = ''; } $html = str_replace('##nav##', $nav, $tpl); $html = str_replace('##nr##', $nr, $html); $html = str_replace('##title##', $title, $html); echo $html; exit; }
调用 server()->help();
https://github.com/shampeak/GraceServer/blob/e69891de3daae7d228c803c06213eb248fc88594/src/Server/Server.php#L186-L222
bseddon/XPath20
XPathComparer.php
XPathComparer.Compare
public function Compare( $x, $y ) { $nav1 = $x instanceof XPathNavigator ? $x : null; $nav2 = $y instanceof XPathNavigator ? $y : null; /** * @var XPathNavigator $nav1 * @var XPathNavigator $nav2 */ if ( ! is_null( $nav1 ) && ! is_null( $nav2 ) ) { switch ( $nav1->ComparePosition( $nav2, $this->useLineNo ) ) { case XmlNodeOrder::Before: return -1; case XmlNodeOrder::After: return 1; case XmlNodeOrder::Same: return 0; default: // It appears to be correct to return -1 every time because $nav1 // will always appear before $nav2 because that's the order in which // they are presented in the XPath query. return -1; /** * Below is an implementation of the C# version which appears to be wrong * because the value of spl_object_hash (or getHashCode in C# is random * so the result here is likely to be random. * @var XPathNavigator $root1 * @var XPathNavigator $root2 */ $root1 = $nav1->CloneInstance(); $root1->MoveToRoot(); $root2 = $nav2->CloneInstance(); $root2->MoveToRoot(); $hashCode1 = spl_object_hash( $root1 ); $hashCode2 = spl_object_hash( $root2 ); if ( $hashCode1 < $hashCode2 ) { return -1; } else if ( $hashCode1 > $hashCode2 ) { return 1; } else { throw new InvalidOperationException(); } } } else throw XPath2Exception::withErrorCodeAndParams( "XPTY0004", Resources::XPTY0004, array( "xs:anyAtomicType", "node()* in function op:union,op:intersect and op:except" ) ); }
php
public function Compare( $x, $y ) { $nav1 = $x instanceof XPathNavigator ? $x : null; $nav2 = $y instanceof XPathNavigator ? $y : null; /** * @var XPathNavigator $nav1 * @var XPathNavigator $nav2 */ if ( ! is_null( $nav1 ) && ! is_null( $nav2 ) ) { switch ( $nav1->ComparePosition( $nav2, $this->useLineNo ) ) { case XmlNodeOrder::Before: return -1; case XmlNodeOrder::After: return 1; case XmlNodeOrder::Same: return 0; default: // It appears to be correct to return -1 every time because $nav1 // will always appear before $nav2 because that's the order in which // they are presented in the XPath query. return -1; /** * Below is an implementation of the C# version which appears to be wrong * because the value of spl_object_hash (or getHashCode in C# is random * so the result here is likely to be random. * @var XPathNavigator $root1 * @var XPathNavigator $root2 */ $root1 = $nav1->CloneInstance(); $root1->MoveToRoot(); $root2 = $nav2->CloneInstance(); $root2->MoveToRoot(); $hashCode1 = spl_object_hash( $root1 ); $hashCode2 = spl_object_hash( $root2 ); if ( $hashCode1 < $hashCode2 ) { return -1; } else if ( $hashCode1 > $hashCode2 ) { return 1; } else { throw new InvalidOperationException(); } } } else throw XPath2Exception::withErrorCodeAndParams( "XPTY0004", Resources::XPTY0004, array( "xs:anyAtomicType", "node()* in function op:union,op:intersect and op:except" ) ); }
Compare @param XPathItem $x @param XPathItem $y @return int
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/XPathComparer.php#L64-L132
fuelphp-storage/security
src/Filter/Base.php
Base.clean
public function clean($input) { // Nothing to escape for non-string scalars, or for already processed values if (is_bool($input) or is_int($input) or is_float($input) or $this->parent->isCleaned($input)) { return $input; } if (is_string($input)) { $input = $this->cleanString($input); } elseif (is_array($input) or ($input instanceof \Iterator and $input instanceof \ArrayAccess)) { $input = $this->cleanArray($input); } elseif ($input instanceof \Iterator or get_class($input) == 'stdClass') { $input = $this->cleanObject($input); } elseif (is_object($input)) { // Check if the object is whitelisted and just return when that's the case foreach ($this->parent->getConfig('whitelistedClasses', array()) as $class) { if (is_a($input, $class)) { return $input; } } // Throw exception when it wasn't whitelisted and can't be converted to String if (! method_exists($input, '__toString')) { throw new \RuntimeException('Object class "'.get_class($input).'" could not be converted to string or '. 'sanitized as ArrayAccess. Whitelist it in security.whitelisted_classes in [application]/config/security.php '. 'to allow it to be passed unchecked.'); } $input = $this->cleanString(strval($input)); } // mark this variable as cleaned $this->parent->isClean($input); return $input; }
php
public function clean($input) { // Nothing to escape for non-string scalars, or for already processed values if (is_bool($input) or is_int($input) or is_float($input) or $this->parent->isCleaned($input)) { return $input; } if (is_string($input)) { $input = $this->cleanString($input); } elseif (is_array($input) or ($input instanceof \Iterator and $input instanceof \ArrayAccess)) { $input = $this->cleanArray($input); } elseif ($input instanceof \Iterator or get_class($input) == 'stdClass') { $input = $this->cleanObject($input); } elseif (is_object($input)) { // Check if the object is whitelisted and just return when that's the case foreach ($this->parent->getConfig('whitelistedClasses', array()) as $class) { if (is_a($input, $class)) { return $input; } } // Throw exception when it wasn't whitelisted and can't be converted to String if (! method_exists($input, '__toString')) { throw new \RuntimeException('Object class "'.get_class($input).'" could not be converted to string or '. 'sanitized as ArrayAccess. Whitelist it in security.whitelisted_classes in [application]/config/security.php '. 'to allow it to be passed unchecked.'); } $input = $this->cleanString(strval($input)); } // mark this variable as cleaned $this->parent->isClean($input); return $input; }
Cleans string, object or array @param mixed $input @return mixed @throws \RuntimeException if the variable passed can not be cleaned
https://github.com/fuelphp-storage/security/blob/2cad42a8432bc9c9de46486623b71e105ff84b1b/src/Filter/Base.php#L39-L88
fuelphp-storage/security
src/Filter/Base.php
Base.cleanArray
protected function cleanArray($input) { // add to the cleaned list when object if (is_object($input)) { $this->parent->isClean($input); } foreach ($input as $k => $v) { $input[$k] = $this->clean($v); } return $input; }
php
protected function cleanArray($input) { // add to the cleaned list when object if (is_object($input)) { $this->parent->isClean($input); } foreach ($input as $k => $v) { $input[$k] = $this->clean($v); } return $input; }
cleanArray base method @param string $input @return string
https://github.com/fuelphp-storage/security/blob/2cad42a8432bc9c9de46486623b71e105ff84b1b/src/Filter/Base.php#L109-L123
fuelphp-storage/security
src/Filter/Base.php
Base.cleanObject
protected function cleanObject($input) { // add to the cleaned list $this->parent->isClean($input); foreach ($value as $k => $v) { $value->{$k} = $this->clean($v); } return $input; }
php
protected function cleanObject($input) { // add to the cleaned list $this->parent->isClean($input); foreach ($value as $k => $v) { $value->{$k} = $this->clean($v); } return $input; }
cleanObject base method. Not defined as abstract become some filters might not implement cleaning objects @param object $input @return object
https://github.com/fuelphp-storage/security/blob/2cad42a8432bc9c9de46486623b71e105ff84b1b/src/Filter/Base.php#L132-L142
Nicofuma/phpbb-ext-webprofiler
phpbb/db/timed.php
timed.sql_query_limit
public function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) { $e = $this->stopwatch->start($query, 'database'); $result = parent::sql_query_limit($query, $total, $offset, $cache_ttl); $e->stop(); return $result; }
php
public function sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0) { $e = $this->stopwatch->start($query, 'database'); $result = parent::sql_query_limit($query, $total, $offset, $cache_ttl); $e->stop(); return $result; }
{@inheritdoc}
https://github.com/Nicofuma/phpbb-ext-webprofiler/blob/5f52e2b67f5b8278af18907615f30ffe20f4802c/phpbb/db/timed.php#L43-L52
Nicofuma/phpbb-ext-webprofiler
phpbb/db/timed.php
timed.sql_query
public function sql_query($query = '', $cache_ttl = 0) { $e = $this->stopwatch->start($query, 'database'); $result = parent::sql_query($query, $cache_ttl); $e->stop(); return $result; }
php
public function sql_query($query = '', $cache_ttl = 0) { $e = $this->stopwatch->start($query, 'database'); $result = parent::sql_query($query, $cache_ttl); $e->stop(); return $result; }
{@inheritdoc}
https://github.com/Nicofuma/phpbb-ext-webprofiler/blob/5f52e2b67f5b8278af18907615f30ffe20f4802c/phpbb/db/timed.php#L57-L66
Nicofuma/phpbb-ext-webprofiler
phpbb/db/timed.php
timed.sql_multi_insert
public function sql_multi_insert($table, $sql_ary) { $e = $this->stopwatch->start(sprintf('multi-insert (%s)', $table), 'database'); $result = parent::sql_multi_insert($table, $sql_ary); $e->stop(); return $result; }
php
public function sql_multi_insert($table, $sql_ary) { $e = $this->stopwatch->start(sprintf('multi-insert (%s)', $table), 'database'); $result = parent::sql_multi_insert($table, $sql_ary); $e->stop(); return $result; }
{@inheritdoc}
https://github.com/Nicofuma/phpbb-ext-webprofiler/blob/5f52e2b67f5b8278af18907615f30ffe20f4802c/phpbb/db/timed.php#L71-L80
y80x86ol/simpla-framework
src/Illuminate/Route/RouteHandle.php
RouteHandle.getRoute
public static function getRoute() { //获取请求URL $requestUrlArr = self::getRouteArray(); //处理请求URL if (count($requestUrlArr) == 1) {//dev.example.com/aaa $data = array(array( 'act' => !empty($requestUrlArr[0]) ? $requestUrlArr[0] : 'index', 'op' => 'actionIndex', 'namespace' => '' )); } elseif (count($requestUrlArr) >= 2) {//dev.example.com/aaa/bbb //dev.example.com/aaa/bbb/index $origRequestUrlArr = $requestUrlArr; $lastParam = array_pop($requestUrlArr); if ($lastParam == 'index') { $data = array(array( 'act' => array_pop($requestUrlArr), 'op' => 'actionIndex', 'namespace' => implode('/', $requestUrlArr) )); } else { $data = array( array( 'act' => array_pop($origRequestUrlArr), 'op' => 'actionIndex', 'namespace' => implode('/', $origRequestUrlArr), ), array( 'act' => array_pop($requestUrlArr), 'op' => 'action' . ucfirst($lastParam), 'namespace' => implode('/', $requestUrlArr), ) ); } } return $data; }
php
public static function getRoute() { //获取请求URL $requestUrlArr = self::getRouteArray(); //处理请求URL if (count($requestUrlArr) == 1) {//dev.example.com/aaa $data = array(array( 'act' => !empty($requestUrlArr[0]) ? $requestUrlArr[0] : 'index', 'op' => 'actionIndex', 'namespace' => '' )); } elseif (count($requestUrlArr) >= 2) {//dev.example.com/aaa/bbb //dev.example.com/aaa/bbb/index $origRequestUrlArr = $requestUrlArr; $lastParam = array_pop($requestUrlArr); if ($lastParam == 'index') { $data = array(array( 'act' => array_pop($requestUrlArr), 'op' => 'actionIndex', 'namespace' => implode('/', $requestUrlArr) )); } else { $data = array( array( 'act' => array_pop($origRequestUrlArr), 'op' => 'actionIndex', 'namespace' => implode('/', $origRequestUrlArr), ), array( 'act' => array_pop($requestUrlArr), 'op' => 'action' . ucfirst($lastParam), 'namespace' => implode('/', $requestUrlArr), ) ); } } return $data; }
处理普通路由,获取命名空间、控制器和执行方法 @return array
https://github.com/y80x86ol/simpla-framework/blob/883858dbfdb3f3c0f64b794a7ea56fa8dc37afe7/src/Illuminate/Route/RouteHandle.php#L19-L56
y80x86ol/simpla-framework
src/Illuminate/Route/RouteHandle.php
RouteHandle.getModuleRoute
public static function getModuleRoute() { //获取请求URL $requestUrlArr = self::getRouteArray(); //处理请求URL if (count($requestUrlArr) == 1) {//dev.example.com/aaa $data = array(array( 'module' => $requestUrlArr[0], 'act' => 'index', 'op' => 'actionIndex', 'namespace' => '' )); } elseif (count($requestUrlArr) == 2) {//dev.example.com/aaa/bbb $data = array(array( 'module' => $requestUrlArr[0], 'act' => $requestUrlArr[1], 'op' => 'actionIndex', 'namespace' => '' )); } elseif (count($requestUrlArr) == 3) {//dev.example.com/aaa/bbb $data = array(array( 'module' => $requestUrlArr[0], 'act' => $requestUrlArr[1], 'op' => 'action' . ucfirst($requestUrlArr[2]), 'namespace' => '' ), array( 'module' => $requestUrlArr[0], 'act' => $requestUrlArr[2], 'op' => 'actionIndex', 'namespace' => $requestUrlArr[1] )); } elseif (count($requestUrlArr) >= 4) {//dev.example.com/aaa/bbb/ccc //dev.example.com/aaa/bbb/ccc/index $module = array_shift($requestUrlArr); //第一个元素即为module名字 $origRequestUrlArr = $requestUrlArr; $lastParam = array_pop($requestUrlArr); if ($lastParam == 'index') { $data = array(array( 'module' => $module, 'act' => array_pop($requestUrlArr), 'op' => 'actionIndex', 'namespace' => implode('/', $requestUrlArr) )); } else { $data = array( array( 'module' => $module, 'act' => array_pop($origRequestUrlArr), 'op' => 'actionIndex', 'namespace' => implode('/', $origRequestUrlArr), ), array( 'module' => $module, 'act' => array_pop($requestUrlArr), 'op' => 'action' . ucfirst($lastParam), 'namespace' => implode('/', $requestUrlArr), ) ); } } return $data; }
php
public static function getModuleRoute() { //获取请求URL $requestUrlArr = self::getRouteArray(); //处理请求URL if (count($requestUrlArr) == 1) {//dev.example.com/aaa $data = array(array( 'module' => $requestUrlArr[0], 'act' => 'index', 'op' => 'actionIndex', 'namespace' => '' )); } elseif (count($requestUrlArr) == 2) {//dev.example.com/aaa/bbb $data = array(array( 'module' => $requestUrlArr[0], 'act' => $requestUrlArr[1], 'op' => 'actionIndex', 'namespace' => '' )); } elseif (count($requestUrlArr) == 3) {//dev.example.com/aaa/bbb $data = array(array( 'module' => $requestUrlArr[0], 'act' => $requestUrlArr[1], 'op' => 'action' . ucfirst($requestUrlArr[2]), 'namespace' => '' ), array( 'module' => $requestUrlArr[0], 'act' => $requestUrlArr[2], 'op' => 'actionIndex', 'namespace' => $requestUrlArr[1] )); } elseif (count($requestUrlArr) >= 4) {//dev.example.com/aaa/bbb/ccc //dev.example.com/aaa/bbb/ccc/index $module = array_shift($requestUrlArr); //第一个元素即为module名字 $origRequestUrlArr = $requestUrlArr; $lastParam = array_pop($requestUrlArr); if ($lastParam == 'index') { $data = array(array( 'module' => $module, 'act' => array_pop($requestUrlArr), 'op' => 'actionIndex', 'namespace' => implode('/', $requestUrlArr) )); } else { $data = array( array( 'module' => $module, 'act' => array_pop($origRequestUrlArr), 'op' => 'actionIndex', 'namespace' => implode('/', $origRequestUrlArr), ), array( 'module' => $module, 'act' => array_pop($requestUrlArr), 'op' => 'action' . ucfirst($lastParam), 'namespace' => implode('/', $requestUrlArr), ) ); } } return $data; }
处理module模块路由,获取命名空间、控制器和执行方法 @return array
https://github.com/y80x86ol/simpla-framework/blob/883858dbfdb3f3c0f64b794a7ea56fa8dc37afe7/src/Illuminate/Route/RouteHandle.php#L63-L126
y80x86ol/simpla-framework
src/Illuminate/Route/RouteHandle.php
RouteHandle.getRouteArray
private static function getRouteArray() { //获取请求URL $requestUrl = ltrim(rtrim($_SERVER['REQUEST_URI'], '/'), '/'); //处理特殊情况,去掉index.php/ if (substr($requestUrl, 0, 9) == 'index.php') { $requestUrl = substr($requestUrl, 10); } //去除?以后的所有参数 $requestUrl = String::urlSafetyFilter($requestUrl); $requestUrlArr = explode('?', $requestUrl); //处理请求URL $requestUrlArr = explode('/', $requestUrlArr[0]); if (count($requestUrlArr) == 0) { error_404(); } $requestUrlArr = self::secondDomainFilter($requestUrlArr); return $requestUrlArr; }
php
private static function getRouteArray() { //获取请求URL $requestUrl = ltrim(rtrim($_SERVER['REQUEST_URI'], '/'), '/'); //处理特殊情况,去掉index.php/ if (substr($requestUrl, 0, 9) == 'index.php') { $requestUrl = substr($requestUrl, 10); } //去除?以后的所有参数 $requestUrl = String::urlSafetyFilter($requestUrl); $requestUrlArr = explode('?', $requestUrl); //处理请求URL $requestUrlArr = explode('/', $requestUrlArr[0]); if (count($requestUrlArr) == 0) { error_404(); } $requestUrlArr = self::secondDomainFilter($requestUrlArr); return $requestUrlArr; }
获取路由数组 @return type
https://github.com/y80x86ol/simpla-framework/blob/883858dbfdb3f3c0f64b794a7ea56fa8dc37afe7/src/Illuminate/Route/RouteHandle.php#L132-L155
y80x86ol/simpla-framework
src/Illuminate/Route/RouteHandle.php
RouteHandle.secondDomainFilter
private static function secondDomainFilter($requestUrlArr) { $domain = Domain::checkSecondDomain(); if ($domain) { if (empty($requestUrlArr[0])) { $requestUrlArr[0] = $domain; } else { array_unshift($requestUrlArr, $domain); } } return $requestUrlArr; }
php
private static function secondDomainFilter($requestUrlArr) { $domain = Domain::checkSecondDomain(); if ($domain) { if (empty($requestUrlArr[0])) { $requestUrlArr[0] = $domain; } else { array_unshift($requestUrlArr, $domain); } } return $requestUrlArr; }
二级域名路由追加处理 如果存在二级域名,则对路由头部插入二级域名标示。 @param array $requestUrlArr 路由数组 @return array 增加了二级域名标示的路由数组
https://github.com/y80x86ol/simpla-framework/blob/883858dbfdb3f3c0f64b794a7ea56fa8dc37afe7/src/Illuminate/Route/RouteHandle.php#L175-L185
mullanaphy/variable
src/PHY/Variable/AVar.php
AVar.set
public function set($value) { $this->validate($value); $this->original = $value; $this->current = $value; $this->chaining = false; $this->chain = null; return $this; }
php
public function set($value) { $this->validate($value); $this->original = $value; $this->current = $value; $this->chaining = false; $this->chain = null; return $this; }
Set the default value. @param mixed @return \PHY\Variable\AVar
https://github.com/mullanaphy/variable/blob/e4eb274a1799a25e33e5e21cd260603c74628031/src/PHY/Variable/AVar.php#L40-L48
mullanaphy/variable
src/PHY/Variable/AVar.php
AVar.complete
public function complete() { $chain = $this->chain; $this->chaining = false; $this->chain = null; return $chain; }
php
public function complete() { $chain = $this->chain; $this->chaining = false; $this->chain = null; return $chain; }
Complete a chain and return it's result. @return mixed
https://github.com/mullanaphy/variable/blob/e4eb274a1799a25e33e5e21cd260603c74628031/src/PHY/Variable/AVar.php#L84-L90
mullanaphy/variable
src/PHY/Variable/AVar.php
AVar.update
public function update($value) { $this->validate($value); if ($this->chaining) { $this->chain = $value; } else { $this->current = $value; } return $this; }
php
public function update($value) { $this->validate($value); if ($this->chaining) { $this->chain = $value; } else { $this->current = $value; } return $this; }
Update a value. @param mixed $value @return \PHY\Variable\AVar
https://github.com/mullanaphy/variable/blob/e4eb274a1799a25e33e5e21cd260603c74628031/src/PHY/Variable/AVar.php#L98-L107
mullanaphy/variable
src/PHY/Variable/AVar.php
AVar.reset
public function reset() { $this->current = $this->original; $this->chaining = false; $this->chain = null; return $this; }
php
public function reset() { $this->current = $this->original; $this->chaining = false; $this->chain = null; return $this; }
Reset the variable back to it's original value. @return \PHY\Variable\AVar
https://github.com/mullanaphy/variable/blob/e4eb274a1799a25e33e5e21cd260603c74628031/src/PHY/Variable/AVar.php#L157-L163
mullanaphy/variable
src/PHY/Variable/AVar.php
AVar.validate
public function validate($value) { if (!in_array(gettype($value), $this->types)) { throw new Exception('Type of value "'.gettype($value)."' is not compatible with ".get_class($this)); } }
php
public function validate($value) { if (!in_array(gettype($value), $this->types)) { throw new Exception('Type of value "'.gettype($value)."' is not compatible with ".get_class($this)); } }
Validate a variables type to make sure our class can use it. @param string $value @throws Exception
https://github.com/mullanaphy/variable/blob/e4eb274a1799a25e33e5e21cd260603c74628031/src/PHY/Variable/AVar.php#L171-L176
OpenConext/Stepup-bundle
src/Value/GssfConfig.php
GssfConfig.getLoaMap
public function getLoaMap() { $loaMap = []; foreach ($this->config as $key => $config) { if (array_key_exists('loa', $config)) { $loaMap[$key] = $config['loa']; } } return $loaMap; }
php
public function getLoaMap() { $loaMap = []; foreach ($this->config as $key => $config) { if (array_key_exists('loa', $config)) { $loaMap[$key] = $config['loa']; } } return $loaMap; }
Flattens the config and returns key value pairs where the key is the SF type and the value is the LOA level
https://github.com/OpenConext/Stepup-bundle/blob/94178ddb421889df9e068109293a8da880793ed2/src/Value/GssfConfig.php#L48-L57
nicmart/DomainSpecificQuery
src/Lucene/Compiler/CompositeLuceneCompiler.php
CompositeLuceneCompiler.terminalExpression
public function terminalExpression(Expression $expression) { $compileds = array(); foreach ($this->compilers as $compiler) { try { $compileds[] = $compiler->compile($expression); } catch (UncompilableValueException $e) {} } if (!$compileds) throw new UncompilableValueException("No compiler has been able to compile the expression"); if (1 == count($compileds)) return $compileds[0]; return new SpanExpression($this->glueOperator, $compileds); }
php
public function terminalExpression(Expression $expression) { $compileds = array(); foreach ($this->compilers as $compiler) { try { $compileds[] = $compiler->compile($expression); } catch (UncompilableValueException $e) {} } if (!$compileds) throw new UncompilableValueException("No compiler has been able to compile the expression"); if (1 == count($compileds)) return $compileds[0]; return new SpanExpression($this->glueOperator, $compileds); }
{@inheritdoc}
https://github.com/nicmart/DomainSpecificQuery/blob/7c01fe94337afdfae5884809e8b5487127a63ac3/src/Lucene/Compiler/CompositeLuceneCompiler.php#L68-L85
agentmedia/phine-core
src/Core/Modules/Backend/ContainerContentTree.php
ContainerContentTree.CanCreateIn
protected function CanCreateIn() { return self::Guard()->GrantAddContentToContainer($this->container)->ToBool() && self::Guard()->Allow(BackendAction::UseIt(), new ModuleForm()); }
php
protected function CanCreateIn() { return self::Guard()->GrantAddContentToContainer($this->container)->ToBool() && self::Guard()->Allow(BackendAction::UseIt(), new ModuleForm()); }
True if contents can be added to root element @return boolean
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Modules/Backend/ContainerContentTree.php#L84-L89
seyfer/ZendPsrLogger
src/ZendPsrLogger/Writer/Doctrine.php
Doctrine.checkEMConnection
protected function checkEMConnection() { if (!$this->getEntityManager()->isOpen()) { $connection = $this->getEntityManager()->getConnection(); $config = $this->getEntityManager()->getConfiguration(); $this->em = $this->getEntityManager()->create( $connection, $config ); } }
php
protected function checkEMConnection() { if (!$this->getEntityManager()->isOpen()) { $connection = $this->getEntityManager()->getConnection(); $config = $this->getEntityManager()->getConfiguration(); $this->em = $this->getEntityManager()->create( $connection, $config ); } }
reconnect
https://github.com/seyfer/ZendPsrLogger/blob/aafd57012bbdc144083362cb7e621c9d7e13aabf/src/ZendPsrLogger/Writer/Doctrine.php#L97-L107
PenoaksDev/Milky-Framework
src/Milky/Database/Eloquent/Nested/Generators/ModelGenerator.php
ModelGenerator.create
public function create( $name, $path ) { $path = $this->getPath( $name, $path ); $stub = $this->getStub( 'model' ); $this->files->put( $path, $this->parseStub( $stub, [ 'table' => $this->tableize( $name ), 'class' => $this->classify( $name ) ] ) ); return $path; }
php
public function create( $name, $path ) { $path = $this->getPath( $name, $path ); $stub = $this->getStub( 'model' ); $this->files->put( $path, $this->parseStub( $stub, [ 'table' => $this->tableize( $name ), 'class' => $this->classify( $name ) ] ) ); return $path; }
Create a new model at the given path. @param string $name @param string $path @return string
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Database/Eloquent/Nested/Generators/ModelGenerator.php#L12-L24
pluf/tenant
src/Tenant/Views/Configuration.php
Tenant_Views_Configuration.internalGet
private function internalGet($request, $match){ $model = new Tenant_Configuration(); $model = $model->getOne("`key`='" . $match['key'] . "'"); return $model; }
php
private function internalGet($request, $match){ $model = new Tenant_Configuration(); $model = $model->getOne("`key`='" . $match['key'] . "'"); return $model; }
Returns configuration with given key in the $match array. Returns null if such configuration does not exist. @param Pluf_HTTP_Request $request @param array $match @return Pluf_Model|NULL
https://github.com/pluf/tenant/blob/a06359c52b9a257b5a0a186264e8770acfc54b73/src/Tenant/Views/Configuration.php#L53-L57
ScaraMVC/Framework
src/Scara/Validation/Errors.php
Errors.get
public function get($key) { $res = $this->_errors[$key]; if (!is_array($res)) { return [$res]; } return $res; }
php
public function get($key) { $res = $this->_errors[$key]; if (!is_array($res)) { return [$res]; } return $res; }
Gets a specific error. @param string $key - The error we're looking for @return string - The error message
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Validation/Errors.php#L36-L44
ScaraMVC/Framework
src/Scara/Validation/Errors.php
Errors.first
public function first($key) { if ($this->has($key)) { $err = $this->_errors[$key]; if (is_array($err)) { for ($i = 0; $i < count($err); $i++) { if (!empty($err[$i])) { return $err[$i]; } } } else { return $err; } } return ''; // return empty string since no key found to prevent errors }
php
public function first($key) { if ($this->has($key)) { $err = $this->_errors[$key]; if (is_array($err)) { for ($i = 0; $i < count($err); $i++) { if (!empty($err[$i])) { return $err[$i]; } } } else { return $err; } } return ''; // return empty string since no key found to prevent errors }
Gets the first message for a specific error. @param string $key - The error we're looking for @return string - The error message
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Validation/Errors.php#L53-L69
ScaraMVC/Framework
src/Scara/Validation/Errors.php
Errors.add
public function add($data) { $ea = (array) $data; foreach ($ea as $key => $value) { if (is_array($value)) { foreach ($value as $k => $v) { if (is_null($v)) { unset($value[$k]); } } $value = array_values($value); $ea[$key] = $value; } } $this->_errors = $ea; }
php
public function add($data) { $ea = (array) $data; foreach ($ea as $key => $value) { if (is_array($value)) { foreach ($value as $k => $v) { if (is_null($v)) { unset($value[$k]); } } $value = array_values($value); $ea[$key] = $value; } } $this->_errors = $ea; }
Adds all error data. Also clears out any null values. @param array $data - The error data to load into
https://github.com/ScaraMVC/Framework/blob/199b08b45fadf5dae14ac4732af03b36e15bbef2/src/Scara/Validation/Errors.php#L76-L92
libgraviton/analytics-mongoshell-converter
src/Command/ConvertCommand.php
ConvertCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { // find php $phpFinder = new PhpExecutableFinder(); $phpProcess = $phpFinder->find(); $fs = new Filesystem(); $finder = new Finder(); $finder ->files() ->in($input->getArgument('scanDir')) ->name('*.js') ->notName('_*') ->sortByName(); foreach ($finder as $file) { $parser = new \AnalyticsConverter\Parser($file->getContents()); if (!is_null($input->getOption('mongoDateClass'))) { $parser->setMongoDateClass($input->getOption('mongoDateClass')); } $classGenerator = new \AnalyticsConverter\ClassGenerator( $file->getFilename(), $parser->parse(), $parser->getConditionals(), $parser->getConditionalParamMap() ); if (!is_null($input->getOption('classNamespace'))) { $classGenerator->setClassNamespace($input->getOption('classNamespace')); } $targetFileName = $input->getArgument('outDir').'/'.$classGenerator->getName().'.php'; $fs->dumpFile($targetFileName, $classGenerator->generate()); $output->writeln("wrote php file '".$targetFileName."'"); // php lint the file.. $proc = new Process([$phpProcess, '-l', $targetFileName]); $proc->start(); $proc->wait(); if ($proc->getExitCode() !== 0) { throw new \LogicException( "Invalid PHP code generated in file '".$targetFileName."' - check your pipeline!" ); } else { $output->writeln("Checked PHP syntax - all OK!"); } } }
php
protected function execute(InputInterface $input, OutputInterface $output) { // find php $phpFinder = new PhpExecutableFinder(); $phpProcess = $phpFinder->find(); $fs = new Filesystem(); $finder = new Finder(); $finder ->files() ->in($input->getArgument('scanDir')) ->name('*.js') ->notName('_*') ->sortByName(); foreach ($finder as $file) { $parser = new \AnalyticsConverter\Parser($file->getContents()); if (!is_null($input->getOption('mongoDateClass'))) { $parser->setMongoDateClass($input->getOption('mongoDateClass')); } $classGenerator = new \AnalyticsConverter\ClassGenerator( $file->getFilename(), $parser->parse(), $parser->getConditionals(), $parser->getConditionalParamMap() ); if (!is_null($input->getOption('classNamespace'))) { $classGenerator->setClassNamespace($input->getOption('classNamespace')); } $targetFileName = $input->getArgument('outDir').'/'.$classGenerator->getName().'.php'; $fs->dumpFile($targetFileName, $classGenerator->generate()); $output->writeln("wrote php file '".$targetFileName."'"); // php lint the file.. $proc = new Process([$phpProcess, '-l', $targetFileName]); $proc->start(); $proc->wait(); if ($proc->getExitCode() !== 0) { throw new \LogicException( "Invalid PHP code generated in file '".$targetFileName."' - check your pipeline!" ); } else { $output->writeln("Checked PHP syntax - all OK!"); } } }
Executes the current command. @param InputInterface $input User input on console @param OutputInterface $output Output of the command @return void
https://github.com/libgraviton/analytics-mongoshell-converter/blob/437731c353c58978d39bcd40ac5a741a0b106667/src/Command/ConvertCommand.php#L68-L118
PenoaksDev/Milky-Framework
src/Milky/Http/View/View.php
View.render
public function render( callable $callback = null ) { try { $contents = $this->renderContents(); $response = isset( $callback ) ? call_user_func( $callback, $this, $contents ) : null; // Once we have the contents of the view, we will flush the sections if we are // done rendering all views so that there is nothing left hanging over when // another view gets rendered in the future by the application developer. $this->factory->flushSectionsIfDoneRendering(); return !is_null( $response ) ? $response : $contents; } catch ( Exception $e ) { $this->factory->flushSections(); throw $e; } catch ( Throwable $e ) { $this->factory->flushSections(); throw $e; } }
php
public function render( callable $callback = null ) { try { $contents = $this->renderContents(); $response = isset( $callback ) ? call_user_func( $callback, $this, $contents ) : null; // Once we have the contents of the view, we will flush the sections if we are // done rendering all views so that there is nothing left hanging over when // another view gets rendered in the future by the application developer. $this->factory->flushSectionsIfDoneRendering(); return !is_null( $response ) ? $response : $contents; } catch ( Exception $e ) { $this->factory->flushSections(); throw $e; } catch ( Throwable $e ) { $this->factory->flushSections(); throw $e; } }
Get the string contents of the view. @param callable|null $callback @return string @throws \Throwable
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Http/View/View.php#L80-L107
eventerza/module-mailer
src/Services/Mailer.php
Mailer.send
public function send(MailMessageInterface $message) : stdClass { return $this->mailer->sendMessage($this->domain, $message->getData()); }
php
public function send(MailMessageInterface $message) : stdClass { return $this->mailer->sendMessage($this->domain, $message->getData()); }
@param MailMessageInterface $message @return stdClass @throws MissingRequiredMIMEParameters
https://github.com/eventerza/module-mailer/blob/7cf27596ce1261ff504c908c8d37ec8abcd8f28c/src/Services/Mailer.php#L40-L43
Revys/revy
src/App/Traits/Translatable.php
Translatable.getAttributeOrFallback
private function getAttributeOrFallback($locale, $attribute) { $value = $this->getTranslation($locale)->$attribute; $usePropertyFallback = $this->useFallback() && $this->usePropertyFallback(); if (empty($value) && $usePropertyFallback) { return $this->getTranslation($this->getFallbackLocale(), true)->$attribute; } return $value; }
php
private function getAttributeOrFallback($locale, $attribute) { $value = $this->getTranslation($locale)->$attribute; $usePropertyFallback = $this->useFallback() && $this->usePropertyFallback(); if (empty($value) && $usePropertyFallback) { return $this->getTranslation($this->getFallbackLocale(), true)->$attribute; } return $value; }
Returns the attribute value from fallback translation if value of attribute is empty and the property fallback is enabled in the configuration. in model. @param $locale @param $attribute @return mixed
https://github.com/Revys/revy/blob/b2c13f5f7e88eec2681b4ec8a0385e18c28fbfd1/src/App/Traits/Translatable.php#L157-L165
Revys/revy
src/App/Traits/Translatable.php
Translatable.getFallbackLocale
private function getFallbackLocale($locale = null) { if ($locale && $this->isLocaleCountryBased($locale)) { if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) { return $fallback; } } $locales = $this->getLocales(); foreach ($locales as $code) { if ($this->getTranslationByLocaleKey($code) !== null) return $code; } return app()->make('config')->get('revy.translatable.fallback_locale'); }
php
private function getFallbackLocale($locale = null) { if ($locale && $this->isLocaleCountryBased($locale)) { if ($fallback = $this->getLanguageFromCountryBasedLocale($locale)) { return $fallback; } } $locales = $this->getLocales(); foreach ($locales as $code) { if ($this->getTranslationByLocaleKey($code) !== null) return $code; } return app()->make('config')->get('revy.translatable.fallback_locale'); }
@param null $locale @return string
https://github.com/Revys/revy/blob/b2c13f5f7e88eec2681b4ec8a0385e18c28fbfd1/src/App/Traits/Translatable.php#L286-L302
Revys/revy
src/App/Traits/Translatable.php
Translatable.deleteTranslations
public function deleteTranslations($locales = null) { if ($locales === null) { $translations = $this->translations()->get(); } else { $locales = (array) $locales; $translations = $this->translations()->whereIn($this->getLocaleKey(), $locales)->get(); } foreach ($translations as $translation) { $translation->delete(); } // we need to manually "reload" the collection built from the relationship // otherwise $this->translations()->get() would NOT be the same as $this->translations $this->load('translations'); }
php
public function deleteTranslations($locales = null) { if ($locales === null) { $translations = $this->translations()->get(); } else { $locales = (array) $locales; $translations = $this->translations()->whereIn($this->getLocaleKey(), $locales)->get(); } foreach ($translations as $translation) { $translation->delete(); } // we need to manually "reload" the collection built from the relationship // otherwise $this->translations()->get() would NOT be the same as $this->translations $this->load('translations'); }
Deletes all translations for this model. @param string|array|null $locales The locales to be deleted (array or single string) (e.g., ["en", "de"] would remove these translations).
https://github.com/Revys/revy/blob/b2c13f5f7e88eec2681b4ec8a0385e18c28fbfd1/src/App/Traits/Translatable.php#L706-L720
Formula9/Core
src/Silex/Provider/SerializerServiceProvider.php
SerializerServiceProvider.register
public function register(Container $app) { $app['serializer'] = function ($app) { return new Serializer($app['serializer.normalizers'], $app['serializer.encoders']); }; $app['serializer.encoders'] = function () { return array(new JsonEncoder(), new XmlEncoder()); }; $app['serializer.normalizers'] = function () { return array(new CustomNormalizer(), new GetSetMethodNormalizer()); }; }
php
public function register(Container $app) { $app['serializer'] = function ($app) { return new Serializer($app['serializer.normalizers'], $app['serializer.encoders']); }; $app['serializer.encoders'] = function () { return array(new JsonEncoder(), new XmlEncoder()); }; $app['serializer.normalizers'] = function () { return array(new CustomNormalizer(), new GetSetMethodNormalizer()); }; }
{@inheritdoc} This method registers a serializer service. {@link http://api.symfony.com/master/Symfony/Component/Serializer/Serializer.html The service is provided by the Symfony Serializer component}.
https://github.com/Formula9/Core/blob/7786e873bceaa32a6ac36b10c959628739218011/src/Silex/Provider/SerializerServiceProvider.php#L36-L49
WellCommerce/LayoutBundle
Renderer/LayoutBoxRenderer.php
LayoutBoxRenderer.resolveControllerAction
private function resolveControllerAction(BoxControllerInterface $controller) { $currentAction = $this->routerHelper->getCurrentAction(); if ($this->routerHelper->hasControllerAction($controller, $currentAction)) { return $currentAction; } return 'indexAction'; }
php
private function resolveControllerAction(BoxControllerInterface $controller) { $currentAction = $this->routerHelper->getCurrentAction(); if ($this->routerHelper->hasControllerAction($controller, $currentAction)) { return $currentAction; } return 'indexAction'; }
Resolves action which can be used in controller method call @param BoxControllerInterface $controller @return string
https://github.com/WellCommerce/LayoutBundle/blob/470efd187d19827058f88317221cb875b4c9ced3/Renderer/LayoutBoxRenderer.php#L111-L120
WellBloud/sovacore-core
src/model/FrontModule/repository/BaseRepository.php
BaseRepository.findPublishedItems
public function findPublishedItems( array $where, $orderBy = null, $limit = null ) { return $this->repository->findBy(array_merge($where, ['published' => true]), $orderBy, $limit); }
php
public function findPublishedItems( array $where, $orderBy = null, $limit = null ) { return $this->repository->findBy(array_merge($where, ['published' => true]), $orderBy, $limit); }
Method which finds published items in the repository according to the where clause @param array $where @param array $orderBy @param int $limit @return array
https://github.com/WellBloud/sovacore-core/blob/1816a0d7cd3ec4a90d64e301fc2469d171ad217f/src/model/FrontModule/repository/BaseRepository.php#L26-L33
teonsystems/php-base
src/Loader.php
Loader.autoloaderTemplate
static function autoloaderTemplate ($className, $nameSpace, $srcDir) { // Only process given namespace $className = ltrim($className, "\\"); $regex = '/^'. str_replace("\\", "\\\\?", $nameSpace) ."\\\\?/"; $classNameNoNs = preg_replace($regex, '', $className); if (NULL === $classNameNoNs) { throw new \Exception("$nameSpace autoload error: ". preg_last_error()); } if ($className == $classNameNoNs) { return; } // Generate file name and final path $fileNameNoNs = str_replace("\\", DIRECTORY_SEPARATOR, $classNameNoNs); $filePath = $srcDir . DIRECTORY_SEPARATOR . $fileNameNoNs .'.php'; // Include if file exists if (is_readable($filePath)) { require $filePath; } }
php
static function autoloaderTemplate ($className, $nameSpace, $srcDir) { // Only process given namespace $className = ltrim($className, "\\"); $regex = '/^'. str_replace("\\", "\\\\?", $nameSpace) ."\\\\?/"; $classNameNoNs = preg_replace($regex, '', $className); if (NULL === $classNameNoNs) { throw new \Exception("$nameSpace autoload error: ". preg_last_error()); } if ($className == $classNameNoNs) { return; } // Generate file name and final path $fileNameNoNs = str_replace("\\", DIRECTORY_SEPARATOR, $classNameNoNs); $filePath = $srcDir . DIRECTORY_SEPARATOR . $fileNameNoNs .'.php'; // Include if file exists if (is_readable($filePath)) { require $filePath; } }
/* METHOD: autoloaderTemplate Template autoloader to be used by actual autoloader functions. Removes namespace, converts remaining class name to path and tries said path for file existence. Example usage: namespace VendorName\ModuleName; function autoload ($className) { \Teon\Base\Loader::autoloaderTemplate($className, __NAMESPACE__, __DIR__."/src"); } spl_autoload_register(__NAMESPACE__ . '\autoload', true, false); Expected name space: VendorName\ModuleName\SubNameSpace\ClassName Expected directory structure: ./vendor/VendorName/ModuleName/src/SubNameSpace/ClassName @param string Class name to search for @param string Namespace that this autoloader handles @param string Source code directory for given namespace @return void
https://github.com/teonsystems/php-base/blob/010418fd9df3c447a74b36cf0d31e2d38a6527ac/src/Loader.php#L71-L92
agentmedia/phine-core
src/Core/Logic/Module/FrontendModule.php
FrontendModule.TemplateFile
public function TemplateFile() { if (!$this->AllowCustomTemplates() || !$this->content || !$this->content->GetTemplate()) { return $this->BuiltInTemplateFile(); } $file = Path::Combine(PathUtil::ModuleCustomTemplatesFolder($this), $this->content->GetTemplate()); return Path::AddExtension($file, 'phtml'); }
php
public function TemplateFile() { if (!$this->AllowCustomTemplates() || !$this->content || !$this->content->GetTemplate()) { return $this->BuiltInTemplateFile(); } $file = Path::Combine(PathUtil::ModuleCustomTemplatesFolder($this), $this->content->GetTemplate()); return Path::AddExtension($file, 'phtml'); }
The template file @return string
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Module/FrontendModule.php#L47-L56
agentmedia/phine-core
src/Core/Logic/Module/FrontendModule.php
FrontendModule.SetTreeItem
public function SetTreeItem(IContentTreeProvider $tree, $item) { $this->tree = $tree; $this->item = $item; $this->content = $this->tree->ContentByItem($item); }
php
public function SetTreeItem(IContentTreeProvider $tree, $item) { $this->tree = $tree; $this->item = $item; $this->content = $this->tree->ContentByItem($item); }
Sets tree and tree item @param IContentTreeProvider $tree @param mixed $item The tree item containing the render content
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Module/FrontendModule.php#L81-L86
agentmedia/phine-core
src/Core/Logic/Module/FrontendModule.php
FrontendModule.BackendName
public function BackendName() { if ($this->ContentForm()) { $this->ContentForm()->ReadTranslations(); } return Trans($this->MyBundle() . '.' . $this->MyName() . '.BackendName'); }
php
public function BackendName() { if ($this->ContentForm()) { $this->ContentForm()->ReadTranslations(); } return Trans($this->MyBundle() . '.' . $this->MyName() . '.BackendName'); }
Gets a display name for backend issues, can be overridden @return string The display name
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Module/FrontendModule.php#L92-L99
agentmedia/phine-core
src/Core/Logic/Module/FrontendModule.php
FrontendModule.BeforeInit
protected function BeforeInit() { //todo: check access rights $cacheFile = PathUtil::ContentCacheFile($this); $this->fileCacher = new FileCacher($cacheFile, $this->content->GetCacheLifetime()); if ($this->fileCacher->MustUseCache()) { $this->output = $this->fileCacher->GetFromCache(); return true; } return parent::BeforeInit(); }
php
protected function BeforeInit() { //todo: check access rights $cacheFile = PathUtil::ContentCacheFile($this); $this->fileCacher = new FileCacher($cacheFile, $this->content->GetCacheLifetime()); if ($this->fileCacher->MustUseCache()) { $this->output = $this->fileCacher->GetFromCache(); return true; } return parent::BeforeInit(); }
Gets cache content if necessary @return boolean
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Module/FrontendModule.php#L197-L208
agentmedia/phine-core
src/Core/Logic/Module/FrontendModule.php
FrontendModule.AfterGather
protected function AfterGather() { if ($this->fileCacher->MustStoreToCache()) { $this->fileCacher->StoreToCache($this->output); } parent::AfterGather(); }
php
protected function AfterGather() { if ($this->fileCacher->MustStoreToCache()) { $this->fileCacher->StoreToCache($this->output); } parent::AfterGather(); }
Stores to cache if necessary
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Module/FrontendModule.php#L212-L219
CalderaWP/caldera-interop
src/Collections/Attributes.php
Attributes.addAttribute
public function addAttribute(Attribute$attribute) : Attributes { $this->getItems();//max sure is array $this->attributes[$attribute->getName()] = $attribute; return $this; }
php
public function addAttribute(Attribute$attribute) : Attributes { $this->getItems();//max sure is array $this->attributes[$attribute->getName()] = $attribute; return $this; }
Add attribute to collection @param Attribute $attribute @return Attributes
https://github.com/CalderaWP/caldera-interop/blob/d25c4bc930200b314fbd42d084080b5d85261c94/src/Collections/Attributes.php#L36-L41
teonsystems/php-base
src/Mailer/Gateway.php
Gateway.sendHtml
public function sendHtml ($subject, $contentHTML, $to, $cc=array(), $bcc=array()) { $mail = $this->phpMailer; // Ensure if all destination specifications are arrays if (!is_array($to )) { $to = array($to) ; } if (!is_array($cc )) { $cc = array($cc) ; } if (!is_array($bcc)) { $bcc = array($bcc) ; } // Add all recipients foreach ($to as $toAddr => $toName) { if (is_numeric($toAddr)) { $toAddr = $toName; } $mail->addAddress($toAddr, $toName); } foreach ($cc as $ccAddr => $ccName) { if (is_numeric($ccAddr)) { $ccAddr = $ccName; } $mail->addCC($ccAddr, $ccName); } foreach ($bcc as $bccAddr => $bccName) { if (is_numeric($bccAddr)) { $bccAddr = $bccName; } $mail->addBCC($bccAddr, $bccName); } // Content $mail->Subject = $subject; $mail->msgHTML($contentHTML); $mail->AltBody = strip_tags(nl2br($contentHTML)); // Send the message, check for errors if (!$mail->send()) { throw new Exception("Mail Error: " . $mail->ErrorInfo . "\n"); } }
php
public function sendHtml ($subject, $contentHTML, $to, $cc=array(), $bcc=array()) { $mail = $this->phpMailer; // Ensure if all destination specifications are arrays if (!is_array($to )) { $to = array($to) ; } if (!is_array($cc )) { $cc = array($cc) ; } if (!is_array($bcc)) { $bcc = array($bcc) ; } // Add all recipients foreach ($to as $toAddr => $toName) { if (is_numeric($toAddr)) { $toAddr = $toName; } $mail->addAddress($toAddr, $toName); } foreach ($cc as $ccAddr => $ccName) { if (is_numeric($ccAddr)) { $ccAddr = $ccName; } $mail->addCC($ccAddr, $ccName); } foreach ($bcc as $bccAddr => $bccName) { if (is_numeric($bccAddr)) { $bccAddr = $bccName; } $mail->addBCC($bccAddr, $bccName); } // Content $mail->Subject = $subject; $mail->msgHTML($contentHTML); $mail->AltBody = strip_tags(nl2br($contentHTML)); // Send the message, check for errors if (!$mail->send()) { throw new Exception("Mail Error: " . $mail->ErrorInfo . "\n"); } }
Send HTML mail @param string Subject @param string Message in HTML format @param array To: recipients @param array Cc: recipients @param array Bcc: recipients @return void
https://github.com/teonsystems/php-base/blob/010418fd9df3c447a74b36cf0d31e2d38a6527ac/src/Mailer/Gateway.php#L129-L170
flamecore/synchronizer-files
src/FilesSynchronizer.php
FilesSynchronizer.synchronize
public function synchronize($preserve = true) { if ($this->observer) { $this->observer->notify('sync.start'); } $diff = new FilesComparer($this->source, $this->target, $this->excludes); $this->updateOutdated($diff); $this->addMissing($diff); if (!$preserve) { $this->removeObsolete($diff); } if ($this->observer) { $this->observer->notify('sync.finish', ['fails' => $this->fails]); } return $this->fails == 0; }
php
public function synchronize($preserve = true) { if ($this->observer) { $this->observer->notify('sync.start'); } $diff = new FilesComparer($this->source, $this->target, $this->excludes); $this->updateOutdated($diff); $this->addMissing($diff); if (!$preserve) { $this->removeObsolete($diff); } if ($this->observer) { $this->observer->notify('sync.finish', ['fails' => $this->fails]); } return $this->fails == 0; }
{@inheritdoc}
https://github.com/flamecore/synchronizer-files/blob/ca05fae95cd2fb4c3db8e7436a1699539923e27d/src/FilesSynchronizer.php#L49-L69
PenoaksDev/Milky-Framework
src/Milky/Facades/Log.php
Log.log
public static function log( $level, $message, array $context = [] ) { return static::__do( __FUNCTION__, args_with_keys( func_get_args(), __CLASS__, __FUNCTION__ ) ); }
php
public static function log( $level, $message, array $context = [] ) { return static::__do( __FUNCTION__, args_with_keys( func_get_args(), __CLASS__, __FUNCTION__ ) ); }
Logging a message to the logs. @param string $level @param string $message @param array $context
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Facades/Log.php#L115-L118
Dhii/expression-renderer-base
src/AbstractBaseFunctionExpressionTemplate.php
AbstractBaseFunctionExpressionTemplate._compileExpressionTerms
protected function _compileExpressionTerms( ExpressionInterface $expression, array $renderedTerms, $context = null ) { $opStr = $this->_getOperatorString(); $argsStr = implode(', ', $renderedTerms); return sprintf('%1$s(%2$s)', $opStr, $argsStr); }
php
protected function _compileExpressionTerms( ExpressionInterface $expression, array $renderedTerms, $context = null ) { $opStr = $this->_getOperatorString(); $argsStr = implode(', ', $renderedTerms); return sprintf('%1$s(%2$s)', $opStr, $argsStr); }
{@inheritdoc} @since [*next-version*]
https://github.com/Dhii/expression-renderer-base/blob/0e9c76d6a20c7aa9aa87ff1287dbfdade847279d/src/AbstractBaseFunctionExpressionTemplate.php#L29-L38
internetofvoice/vsms-core
src/Controller/AbstractSkillController.php
AbstractSkillController.createAlexaRequest
protected function createAlexaRequest($request) { $this->voiceInterface = 'Alexa'; // Create AlexaRequest from HTTP request $this->alexaRequest = new AlexaRequest( $request->getBody()->getContents(), $this->askApplicationIds, $request->getHeaderLine('Signaturecertchainurl'), $request->getHeaderLine('Signature'), $this->settings['validateTimestamp'], $this->settings['validateCertificate'] ); // Update auto initialized translator as Alexa request might contain a locale if($this->alexaRequest->getRequest()->getLocale() && in_array('translator', $this->settings['auto_init'])) { $this->translator->chooseLocale($this->alexaRequest->getRequest()->getLocale()); } // Create new AlexaResponse $this->alexaResponse = new AlexaResponse; }
php
protected function createAlexaRequest($request) { $this->voiceInterface = 'Alexa'; // Create AlexaRequest from HTTP request $this->alexaRequest = new AlexaRequest( $request->getBody()->getContents(), $this->askApplicationIds, $request->getHeaderLine('Signaturecertchainurl'), $request->getHeaderLine('Signature'), $this->settings['validateTimestamp'], $this->settings['validateCertificate'] ); // Update auto initialized translator as Alexa request might contain a locale if($this->alexaRequest->getRequest()->getLocale() && in_array('translator', $this->settings['auto_init'])) { $this->translator->chooseLocale($this->alexaRequest->getRequest()->getLocale()); } // Create new AlexaResponse $this->alexaResponse = new AlexaResponse; }
Create Alexa Request from Slim Request @param \Slim\Http\Request $request Slim request @access protected @author [email protected]
https://github.com/internetofvoice/vsms-core/blob/bd1eb6ca90a55f4928c35b9f0742a5cc922298ef/src/Controller/AbstractSkillController.php#L60-L80
internetofvoice/vsms-core
src/Controller/AbstractSkillController.php
AbstractSkillController.dispatchAlexaRequest
protected function dispatchAlexaRequest($response) { switch($this->alexaRequest->getRequest()->getType()) { // LibVoice catches unknown request types, so no default case required. case 'LaunchRequest': $this->launch(); break; case 'IntentRequest': /** @var IntentRequest $intentRequest */ $intentRequest = $this->alexaRequest->getRequest(); // derive handler method name from intent name $method = 'intent' . preg_replace('#\W#', '', $intentRequest->getIntent()->getName()); if(method_exists($this, $method)) { call_user_func(array($this, $method)); } else { throw new InvalidArgumentException('Undefined intent handler: ' . $method); } break; case 'SessionEndedRequest': $this->sessionEnded(); break; } return $response->withJson($this->alexaResponse->render()); }
php
protected function dispatchAlexaRequest($response) { switch($this->alexaRequest->getRequest()->getType()) { // LibVoice catches unknown request types, so no default case required. case 'LaunchRequest': $this->launch(); break; case 'IntentRequest': /** @var IntentRequest $intentRequest */ $intentRequest = $this->alexaRequest->getRequest(); // derive handler method name from intent name $method = 'intent' . preg_replace('#\W#', '', $intentRequest->getIntent()->getName()); if(method_exists($this, $method)) { call_user_func(array($this, $method)); } else { throw new InvalidArgumentException('Undefined intent handler: ' . $method); } break; case 'SessionEndedRequest': $this->sessionEnded(); break; } return $response->withJson($this->alexaResponse->render()); }
Dispatch AlexaRequest Dispatches AlexaRequest to either: - corresponding RequestType - IntentRequests to a method derived from intent name (see below), example: "AMAZON.HelpIntent" -> "intentAMAZONHelpIntent()" "MyIntent" -> "intentMyIntent()" @param \Slim\Http\Response $response Slim response @return \Slim\Http\Response @throws \InvalidArgumentException @access protected @author [email protected]
https://github.com/internetofvoice/vsms-core/blob/bd1eb6ca90a55f4928c35b9f0742a5cc922298ef/src/Controller/AbstractSkillController.php#L97-L125
Linkvalue-Interne/MajoraOAuthServerBundle
src/Majora/Component/OAuth/Generator/RandomTokenGenerator.php
RandomTokenGenerator.generate
public function generate($intention = 'm@J0raOaUth') { $bytes = false; if (function_exists('openssl_random_pseudo_bytes') && 0 !== stripos(PHP_OS, 'win')) { $bytes = openssl_random_pseudo_bytes(32, $strong); if (true !== $strong) { $bytes = false; } } // let's just hope we got a good seed if (false === $bytes) { $bytes = hash('sha512', sprintf('-[%s}\%s/{%s]-', $intention, uniqid(mt_rand(), true), $this->secret ), true ); } return str_pad( base_convert(bin2hex($bytes), 16, 36), 50, rand(0, 9) ); }
php
public function generate($intention = 'm@J0raOaUth') { $bytes = false; if (function_exists('openssl_random_pseudo_bytes') && 0 !== stripos(PHP_OS, 'win')) { $bytes = openssl_random_pseudo_bytes(32, $strong); if (true !== $strong) { $bytes = false; } } // let's just hope we got a good seed if (false === $bytes) { $bytes = hash('sha512', sprintf('-[%s}\%s/{%s]-', $intention, uniqid(mt_rand(), true), $this->secret ), true ); } return str_pad( base_convert(bin2hex($bytes), 16, 36), 50, rand(0, 9) ); }
Generate a random token. @param string $intention contextual string @return string
https://github.com/Linkvalue-Interne/MajoraOAuthServerBundle/blob/3e84e2494c947d1bd5d5c16221a3b9e343ebff92/src/Majora/Component/OAuth/Generator/RandomTokenGenerator.php#L34-L62
icicleio/dns
src/Connector/DefaultConnector.php
DefaultConnector.connect
public function connect(string $domain, int $port = null, array $options = []): \Generator { // Check if $domain is actually an IP address. if (preg_match(self::IP_REGEX, $domain)) { return yield from $this->connector->connect($domain, $port, $options); } $options = array_merge(['name' => $domain], $options); try { $ips = yield from $this->resolver->resolve($domain, $options); } catch (DnsException $exception) { throw new FailureException(sprintf('Could not resolve host %s.', $domain), 0, $exception); } if (empty($ips)) { throw new FailureException(sprintf('Host for %s not found.', $domain)); } foreach ($ips as $ip) { try { return yield from $this->connector->connect($ip, $port, $options); } catch (TimeoutException $exception) { // Connection timed out, try next IP address. } catch (FailureException $exception) { // Connection failed, try next IP address. } } throw new FailureException(sprintf('Could not connect to %s:%d.', $domain, $port), 0, $exception); }
php
public function connect(string $domain, int $port = null, array $options = []): \Generator { // Check if $domain is actually an IP address. if (preg_match(self::IP_REGEX, $domain)) { return yield from $this->connector->connect($domain, $port, $options); } $options = array_merge(['name' => $domain], $options); try { $ips = yield from $this->resolver->resolve($domain, $options); } catch (DnsException $exception) { throw new FailureException(sprintf('Could not resolve host %s.', $domain), 0, $exception); } if (empty($ips)) { throw new FailureException(sprintf('Host for %s not found.', $domain)); } foreach ($ips as $ip) { try { return yield from $this->connector->connect($ip, $port, $options); } catch (TimeoutException $exception) { // Connection timed out, try next IP address. } catch (FailureException $exception) { // Connection failed, try next IP address. } } throw new FailureException(sprintf('Could not connect to %s:%d.', $domain, $port), 0, $exception); }
{@inheritdoc}
https://github.com/icicleio/dns/blob/31ca939e2661f87bd807c54be0e7ad1762a5b14a/src/Connector/DefaultConnector.php#L47-L77
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php
GraphvizDumper.dump
public function dump(array $options = array()) { foreach (array('graph', 'node', 'edge', 'node.instance', 'node.definition', 'node.missing') as $key) { if (isset($options[$key])) { $this->options[$key] = array_merge($this->options[$key], $options[$key]); } } $this->nodes = $this->findNodes(); $this->edges = array(); foreach ($this->container->getDefinitions() as $id => $definition) { $this->edges[$id] = array_merge( $this->findEdges($id, $definition->getArguments(), true, ''), $this->findEdges($id, $definition->getProperties(), false, '') ); foreach ($definition->getMethodCalls() as $call) { $this->edges[$id] = array_merge( $this->edges[$id], $this->findEdges($id, $call[1], false, $call[0].'()') ); } } return $this->container->resolveEnvPlaceholders($this->startDot().$this->addNodes().$this->addEdges().$this->endDot(), '__ENV_%s__'); }
php
public function dump(array $options = array()) { foreach (array('graph', 'node', 'edge', 'node.instance', 'node.definition', 'node.missing') as $key) { if (isset($options[$key])) { $this->options[$key] = array_merge($this->options[$key], $options[$key]); } } $this->nodes = $this->findNodes(); $this->edges = array(); foreach ($this->container->getDefinitions() as $id => $definition) { $this->edges[$id] = array_merge( $this->findEdges($id, $definition->getArguments(), true, ''), $this->findEdges($id, $definition->getProperties(), false, '') ); foreach ($definition->getMethodCalls() as $call) { $this->edges[$id] = array_merge( $this->edges[$id], $this->findEdges($id, $call[1], false, $call[0].'()') ); } } return $this->container->resolveEnvPlaceholders($this->startDot().$this->addNodes().$this->addEdges().$this->endDot(), '__ENV_%s__'); }
Dumps the service container as a graphviz graph. Available options: * graph: The default options for the whole graph * node: The default options for nodes * edge: The default options for edges * node.instance: The default options for services that are defined directly by object instances * node.definition: The default options for services that are defined via service definition instances * node.missing: The default options for missing services @return string The dot representation of the service container
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php#L58-L84
zhaoxianfang/tools
src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php
GraphvizDumper.startDot
private function startDot() { return sprintf("digraph sc {\n %s\n node [%s];\n edge [%s];\n\n", $this->addOptions($this->options['graph']), $this->addOptions($this->options['node']), $this->addOptions($this->options['edge']) ); }
php
private function startDot() { return sprintf("digraph sc {\n %s\n node [%s];\n edge [%s];\n\n", $this->addOptions($this->options['graph']), $this->addOptions($this->options['node']), $this->addOptions($this->options['edge']) ); }
Returns the start dot. @return string The string representation of a start dot
https://github.com/zhaoxianfang/tools/blob/d8fc8a9ecd75b5ce4236f0a2e9fdc055108573e7/src/Symfony/Component/DependencyInjection/Dumper/GraphvizDumper.php#L220-L227
gplcart/cli
controllers/commands/Status.php
Status.cmdStatusStatus
public function cmdStatusStatus() { $result = $this->report->getStatus(); $this->outputFormat($result); $this->outputFormatTableStatus($result); $this->output(); }
php
public function cmdStatusStatus() { $result = $this->report->getStatus(); $this->outputFormat($result); $this->outputFormatTableStatus($result); $this->output(); }
Callback for "status" command
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Status.php#L40-L46
gplcart/cli
controllers/commands/Status.php
Status.outputFormatTableStatus
protected function outputFormatTableStatus(array $items) { $header = array( $this->text('Name'), $this->text('Status') ); $rows = array(); foreach ($items as $item) { $rows[] = array( $item['title'], $item['status'] ); } $this->outputFormatTable($rows, $header); }
php
protected function outputFormatTableStatus(array $items) { $header = array( $this->text('Name'), $this->text('Status') ); $rows = array(); foreach ($items as $item) { $rows[] = array( $item['title'], $item['status'] ); } $this->outputFormatTable($rows, $header); }
Output table format @param array $items
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Status.php#L52-L69
t-kanstantsin/fileupload
src/formatter/adapter/PsImageOptimizer.php
PsImageOptimizer.exec
public function exec(IFile $file, $content) { $tmpPath = tempnam($this->getTempDir(), ''); file_put_contents($tmpPath, $content); $this->getOptimizer()->optimize($tmpPath); $content = file_get_contents($tmpPath); @unlink($tmpPath); return $content; }
php
public function exec(IFile $file, $content) { $tmpPath = tempnam($this->getTempDir(), ''); file_put_contents($tmpPath, $content); $this->getOptimizer()->optimize($tmpPath); $content = file_get_contents($tmpPath); @unlink($tmpPath); return $content; }
Applies filters or something to content and return it @param IFile $file @param $content @return mixed @throws \ImageOptimizer\Exception\Exception
https://github.com/t-kanstantsin/fileupload/blob/d6317a9b9b36d992f09affe3900ef7d7ddfd855f/src/formatter/adapter/PsImageOptimizer.php#L57-L67
t-kanstantsin/fileupload
src/formatter/adapter/PsImageOptimizer.php
PsImageOptimizer.getOptimizer
protected function getOptimizer($name = OptimizerFactory::OPTIMIZER_SMART): Optimizer { return (new OptimizerFactory($this->optimizerConfig))->get($name); }
php
protected function getOptimizer($name = OptimizerFactory::OPTIMIZER_SMART): Optimizer { return (new OptimizerFactory($this->optimizerConfig))->get($name); }
@param string $name @return Optimizer @throws \ImageOptimizer\Exception\Exception
https://github.com/t-kanstantsin/fileupload/blob/d6317a9b9b36d992f09affe3900ef7d7ddfd855f/src/formatter/adapter/PsImageOptimizer.php#L83-L86
ekyna/Resource
Doctrine/ORM/Util/ResourceRepositoryTrait.php
ResourceRepositoryTrait.find
public function find($id) { return $this ->getQueryBuilder() ->andWhere($this->getAlias().'.id = '.intval($id)) ->getQuery() ->getOneOrNullResult() ; }
php
public function find($id) { return $this ->getQueryBuilder() ->andWhere($this->getAlias().'.id = '.intval($id)) ->getQuery() ->getOneOrNullResult() ; }
Finds the resource by his ID. @param int $id @return null|object
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Doctrine/ORM/Util/ResourceRepositoryTrait.php#L44-L52
ekyna/Resource
Doctrine/ORM/Util/ResourceRepositoryTrait.php
ResourceRepositoryTrait.findBy
public function findBy(array $criteria, array $sorting = null, $limit = null, $offset = null) { $queryBuilder = $this->getCollectionQueryBuilder(); $this->applyCriteria($queryBuilder, $criteria); $this->applySorting($queryBuilder, (array) $sorting); if (null !== $limit) { $queryBuilder->setMaxResults($limit); } if (null !== $offset) { $queryBuilder->setFirstResult($offset); } $query = $queryBuilder->getQuery(); if (null !== $limit) { return $this->collectionResult($query); } return $query->getResult(); }
php
public function findBy(array $criteria, array $sorting = null, $limit = null, $offset = null) { $queryBuilder = $this->getCollectionQueryBuilder(); $this->applyCriteria($queryBuilder, $criteria); $this->applySorting($queryBuilder, (array) $sorting); if (null !== $limit) { $queryBuilder->setMaxResults($limit); } if (null !== $offset) { $queryBuilder->setFirstResult($offset); } $query = $queryBuilder->getQuery(); if (null !== $limit) { return $this->collectionResult($query); } return $query->getResult(); }
Finds resources by criteria, sorting, limit and offset. @param array $criteria @param array $sorting @param int $limit @param int $offset @return array|\Doctrine\ORM\Tools\Pagination\Paginator
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Doctrine/ORM/Util/ResourceRepositoryTrait.php#L97-L119
ekyna/Resource
Doctrine/ORM/Util/ResourceRepositoryTrait.php
ResourceRepositoryTrait.findRandomOneBy
public function findRandomOneBy(array $criteria) { $queryBuilder = $this->getQueryBuilder(); $this->applyCriteria($queryBuilder, $criteria); return $queryBuilder ->addSelect('RAND() as HIDDEN rand') ->orderBy('rand') ->setMaxResults(1) ->getQuery() ->getOneOrNullResult() ; }
php
public function findRandomOneBy(array $criteria) { $queryBuilder = $this->getQueryBuilder(); $this->applyCriteria($queryBuilder, $criteria); return $queryBuilder ->addSelect('RAND() as HIDDEN rand') ->orderBy('rand') ->setMaxResults(1) ->getQuery() ->getOneOrNullResult() ; }
Finds a random resource by criteria. @param array $criteria @return null|object
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Doctrine/ORM/Util/ResourceRepositoryTrait.php#L128-L141
ekyna/Resource
Doctrine/ORM/Util/ResourceRepositoryTrait.php
ResourceRepositoryTrait.findRandomBy
public function findRandomBy(array $criteria, $limit) { $limit = intval($limit); if ($limit <= 1) { throw new \InvalidArgumentException('Please use `findRandomOneBy()` for single result.'); } $queryBuilder = $this->getCollectionQueryBuilder(); $this->applyCriteria($queryBuilder, $criteria); $query = $queryBuilder ->addSelect('RAND() as HIDDEN rand') ->orderBy('rand') ->setMaxResults($limit) ->getQuery() ; return $this->collectionResult($query); }
php
public function findRandomBy(array $criteria, $limit) { $limit = intval($limit); if ($limit <= 1) { throw new \InvalidArgumentException('Please use `findRandomOneBy()` for single result.'); } $queryBuilder = $this->getCollectionQueryBuilder(); $this->applyCriteria($queryBuilder, $criteria); $query = $queryBuilder ->addSelect('RAND() as HIDDEN rand') ->orderBy('rand') ->setMaxResults($limit) ->getQuery() ; return $this->collectionResult($query); }
Finds random resource by criteria and limit. @param array $criteria @param int $limit @return array|\Doctrine\ORM\Tools\Pagination\Paginator
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Doctrine/ORM/Util/ResourceRepositoryTrait.php#L151-L170
ekyna/Resource
Doctrine/ORM/Util/ResourceRepositoryTrait.php
ResourceRepositoryTrait.createPager
public function createPager(array $criteria = [], array $sorting = []) { $queryBuilder = $this->getCollectionQueryBuilder(); $this->applyCriteria($queryBuilder, $criteria); $this->applySorting($queryBuilder, $sorting); return $this->getPager($queryBuilder); }
php
public function createPager(array $criteria = [], array $sorting = []) { $queryBuilder = $this->getCollectionQueryBuilder(); $this->applyCriteria($queryBuilder, $criteria); $this->applySorting($queryBuilder, $sorting); return $this->getPager($queryBuilder); }
Creates a pager. @param array $criteria @param array $sorting @return Pagerfanta
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Doctrine/ORM/Util/ResourceRepositoryTrait.php#L180-L188
ekyna/Resource
Doctrine/ORM/Util/ResourceRepositoryTrait.php
ResourceRepositoryTrait.getPager
public function getPager($query) { $pager = new Pagerfanta(new DoctrineORMAdapter($query, true, false)); return $pager->setNormalizeOutOfRangePages(true); }
php
public function getPager($query) { $pager = new Pagerfanta(new DoctrineORMAdapter($query, true, false)); return $pager->setNormalizeOutOfRangePages(true); }
Returns the (doctrine) pager. @param Query|QueryBuilder $query @return Pagerfanta
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Doctrine/ORM/Util/ResourceRepositoryTrait.php#L197-L201
ekyna/Resource
Doctrine/ORM/Util/ResourceRepositoryTrait.php
ResourceRepositoryTrait.applyCriteria
protected function applyCriteria(QueryBuilder $queryBuilder, array $criteria = []) { foreach ($criteria as $property => $value) { $name = $this->getPropertyName($property); if (null === $value) { $queryBuilder->andWhere($queryBuilder->expr()->isNull($name)); } elseif (is_array($value)) { $queryBuilder->andWhere($queryBuilder->expr()->in($name, $value)); } elseif ('' !== $value) { $parameter = str_replace('.', '_', $property); $queryBuilder ->andWhere($queryBuilder->expr()->eq($name, ':'.$parameter)) ->setParameter($parameter, $value) ; } } }
php
protected function applyCriteria(QueryBuilder $queryBuilder, array $criteria = []) { foreach ($criteria as $property => $value) { $name = $this->getPropertyName($property); if (null === $value) { $queryBuilder->andWhere($queryBuilder->expr()->isNull($name)); } elseif (is_array($value)) { $queryBuilder->andWhere($queryBuilder->expr()->in($name, $value)); } elseif ('' !== $value) { $parameter = str_replace('.', '_', $property); $queryBuilder ->andWhere($queryBuilder->expr()->eq($name, ':'.$parameter)) ->setParameter($parameter, $value) ; } } }
Applies the criteria to the query builder. @param QueryBuilder $queryBuilder @param array $criteria
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Doctrine/ORM/Util/ResourceRepositoryTrait.php#L265-L281
ekyna/Resource
Doctrine/ORM/Util/ResourceRepositoryTrait.php
ResourceRepositoryTrait.getCachePrefix
public function getCachePrefix() { if ($this->cachePrefix) { return $this->cachePrefix; } $class = $this->getClassName(); if (!in_array(TaggedEntityInterface::class, class_implements($class))) { throw new \RuntimeException(sprintf( 'The entity %s does not implements %s, query should not be cached.', $class, TaggedEntityInterface::class )); } return $this->cachePrefix = call_user_func([$this->getClassName(), 'getEntityTagPrefix']); }
php
public function getCachePrefix() { if ($this->cachePrefix) { return $this->cachePrefix; } $class = $this->getClassName(); if (!in_array(TaggedEntityInterface::class, class_implements($class))) { throw new \RuntimeException(sprintf( 'The entity %s does not implements %s, query should not be cached.', $class, TaggedEntityInterface::class )); } return $this->cachePrefix = call_user_func([$this->getClassName(), 'getEntityTagPrefix']); }
Returns the cache prefix. @return string
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Doctrine/ORM/Util/ResourceRepositoryTrait.php#L330-L346
Dhii/callback-abstract
src/InvokeCallbackCapableTrait.php
InvokeCallbackCapableTrait._invokeCallback
protected function _invokeCallback($args = array()) { $args = $this->_normalizeIterable($args); $callback = $this->_getCallback(); try { return $this->_invokeCallable($callback, $args); } catch (InvalidArgumentException $e) { /* We know that `$args` is correct, so the only way * `_invokeCallback()` would throw `InvalidArgumentException` * is if the callback is wrong. But we cannot let it bubble * up, because it is not an argument to this method. Therefore, * catch it, wrap, and throw a more appropriate exception. */ throw $this->_createOutOfRangeException( $this->__('Invalid callback'), null, $e, $callback ); } }
php
protected function _invokeCallback($args = array()) { $args = $this->_normalizeIterable($args); $callback = $this->_getCallback(); try { return $this->_invokeCallable($callback, $args); } catch (InvalidArgumentException $e) { /* We know that `$args` is correct, so the only way * `_invokeCallback()` would throw `InvalidArgumentException` * is if the callback is wrong. But we cannot let it bubble * up, because it is not an argument to this method. Therefore, * catch it, wrap, and throw a more appropriate exception. */ throw $this->_createOutOfRangeException( $this->__('Invalid callback'), null, $e, $callback ); } }
@since [*next-version*] @param Traversable|array|stdClass The list of arguments for the invocation. @throws InvalidArgumentException If args are not a valid list. @throws OutOfRangeException If callback is invalid. @throws InvocationExceptionInterface If error during invocation. @return mixed The value resulting from the invocation.
https://github.com/Dhii/callback-abstract/blob/43ed4e99fc6ccdaf46a25d06da482a2fba8d9b19/src/InvokeCallbackCapableTrait.php#L31-L52
Kris-Kuiper/sFire-Framework
src/Validator/Form/Rules/Email.php
Email.check
private function check($value) { if(true === is_string($value)) { return false !== filter_var(trim($value), \FILTER_VALIDATE_EMAIL); } return false; }
php
private function check($value) { if(true === is_string($value)) { return false !== filter_var(trim($value), \FILTER_VALIDATE_EMAIL); } return false; }
Check if rule passes @param mixed $value @return boolean
https://github.com/Kris-Kuiper/sFire-Framework/blob/deefe1d9d2b40e7326381e8dcd4f01f9aa61885c/src/Validator/Form/Rules/Email.php#L59-L66
itkg/core
src/Itkg/Core/Cache/Factory.php
Factory.create
public function create($adapterType, array $config) { if (!array_key_exists($adapterType, $this->adapters)) { throw new \InvalidArgumentException( sprintf('Cache Adapter\'s key %s does not exist', $adapterType) ); } /** * @fixme : Active this part & clean cache config */ if (!isset($config[$adapterType])) { throw new InvalidConfigurationException( sprintf('Config is not set for adapter %s', $adapterType) ); } return new $this->adapters[$adapterType]($config[$adapterType]); }
php
public function create($adapterType, array $config) { if (!array_key_exists($adapterType, $this->adapters)) { throw new \InvalidArgumentException( sprintf('Cache Adapter\'s key %s does not exist', $adapterType) ); } /** * @fixme : Active this part & clean cache config */ if (!isset($config[$adapterType])) { throw new InvalidConfigurationException( sprintf('Config is not set for adapter %s', $adapterType) ); } return new $this->adapters[$adapterType]($config[$adapterType]); }
Create an adapter @param string $adapterType @return AdapterInterface @throws \InvalidArgumentException
https://github.com/itkg/core/blob/e5e4efb05feb4d23b0df41f2b21fd095103e593b/src/Itkg/Core/Cache/Factory.php#L41-L59
AnnotateFramework/framework
src/Application/Components/BaseComponent.php
BaseComponent.prepareTemplate
private function prepareTemplate($localPath) { /** @var Template $template */ $template = $this->getTemplate(); $this->presenter->context->getByType('Annotate\Templating\ITemplateFactory') ->formatComponentTemplateFiles($template, $this->templateName, $localPath); if (!$template->getFile()) { throw new ComponentTemplateNotFoundException("Template for component '{$this->getName()}' was not found."); } return $template; }
php
private function prepareTemplate($localPath) { /** @var Template $template */ $template = $this->getTemplate(); $this->presenter->context->getByType('Annotate\Templating\ITemplateFactory') ->formatComponentTemplateFiles($template, $this->templateName, $localPath); if (!$template->getFile()) { throw new ComponentTemplateNotFoundException("Template for component '{$this->getName()}' was not found."); } return $template; }
@param string @throws ComponentTemplateNotFoundException @return Template
https://github.com/AnnotateFramework/framework/blob/f46677a0e4920658a9b9210d6947c985377af232/src/Application/Components/BaseComponent.php#L88-L100
Dhii/regex-abstract
src/QuoteRegexCapablePcreTrait.php
QuoteRegexCapablePcreTrait._quoteRegex
protected function _quoteRegex($string, $delimiter = null) { $string = $this->_normalizeString($string); $delimiter = is_null($delimiter) ? null : $this->_normalizeString($delimiter); return preg_quote($string, $delimiter); }
php
protected function _quoteRegex($string, $delimiter = null) { $string = $this->_normalizeString($string); $delimiter = is_null($delimiter) ? null : $this->_normalizeString($delimiter); return preg_quote($string, $delimiter); }
Escapes special characters in a string such that it is interpreted literally by a PCRE parser. @since [*next-version*] @param string|Stringable $string The string to quote. @param string|Stringable|null $delimiter The delimiter that will be used in the expression, if any. If specified, this delimiter will be quoted too. @throws InvalidArgumentException If the string or the delimiter are invalid. @return string The quoted string.
https://github.com/Dhii/regex-abstract/blob/0751f9c91a6f86d5f901b6b7f3613dc80bb69a8a/src/QuoteRegexCapablePcreTrait.php#L28-L34
SahilDude89ss/PyntaxFramework
src/Pyntax/DAO/Bean/Column/Column.php
Column.getValueFromDefinition
protected function getValueFromDefinition($key) { return (isset($this->definition) && !empty($this->definition[$key])) ? $this->definition[$key] : false; }
php
protected function getValueFromDefinition($key) { return (isset($this->definition) && !empty($this->definition[$key])) ? $this->definition[$key] : false; }
This function returns the value of the key from the column definitions. @param $key @return bool|string
https://github.com/SahilDude89ss/PyntaxFramework/blob/045cca87d24eb2b6405734966c64344e00224c7b/src/Pyntax/DAO/Bean/Column/Column.php#L121-L124
SahilDude89ss/PyntaxFramework
src/Pyntax/DAO/Bean/Column/Column.php
Column.validate
public function validate($value = "") { if (is_null($value) && $this->isEmptyAllowed()) { return true; } if ($this->isNullNotAllowed() && is_null($value)) { return false; } return true; }
php
public function validate($value = "") { if (is_null($value) && $this->isEmptyAllowed()) { return true; } if ($this->isNullNotAllowed() && is_null($value)) { return false; } return true; }
@ToDo: Add the possible validation here. @param string $value @return bool
https://github.com/SahilDude89ss/PyntaxFramework/blob/045cca87d24eb2b6405734966c64344e00224c7b/src/Pyntax/DAO/Bean/Column/Column.php#L132-L143
SahilDude89ss/PyntaxFramework
src/Pyntax/DAO/Bean/Column/Column.php
Column.getHtmlElementType
public function getHtmlElementType() { if(preg_match('/.*(enum|set).*/', $this->definition['Type'])) { $selectTag = array( 'elTag' => 'select', ); $option_string = ""; if(preg_match('/.*enum.*/',$this->definition['Type'])) { $option_string = str_replace("')","",str_replace("enum('","",$this->definition['Type'])); } else if(preg_match('/.*set.*/',$this->definition['Type'])) { $option_string = str_replace("')","",str_replace("set('","",$this->definition['Type'])); } if(!empty($option_string)) { $optionArray = explode("','", $option_string); if(is_array($optionArray)) { $selectTag['options'] = $optionArray; } } return $selectTag; } else if(preg_match('/.*(tinytext|text|mediumtext|longtext).*/', $this->definition['Type'])) { return array( 'elTag' => 'textarea' ); } else if(preg_match('/.*(date|datetime).*/', $this->definition['Type'])) { return array( 'elTag' => 'input', 'attributes' => array( 'type' => 'text', 'data-type' => 'date' ) ); } else { return array( 'elTag' => 'input', 'attributes' => array( 'type' => 'text' ) ); } }
php
public function getHtmlElementType() { if(preg_match('/.*(enum|set).*/', $this->definition['Type'])) { $selectTag = array( 'elTag' => 'select', ); $option_string = ""; if(preg_match('/.*enum.*/',$this->definition['Type'])) { $option_string = str_replace("')","",str_replace("enum('","",$this->definition['Type'])); } else if(preg_match('/.*set.*/',$this->definition['Type'])) { $option_string = str_replace("')","",str_replace("set('","",$this->definition['Type'])); } if(!empty($option_string)) { $optionArray = explode("','", $option_string); if(is_array($optionArray)) { $selectTag['options'] = $optionArray; } } return $selectTag; } else if(preg_match('/.*(tinytext|text|mediumtext|longtext).*/', $this->definition['Type'])) { return array( 'elTag' => 'textarea' ); } else if(preg_match('/.*(date|datetime).*/', $this->definition['Type'])) { return array( 'elTag' => 'input', 'attributes' => array( 'type' => 'text', 'data-type' => 'date' ) ); } else { return array( 'elTag' => 'input', 'attributes' => array( 'type' => 'text' ) ); } }
data_type: BIT[(length)] | TINYINT[(length)] [UNSIGNED] [ZEROFILL] | SMALLINT[(length)] [UNSIGNED] [ZEROFILL] | MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL] | INT[(length)] [UNSIGNED] [ZEROFILL] | INTEGER[(length)] [UNSIGNED] [ZEROFILL] | BIGINT[(length)] [UNSIGNED] [ZEROFILL] | REAL[(length,decimals)] [UNSIGNED] [ZEROFILL] | DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL] | FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL] | DECIMAL[(length[,decimals])] [UNSIGNED] [ZEROFILL] | NUMERIC[(length[,decimals])] [UNSIGNED] [ZEROFILL] ----------------------------------------------------- | DATE | TIME | TIMESTAMP | DATETIME | YEAR ---------------------------------------------------------- | CHAR[(length)] [BINARY] [CHARACTER SET charset_name] [COLLATE collation_name] | VARCHAR(length) [BINARY] [CHARACTER SET charset_name] [COLLATE collation_name] ----------------------------------------------------- | BINARY[(length)] | VARBINARY(length) | TINYBLOB | BLOB | MEDIUMBLOB | LONGBLOB ---------------------------------------------------------- | TINYTEXT [BINARY] [CHARACTER SET charset_name] [COLLATE collation_name] | TEXT [BINARY] [CHARACTER SET charset_name] [COLLATE collation_name] | MEDIUMTEXT [BINARY] [CHARACTER SET charset_name] [COLLATE collation_name] | LONGTEXT [BINARY] [CHARACTER SET charset_name] [COLLATE collation_name] ---------------------------------------------------------- | ENUM(value1,value2,value3,...) [CHARACTER SET charset_name] [COLLATE collation_name] | SET(value1,value2,value3,...) [CHARACTER SET charset_name] [COLLATE collation_name] | spatial_type @return array
https://github.com/SahilDude89ss/PyntaxFramework/blob/045cca87d24eb2b6405734966c64344e00224c7b/src/Pyntax/DAO/Bean/Column/Column.php#L214-L260
Wedeto/Util
src/Cache/Item.php
Item.isHit
public function isHit() { if (!$this->hit) return false; if ($this->expires === null) return true; return $this->expires->getTimestamp() > time(); }
php
public function isHit() { if (!$this->hit) return false; if ($this->expires === null) return true; return $this->expires->getTimestamp() > time(); }
Confirms if the cache item lookup resulted in a cache hit. Note: This method MUST NOT have a race condition between calling isHit() and calling get(). @return bool True if the request resulted in a cache hit. False otherwise.
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Cache/Item.php#L101-L110
Wedeto/Util
src/Cache/Item.php
Item.expiresAt
public function expiresAt($expiration) { if ($expiration instanceof \DateTimeInterface) $this->expires = $expiration; elseif ($expiration === null) $this->expires = null; return $this; }
php
public function expiresAt($expiration) { if ($expiration instanceof \DateTimeInterface) $this->expires = $expiration; elseif ($expiration === null) $this->expires = null; return $this; }
Sets the expiration time for this cache item. @param \DateTimeInterface|null $expiration The point in time after which the item MUST be considered expired. If null is passed explicitly, a default value MAY be used. If none is set, the value should be stored permanently or for as long as the implementation allows. @return Item Provides fluent interface
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Cache/Item.php#L141-L149
Wedeto/Util
src/Cache/Item.php
Item.expiresAfter
public function expiresAfter($time) { if (is_int($time)) { $neg = $time < 0; $abs = abs($time); $time = new \DateInterval("PT" . $abs . "S"); $time->invert = $neg; } if ($time instanceof \DateInterval) { $now = new \DateTimeImmutable(); $expires = $now->add($time); $this->expires = $expires; } elseif ($time === null) { $this->expires = null; } return $this; }
php
public function expiresAfter($time) { if (is_int($time)) { $neg = $time < 0; $abs = abs($time); $time = new \DateInterval("PT" . $abs . "S"); $time->invert = $neg; } if ($time instanceof \DateInterval) { $now = new \DateTimeImmutable(); $expires = $now->add($time); $this->expires = $expires; } elseif ($time === null) { $this->expires = null; } return $this; }
Sets the expiration time for this cache item. @param int|\DateInterval|null $time The period of time from the present after which the item MUST be considered expired. An integer parameter is understood to be the time in seconds until expiration. If null is passed explicitly, a default value MAY be used. If none is set, the value should be stored permanently or for as long as the implementation allows. @return Item Provides fluent interface
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Cache/Item.php#L163-L185
Wedeto/Util
src/Cache/Item.php
Item.serialize
public function serialize() { return serialize([ 'key' => $this->key, 'value' => $this->value, 'expires' => $this->expires, 'hit' => $this->hit ]); }
php
public function serialize() { return serialize([ 'key' => $this->key, 'value' => $this->value, 'expires' => $this->expires, 'hit' => $this->hit ]); }
Serialize the item. Required for storing in the containing cache
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Cache/Item.php#L190-L198