idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
48,000
public static function firstLine ( $ filepath ) { if ( file_exists ( $ filepath ) ) { $ cacheRes = fopen ( $ filepath , 'rb' ) ; $ firstLine = fgets ( $ cacheRes ) ; fclose ( $ cacheRes ) ; return $ firstLine ; } return null ; }
Quickest way for getting first file line
48,001
public static function isFile ( $ path ) : bool { $ path = self :: clean ( $ path ) ; return file_exists ( $ path ) && is_file ( $ path ) ; }
Check is current path regular file
48,002
public static function v4InRange ( $ ipAddress , $ range ) { if ( strpos ( $ range , '/' ) !== false ) { list ( $ range , $ netMask ) = explode ( '/' , $ range , 2 ) ; if ( strpos ( $ netMask , '.' ) !== false ) { $ netMask = str_replace ( '*' , '0' , $ netMask ) ; $ netMaskDec = ip2long ( $ netMask ) ; return ( ( ip2long ( $ ipAddress ) & $ netMaskDec ) === ( ip2long ( $ range ) & $ netMaskDec ) ) ; } $ blocks = explode ( '.' , $ range ) ; while ( count ( $ blocks ) < 4 ) { $ blocks [ ] = '0' ; } list ( $ blockA , $ blockB , $ blockC , $ blockD ) = $ blocks ; $ range = sprintf ( '%u.%u.%u.%u' , empty ( $ blockA ) ? '0' : $ blockA , empty ( $ blockB ) ? '0' : $ blockB , empty ( $ blockC ) ? '0' : $ blockC , empty ( $ blockD ) ? '0' : $ blockD ) ; $ rangeDec = ip2long ( $ range ) ; $ ipDec = ip2long ( $ ipAddress ) ; $ wildcardDec = ( 2 ** ( 32 - $ netMask ) ) - 1 ; $ netMaskDec = ~ $ wildcardDec ; return ( ( $ ipDec & $ netMaskDec ) === ( $ rangeDec & $ netMaskDec ) ) ; } if ( strpos ( $ range , '*' ) !== false ) { $ lower = str_replace ( '*' , '0' , $ range ) ; $ upper = str_replace ( '*' , '255' , $ range ) ; $ range = "$lower-$upper" ; } if ( strpos ( $ range , '-' ) !== false ) { list ( $ lower , $ upper ) = explode ( '-' , $ range , 2 ) ; $ lowerDec = ( float ) sprintf ( '%u' , ip2long ( $ lower ) ) ; $ upperDec = ( float ) sprintf ( '%u' , ip2long ( $ upper ) ) ; $ ipDec = ( float ) sprintf ( '%u' , ip2long ( $ ipAddress ) ) ; return ( ( $ ipDec >= $ lowerDec ) && ( $ ipDec <= $ upperDec ) ) ; } return false ; }
Check if a given ip is in a network
48,003
public static function key ( $ key , $ array , $ returnValue = false ) { $ isExists = array_key_exists ( ( string ) $ key , ( array ) $ array ) ; if ( $ returnValue ) { if ( $ isExists ) { return $ array [ $ key ] ; } return null ; } return $ isExists ; }
Check is key exists
48,004
public static function in ( $ value , array $ array , $ returnKey = false ) { $ inArray = in_array ( $ value , $ array , true ) ; if ( $ returnKey ) { if ( $ inArray ) { return array_search ( $ value , $ array , true ) ; } return null ; } return $ inArray ; }
Check is value exists in the array
48,005
public static function cleanBeforeJson ( array $ array ) : array { foreach ( $ array as $ key => $ value ) { if ( is_array ( $ value ) ) { $ array [ $ key ] = self :: cleanBeforeJson ( $ array [ $ key ] ) ; } if ( $ array [ $ key ] === '' || null === $ array [ $ key ] ) { unset ( $ array [ $ key ] ) ; } } return $ array ; }
Clean array before serialize to JSON
48,006
public static function groupByKey ( array $ arrayList , $ key = 'id' ) : array { $ result = [ ] ; foreach ( $ arrayList as $ item ) { if ( is_object ( $ item ) ) { if ( isset ( $ item -> { $ key } ) ) { $ result [ $ item -> { $ key } ] [ ] = $ item ; } } elseif ( is_array ( $ item ) ) { if ( self :: key ( $ key , $ item ) ) { $ result [ $ item [ $ key ] ] [ ] = $ item ; } } } return $ result ; }
Group array by key
48,007
public static function map ( $ function , $ array ) : array { $ result = [ ] ; foreach ( $ array as $ key => $ value ) { if ( is_array ( $ value ) ) { $ result [ $ key ] = self :: map ( $ function , $ value ) ; } else { $ result [ $ key ] = $ function ( $ value ) ; } } return $ result ; }
Recursive array mapping
48,008
public static function addEachKey ( array $ array , $ prefix ) : array { $ result = [ ] ; foreach ( $ array as $ key => $ item ) { $ result [ $ prefix . $ key ] = $ item ; } return $ result ; }
Add some prefix to each key
48,009
public static function toComment ( array $ data ) : string { $ result = [ ] ; foreach ( $ data as $ key => $ value ) { $ result [ ] = $ key . ': ' . $ value . ';' ; } return implode ( PHP_EOL , $ result ) ; }
Convert assoc array to comment style
48,010
public static function wrap ( $ object ) : array { if ( null === $ object ) { return [ ] ; } if ( is_array ( $ object ) && ! self :: isAssoc ( $ object ) ) { return $ object ; } return [ $ object ] ; }
Wraps its argument in an array unless it is already an array
48,011
public static function checkGD ( $ throwException = true ) : bool { $ isGd = extension_loaded ( 'gd' ) ; if ( $ throwException && ! $ isGd ) { throw new Exception ( 'Required extension GD is not loaded.' ) ; } return $ isGd ; }
Require GD library
48,012
protected static function normalizeColorString ( $ origColor ) : array { $ color = trim ( $ origColor , '#' ) ; $ color = trim ( $ color ) ; if ( strlen ( $ color ) === 6 ) { list ( $ red , $ green , $ blue ) = [ $ color [ 0 ] . $ color [ 1 ] , $ color [ 2 ] . $ color [ 3 ] , $ color [ 4 ] . $ color [ 5 ] , ] ; } elseif ( strlen ( $ color ) === 3 ) { list ( $ red , $ green , $ blue ) = [ $ color [ 0 ] . $ color [ 0 ] , $ color [ 1 ] . $ color [ 1 ] , $ color [ 2 ] . $ color [ 2 ] , ] ; } else { throw new Exception ( 'Undefined color format (string): ' . $ origColor ) ; } $ red = hexdec ( $ red ) ; $ green = hexdec ( $ green ) ; $ blue = hexdec ( $ blue ) ; return [ $ red , $ green , $ blue , 0 ] ; }
Normalize color from string
48,013
protected static function normalizeColorArray ( array $ origColor ) : array { $ result = [ ] ; if ( Arr :: key ( 'r' , $ origColor ) && Arr :: key ( 'g' , $ origColor ) && Arr :: key ( 'b' , $ origColor ) ) { $ result = [ self :: color ( $ origColor [ 'r' ] ) , self :: color ( $ origColor [ 'g' ] ) , self :: color ( $ origColor [ 'b' ] ) , self :: alpha ( Arr :: key ( 'a' , $ origColor ) ? $ origColor [ 'a' ] : 0 ) , ] ; } elseif ( Arr :: key ( 0 , $ origColor ) && Arr :: key ( 1 , $ origColor ) && Arr :: key ( 2 , $ origColor ) ) { $ result = [ self :: color ( $ origColor [ 0 ] ) , self :: color ( $ origColor [ 1 ] ) , self :: color ( $ origColor [ 2 ] ) , self :: alpha ( Arr :: key ( 3 , $ origColor ) ? $ origColor [ 3 ] : 0 ) , ] ; } return $ result ; }
Normalize color from array
48,014
public static function opacity ( $ opacity ) : int { if ( $ opacity <= 1 ) { $ opacity *= 100 ; } $ opacity = Filter :: int ( $ opacity ) ; $ opacity = Vars :: limit ( $ opacity , 0 , 100 ) ; return $ opacity ; }
Check opacity value
48,015
public static function opacity2Alpha ( $ opacity ) : int { $ opacity = self :: opacity ( $ opacity ) ; $ opacity /= 100 ; $ alpha = 127 - ( 127 * $ opacity ) ; $ alpha = self :: alpha ( $ alpha ) ; return $ alpha ; }
Convert opacity value to alpha
48,016
public static function strToBin ( $ imageString ) : string { $ cleanedString = str_replace ( ' ' , '+' , preg_replace ( '#^data:image/[^;]+;base64,#' , '' , $ imageString ) ) ; $ result = base64_decode ( $ cleanedString , true ) ; if ( ! $ result ) { $ result = $ imageString ; } return $ result ; }
Convert string to binary data
48,017
public static function isSupportedFormat ( $ format ) : bool { if ( $ format ) { return self :: isJpeg ( $ format ) || self :: isPng ( $ format ) || self :: isGif ( $ format ) ; } return false ; }
Check is format supported by lib
48,018
public static function position ( $ position ) : string { $ position = strtolower ( trim ( $ position ) ) ; $ position = str_replace ( [ '-' , '_' ] , ' ' , $ position ) ; if ( in_array ( $ position , [ self :: TOP , 'top' , 't' ] , true ) ) { return self :: TOP ; } if ( in_array ( $ position , [ self :: TOP_RIGHT , 'top right' , 'right top' , 'tr' , 'rt' ] , true ) ) { return self :: TOP_RIGHT ; } if ( in_array ( $ position , [ self :: RIGHT , 'right' , 'r' ] , true ) ) { return self :: RIGHT ; } if ( in_array ( $ position , [ self :: BOTTOM_RIGHT , 'bottom right' , 'right bottom' , 'br' , 'rb' ] , true ) ) { return self :: BOTTOM_RIGHT ; } if ( in_array ( $ position , [ self :: BOTTOM , 'bottom' , 'b' ] , true ) ) { return self :: BOTTOM ; } if ( in_array ( $ position , [ self :: BOTTOM_LEFT , 'bottom left' , 'left bottom' , 'bl' , 'lb' ] , true ) ) { return self :: BOTTOM_LEFT ; } if ( in_array ( $ position , [ self :: LEFT , 'left' , 'l' ] , true ) ) { return self :: LEFT ; } if ( in_array ( $ position , [ self :: TOP_LEFT , 'top left' , 'left top' , 'tl' , 'lt' ] , true ) ) { return self :: TOP_LEFT ; } return self :: CENTER ; }
Check position name
48,019
public static function addAlpha ( $ image , $ isBlend = true ) { imagesavealpha ( $ image , true ) ; imagealphablending ( $ image , $ isBlend ) ; }
Add alpha chanel to image resource
48,020
public static function limit ( $ number , $ min , $ max ) : int { return self :: max ( self :: min ( $ number , $ min ) , $ max ) ; }
Limits the number between two bounds .
48,021
public static function relativePercent ( $ normal , $ current ) : string { $ normal = ( float ) $ normal ; $ current = ( float ) $ current ; if ( ! $ normal || $ normal === $ current ) { return '100' ; } $ normal = abs ( $ normal ) ; $ percent = round ( $ current / $ normal * 100 ) ; return number_format ( $ percent , 0 , '.' , ' ' ) ; }
Get relative percent
48,022
public static function _ ( $ value , $ filters = 'raw' ) { if ( is_string ( $ filters ) ) { $ filters = Str :: trim ( $ filters ) ; $ filters = explode ( ',' , $ filters ) ; if ( count ( $ filters ) > 0 ) { foreach ( $ filters as $ filter ) { $ filterName = self :: cmd ( $ filter ) ; if ( $ filterName ) { if ( method_exists ( __CLASS__ , $ filterName ) ) { $ value = self :: $ filterName ( $ value ) ; } else { throw new Exception ( 'Undefined filter method: ' . $ filter ) ; } } } } } elseif ( $ filters instanceof \ Closure ) { $ value = $ filters ( $ value ) ; } return $ value ; }
Apply custom filter to variable
48,023
public static function int ( $ value ) : int { $ cleaned = preg_replace ( '#[^0-9-+.,]#' , '' , $ value ) ; preg_match ( '#[-+]?[\d]+#' , $ cleaned , $ matches ) ; $ result = $ matches [ 0 ] ?? 0 ; return ( int ) $ result ; }
Smart convert any string to int
48,024
public static function digits ( $ value ) { $ cleaned = str_replace ( [ '-' , '+' ] , '' , $ value ) ; $ cleaned = filter_var ( $ cleaned , FILTER_SANITIZE_NUMBER_INT ) ; return $ cleaned ; }
Return only digits chars
48,025
public static function cmd ( $ value ) : string { $ value = Str :: low ( $ value ) ; $ value = preg_replace ( '#[^a-z0-9\_\-\.]#' , '' , $ value ) ; $ value = Str :: trim ( $ value ) ; return $ value ; }
Cleanup system command
48,026
public static function low ( $ string ) : string { $ cleaned = Str :: low ( $ string ) ; $ cleaned = Str :: trim ( $ cleaned ) ; return $ cleaned ; }
String to lower and trim
48,027
public static function up ( $ string ) : string { $ cleaned = Str :: up ( $ string ) ; $ cleaned = Str :: trim ( $ cleaned ) ; return $ cleaned ; }
String to upper and trim
48,028
public static function ucFirst ( $ input ) : string { $ string = Str :: low ( $ input ) ; $ string = ucfirst ( $ string ) ; return $ string ; }
First char to upper other to lower
48,029
public static function parseLines ( $ input ) : array { if ( is_array ( $ input ) ) { $ input = implode ( PHP_EOL , $ input ) ; } return Str :: parseLines ( $ input ) ; }
Parse lines to assoc list
48,030
public static function className ( $ input ) : string { $ output = preg_replace ( [ '#(?<=[^A-Z\s])([A-Z\s])#i' ] , ' $0' , $ input ) ; $ output = explode ( ' ' , $ output ) ; $ output = array_map ( function ( $ item ) { $ item = preg_replace ( '#[^a-z0-9]#i' , '' , $ item ) ; $ item = Filter :: ucFirst ( $ item ) ; return $ item ; } , $ output ) ; $ output = array_filter ( $ output ) ; return implode ( '' , $ output ) ; }
Convert words to PHP Class name
48,031
public static function getDomain ( $ emails ) : array { $ result = [ ] ; if ( empty ( $ emails ) ) { return $ result ; } $ emails = self :: handleEmailsInput ( $ emails ) ; foreach ( $ emails as $ email ) { if ( ! self :: isValid ( $ email ) ) { continue ; } $ domain = self :: extractDomain ( $ email ) ; if ( ! empty ( $ domain ) && ! in_array ( $ domain , $ result , true ) ) { $ result [ ] = $ domain ; } } return $ result ; }
Get domains from email addresses . The not valid email addresses will be skipped .
48,032
public static function getDomainSorted ( array $ emails ) : array { $ domains = self :: getDomain ( $ emails ) ; if ( count ( $ domains ) < 2 ) { return $ domains ; } sort ( $ domains , SORT_STRING ) ; return $ domains ; }
Get domains from email addresses in alphabetical order .
48,033
public static function getGravatarUrl ( $ email , $ size = 32 , $ defaultImage = 'identicon' ) { if ( empty ( $ email ) || self :: isValid ( $ email ) === false ) { return null ; } $ hash = md5 ( strtolower ( trim ( $ email ) ) ) ; $ parts = [ 'scheme' => 'http' , 'host' => 'www.gravatar.com' ] ; if ( Url :: isHttps ( ) ) { $ parts = [ 'scheme' => 'https' , 'host' => 'secure.gravatar.com' ] ; } $ size = Vars :: limit ( Filter :: int ( $ size ) , 32 , 2048 ) ; $ defaultImage = trim ( $ defaultImage ) ; if ( preg_match ( '/^(http|https)./' , $ defaultImage ) ) { $ defaultImage = urldecode ( $ defaultImage ) ; } else { $ defaultImage = strtolower ( $ defaultImage ) ; if ( ! Arr :: in ( ( string ) $ defaultImage , self :: getGravatarBuiltInImages ( ) ) ) { $ defaultImage = self :: getGravatarBuiltInDefaultImage ( ) ; } } $ parts [ 'path' ] = '/avatar/' . $ hash . '/' ; $ parts [ 'query' ] = [ 's' => $ size , 'd' => $ defaultImage , ] ; return Url :: create ( $ parts ) ; }
Generates an Gravatar URL .
48,034
public static function parseLines ( $ text , $ toAssoc = true ) : array { $ text = htmlspecialchars_decode ( $ text ) ; $ text = self :: clean ( $ text , false , false , false ) ; $ text = str_replace ( [ "\n" , "\r" , "\r\n" , PHP_EOL ] , "\n" , $ text ) ; $ lines = explode ( "\n" , $ text ) ; $ result = [ ] ; if ( ! empty ( $ lines ) ) { foreach ( $ lines as $ line ) { $ line = trim ( $ line ) ; if ( $ line === '' ) { continue ; } if ( $ toAssoc ) { $ result [ $ line ] = $ line ; } else { $ result [ ] = $ line ; } } } return $ result ; }
Parse text by lines
48,035
public static function unique ( $ prefix = 'unique' ) : string { $ prefix = rtrim ( trim ( $ prefix ) , '-' ) ; $ random = random_int ( 10000000 , 99999999 ) ; $ result = $ random ; if ( $ prefix ) { $ result = $ prefix . '-' . $ random ; } return $ result ; }
Get unique string
48,036
public static function random ( $ length = 10 , $ isReadable = true ) : string { $ result = '' ; if ( $ isReadable ) { $ vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' , '0' ] ; $ consonants = [ 'b' , 'c' , 'd' , 'f' , 'g' , 'h' , 'j' , 'k' , 'l' , 'm' , 'n' , 'p' , 'r' , 's' , 't' , 'v' , 'w' , 'x' , 'y' , 'z' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , ] ; $ max = $ length / 2 ; for ( $ pos = 1 ; $ pos <= $ max ; $ pos ++ ) { $ result .= $ consonants [ random_int ( 0 , count ( $ consonants ) - 1 ) ] ; $ result .= $ vowels [ random_int ( 0 , count ( $ vowels ) - 1 ) ] ; } } else { $ chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' ; for ( $ pos = 0 ; $ pos < $ length ; $ pos ++ ) { $ result .= $ chars [ mt_rand ( ) % strlen ( $ chars ) ] ; } } return $ result ; }
Generate readable random string
48,037
public static function like ( $ pattern , $ string , $ caseSensitive = true ) : bool { if ( $ pattern === $ string ) { return true ; } $ flags = $ caseSensitive ? '' : 'i' ; $ pattern = preg_quote ( $ pattern , '#' ) ; $ pattern = str_replace ( '\*' , '.*' , $ pattern ) ; return ( bool ) preg_match ( '#^' . $ pattern . '$#' . $ flags , $ string ) ; }
Check if a given string matches a given pattern .
48,038
public static function slug ( $ text = '' , $ isCache = false ) : string { static $ cache = [ ] ; if ( ! $ isCache ) { return Slug :: filter ( $ text ) ; } if ( ! array_key_exists ( $ text , $ cache ) ) { $ cache [ $ text ] = Slug :: filter ( $ text ) ; } return $ cache [ $ text ] ; }
Converts any accent characters to their equivalent normal characters
48,039
public static function isMBString ( ) : bool { static $ isLoaded ; if ( null === $ isLoaded ) { $ isLoaded = extension_loaded ( 'mbstring' ) ; if ( $ isLoaded ) { mb_internal_encoding ( self :: $ encoding ) ; } } return $ isLoaded ; }
Check is mbstring loaded
48,040
public static function len ( $ string ) : int { if ( self :: isMBString ( ) ) { return mb_strlen ( $ string , self :: $ encoding ) ; } return strlen ( $ string ) ; }
Get string length
48,041
public static function pos ( $ haystack , $ needle , $ offset = 0 ) { if ( self :: isMBString ( ) ) { return mb_strpos ( $ haystack , $ needle , $ offset , self :: $ encoding ) ; } return strpos ( $ haystack , $ needle , $ offset ) ; }
Find position of first occurrence of string in a string
48,042
public static function rPos ( $ haystack , $ needle , $ offset = 0 ) { if ( self :: isMBString ( ) ) { return mb_strrpos ( $ haystack , $ needle , $ offset , self :: $ encoding ) ; } return strrpos ( $ haystack , $ needle , $ offset ) ; }
Find position of last occurrence of a string in a string
48,043
public static function iPos ( $ haystack , $ needle , $ offset = 0 ) { if ( self :: isMBString ( ) ) { return mb_stripos ( $ haystack , $ needle , $ offset , self :: $ encoding ) ; } return stripos ( $ haystack , $ needle , $ offset ) ; }
Finds position of first occurrence of a string within another case insensitive
48,044
public static function strStr ( $ haystack , $ needle , $ beforeNeedle = false ) { if ( self :: isMBString ( ) ) { return mb_strstr ( $ haystack , $ needle , $ beforeNeedle , self :: $ encoding ) ; } return strstr ( $ haystack , $ needle , $ beforeNeedle ) ; }
Finds first occurrence of a string within another
48,045
public static function iStr ( $ haystack , $ needle , $ beforeNeedle = false ) { if ( self :: isMBString ( ) ) { return mb_stristr ( $ haystack , $ needle , $ beforeNeedle , self :: $ encoding ) ; } return stristr ( $ haystack , $ needle , $ beforeNeedle ) ; }
Finds first occurrence of a string within another case insensitive
48,046
public static function rChr ( $ haystack , $ needle , $ part = null ) { if ( self :: isMBString ( ) ) { return mb_strrchr ( $ haystack , $ needle , $ part , self :: $ encoding ) ; } return strrchr ( $ haystack , $ needle ) ; }
Finds the last occurrence of a character in a string within another
48,047
public static function low ( $ string ) : string { if ( self :: isMBString ( ) ) { return mb_strtolower ( $ string , self :: $ encoding ) ; } return strtolower ( $ string ) ; }
Make a string lowercase
48,048
public static function up ( $ string ) : string { if ( self :: isMBString ( ) ) { return mb_strtoupper ( $ string , self :: $ encoding ) ; } return strtoupper ( $ string ) ; }
Make a string uppercase
48,049
public static function trim ( $ value , $ extendMode = false ) : string { $ result = ( string ) trim ( $ value ) ; if ( $ extendMode ) { $ result = trim ( $ result , chr ( 0xE3 ) . chr ( 0x80 ) . chr ( 0x80 ) ) ; $ result = trim ( $ result , chr ( 0xC2 ) . chr ( 0xA0 ) ) ; $ result = trim ( $ result ) ; } return $ result ; }
Trim whitespaces and other special chars
48,050
public static function splitCamelCase ( $ input , $ separator = '_' , $ toLower = true ) : string { $ original = $ input ; $ output = preg_replace ( [ '/(?<=[^A-Z])([A-Z])/' , '/(?<=[^0-9])([0-9])/' ] , '_$0' , $ input ) ; $ output = preg_replace ( '#_{1,}#' , $ separator , $ output ) ; $ output = trim ( $ output ) ; if ( $ toLower ) { $ output = strtolower ( $ output ) ; } if ( '' === $ output ) { return $ original ; } return $ output ; }
Convert camel case to human readable format
48,051
public static function getClassName ( $ object , $ toLower = false ) { $ className = $ object ; if ( is_object ( $ object ) ) { $ className = get_class ( $ object ) ; } $ result = $ className ; if ( strpos ( $ className , '\\' ) !== false ) { $ className = explode ( '\\' , $ className ) ; reset ( $ className ) ; $ result = end ( $ className ) ; } if ( $ toLower ) { $ result = strtolower ( $ result ) ; } return $ result ; }
Get class name without namespace
48,052
public function scopeWithinPeriod ( Builder $ query , Period $ period ) { $ startDateTime = $ period -> getStartDateTime ( ) ; $ endDateTime = $ period -> getEndDateTime ( ) ; if ( $ startDateTime && ! $ endDateTime ) { $ query -> where ( 'viewed_at' , '>=' , $ startDateTime ) ; } elseif ( ! $ startDateTime && $ endDateTime ) { $ query -> where ( 'viewed_at' , '<=' , $ endDateTime ) ; } elseif ( $ startDateTime && $ endDateTime ) { $ query -> whereBetween ( 'viewed_at' , [ $ startDateTime , $ endDateTime ] ) ; } return $ query ; }
Scope a query to only include views within the period .
48,053
public function scopeOrderByViews ( Builder $ query , string $ direction = 'desc' , $ period = null ) : Builder { return $ query -> withCount ( [ 'views' => function ( $ query ) use ( $ period ) { if ( $ period ) { $ query -> withinPeriod ( $ period ) ; } } ] ) -> orderBy ( 'views_count' , $ direction ) ; }
Scope a query to order records by views count .
48,054
public function scopeOrderByUniqueViews ( Builder $ query , string $ direction = 'desc' , $ period = null ) : Builder { return $ query -> withCount ( [ 'views' => function ( $ query ) use ( $ period ) { $ query -> uniqueVisitor ( ) ; if ( $ period ) { $ query -> withinPeriod ( $ period ) ; } } ] ) -> orderBy ( 'views_count' , $ direction ) ; }
Scope a query to order records by unique views count .
48,055
public static function subToday ( string $ subType , int $ subValue ) : self { $ subTypeMethod = 'sub' . ucfirst ( strtolower ( Str :: after ( $ subType , 'PAST_' ) ) ) ; $ today = Carbon :: today ( ) ; return self :: sub ( $ today , $ subTypeMethod , $ subType , $ subValue ) ; }
Create a new Period instance with a start date time of today minus the given subType .
48,056
public static function subNow ( string $ subType , int $ subValue ) : self { $ subTypeMethod = 'sub' . ucfirst ( strtolower ( Str :: after ( $ subType , 'SUB_' ) ) ) ; $ now = Carbon :: now ( ) ; return self :: sub ( $ now , $ subTypeMethod , $ subType , $ subValue ) ; }
Create a new Period instance with a start date time of now minus the given subType .
48,057
public static function sub ( DateTime $ startDateTime , string $ subTypeMethod , string $ subType , int $ subValue ) { if ( ! is_callable ( [ $ startDateTime , $ subTypeMethod ] ) ) { throw new Exception ( "Method `{$subTypeMethod}` is not callable on the given start date time instance." ) ; } $ startDateTime = $ startDateTime -> $ subTypeMethod ( $ subValue ) ; $ period = new static ( $ startDateTime ) ; return $ period -> setFixedDateTimes ( false ) -> setSubType ( $ subType ) -> setSubValue ( $ subValue ) ; }
Create a new Period instance with a start date time of startDateTime minus the given subType .
48,058
public function deleted ( ViewableContract $ viewable ) { if ( $ this -> removeViewsOnDelete ( $ viewable ) ) { app ( Views :: class ) -> forViewable ( $ viewable ) -> destroy ( ) ; } }
Handle the deleted event for the viewable model .
48,059
public static function createForEntity ( ViewableContract $ viewable , $ period , bool $ unique , string $ collection = null ) : string { $ cacheKey = config ( 'eloquent-viewable.cache.key' , 'cyrildewit.eloquent-viewable.cache' ) ; $ viewableKey = $ viewable -> getKey ( ) ; $ viewableType = strtolower ( str_replace ( '\\' , '-' , $ viewable -> getMorphClass ( ) ) ) ; $ typeKey = $ unique ? 'unique' : 'normal' ; $ periodKey = static :: createPeriodKey ( $ period ) ; $ collection = $ collection ? ".{$collection}" : '' ; return "{$cacheKey}{$collection}.{$viewableType}.{$viewableKey}.{$typeKey}.{$periodKey}" ; }
Create a unique key for the viewable model .
48,060
public static function createForType ( $ viewableType , $ period , bool $ unique ) : string { $ cacheKey = config ( 'eloquent-viewable.cache.key' , 'cyrildewit.eloquent-viewable.cache' ) ; $ viewableType = strtolower ( str_replace ( '\\' , '-' , $ viewableType ) ) ; $ typeKey = $ unique ? 'unique' : 'normal' ; $ periodKey = static :: createPeriodKey ( $ period ) ; return "{$cacheKey}.{$viewableType}.{$typeKey}.{$periodKey}" ; }
Create a unique key for the viewable type .
48,061
public static function createPeriodKey ( $ period ) : string { if ( $ period -> hasFixedDateTimes ( ) ) { return "{$period->getStartDateTimeString()}|{$period->getEndDateTimeString()}" ; } list ( $ subType , $ subValueType ) = explode ( '_' , strtolower ( $ period -> getSubType ( ) ) ) ; return "{$subType}{$period->getSubValue()}{$subValueType}|" ; }
Format a period class into a key .
48,062
public function get ( ) { if ( ! Cookie :: has ( $ this -> key ) ) { Cookie :: queue ( $ this -> key , $ uniqueString = $ this -> generateUniqueString ( ) , $ this -> expirationInMinutes ( ) ) ; return $ uniqueString ; } return Cookie :: get ( $ this -> key ) ; }
Get the visitor s unique key .
48,063
public function countByType ( $ viewableType ) : int { if ( $ viewableType instanceof ViewableContract ) { $ viewableType = $ viewableType -> getMorphClass ( ) ; } $ cacheKey = Key :: createForType ( $ viewableType , $ this -> period ?? Period :: create ( ) , $ this -> unique ) ; if ( $ this -> shouldCache ) { $ cachedViewsCount = $ this -> cache -> get ( $ cacheKey ) ; if ( $ cachedViewsCount !== null ) { return ( int ) $ cachedViewsCount ; } } $ query = app ( ViewContract :: class ) -> where ( 'viewable_type' , $ viewableType ) ; if ( $ period = $ this -> period ) { $ query -> withinPeriod ( $ period ) ; } if ( $ this -> unique ) { $ viewsCount = $ query -> uniqueVisitor ( ) -> count ( 'visitor' ) ; } else { $ viewsCount = $ query -> count ( ) ; } if ( $ this -> shouldCache ) { $ this -> cache -> put ( $ cacheKey , $ viewsCount , $ this -> cacheLifetime ) ; } return $ viewsCount ; }
Count the views for a viewable type .
48,064
public function record ( ) : bool { if ( $ this -> shouldRecord ( ) ) { $ view = app ( ViewContract :: class ) ; $ view -> viewable_id = $ this -> viewable -> getKey ( ) ; $ view -> viewable_type = $ this -> viewable -> getMorphClass ( ) ; $ view -> visitor = $ this -> resolveVisitorId ( ) ; $ view -> collection = $ this -> collection ; $ view -> viewed_at = Carbon :: now ( ) ; return $ view -> save ( ) ; } return false ; }
Save a new record of the made view .
48,065
public function count ( ) : int { $ query = $ this -> viewable -> views ( ) ; $ cacheKey = Key :: createForEntity ( $ this -> viewable , $ this -> period ?? Period :: create ( ) , $ this -> unique , $ this -> collection ) ; if ( $ this -> shouldCache ) { $ cachedViewsCount = $ this -> cache -> get ( $ cacheKey ) ; if ( $ cachedViewsCount !== null ) { return ( int ) $ cachedViewsCount ; } } if ( $ period = $ this -> period ) { $ query -> withinPeriod ( $ period ) ; } $ query -> where ( 'collection' , $ this -> collection ) ; if ( $ this -> unique ) { $ viewsCount = $ query -> uniqueVisitor ( ) -> count ( 'visitor' ) ; } else { $ viewsCount = $ query -> count ( ) ; } if ( $ this -> shouldCache ) { $ this -> cache -> put ( $ cacheKey , $ viewsCount , $ this -> cacheLifetime ) ; } return $ viewsCount ; }
Count the views .
48,066
public function delayInSession ( $ delay ) : self { if ( is_int ( $ delay ) ) { $ delay = Carbon :: now ( ) -> addMinutes ( $ delay ) ; } $ this -> sessionDelay = $ delay ; return $ this ; }
Set the delay in the session .
48,067
public function remember ( $ lifetime = null ) { $ this -> shouldCache = true ; if ( $ lifetime !== null ) { $ this -> cacheLifetime = $ this -> resolveCacheLifetime ( $ lifetime ) ; } return $ this ; }
Cache the current views count .
48,068
protected function shouldRecord ( ) : bool { if ( config ( 'eloquent-viewable.ignore_bots' ) && $ this -> crawlerDetector -> isCrawler ( ) ) { return false ; } if ( config ( 'eloquent-viewable.honor_dnt' , false ) && $ this -> requestHasDoNotTrackHeader ( ) ) { return false ; } if ( collect ( config ( 'eloquent-viewable.ignored_ip_addresses' ) ) -> contains ( $ this -> resolveIpAddress ( ) ) ) { return false ; } if ( ! is_null ( $ this -> sessionDelay ) && ! $ this -> viewSessionHistory -> push ( $ this -> viewable , $ this -> sessionDelay ) ) { return false ; } return true ; }
Determine if we should record the view .
48,069
protected function resolveCacheLifetime ( $ lifetime ) : DateTime { if ( $ lifetime instanceof DateTime ) { return $ lifetime ; } if ( is_int ( $ lifetime ) ) { return Carbon :: now ( ) -> addMinutes ( $ lifetime ) ; } }
Resolve cache lifetime .
48,070
public function push ( ViewableContract $ viewable , $ delay ) : bool { $ namespaceKey = $ this -> createNamespaceKey ( $ viewable ) ; $ viewableKey = $ this -> createViewableKey ( $ viewable ) ; $ this -> forgetExpiredViews ( $ namespaceKey ) ; if ( ! $ this -> has ( $ viewableKey ) ) { $ this -> session -> put ( $ viewableKey , $ this -> createRecord ( $ viewable , $ delay ) ) ; return true ; } return false ; }
Push a viewable model with an expiry date to the session .
48,071
protected function forgetExpiredViews ( string $ key ) { $ currentTime = Carbon :: now ( ) ; $ viewHistory = $ this -> session -> get ( $ key , [ ] ) ; foreach ( $ viewHistory as $ record ) { if ( $ record [ 'expires_at' ] -> lte ( $ currentTime ) ) { $ recordId = array_search ( $ record [ 'viewable_id' ] , array_column ( $ record , 'viewable_id' ) ) ; $ this -> session -> pull ( $ key . $ recordId ) ; } } }
Remove all expired views from the session .
48,072
protected function createNamespaceKey ( ViewableContract $ viewable ) : string { return $ this -> primaryKey . '.' . strtolower ( str_replace ( '\\' , '-' , $ viewable -> getMorphClass ( ) ) ) ; }
Create a base key from the given viewable model .
48,073
private function validateGovernment ( string $ vatNumber ) : bool { $ prefix = strtoupper ( substr ( $ vatNumber , 0 , 2 ) ) ; $ number = ( int ) substr ( $ vatNumber , 2 , 3 ) ; if ( $ prefix == 'GD' ) { return $ number < 500 ; } if ( $ prefix == 'HA' ) { return $ number > 499 ; } return false ; }
Validate Government VAT
48,074
private function validateTemporaryTaxpayer ( string $ vatNumber ) : bool { if ( $ vatNumber [ 10 ] != 1 ) { return false ; } $ weights = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 1 , 2 ] ; $ checksum = ( int ) $ vatNumber [ 11 ] ; $ checkval = $ this -> sumWeights ( $ weights , $ vatNumber ) ; if ( ( $ checkval % 11 ) == 10 ) { $ weights = [ 3 , 4 , 5 , 6 , 7 , 8 , 9 , 1 , 2 , 3 , 4 ] ; $ checkval = $ this -> sumWeights ( $ weights , $ vatNumber ) ; $ checkval = ( $ checkval % 11 == 10 ) ? 0 : $ checkval % 11 ; return $ checkval == $ checksum ; } return $ checkval % 11 == $ checksum ; }
Validate Temporary Tax Payer
48,075
private function validateBusiness ( string $ vatNumber ) : bool { $ weights = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] ; $ checkval = $ this -> sumWeights ( $ weights , $ vatNumber ) ; if ( $ checkval % 11 == 10 ) { $ weights = [ 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] ; $ checkval = $ this -> sumWeights ( $ weights , $ vatNumber ) ; $ checkval = ( $ checkval % 11 ) == 10 ? 0 : ( $ checkval % 11 ) ; } else { $ checkval = $ checkval % 11 ; } return $ checkval == ( int ) $ vatNumber [ 8 ] ; }
Validation for business VAT ID s with 9 digits
48,076
public function isAlive ( ) : bool { if ( false === static :: $ testingEnabled ) { return false !== fsockopen ( $ this -> getHost ( ) , $ this -> getPort ( ) ) ; } return static :: $ testingServiceIsUp ; }
Checks if the VIES service is online and available
48,077
public function populate ( $ row ) : void { if ( is_array ( $ row ) ) { $ row = ( object ) $ row ; } $ requiredFields = [ 'countryCode' , 'vatNumber' , 'requestDate' , 'valid' ] ; foreach ( $ requiredFields as $ requiredField ) { if ( ! isset ( $ row -> $ requiredField ) ) { throw new InvalidArgumentException ( 'Required field "' . $ requiredField . '" is missing' ) ; } } $ this -> setCountryCode ( $ row -> countryCode ) -> setVatNumber ( $ row -> vatNumber ) -> setRequestDate ( $ row -> requestDate ) -> setValid ( $ row -> valid ) -> setName ( $ row -> traderName ?? '---' ) -> setAddress ( $ row -> traderAddress ?? '---' ) -> setIdentifier ( $ row -> requestIdentifier ?? '' ) -> setNameMatch ( $ row -> traderNameMatch ?? '' ) -> setCompanyTypeMatch ( $ row -> traderCompanyTypeMatch ?? '' ) -> setStreetMatch ( $ row -> traderStreetMatch ?? '' ) -> setPostcodeMatch ( $ row -> traderPostcodeMatch ?? '' ) -> setCityMatch ( $ row -> traderCityMatch ?? '' ) ; }
Populates this response object with external data
48,078
public function toArray ( ) : array { return [ 'countryCode' => $ this -> getCountryCode ( ) , 'vatNumber' => $ this -> getVatNumber ( ) , 'requestDate' => $ this -> getRequestDate ( ) -> format ( 'Y-m-d' ) , 'valid' => $ this -> isValid ( ) , 'name' => $ this -> getName ( ) , 'address' => $ this -> getAddress ( ) , 'identifier' => $ this -> getIdentifier ( ) , 'nameMatch' => $ this -> getNameMatch ( ) , 'companyTypeMatch' => $ this -> getCompanyTypeMatch ( ) , 'streetMatch' => $ this -> getStreetMatch ( ) , 'postcodeMatch' => $ this -> getPostcodeMatch ( ) , 'cityMatch' => $ this -> getCityMatch ( ) , ] ; }
Return this object as an array
48,079
public function connect ( ) { $ this -> socket = fsockopen ( $ this -> host , $ this -> port , $ errno , $ errstr , $ this -> timeout ) ; if ( ! $ this -> socket ) { $ this -> lastResponse = $ errstr ; return false ; } stream_set_timeout ( $ this -> socket , 3 , 0 ) ; return $ this -> authorize ( ) ; }
Connect to a server .
48,080
public function sendCommand ( $ command ) { if ( ! $ this -> isConnected ( ) ) { return false ; } $ this -> writePacket ( self :: PACKET_COMMAND , self :: SERVERDATA_EXECCOMMAND , $ command ) ; $ response_packet = $ this -> readPacket ( ) ; if ( $ response_packet [ 'id' ] == self :: PACKET_COMMAND ) { if ( $ response_packet [ 'type' ] == self :: SERVERDATA_RESPONSE_VALUE ) { $ this -> lastResponse = $ response_packet [ 'body' ] ; return $ response_packet [ 'body' ] ; } } return false ; }
Send a command to the connected server .
48,081
private function authorize ( ) { $ this -> writePacket ( self :: PACKET_AUTHORIZE , self :: SERVERDATA_AUTH , $ this -> password ) ; $ response_packet = $ this -> readPacket ( ) ; if ( $ response_packet [ 'type' ] == self :: SERVERDATA_AUTH_RESPONSE ) { if ( $ response_packet [ 'id' ] == self :: PACKET_AUTHORIZE ) { $ this -> authorized = true ; return true ; } } $ this -> disconnect ( ) ; return false ; }
Log into the server with the given credentials .
48,082
private function writePacket ( $ packetId , $ packetType , $ packetBody ) { $ packet = pack ( 'VV' , $ packetId , $ packetType ) ; $ packet = $ packet . $ packetBody . "\x00" ; $ packet = $ packet . "\x00" ; $ packet_size = strlen ( $ packet ) ; $ packet = pack ( 'V' , $ packet_size ) . $ packet ; fwrite ( $ this -> socket , $ packet , strlen ( $ packet ) ) ; }
Writes a packet to the socket stream .
48,083
private function readPacket ( ) { $ size_data = fread ( $ this -> socket , 4 ) ; $ size_pack = unpack ( 'V1size' , $ size_data ) ; $ size = $ size_pack [ 'size' ] ; $ packet_data = fread ( $ this -> socket , $ size ) ; $ packet_pack = unpack ( 'V1id/V1type/a*body' , $ packet_data ) ; return $ packet_pack ; }
Read a packet from the socket stream .
48,084
public function handleRequest ( ActionRequest $ request ) { $ this -> handleWriterType ( $ request ) ; $ this -> handleFilename ( $ request ) ; $ this -> resource = $ request -> resource ( ) ; $ this -> request = ExportActionRequestFactory :: make ( $ request ) ; $ query = $ this -> request -> toExportQuery ( ) ; $ this -> handleOnly ( $ this -> request ) ; $ this -> handleHeadings ( $ query , $ this -> request ) ; return $ this -> handle ( $ request , $ this -> withQuery ( $ query ) ) ; }
Execute the action for the given request .
48,085
public function availableLenses ( ) { if ( ! $ this -> resourceInstance ) { $ this -> resourceInstance = $ this -> newResource ( ) ; } return $ this -> resourceInstance -> availableLenses ( $ this ) ; }
Get all of the possible lenses for the request .
48,086
public static function run ( $ script , string $ cwd = null , array $ env = [ ] , string $ binary = null ) : Promise { $ process = new self ( $ script , $ cwd , $ env , $ binary ) ; return call ( function ( ) use ( $ process ) { yield $ process -> start ( ) ; return $ process ; } ) ; }
Creates and starts the process at the given path using the optional PHP binary path .
48,087
private function memGet ( int $ offset , int $ size ) : string { $ data = \ shmop_read ( $ this -> handle , $ offset , $ size ) ; if ( $ data === false ) { throw new SharedMemoryException ( 'Failed to read from shared memory block.' ) ; } return $ data ; }
Reads binary data from shared memory .
48,088
private function memSet ( int $ offset , string $ data ) { if ( ! \ shmop_write ( $ this -> handle , $ data , $ offset ) ) { throw new SharedMemoryException ( 'Failed to write to shared memory block.' ) ; } }
Writes binary data to shared memory .
48,089
private function pull ( ) : Worker { if ( ! $ this -> isRunning ( ) ) { throw new StatusError ( "The pool was shutdown" ) ; } do { if ( $ this -> idleWorkers -> isEmpty ( ) ) { if ( $ this -> getWorkerCount ( ) >= $ this -> maxSize ) { $ worker = $ this -> busyQueue -> shift ( ) ; } else { $ worker = $ this -> factory -> create ( ) ; $ this -> workers -> attach ( $ worker , 0 ) ; break ; } } else { $ worker = $ this -> idleWorkers -> shift ( ) ; } if ( $ worker -> isRunning ( ) ) { break ; } $ this -> workers -> detach ( $ worker ) ; } while ( true ) ; $ this -> busyQueue -> push ( $ worker ) ; $ this -> workers [ $ worker ] += 1 ; return $ worker ; }
Pulls a worker from the pool .
48,090
public function add ( $ columns , $ label = null ) { if ( ! is_array ( $ columns ) ) { $ columns = [ $ columns => $ label ] ; } foreach ( $ columns as $ column => $ label ) { if ( is_null ( $ label ) ) { $ label = str_replace ( [ '_' , '-' ] , ' ' , ucfirst ( $ column ) ) ; } $ this -> add [ $ column ] = $ label ; } return $ this ; }
Add a new column
48,091
public function hide ( $ columns ) { if ( ! is_array ( $ columns ) ) { $ columns = [ $ columns ] ; } foreach ( $ columns as $ column ) { $ this -> hide [ ] = $ column ; } return $ this ; }
Add a column to hide
48,092
public function order ( $ columns ) { foreach ( $ columns as $ column => $ position ) { $ this -> positions [ $ column ] = $ position ; } return $ this ; }
Define the postion for a columns
48,093
public function sortable ( $ sortable ) { foreach ( $ sortable as $ column => $ options ) { $ this -> sortable [ $ column ] = $ options ; } return $ this ; }
Set columns that are sortable
48,094
public function modifyColumns ( $ columns ) { if ( ! empty ( $ this -> items ) ) { return $ this -> items ; } if ( ! empty ( $ this -> add ) ) { foreach ( $ this -> add as $ key => $ label ) { $ columns [ $ key ] = $ label ; } } if ( ! empty ( $ this -> hide ) ) { foreach ( $ this -> hide as $ key ) { unset ( $ columns [ $ key ] ) ; } } if ( ! empty ( $ this -> positions ) ) { foreach ( $ this -> positions as $ key => $ position ) { $ index = array_search ( $ key , array_keys ( $ columns ) ) ; $ item = array_slice ( $ columns , $ index , 1 ) ; unset ( $ columns [ $ key ] ) ; $ start = array_slice ( $ columns , 0 , $ position , true ) ; $ end = array_slice ( $ columns , $ position , count ( $ columns ) - 1 , true ) ; $ columns = $ start + $ item + $ end ; } } return $ columns ; }
Modify the columns for the object
48,095
public function registerTaxonomy ( ) { if ( ! taxonomy_exists ( $ this -> name ) ) { $ options = $ this -> createOptions ( ) ; register_taxonomy ( $ this -> name , null , $ options ) ; } }
Register the Taxonomy to WordPress
48,096
public function registerTaxonomyToObjects ( ) { if ( ! empty ( $ this -> posttypes ) ) { foreach ( $ this -> posttypes as $ posttype ) { register_taxonomy_for_object_type ( $ this -> name , $ posttype ) ; } } }
Register the Taxonomy to PostTypes
48,097
public function createOptions ( ) { $ options = [ 'hierarchical' => true , 'show_admin_column' => true , 'rewrite' => [ 'slug' => $ this -> slug , ] , ] ; $ options = array_replace_recursive ( $ options , $ this -> options ) ; if ( ! isset ( $ options [ 'labels' ] ) ) { $ options [ 'labels' ] = $ this -> createLabels ( ) ; } return $ options ; }
Create options for Taxonomy
48,098
public function createLabels ( ) { $ labels = [ 'name' => $ this -> plural , 'singular_name' => $ this -> singular , 'menu_name' => $ this -> plural , 'all_items' => "All {$this->plural}" , 'edit_item' => "Edit {$this->singular}" , 'view_item' => "View {$this->singular}" , 'update_item' => "Update {$this->singular}" , 'add_new_item' => "Add New {$this->singular}" , 'new_item_name' => "New {$this->singular} Name" , 'parent_item' => "Parent {$this->plural}" , 'parent_item_colon' => "Parent {$this->plural}:" , 'search_items' => "Search {$this->plural}" , 'popular_items' => "Popular {$this->plural}" , 'separate_items_with_commas' => "Seperate {$this->plural} with commas" , 'add_or_remove_items' => "Add or remove {$this->plural}" , 'choose_from_most_used' => "Choose from most used {$this->plural}" , 'not_found' => "No {$this->plural} found" , ] ; return array_replace ( $ labels , $ this -> labels ) ; }
Create labels for the Taxonomy
48,099
public function populateColumns ( $ content , $ column , $ term_id ) { if ( isset ( $ this -> columns -> populate [ $ column ] ) ) { $ content = call_user_func_array ( $ this -> columns ( ) -> populate [ $ column ] , [ $ content , $ column , $ term_id ] ) ; } return $ content ; }
Populate custom columns for the Taxonomy