code
stringlengths
31
1.39M
docstring
stringlengths
23
16.8k
func_name
stringlengths
1
126
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
166
url
stringlengths
50
220
license
stringclasses
7 values
public function offsetExists($offset): bool { return isset($this->string[$offset]); }
Determine whether a character exists in the string at a specific offset. @param int $offset Offset to check for existence
offsetExists
php
PHLAK/Twine
src/Traits/ArrayAccess.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/ArrayAccess.php
MIT
public function offsetGet($offset): string { // NOTE: Return an instance of Str? return $this->string[$offset]; }
Retrieve a character from the string at a specific offset. @param int $offset Position of character to get
offsetGet
php
PHLAK/Twine
src/Traits/ArrayAccess.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/ArrayAccess.php
MIT
public function offsetSet($offset, $value): void { throw new \RuntimeException('Cannot set string offsets; Twine\Str objects are immutable'); }
Not implemented due to immutability. @param int $offset Not implemented @param mixed $value Not implemented @throws \RuntimeException
offsetSet
php
PHLAK/Twine
src/Traits/ArrayAccess.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/ArrayAccess.php
MIT
public function offsetUnset($offset): void { throw new \RuntimeException('Cannot unset string offsets; Twine\Str objects are immutable'); }
Not implemented due to immutability. @param int $offset Not implemented @throws \RuntimeException
offsetUnset
php
PHLAK/Twine
src/Traits/ArrayAccess.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/ArrayAccess.php
MIT
public function uppercase(Config\Uppercase $mode = Config\Uppercase::ALL): self { return match ($mode) { Config\Uppercase::ALL => new self(mb_strtoupper($this->string, $this->encoding), $this->encoding), Config\Uppercase::FIRST => new self( mb_strtoupper( mb_substr($this->string, 0, 1, $this->encoding), $this->encoding ) . mb_substr($this->string, 1, null, $this->encoding), $this->encoding ), Config\Uppercase::WORDS => new self(preg_replace_callback('/(\p{Ll})[\S]*/u', function (array $matched) { return mb_strtoupper($matched[1], $this->encoding) . mb_substr($matched[0], 1, null, $this->encoding); }, $this->string), $this->encoding) }; }
Convert all or parts of the string to uppercase. @param Config\Uppercase $mode An uppercase mode flag Available mode flags: - Twine\Config\Uppercase::ALL - Uppercase all characters of the string (default) - Twine\Config\Uppercase::FIRST - Uppercase the first character of the string only - Twine\Config\Uppercase::WORDS - Uppercase the first character of each word of the string
uppercase
php
PHLAK/Twine
src/Traits/Caseable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Caseable.php
MIT
public function lowercase(Config\Lowercase $mode = Config\Lowercase::ALL): self { return match ($mode) { Config\Lowercase::ALL => new self(mb_strtolower($this->string, $this->encoding), $this->encoding), Config\Lowercase::FIRST => new self( mb_strtolower(mb_substr($this->string, 0, 1, $this->encoding), $this->encoding) . mb_substr($this->string, 1, null, $this->encoding), $this->encoding ), Config\Lowercase::WORDS => new self(preg_replace_callback('/(\p{Lu})[\S]*/u', function (array $matched) { return mb_strtolower($matched[1], $this->encoding) . mb_substr($matched[0], 1, null, $this->encoding); }, $this->string), $this->encoding) }; }
Convert all or parts of the string to lowercase. @param Config\Lowercase $mode A lowercase mode flag Available mode flags: - Twine\Config\Lowercase::ALL - Lowercase all characters of the string (default) - Twine\Config\Lowercase::FIRST - Lowercase the first character of the string only - Twine\Config\Lowercase::WORDS - Lowercase the first character of each word of the string
lowercase
php
PHLAK/Twine
src/Traits/Caseable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Caseable.php
MIT
public function kebabCase(): self { $words = array_map(function ($word) { return mb_strtolower($word, $this->encoding); }, Support\Str::words($this->string)); return new self(implode('-', $words), $this->encoding); }
Convert the string to kebab-case.
kebabCase
php
PHLAK/Twine
src/Traits/Caseable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Caseable.php
MIT
public function equals(string $string, Config\Equals $mode = Config\Equals::CASE_SENSITIVE): bool { return match ($mode) { Config\Equals::CASE_SENSITIVE => strcmp($this->string, $string), Config\Equals::CASE_INSENSITIVE => strcasecmp($this->string, $string), } === 0; }
Determine if the string is equal to another string. @param string $string The string to compare against @param Config\Equals $mode An equals mode flag Available mode flags: - Twine\Config\Equals::CASE_SENSITIVE - Match the string with case sensitivity (default) - Twine\Config\Equals::CASE_INSENSITIVE - Match the string with case insensitivity @return bool True if the string matches the comparing string
equals
php
PHLAK/Twine
src/Traits/Comparable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Comparable.php
MIT
public function matches(string $pattern): bool { return (bool) preg_match($pattern, $this->string); }
Determine if the string matches a regular expression pattern. @param string $pattern A regular expression pattern @return bool True if the string matches the regular expression pattern
matches
php
PHLAK/Twine
src/Traits/Comparable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Comparable.php
MIT
public function startsWith(string $string): bool { if ($this->string === '' || $string === '') { return false; } if (strpos($this->string, $string) === 0) { return true; } return false; }
Determine if the string starts with another string. @param string $string The string to compare against @return bool True if the string starts with $string, otherwise false
startsWith
php
PHLAK/Twine
src/Traits/Comparable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Comparable.php
MIT
public function endsWith(string $string): bool { if ($this->string === '' || $string === '') { return false; } return mb_substr($this->string, -mb_strlen($string, $this->encoding), null, $this->encoding) === $string; }
Determine if the string ends with another string. @param string $string The string to compare against @return bool True if the string ends with $string, otherwise false
endsWith
php
PHLAK/Twine
src/Traits/Comparable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Comparable.php
MIT
public function contains(string $string): bool { return mb_strpos($this->string, $string, 0, $this->encoding) !== false; }
Determine if the string contains another string. @param string $string The string to compare against @return bool True if the string contains $string, otherwise false
contains
php
PHLAK/Twine
src/Traits/Comparable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Comparable.php
MIT
public function in(string $string, Config\In $mode = Config\In::CASE_SENSITIVE): bool { return match ($mode) { Config\In::CASE_SENSITIVE => mb_strpos($string, $this->string, 0, $this->encoding), Config\In::CASE_INSENSITIVE => mb_stripos($string, $this->string, 0, $this->encoding), } !== false; }
Determine if the string exists in another string. @param string $string The string to compare against @param Config\In $mode Flag for case-sensitive and case-insensitive mode Available mode flags: - Twine\Config\In::CASE_SENSITIVE - Match the string with case sensitivity (default) - Twine\Config\In::CASE_INSENSITIVE - Match the string with case insensitivity @return bool True if the string exists in $string, otherwise false
in
php
PHLAK/Twine
src/Traits/Comparable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Comparable.php
MIT
public function similarity(string $string): float { similar_text($this->string, $string, $percent); return $percent; }
Calculate the similarity percentage between two strings. @param string $string The string to compare against
similarity
php
PHLAK/Twine
src/Traits/Comparable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Comparable.php
MIT
public function count(string $string): int { return mb_substr_count($this->string, $string, $this->encoding); }
Count the number of occurrences of a substring in the string. @param string $string The substring to count
count
php
PHLAK/Twine
src/Traits/Convenience.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Convenience.php
MIT
public function format(...$args): self { return new self(sprintf($this->string, ...$args), $this->encoding); }
Return the formatted string. @param string|int|float ...$args Any number of elements to fill the string
format
php
PHLAK/Twine
src/Traits/Convenience.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Convenience.php
MIT
public function length(): int { return mb_strlen($this->string, $this->encoding); }
Get the length of the string. @return int Length of the string
length
php
PHLAK/Twine
src/Traits/Convenience.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Convenience.php
MIT
public function words(): array { preg_match_all('/\p{Lu}?[\p{Ll}0-9]+/u', $this->string, $matches); return array_map(function (string $words) { return new self($words, $this->encoding); }, $matches[0]); }
Split the string into an array of words. @return \PHLAK\Twine\Str[]
words
php
PHLAK/Twine
src/Traits/Convenience.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Convenience.php
MIT
public function characters(Characters $mode = Config\Characters::ALL): array { $characters = Support\Str::characters($this->string); if ($mode === Config\Characters::UNIQUE) { $characters = array_values(array_unique($characters)); } return array_map(function ($character) { return new self($character, $this->encoding); }, $characters); }
Split the string into an array of characters. @return \PHLAK\Twine\Str[]
characters
php
PHLAK/Twine
src/Traits/Convenience.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Convenience.php
MIT
public function nth(int $step, int $offset = 0): self { $length = $step - 1; $substring = mb_substr($this->string, $offset, null, $this->encoding); preg_match_all("/(?:^|(?:.|\p{L}|\w){{$length}})(.|\p{L}|\w)/u", $substring, $matches); return new self(implode($matches[1]), $this->encoding); }
Get every nth character of the string. @param int $step The number of characters to step @param int $offset The string offset to start at
nth
php
PHLAK/Twine
src/Traits/Convenience.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Convenience.php
MIT
public function isEmpty(): bool { return empty($this->string); }
Determine if the string is empty.
isEmpty
php
PHLAK/Twine
src/Traits/Convenience.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Convenience.php
MIT
public function isNotEmpty(): bool { return ! empty($this->string); }
Determine if the string is not empty.
isNotEmpty
php
PHLAK/Twine
src/Traits/Convenience.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Convenience.php
MIT
public function base64(Config\Base64 $mode = Config\Base64::ENCODE): self { return new self(match ($mode) { Config\Base64::ENCODE => base64_encode($this->string), Config\Base64::DECODE => base64_decode($this->string), }, $this->encoding); }
Encode the string to or decode from a base64 encoded value. @param Config\Base64 $mode A base64 mode flag Available base64 modes: - Twine\Config\Base64::ENCODE - Encode the string to base64 - Twin\Config\Base64::DECODE - Decode the string from base64
base64
php
PHLAK/Twine
src/Traits/Encodable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Encodable.php
MIT
public function url(Config\Url $mode = Config\Url::ENCODE): self { return match ($mode) { Config\Url::ENCODE => new self(urlencode($this->string), $this->encoding), Config\Url::DECODE => new self(urldecode($this->string), $this->encoding), }; }
Encode the string to or decode it from a URL safe string. @param Config\Url $mode A url mode flag Available url modes: - Twine\Config\Url::ENCODE - Encode the string to a URL safe string - Twine\Config\Url::DECODE - Decode the string from a URL safe string
url
php
PHLAK/Twine
src/Traits/Encodable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Encodable.php
MIT
public function hex(Config\Hex $mode = Config\Hex::ENCODE): self { $string = match ($mode) { Config\Hex::ENCODE => array_reduce(Support\Str::characters($this->string), function (string $str, string $char) { return $str . '\x' . dechex((int) mb_ord($char, $this->encoding)); }, ''), Config\Hex::DECODE => preg_replace_callback('/\\\\x([0-9A-Fa-f]+)/', function (array $matched) { return (string) mb_chr((int) hexdec($matched[1]), $this->encoding); }, $this->string), }; return new self($string, $this->encoding); }
Encode and decode the string to and from hex. @param Config\Hex $mode A hex mode flag Available hex modes: - Twine\Config\Hex::ENCODE - Encode the string to hex - Twine\Config\Hex::DECODE - Decode the string from hex
hex
php
PHLAK/Twine
src/Traits/Encodable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Encodable.php
MIT
public function encrypt(string $key, string $cipher = 'AES-128-CBC'): self { if (! in_array($cipher, $this->supportedCiphers)) { throw new EncryptionException('The cipher must be one of: ' . implode(', ', $this->supportedCiphers)); } $length = openssl_cipher_iv_length($cipher); if (! $length) { throw new EncryptionException('Failed to get cipher IV length'); } $iv = openssl_random_pseudo_bytes($length); $ciphertext = openssl_encrypt($this->string, $cipher, $key = md5($key), 0, $iv); try { $json = json_encode([ 'iv' => $iv = base64_encode($iv), 'ciphertext' => $ciphertext, 'hmac' => hash_hmac('sha256', $iv . $ciphertext, $key), ], JSON_THROW_ON_ERROR); } catch (JsonException) { throw new EncryptionException('Failed to encrypt the string'); } return new self(base64_encode($json), $this->encoding); }
Encrypt the string. @param string $key The key for encrypting @param string $cipher The cipher method Supported cipher methods: - AES-128-CBC (default) - AES-256-CBC @throws \PHLAK\Twine\Exceptions\EncryptionException
encrypt
php
PHLAK/Twine
src/Traits/Encryptable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Encryptable.php
MIT
public function decrypt(string $key, string $cipher = 'AES-128-CBC'): self { if (! $this->isEncrypted($cipher)) { throw new DecryptionException('The string is not an encrypted string'); } /** @var object{iv: string, ciphertext: string, hmac: string} $payload */ $payload = json_decode(base64_decode($this->string)); $expectedHmac = hash_hmac('sha256', $payload->iv . $payload->ciphertext, $key = md5($key)); if (! hash_equals($payload->hmac, $expectedHmac)) { throw new DecryptionException('The HMAC is invalid'); } $plaintext = openssl_decrypt($payload->ciphertext, $cipher, $key, 0, base64_decode($payload->iv)); if ($plaintext === false) { throw new DecryptionException('Failed to decrypt the string'); } return new self($plaintext, $this->encoding); }
Decrypt the string. @param string $key The key for decrypting @param string $cipher The cipher method Supported cipher methods: - AES-128-CBC (default) - AES-256-CBC @throws \PHLAK\Twine\Exceptions\DecryptionException
decrypt
php
PHLAK/Twine
src/Traits/Encryptable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Encryptable.php
MIT
protected function isEncrypted(string $cipher) { /** @var object{iv?: string, ciphertext?: string, hmac?: string} $payload */ $payload = json_decode(base64_decode($this->string)); return isset($payload->iv, $payload->ciphertext, $payload->hmac) && strlen(base64_decode($payload->iv)) === openssl_cipher_iv_length($cipher); }
Determine if the string is an encrypted string. @return bool True if the string is an encrypted string, otherwise false
isEncrypted
php
PHLAK/Twine
src/Traits/Encryptable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Encryptable.php
MIT
public function crc32(): int { return crc32($this->string); }
Calculate the crc32 polynomial of the string. @return int The crc32 polynomial of the string
crc32
php
PHLAK/Twine
src/Traits/Hashable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Hashable.php
MIT
public function crypt(string $salt): self { return new self(crypt($this->string, $salt), $this->encoding); }
Hash the string using the standard Unix DES-based algorithm or an alternative algorithm that may be available on the system. @param string $salt A salt string to base the hashing on
crypt
php
PHLAK/Twine
src/Traits/Hashable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Hashable.php
MIT
public function md5(Config\Md5 $mode = Config\Md5::DEFAULT): self { return new self(hash('md5', $this->string, $mode === Config\Md5::RAW), $this->encoding); }
Calculate the md5 hash of the string. @param Config\Md5 $mode A md5 mode flag Available md5 modes: - Twine\Config\Md5::DEFAULT - Return the hash - Twine\Config\Md5::RAW - Return the raw binary of the hash
md5
php
PHLAK/Twine
src/Traits/Hashable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Hashable.php
MIT
public function sha1(Config\Sha1 $mode = Config\Sha1::DEFAULT): self { return new self(hash('sha1', $this->string, $mode === Config\Sha1::RAW), $this->encoding); }
Calculate the sha1 hash of the string. @param Config\Sha1 $mode A sha1 mode flag Available sha1 modes: - Twine\Config\Sha1::DEFAULT - Return the hash - Twine\Config\Sha1::RAW - Return the raw binary of the hash
sha1
php
PHLAK/Twine
src/Traits/Hashable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Hashable.php
MIT
public function sha256(Config\Sha256 $mode = Config\Sha256::DEFAULT): self { return new self(hash('sha256', $this->string, $mode === Config\Sha256::RAW), $this->encoding); }
Calculate the sha256 hash of the string. @param Config\Sha256 $mode A sha256 mode flag Available sha256 modes: - Twine\Config\Sha256::DEFAULT - Return the hash - Twine\Config\Sha256::RAW - Return the raw binary of the hash
sha256
php
PHLAK/Twine
src/Traits/Hashable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Hashable.php
MIT
public function bcrypt(array $options = []): self { return new self(password_hash($this->string, PASSWORD_BCRYPT, $options), $this->encoding); }
Creates a hash from the string using the CRYPT_BLOWFISH algorithm. @param array<int|string> $options An array of bcrypt hashing options
bcrypt
php
PHLAK/Twine
src/Traits/Hashable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Hashable.php
MIT
public function append(string ...$strings): self { array_unshift($strings, $this->string); return new self(implode($strings), $this->encoding); }
Append one or more strings to the string. @param string ...$strings One or more strings to append
append
php
PHLAK/Twine
src/Traits/Joinable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Joinable.php
MIT
public function prepend(string ...$strings): self { array_push($strings, $this->string); return new self(implode($strings), $this->encoding); }
Prepend one or more strings to the string. @param string ...$strings One or more strings to prepend
prepend
php
PHLAK/Twine
src/Traits/Joinable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Joinable.php
MIT
public function join(string $string, string $glue = ' ') { return new self($this->string . $glue . $string, $this->encoding); }
Join two strings with another string in between. @param string $string The string to be joined @param string $glue A string to use as the glue @return self
join
php
PHLAK/Twine
src/Traits/Joinable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Joinable.php
MIT
public function match(string $pattern): self { preg_match($pattern, $this->string, $matches); return new self($matches[0], $this->encoding); }
Return the first occurrence of a matched pattern. @param string $pattern The pattern to be matched
match
php
PHLAK/Twine
src/Traits/Searchable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Searchable.php
MIT
public function matchAll(string $pattern): array { preg_match_all($pattern, $this->string, $matches); return array_map(function (string $match) { return new self($match, $this->encoding); }, $matches[0]); }
Return an array of occurrences of a matched pattern. @param string $pattern The pattern to be matched @return list<string>
matchAll
php
PHLAK/Twine
src/Traits/Searchable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Searchable.php
MIT
public function substring(int $start, ?int $length = null): self { $length = isset($length) ? $length : $this->length() - $start; return new self(mb_substr($this->string, $start, $length, $this->encoding), $this->encoding); }
Return part of the string. @param int $start Starting position of the substring @param int|null $length Length of substring
substring
php
PHLAK/Twine
src/Traits/Segmentable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Segmentable.php
MIT
public function from(string $string): self { return new self(mb_strstr($this->string, $string, false, $this->encoding), $this->encoding); }
Return part of the string starting from the first occurrence of another string. @param string $string The string to start from
from
php
PHLAK/Twine
src/Traits/Segmentable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Segmentable.php
MIT
public function to(string $string): self { $substring = mb_strstr($this->string, $string, true, $this->encoding); return new self($substring ? $substring . $string : null, $this->encoding); }
Return part of the string up to and including the first occurrence of another string. @param string $string The string to end with
to
php
PHLAK/Twine
src/Traits/Segmentable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Segmentable.php
MIT
public function truncate(int $length, string $suffix = '...'): self { return new self( $this->first($length - mb_strlen($suffix, $this->encoding))->trimRight()->append($suffix), $this->encoding ); }
Truncate a string to a specific length and append a suffix. @param int $length Length string will be truncated to, including suffix @param string $suffix Suffix to append (default: '...')
truncate
php
PHLAK/Twine
src/Traits/Segmentable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Segmentable.php
MIT
public function chunk(int $length): array { preg_match_all("/(?:.|\p{L}|\w){1,{$length}}/u", $this->string, $chunks); return array_map(function (string $chunk) { return new self($chunk, $this->encoding); }, $chunks[0]); }
Spit the string into an array of chunks of a given length. @param int $length The desired chunk length @return \PHLAK\Twine\Str[]
chunk
php
PHLAK/Twine
src/Traits/Segmentable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Segmentable.php
MIT
public function split(int $chunks): array { $length = ceil($this->length() / $chunks); preg_match_all("/(?:.|\p{L}|\w){1,{$length}}/u", $this->string, $strings); return array_map(function (string $chunk) { return new self($chunk, $this->encoding); }, $strings[0]); }
Split the string into an array containing a specific number of chunks. @param int $chunks The number of chunks @return \PHLAK\Twine\Str[]
split
php
PHLAK/Twine
src/Traits/Segmentable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Segmentable.php
MIT
public function insert(string $string, int $position): self { return new self( mb_substr($this->string, 0, $position, $this->encoding) . $string . mb_substr($this->string, $position, null, $this->encoding), $this->encoding ); }
Insert some text into the string at a given position. @param string $string Text to insert @param int $position Position at which to insert the text
insert
php
PHLAK/Twine
src/Traits/Transformable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Transformable.php
MIT
public function replace(string|array $search, string|array $replace, ?int &$count = null): self { return new self(str_replace($search, $replace, $this->string, $count), $this->encoding); }
Replace parts of the string with another string. @param string|array<string> $search One or more strings to be replaced @param string|array<string> $replace One or more strings to replace with @param int|null $count This will be set to the number of replacements performed
replace
php
PHLAK/Twine
src/Traits/Transformable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Transformable.php
MIT
public function shuffle(): self { $characters = Support\Str::characters($this->string); shuffle($characters); return new self(implode($characters), $this->encoding); }
Randomly shuffle the characters of the string.
shuffle
php
PHLAK/Twine
src/Traits/Transformable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Transformable.php
MIT
public function repeat(int $multiplier, string $glue = ''): self { $strings = array_fill(0, $multiplier, $this->string); return new self(implode($glue, $strings), $this->encoding); }
Repeat the string multiple times. @param int $multiplier Number of times to repeat the string
repeat
php
PHLAK/Twine
src/Traits/Transformable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Transformable.php
MIT
public function wrap(int $width, string $break = "\n", Config\Wrap $mode = Config\Wrap::SOFT): self { return new self(wordwrap($this->string, $width, $break, $mode === Config\Wrap::HARD), $this->encoding); }
Wrap the string to a given number of characters. @param int $width Number of characters at which to wrap @param string $break Character used to break the string @param Config\Wrap $mode A wrap mode flag Available wrap modes: - Twine\Config\Wrap::SOFT - Wrap at the first whitespace character after the specified width (default) - Twine\Config\Wrap::HARD - Always wrap at or before the specified width
wrap
php
PHLAK/Twine
src/Traits/Transformable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Transformable.php
MIT
public function pad(int $length, string $padding = ' ', Config\Pad $mode = Config\Pad::RIGHT): self { $diff = strlen($this->string) - mb_strlen($this->string, $this->encoding); return new self(str_pad($this->string, $length + $diff, $padding, $mode->value), $this->encoding); }
Pad the string to a specific length. @param int $length Length to pad the string to @param string $padding Character to pad the string with @param Config\Pad $mode A pad mode flag Available mode flags: - Twine\Config\Pad::RIGHT - Only pad the right side of the string (default) - Twine\Config\Pad::LEFT - Only pad the left side of the string - Twine\Config\Pad::BOTH - Pad both sides of the string
pad
php
PHLAK/Twine
src/Traits/Transformable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Transformable.php
MIT
public function trim(string $mask = " \t\n\r\0\x0B", Config\Trim $mode = Config\Trim::BOTH): self { return new self(match ($mode) { Config\Trim::BOTH => trim($this->string, $mask), Config\Trim::LEFT => ltrim($this->string, $mask), Config\Trim::RIGHT => rtrim($this->string, $mask), }, $this->encoding); }
Remove white space or a specific set of characters from the beginning and/or end of the string. @param string $mask A list of characters to be stripped (default: " \t\n\r\0\x0B") @param Config\Trim $mode A trim mode flag Available trim modes: - Twine\Config\Trim::BOTH - Trim characters from the beginning and end of the string (default) - Twine\Config\Trim::LEFT - Only trim characters from the beginning of the string - Twine\Config\Trim::RIGHT - Only trim characters from the end of the strring
trim
php
PHLAK/Twine
src/Traits/Transformable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Transformable.php
MIT
public function strip(string|array $search): self { return $this->replace($search, ''); }
Remove one or more strings from the string. @param string|array<string> $search One or more strings to be removed
strip
php
PHLAK/Twine
src/Traits/Transformable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Transformable.php
MIT
public function isAlphanumeric(): bool { return ctype_alnum($this->string); }
Determine if the string is composed of alphanumeric characters.
isAlphanumeric
php
PHLAK/Twine
src/Traits/Typeable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Typeable.php
MIT
public function isAlphabetic(): bool { return ctype_alpha($this->string); }
Determine if the string is composed of alphabetic characters.
isAlphabetic
php
PHLAK/Twine
src/Traits/Typeable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Typeable.php
MIT
public function isNumeric(): bool { return ctype_digit($this->string); }
Determine if the string is composed of numeric characters.
isNumeric
php
PHLAK/Twine
src/Traits/Typeable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Typeable.php
MIT
public function isLowercase(): bool { return ctype_lower($this->string); }
Determine if the string is composed of lowercase characters.
isLowercase
php
PHLAK/Twine
src/Traits/Typeable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Typeable.php
MIT
public function isUppercase(): bool { return ctype_upper($this->string); }
Determine if the string is composed of uppercase characters.
isUppercase
php
PHLAK/Twine
src/Traits/Typeable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Typeable.php
MIT
public function isWhitespace(): bool { return ctype_space($this->string); }
Determine if the string is composed of whitespace characters.
isWhitespace
php
PHLAK/Twine
src/Traits/Typeable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Typeable.php
MIT
public function isPunctuation(): bool { return ctype_punct($this->string); }
Determine if the string is composed of punctuation characters.
isPunctuation
php
PHLAK/Twine
src/Traits/Typeable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Typeable.php
MIT
public function isPrintable(): bool { return ctype_print($this->string); }
Determine if the string is composed of printable characters.
isPrintable
php
PHLAK/Twine
src/Traits/Typeable.php
https://github.com/PHLAK/Twine/blob/master/src/Traits/Typeable.php
MIT
protected function hasDsnSet(): bool { $config = $this->getUserConfig(); return !empty($config['dsn']); }
Check if a DSN was set in the config. @return bool
hasDsnSet
php
getsentry/sentry-laravel
src/Sentry/Laravel/BaseServiceProvider.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/BaseServiceProvider.php
MIT
protected function hasSpotlightEnabled(): bool { $config = $this->getUserConfig(); return ($config['spotlight'] ?? false) === true; }
Check if Spotlight was enabled in the config. @return bool
hasSpotlightEnabled
php
getsentry/sentry-laravel
src/Sentry/Laravel/BaseServiceProvider.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/BaseServiceProvider.php
MIT
protected function getUserConfig(): array { $config = $this->app['config'][static::$abstract]; return empty($config) ? [] : $config; }
Retrieve the user configuration. @return array
getUserConfig
php
getsentry/sentry-laravel
src/Sentry/Laravel/BaseServiceProvider.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/BaseServiceProvider.php
MIT
protected function couldHavePerformanceTracingEnabled(): bool { $config = $this->getUserConfig(); return !empty($config['traces_sample_rate']) || !empty($config['traces_sampler']) || ($config['spotlight'] ?? false) === true; }
Checks if the config is set in such a way that performance tracing could be enabled. Because of `traces_sampler` being dynamic we can never be 100% confident but that is also not important. @deprecated since version 4.6. To be removed in version 5.0. @return bool
couldHavePerformanceTracingEnabled
php
getsentry/sentry-laravel
src/Sentry/Laravel/BaseServiceProvider.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/BaseServiceProvider.php
MIT
public function __construct(Container $container, array $config) { $this->container = $container; $this->recordSqlQueries = ($config['breadcrumbs.sql_queries'] ?? $config['breadcrumbs']['sql_queries'] ?? true) === true; $this->recordSqlBindings = ($config['breadcrumbs.sql_bindings'] ?? $config['breadcrumbs']['sql_bindings'] ?? false) === true; $this->recordLaravelLogs = ($config['breadcrumbs.logs'] ?? $config['breadcrumbs']['logs'] ?? true) === true; $this->recordOctaneTickInfo = ($config['breadcrumbs.octane_tick_info'] ?? $config['breadcrumbs']['octane_tick_info'] ?? true) === true; $this->recordOctaneTaskInfo = ($config['breadcrumbs.octane_task_info'] ?? $config['breadcrumbs']['octane_task_info'] ?? true) === true; }
EventHandler constructor. @param \Illuminate\Contracts\Container\Container $container @param array $config
__construct
php
getsentry/sentry-laravel
src/Sentry/Laravel/EventHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/EventHandler.php
MIT
public function __call(string $method, array $arguments) { $handlerMethod = "{$method}Handler"; if (!method_exists($this, $handlerMethod)) { throw new RuntimeException("Missing event handler: {$handlerMethod}"); } try { $this->{$handlerMethod}(...$arguments); } catch (Exception $exception) { // Ignore } }
Pass through the event and capture any errors. @param string $method @param array $arguments
__call
php
getsentry/sentry-laravel
src/Sentry/Laravel/EventHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/EventHandler.php
MIT
private function configureUserScopeFromModel($authUser): void { $userData = []; // If the user is a Laravel Eloquent model we try to extract some common fields from it if ($authUser instanceof Model) { $email = null; if ($this->modelHasAttribute($authUser, 'email')) { $email = $authUser->getAttribute('email'); } elseif ($this->modelHasAttribute($authUser, 'mail')) { $email = $authUser->getAttribute('mail'); } $username = $this->modelHasAttribute($authUser, 'username') ? (string)$authUser->getAttribute('username') : null; $userData = [ 'id' => $authUser instanceof Authenticatable ? $authUser->getAuthIdentifier() : $authUser->getKey(), 'email' => $email, 'username' => $username, ]; } try { /** @var \Illuminate\Http\Request $request */ $request = $this->container->make('request'); if ($request instanceof Request) { $ipAddress = $request->ip(); if ($ipAddress !== null) { $userData['ip_address'] = $ipAddress; } } } catch (BindingResolutionException $e) { // If there is no request bound we cannot get the IP address from it } Integration::configureScope(static function (Scope $scope) use ($userData): void { $scope->setUser(array_filter($userData)); }); }
Configures the user scope with the user data and values from the HTTP request. @param mixed $authUser @return void
configureUserScopeFromModel
php
getsentry/sentry-laravel
src/Sentry/Laravel/EventHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/EventHandler.php
MIT
private function logLevelToBreadcrumbLevel(string $level): string { switch (strtolower($level)) { case 'debug': return Breadcrumb::LEVEL_DEBUG; case 'warning': return Breadcrumb::LEVEL_WARNING; case 'error': return Breadcrumb::LEVEL_ERROR; case 'critical': case 'alert': case 'emergency': return Breadcrumb::LEVEL_FATAL; case 'info': case 'notice': default: return Breadcrumb::LEVEL_INFO; } }
Translates common log levels to Sentry breadcrumb levels. @param string $level Log level. Maybe any standard. @return string Breadcrumb level.
logLevelToBreadcrumbLevel
php
getsentry/sentry-laravel
src/Sentry/Laravel/EventHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/EventHandler.php
MIT
private function afterTaskWithinLongRunningProcess(): void { Integration::flushEvents(); }
Should be called after a task within a long running process has ended so events can be flushed.
afterTaskWithinLongRunningProcess
php
getsentry/sentry-laravel
src/Sentry/Laravel/EventHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/EventHandler.php
MIT
private function prepareScopeForTaskWithinLongRunningProcess(): void { SentrySdk::getCurrentHub()->pushScope(); // When a job starts, we want to make sure the scope is cleared of breadcrumbs SentrySdk::getCurrentHub()->configureScope(static function (Scope $scope) { $scope->clearBreadcrumbs(); }); }
Should be called before starting a task within a long running process, this is done to prevent the task to have effect on the scope for the next task to run within the long running process.
prepareScopeForTaskWithinLongRunningProcess
php
getsentry/sentry-laravel
src/Sentry/Laravel/EventHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/EventHandler.php
MIT
private function cleanupScopeForTaskWithinLongRunningProcessWhen(bool $when): void { if (!$when) { return; } $this->afterTaskWithinLongRunningProcess(); SentrySdk::getCurrentHub()->popScope(); }
Cleanup a previously prepared scope. @param bool $when Only cleanup the scope when this is true. @see prepareScopeForTaskWithinLongRunningProcess
cleanupScopeForTaskWithinLongRunningProcessWhen
php
getsentry/sentry-laravel
src/Sentry/Laravel/EventHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/EventHandler.php
MIT
public static function handles(Exceptions $exceptions): void { $exceptions->reportable(static function (Throwable $exception) { self::captureUnhandledException($exception); }); }
Convenience method to register the exception handler with Laravel 11.0 and up.
handles
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function addBreadcrumb(Breadcrumb $breadcrumb): void { $self = SentrySdk::getCurrentHub()->getIntegration(self::class); if (!$self instanceof self) { return; } addBreadcrumb($breadcrumb); }
Adds a breadcrumb if the integration is enabled for Laravel. @param Breadcrumb $breadcrumb
addBreadcrumb
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function configureScope(callable $callback): void { $self = SentrySdk::getCurrentHub()->getIntegration(self::class); if (!$self instanceof self) { return; } configureScope($callback); }
Configures the scope if the integration is enabled for Laravel. @param callable $callback
configureScope
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function flushEvents(): void { $client = SentrySdk::getCurrentHub()->getClient(); if ($client !== null) { $client->flush(); Logs::getInstance()->flush(); } }
Block until all events are processed by the PHP SDK client. @internal This is not part of the public API and is here temporarily until the underlying issue can be resolved, this method will be removed.
flushEvents
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function extractNameAndSourceForRoute(Route $route): array { return [ '/' . ltrim($route->uri(), '/'), TransactionSource::route(), ]; }
Extract the readable name for a route and the transaction source for where that route name came from. @param \Illuminate\Routing\Route $route @return array{0: string, 1: \Sentry\Tracing\TransactionSource} @internal This helper is used in various places to extract meaningful info from a Laravel Route object.
extractNameAndSourceForRoute
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function extractNameAndSourceForLumenRoute(array $routeData, string $path): array { $routeUri = array_reduce( array_keys($routeData[2]), static function ($carry, $key) use ($routeData) { $search = '/' . preg_quote($routeData[2][$key], '/') . '/'; // Replace the first occurrence of the route parameter value with the key name // This is by no means a perfect solution, but it's the best we can do with the data we have return preg_replace($search, "{{$key}}", $carry, 1); }, $path ); return [ '/' . ltrim($routeUri, '/'), TransactionSource::route(), ]; }
Extract the readable name for a Lumen route and the transaction source for where that route name came from. @param array $routeData The array of route data @param string $path The path of the request @return array{0: string, 1: \Sentry\Tracing\TransactionSource} @internal This helper is used in various places to extract meaningful info from Lumen route data.
extractNameAndSourceForLumenRoute
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function sentryMeta(): string { return self::sentryTracingMeta() . self::sentryW3CTracingMeta() . self::sentryBaggageMeta(); }
Retrieve the meta tags with tracing information to link this request to front-end requests. This propagates the Dynamic Sampling Context. @return string
sentryMeta
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function sentryTracingMeta(): string { return sprintf('<meta name="sentry-trace" content="%s"/>', getTraceparent()); }
Retrieve the `sentry-trace` meta tag with tracing information to link this request to front-end requests. @return string
sentryTracingMeta
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function sentryW3CTracingMeta(): string { return ''; }
Retrieve the `traceparent` meta tag with tracing information to link this request to front-end requests. @deprecated since version 4.14. To be removed in version 5.0. @return string
sentryW3CTracingMeta
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function sentryBaggageMeta(): string { return sprintf('<meta name="baggage" content="%s"/>', getBaggage()); }
Retrieve the `baggage` meta tag with information to link this request to front-end requests. This propagates the Dynamic Sampling Context. @return string
sentryBaggageMeta
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function captureUnhandledException(Throwable $throwable): ?EventId { // We instruct users to call `captureUnhandledException` in their exception handler, however this does not mean // the exception was actually unhandled. Laravel has the `report` helper function that is used to report to a log // file or Sentry, but that means they are handled otherwise they wouldn't have been routed through `report`. So to // prevent marking those as "unhandled" we try and make an educated guess if the call to `captureUnhandledException` // came from the `report` helper and shouldn't be marked as "unhandled" even though the come to us here to be reported $handled = self::makeAnEducatedGuessIfTheExceptionMaybeWasHandled(); $hint = EventHint::fromArray([ 'mechanism' => new ExceptionMechanism(ExceptionMechanism::TYPE_GENERIC, $handled), ]); return SentrySdk::getCurrentHub()->captureException($throwable, $hint); }
Capture a unhandled exception and report it to Sentry. @param \Throwable $throwable @return \Sentry\EventId|null
captureUnhandledException
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function missingAttributeViolationReporter(?callable $callback = null, bool $suppressDuplicateReports = true, bool $reportAfterResponse = true): callable { return new ModelViolationReports\MissingAttributeModelViolationReporter($callback, $suppressDuplicateReports, $reportAfterResponse); }
Returns a callback that can be passed to `Model::handleMissingAttributeViolationUsing` to report missing attribute violations to Sentry. @param callable|null $callback Optional callback to be called after the violation is reported to Sentry. @param bool $suppressDuplicateReports Whether to suppress duplicate reports of the same violation. @param bool $reportAfterResponse Whether to delay sending the report to after the response has been sent. @return callable
missingAttributeViolationReporter
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function lazyLoadingViolationReporter(?callable $callback = null, bool $suppressDuplicateReports = true, bool $reportAfterResponse = true): callable { return new ModelViolationReports\LazyLoadingModelViolationReporter($callback, $suppressDuplicateReports, $reportAfterResponse); }
Returns a callback that can be passed to `Model::handleLazyLoadingViolationUsing` to report lazy loading violations to Sentry. @param callable|null $callback Optional callback to be called after the violation is reported to Sentry. @param bool $suppressDuplicateReports Whether to suppress duplicate reports of the same violation. @param bool $reportAfterResponse Whether to delay sending the report to after the response has been sent. @return callable
lazyLoadingViolationReporter
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public static function discardedAttributeViolationReporter(?callable $callback = null, bool $suppressDuplicateReports = true, bool $reportAfterResponse = true): callable { return new ModelViolationReports\DiscardedAttributeViolationReporter($callback, $suppressDuplicateReports, $reportAfterResponse); }
Returns a callback that can be passed to `Model::handleDiscardedAttributeViolationUsing` to report discarded attribute violations to Sentry. @param callable|null $callback Optional callback to be called after the violation is reported to Sentry. @param bool $suppressDuplicateReports Whether to suppress duplicate reports of the same violation. @param bool $reportAfterResponse Whether to delay sending the report to after the response has been sent. @return callable
discardedAttributeViolationReporter
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
private static function makeAnEducatedGuessIfTheExceptionMaybeWasHandled(): bool { // We limit the amount of backtrace frames since it is very unlikely to be any deeper $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 20); // We are looking for `$handler->report()` to be called from the `report()` function foreach ($trace as $frameIndex => $frame) { // We need a frame with a class and function defined, we can skip frames missing either if (!isset($frame['class'], $frame['function'])) { continue; } // Check if the frame was indeed `$handler->report()` if ($frame['type'] !== '->' || $frame['function'] !== 'report') { continue; } // Make sure we have a next frame, we could have reached the end of the trace if (!isset($trace[$frameIndex + 1])) { continue; } // The next frame should contain the call to the `report()` helper function $nextFrame = $trace[$frameIndex + 1]; // If a class was set or the function name is not `report` we can skip this frame if (isset($nextFrame['class']) || !isset($nextFrame['function']) || $nextFrame['function'] !== 'report') { continue; } // If we reached this point we can be pretty sure the `report` function was called // and we can come to the educated conclusion the exception was indeed handled return true; } // If we reached this point we can be pretty sure the `report` function was not called return false; }
Try to make an educated guess if the call came from the Laravel `report` helper. @see https://github.com/laravel/framework/blob/008a4dd49c3a13343137d2bc43297e62006c7f29/src/Illuminate/Foundation/helpers.php#L667-L682 @return bool
makeAnEducatedGuessIfTheExceptionMaybeWasHandled
php
getsentry/sentry-laravel
src/Sentry/Laravel/Integration.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration.php
MIT
public function __construct(HubInterface $hub, $level = Logger::DEBUG, bool $bubble = true, bool $reportExceptions = true, bool $useFormattedMessage = false) { parent::__construct($level, $bubble); $this->hub = $hub; $this->reportExceptions = $reportExceptions; $this->useFormattedMessage = $useFormattedMessage; }
@param HubInterface $hub @param int $level The minimum logging level at which this handler will be triggered @param bool $bubble Whether the messages that are handled can bubble up the stack or not @param bool $reportExceptions @param bool $useFormattedMessage
__construct
php
getsentry/sentry-laravel
src/Sentry/Laravel/SentryHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/SentryHandler.php
MIT
public function setBatchFormatter(FormatterInterface $formatter): self { $this->batchFormatter = $formatter; return $this; }
Sets the formatter for the logs generated by handleBatch(). @param FormatterInterface $formatter @return \Sentry\Laravel\SentryHandler
setBatchFormatter
php
getsentry/sentry-laravel
src/Sentry/Laravel/SentryHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/SentryHandler.php
MIT
public function getBatchFormatter(): FormatterInterface { if (!$this->batchFormatter) { $this->batchFormatter = $this->getDefaultBatchFormatter(); } return $this->batchFormatter; }
Gets the formatter for the logs generated by handleBatch().
getBatchFormatter
php
getsentry/sentry-laravel
src/Sentry/Laravel/SentryHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/SentryHandler.php
MIT
protected function getLogLevel(int $logLevel): Severity { return $this->getSeverityFromLevel($logLevel); }
Translates Monolog log levels to Sentry Severity. @param int $logLevel @return \Sentry\Severity
getLogLevel
php
getsentry/sentry-laravel
src/Sentry/Laravel/SentryHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/SentryHandler.php
MIT
protected function getDefaultBatchFormatter(): FormatterInterface { return new LineFormatter(); }
Gets the default formatter for the logs generated by handleBatch(). @return FormatterInterface
getDefaultBatchFormatter
php
getsentry/sentry-laravel
src/Sentry/Laravel/SentryHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/SentryHandler.php
MIT
public function setRelease($value): self { $this->release = $value; return $this; }
Set the release. @param string $value @return self
setRelease
php
getsentry/sentry-laravel
src/Sentry/Laravel/SentryHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/SentryHandler.php
MIT
public function setEnvironment($value): self { $this->environment = $value; return $this; }
Set the current application environment. @param string $value @return self
setEnvironment
php
getsentry/sentry-laravel
src/Sentry/Laravel/SentryHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/SentryHandler.php
MIT
public function addBreadcrumb(Breadcrumb $crumb): self { $this->hub->addBreadcrumb($crumb); return $this; }
Add a breadcrumb. @link https://docs.sentry.io/learn/breadcrumbs/ @param \Sentry\Breadcrumb $crumb @return \Sentry\Laravel\SentryHandler
addBreadcrumb
php
getsentry/sentry-laravel
src/Sentry/Laravel/SentryHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/SentryHandler.php
MIT
private function consumeContextAndApplyToScope(Scope $scope, array &$context): void { if (!empty($context['extra']) && is_array($context['extra'])) { foreach ($context['extra'] as $key => $value) { $scope->setExtra($key, $value); } unset($context['extra']); } if (!empty($context['tags']) && is_array($context['tags'])) { foreach ($context['tags'] as $tag => $value) { // Ignore tags with a value that is not a string or can be casted to a string if (!$this->valueCanBeString($value)) { continue; } $scope->setTag($tag, (string)$value); } unset($context['tags']); } if (!empty($context['fingerprint']) && is_array($context['fingerprint'])) { $scope->setFingerprint($context['fingerprint']); unset($context['fingerprint']); } if (!empty($context['user']) && is_array($context['user'])) { try { $scope->setUser($context['user']); unset($context['user']); } catch (TypeError $e) { // In some cases the context can be invalid, in that case we ignore it and // choose to not send it to Sentry in favor of not breaking the application } } }
Consumes the context and applies it to the scope. @param \Sentry\State\Scope $scope @param array $context @return void
consumeContextAndApplyToScope
php
getsentry/sentry-laravel
src/Sentry/Laravel/SentryHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/SentryHandler.php
MIT
private function valueCanBeString($value): bool { return is_string($value) || is_scalar($value) || (is_object($value) && method_exists($value, '__toString')); }
Check if the value passed can be cast to a string. @param mixed $value @return bool
valueCanBeString
php
getsentry/sentry-laravel
src/Sentry/Laravel/SentryHandler.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/SentryHandler.php
MIT
protected function bindEvents(): void { $userConfig = $this->getUserConfig(); $handler = new EventHandler($this->app, $userConfig); try { /** @var \Illuminate\Contracts\Events\Dispatcher $dispatcher */ $dispatcher = $this->app->make(Dispatcher::class); $handler->subscribe($dispatcher); if ($this->app->bound('octane')) { $handler->subscribeOctaneEvents($dispatcher); } if (isset($userConfig['send_default_pii']) && $userConfig['send_default_pii'] !== false) { $handler->subscribeAuthEvents($dispatcher); } } catch (BindingResolutionException $e) { // If we cannot resolve the event dispatcher we also cannot listen to events } }
Bind to the Laravel event dispatcher to log events.
bindEvents
php
getsentry/sentry-laravel
src/Sentry/Laravel/ServiceProvider.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/ServiceProvider.php
MIT
protected function registerFeatures(): void { // Register all the features as singletons, so there is only one instance of each feature in the application foreach (self::FEATURES as $feature) { $this->app->singleton($feature); } foreach (self::FEATURES as $feature) { try { /** @var Feature $featureInstance */ $featureInstance = $this->app->make($feature); $featureInstance->register(); } catch (Throwable $e) { // Ensure that features do not break the whole application } } }
Bind and register all the features.
registerFeatures
php
getsentry/sentry-laravel
src/Sentry/Laravel/ServiceProvider.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/ServiceProvider.php
MIT
protected function registerAboutCommandIntegration(): void { // The about command is only available in Laravel 9 and up so we need to check if it's available to us if (!class_exists(AboutCommand::class)) { return; } AboutCommand::add('Sentry', AboutCommandIntegration::class); }
Register the `php artisan about` command integration.
registerAboutCommandIntegration
php
getsentry/sentry-laravel
src/Sentry/Laravel/ServiceProvider.php
https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/ServiceProvider.php
MIT