sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function getInstalledPackages()
{
$packages = [];
$content = $this->getFileContents('composer.lock');
foreach (['packages', 'packages-dev'] as $key) {
if (!isset($content[$key])) {
continue;
}
foreach ($content[$key] as $package) {
$name = $package['name'];
$packages[$name] = [
'name' => $name,
'version' => $package['version'],
'devDependency' => $key === 'packages-dev',
];
}
}
if (empty($packages)) {
throw new LogicException('We couldn\'t find any installed packages.');
}
return $packages;
} | Get installed package versions.
@throws \LogicException
@return array | entailment |
public function getRequiredPackages()
{
$packages = [];
$content = $this->getFileContents('composer.json');
foreach (['require', 'require-dev'] as $key) {
if (!isset($content[$key])) {
continue;
}
foreach ($content[$key] as $name => $version) {
if (!strstr($name, '/')) {
continue;
}
$packages[$name] = [
'name' => $name,
'version' => $version,
'devDependency' => $key === 'require-dev',
];
}
}
if (empty($packages)) {
throw new LogicException('We couldn\'t find any required packages.');
}
return $packages;
} | Get required package versions.
@throws \LogicException
@return array | entailment |
protected function getFileContents($file)
{
$filePath = $this->directory.'/'.$file;
if (!file_exists($filePath)) {
throw new InvalidArgumentException("The file [$filePath] does not exist.");
}
return json_decode(file_get_contents($filePath), true);
} | Get file content.
@param string $file
@throws \InvalidArgumentException
@return array | entailment |
protected function getVariables()
{
foreach ($this->fields as $field) {
$field->fill($this->data);
}
return [
'fields' => $this->fields,
'attributes' => $this->formatAttribute(),
'method' => $this->attributes['method'],
];
} | Get variables for render form.
@return array | entailment |
public function versionDiff($current, $latest)
{
$needle = 0;
while ($needle < strlen($current) && $needle < strlen($latest)) {
if ($current[$needle] !== $latest[$needle]) {
break;
}
$needle++;
}
return substr($latest, 0, $needle).'<green>'.substr($latest, $needle).'</green>';
} | Get the diff between the current and latest version.
@param string $current
@param string $latest
@return string | entailment |
protected function getComposerPathFromInput(InputInterface $input)
{
if ($input->getOption('directory')) {
return $input->getOption('directory');
}
if ($input->getOption('global')) {
return getenv('HOME').'/.composer';
}
} | Get composer path based on user input.
@param \Symfony\Component\Console\Input\InputInterface $input
@return null|string | entailment |
public function getNewRegistrationIds()
{
if ($this->getNewRegistrationIdsCount() == 0) {
return array();
}
$filteredResults = array_filter(
$this->results,
function ($result) {
return isset($result['registration_id']);
}
);
$data = array_map(function ($result) {
return $result['registration_id'];
}, $filteredResults);
return $data;
} | Return an array of expired registration ids linked to new id
All old registration ids must be updated to new ones in DB
@return array oldRegistrationId => newRegistrationId | entailment |
public function getUnavailableRegistrationIds()
{
if ($this->getFailureCount() == 0) {
return array();
}
$filteredResults = array_filter(
$this->results,
function ($result) {
return (
isset($result['error'])
&&
($result['error'] == "Unavailable")
);
}
);
return array_keys($filteredResults);
} | Returns an array of registration ids for which you must resend a message (?),
cause devices aren't available now.
@TODO: check if it be auto sent later
@return array | entailment |
public function register_control( \WP_Customize_Manager $wp_customize ) {
$this->args['type'] = 'upload';
$wp_customize->add_control(
new \WP_Customize_Upload_Control(
$wp_customize,
$this->get_id(),
$this->_generate_register_control_args()
)
);
} | Add control
@param WP_Customize_Manager $wp_customize
@see https://developer.wordpress.org/reference/classes/wp_customize_manager/add_control/
@see https://developer.wordpress.org/reference/classes/wp_customize_manager/add_setting/ | entailment |
public function chunk($callback, $count = 100)
{
if ($this->usePaginate) {
return $this->buildData(false)->chunk($count)->each($callback);
}
$this->setSort();
$this->queries->reject(function ($query) {
return 'paginate' === $query['method'];
})->each(function ($query) {
$this->model = $this->model->{$query['method']}(...$query['arguments']);
});
return $this->model->chunk($count, $callback);
} | @param callable $callback
@param int $count
@return bool | entailment |
protected function resolvePerPage($paginate)
{
if ($perPage = app('request')->input($this->perPageName)) {
if (is_array($paginate)) {
$paginate['arguments'][0] = (int) $perPage;
return $paginate['arguments'];
}
$this->perPage = (int) $perPage;
}
if (isset($paginate['arguments'][0])) {
return $paginate['arguments'];
}
return [$this->perPage];
} | Resolve perPage for pagination.
@param array|null $paginate
@return array | entailment |
protected function setSort()
{
$this->sort = Input::get($this->sortName, []);
if (!is_array($this->sort)) {
return;
}
if (empty($this->sort['column']) || empty($this->sort['type'])) {
return;
}
if (str_contains($this->sort['column'], '.')) {
$this->setRelationSort($this->sort['column']);
} else {
$this->resetOrderBy();
$this->queries->push([
'method' => 'orderBy',
'arguments' => [$this->sort['column'], $this->sort['type']],
]);
}
} | Set the grid sort. | entailment |
protected function setRelationSort($column)
{
list($relationName, $relationColumn) = explode('.', $column);
if ($this->queries->contains(function ($query) use ($relationName) {
return 'with' === $query['method'] && in_array($relationName, $query['arguments'], true);
})) {
$relation = $this->model->$relationName();
$this->queries->push([
'method' => 'join',
'arguments' => $this->joinParameters($relation),
]);
$this->resetOrderBy();
$this->queries->push([
'method' => 'orderBy',
'arguments' => [
$relation->getRelated()->getTable().'.'.$relationColumn,
$this->sort['type'],
],
]);
}
} | Set relation sort.
@param string $column | entailment |
protected function joinParameters(Relation $relation)
{
$relatedTable = $relation->getRelated()->getTable();
if ($relation instanceof BelongsTo) {
return [
$relatedTable,
$relation->getForeignKey(),
'=',
$relatedTable.'.'.$relation->getRelated()->getKeyName(),
];
}
if ($relation instanceof HasOne) {
return [
$relatedTable,
$relation->getQualifiedParentKeyName(),
'=',
$relation->getQualifiedForeignKeyName(),
];
}
throw new \Exception('Related sortable only support `HasOne` and `BelongsTo` relation.');
} | Build join parameters for related model.
`HasOne` and `BelongsTo` relation has different join parameters.
@param Relation $relation
@throws \Exception
@return array | entailment |
public function _amp_post_template_css() {
ob_start();
$this->_print_front_styles();
$css = ob_get_clean();
$css = str_replace( '!important', '', $css );
// @codingStandardsIgnoreStart
echo $css;
// @codingStandardsIgnoreEnd
} | Styles for AMP
@return void | entailment |
public function _tiny_mce_before_init( $mce_init ) {
$styles = WP_Customizer_Framework\Style::get_registerd_styles();
if ( ! isset( $mce_init['content_style'] ) ) {
$mce_init['content_style'] = '';
}
foreach ( $styles as $style ) {
foreach ( $style['selectors'] as $i => $selector ) {
$selector = trim( $selector );
if ( preg_match( '|^[\.#>]|', $selector ) ) {
$style['selectors'][ $i ] = '.mce-content-body.mceContentBody ' . $selector;
} else {
$style['selectors'][ $i ] = $selector;
}
}
$selectors = addslashes( implode( ',', $style['selectors'] ) );
$properties = addslashes( implode( ';', $style['properties'] ) );
if ( ! $style['media_query'] ) {
$mce_init['content_style'] .= "{$selectors} { {$properties} }";
} else {
$mce_init['content_style'] .= "{$style['media_query']} { {$selectors} { {$properties} } }";
}
}
return $mce_init;
} | Styles for TinyMCE
@param array $mce_init
@return array | entailment |
public function _print_gutenberg_styles() {
$styles = WP_Customizer_Framework\Style::get_registerd_styles();
$new_styles = [];
foreach ( $styles as $styles_index => $style ) {
foreach ( $style['selectors'] as $selectors_index => $selector ) {
$selector = trim( $selector );
$style['selectors'][ $selectors_index ] = '.edit-post-layout__content .editor-styles-wrapper ' . $selector;
}
$new_styles[ $styles_index ] = $style;
}
$this->_print_styles( $new_styles );
} | Print styles for Gutenberg
@return void | entailment |
protected function _print_styles( $styles ) {
foreach ( $styles as $style ) {
$selectors = implode( ',', $style['selectors'] );
$properties = implode( ';', $style['properties'] );
if ( ! $style['media_query'] ) {
printf(
'%1$s { %2$s }',
// @todo
// @codingStandardsIgnoreStart
strip_tags( $selectors ),
str_replace( '"', '"', esc_textarea( $properties ) )
// @codingStandardsIgnoreEnd
);
} else {
printf(
'%1$s { %2$s { %3$s } }',
esc_html( $style['media_query'] ),
// @todo
// @codingStandardsIgnoreStart
strip_tags( $selectors ),
str_replace( '"', '"', esc_textarea( $properties ) )
// @codingStandardsIgnoreEnd
);
}
}
} | Print styles in head
@param array $styles
@return void | entailment |
public function getResults()
{
if(!$this->statManager->checkStatus()){
$this->runValidation($this->options);
}
return $this->statManager->getStatus();
} | Returns results
@return array | entailment |
public function edit($channelId, $typeId, $type, $allow = null, $deny = null)
{
$current = $this->show($channelId, $typeId, $type);
if (is_null($current)) {
return $this->create($channelId, $typeId, $type, $allow, $deny);
}
if (is_null($allow)) {
$allow = $current['allow'];
}
if (is_null($deny)) {
$deny = $current['deny'];
}
return $this->request('PUT', 'channels/' . $channelId . '/permissions/' . $typeId, [
'json' => [
'type' => $current['type'],
'id' => $current['id'],
'allow' => $allow,
'deny' => $deny
]
]);
} | Edit channel permissions.
@param string $channelId
@param string $typeId
@param string $type
@param null $allow
@param null $deny
@return array | entailment |
public function setEmailsDomains(BagHelper $emailBag)
{
$domainBag = new BagHelper();
foreach ($emailBag as $key => $emails) {
foreach ($emails as $email) {
$mail = new Email($email);
list($user, $domain) = $mail->parse();
$domainBag->set($domain, $user, false);
}
}
return $domainBag;
} | Sets the email addresses that should be validated.
@param BagHelper $emailBag
@return BagHelper $domainBag | entailment |
public function setSender($email)
{
$mail = new Email($email);
$parts = $mail->parse();
$this->fromUser = $parts[0];
$this->fromDomain = $parts[1];
} | Sets the email address to use as the sender/validator.
@param string $email
@return void | entailment |
public function register( $selectors, $properties, $media_query = null ) {
Style::register( $selectors, $properties, $media_query );
} | Registers style setting
@param string|array $selectors
@param string|array $properties
@param string $media_query
@return void | entailment |
protected function _color_luminance( $hex, $percent ) {
$hex = $this->_hex_normalization( $hex );
$hue = $this->_get_hue( $hex );
$saturation = $this->_get_saturation( $hex );
$luminance = $this->_get_luminance( $hex );
// Add luminance.
$luminance += $percent * 100;
$luminance = ( 100 < $luminance ) ? 100 : $luminance;
$luminance = ( 0 > $luminance ) ? 0 : $luminance;
$hex = $this->_convert_hsl_to_hex( $hue, $saturation, $luminance );
return $hex;
} | Change brightness
@param hex $hex
@param int $percent
@return hex | entailment |
protected function _hex_normalization( $hex ) {
$hex = preg_replace( '/[^0-9a-f]/i', '', ltrim( $hex, '#' ) );
if ( strlen( $hex ) < 6 ) {
$hex = $hex[0] + $hex[0] + $hex[1] + $hex[1] + $hex[2] + $hex[2];
}
return $hex;
} | Normalize hex
.e.g #000000 -> 000000
.e.g #000 -> 000000
@param hex $hex
@return hex | entailment |
private function _get_hue( $hex ) {
$red = hexdec( substr( $hex, 0, 2 ) );
$green = hexdec( substr( $hex, 2, 2 ) );
$blue = hexdec( substr( $hex, 4, 2 ) );
$max_rgb = max( $red, $green, $blue );
$min_rgb = min( $red, $green, $blue );
if ( $red === $green && $red === $blue ) {
return 0;
}
$diff_max_min_rgb = $max_rgb - $min_rgb;
if ( $red === $max_rgb ) {
$hue = 60 * ( $diff_max_min_rgb ? ( $green - $blue ) / $diff_max_min_rgb : 0 );
} elseif ( $green === $max_rgb ) {
$hue = 60 * ( $diff_max_min_rgb ? ( $blue - $red ) / $diff_max_min_rgb : 0 ) + 120;
} elseif ( $blue === $max_rgb ) {
$hue = 60 * ( $diff_max_min_rgb ? ( $red - $green ) / $diff_max_min_rgb : 0 ) + 240;
}
if ( 0 > $hue ) {
$hue += 360;
}
return $hue;
} | Return hue from hex
@SuppressWarnings(PHPMD.CyclomaticComplexity)
@param hex $hex
@return hue | entailment |
private function _convert_hsl_to_hex( $hue, $saturation, $luminance ) {
if ( 49 >= $luminance ) {
$max_hsl = 2.55 * ( $luminance + $luminance * ( $saturation / 100 ) );
$min_hsl = 2.55 * ( $luminance - $luminance * ( $saturation / 100 ) );
} else {
$max_hsl = 2.55 * ( $luminance + ( 100 - $luminance ) * ( $saturation / 100 ) );
$min_hsl = 2.55 * ( $luminance - ( 100 - $luminance ) * ( $saturation / 100 ) );
}
if ( 60 >= $hue ) {
$red = $max_hsl;
$green = ( $hue / 60 ) * ( $max_hsl - $min_hsl ) + $min_hsl;
$blue = $min_hsl;
} elseif ( 120 >= $hue ) {
$red = ( ( 120 - $hue ) / 60 ) * ( $max_hsl - $min_hsl ) + $min_hsl;
$green = $max_hsl;
$blue = $min_hsl;
} elseif ( 180 >= $hue ) {
$red = $min_hsl;
$green = $max_hsl;
$blue = ( ( $hue - 120 ) / 60 ) * ( $max_hsl - $min_hsl ) + $min_hsl;
} elseif ( 240 >= $hue ) {
$red = $min_hsl;
$green = ( ( 240 - $hue ) / 60 ) * ( $max_hsl - $min_hsl ) + $min_hsl;
$blue = $max_hsl;
} elseif ( 300 >= $hue ) {
$red = ( ( $hue - 240 ) / 60 ) * ( $max_hsl - $min_hsl ) + $min_hsl;
$green = $min_hsl;
$blue = $max_hsl;
} else {
$red = $max_hsl;
$green = $min_hsl;
$blue = ( ( 360 - $hue ) / 60 ) * ( $max_hsl - $min_hsl ) + $min_hsl;
}
$red = sprintf( '%02s', dechex( round( $red ) ) );
$green = sprintf( '%02s', dechex( round( $green ) ) );
$blue = sprintf( '%02s', dechex( round( $blue ) ) );
return '#' . $red . $green . $blue;
} | Convert hsl to hex
@param hue $hue
@param saturation $saturation
@param luminance $luminance
@return hex | entailment |
public function bulkSet($registrationIds = array(), $data = null, $collapseKey = null)
{
$this->setRegistrationIds($registrationIds);
$this->setData($data);
$this->setCollapseKey($collapseKey);
} | Set multiple fields at once.
@param string[] $registrationIds
@param array|null $data
@param string|null $collapseKey | entailment |
public function getIssuers()
{
$issuers = array();
if (isset($this->data->directory)) {
foreach ($this->data->directory->issuer as $issuer) {
$issuers[] = new Issuer((string) $issuer->issuerid, (string) $issuer->issuername);
}
}
return $issuers;
} | {@inheritdoc} | entailment |
private function isTokenInRequest(Request $request)
{
return $request->query->has($this->tokenParam) ||
$request->attributes->has($this->tokenParam) ||
$request->request->has($this->tokenParam);
} | Check the ParameterBags consulted by Request::get() for the token.
@param Request $request
@return boolean | entailment |
public function connect($host,$domain)
{
$remoteSocket = $host . ':' . $this->config['port'];
$this->domain = $domain;
$errnum = 0;
$errstr = '';
$this->host = $remoteSocket;
// open connection
$this->socket = @stream_socket_client(
$this->host,
$errnum,
$errstr,
$this->timeout,
STREAM_CLIENT_CONNECT,
stream_context_create($this->validationOptions['context'])
);
// connected?
if (!$this->isConnect()) {
return 'no connection';
}
$result = stream_set_timeout($this->socket, $this->timeout);
if (!$result) {
return 'Cannot set timeout';
}
return 'connected';
} | Tries to connect to the specified host on the pre-configured port.
@param string $host The host to connect to
@return String weather a error string or success string
@throws Exception\ExceptionNoConnection
@throws Exception\ExceptionNoTimeout | entailment |
public function acceptsAnyRecipient(Domain $domain)
{
$test = 'catch-all-test-' . time();
$accepted = $this->rcpt($test . '@' . $domain->getDomain());
if ($accepted) {
$domain->addDescription(array('catchall' => 1));
// success on a non-existing address is a "catch-all"
return 1;
}
// log the case in which we get disconnected
// while trying to perform a catchall detect
$this->noop();
if (!($this->isConnect())) {
}
// nb: disconnects are considered as a non-catch-all case this way
// this might not be true always
return 0;
} | @param Domain $domain
@return bool | entailment |
public function helo()
{
// don't try if it was already done
if ($this->state['helo']) {
return true;
}
try {
$this->expect(
$this->config['responseCodes']['SMTP_CONNECT_SUCCESS'],
$this->config['commandTimeouts']['helo']
);
$this->ehlo();
// session started
$this->state['helo'] = true;
//todo: are we going for a TLS connection?
return true;
} catch (Exception\ExceptionUnexpectedResponse $e) {
// connected, but received an unexpected response, so disconnect
$this->disconnect(false);
return false;
}
} | Sends a HELO/EHLO sequence
@todo Implement TLS, add logs
@return bool True if successful, false otherwise | entailment |
protected function ehlo()
{
try {
// modern, timeout 5 minutes
$this->send('EHLO ' . $this->options['fromDomain']);
$this->expect($this->config['responseCodes']['SMTP_GENERIC_SUCCESS'], $this->config['commandTimeouts']['ehlo']);
} catch (Exception\ExceptionUnexpectedResponse $e) {
// legacy, timeout 5 minutes
$this->send('HELO ' . $this->options['fromDomain']);
$this->expect($this->config['responseCodes']['SMTP_GENERIC_SUCCESS'], $this->config['commandTimeouts']['helo']);
}
} | Send EHLO or HELO, depending on what's supported by the remote host.
@return void | entailment |
public function mail($from)
{
if (!$this->state['helo']) {
throw new Exception\ExceptionNoHelo('Need HELO before MAIL FROM');
}
try {
// issue MAIL FROM, 5 minute timeout
$this->send('MAIL FROM:<' . $from . '>');
$this->expect($this->config['responseCodes']['SMTP_GENERIC_SUCCESS'], $this->config['commandTimeouts']['mail']);
// set state flags
$this->state['mail'] = true;
$this->state['rcpt'] = false;
return true;
} catch (Exception\ExceptionUnexpectedResponse $e) {
// got something unexpected in response to MAIL FROM
// hotmail is know to do this, and is closing the connection
// forcibly on their end, so I'm killing the socket here too
$this->disconnect(false);
return false;
}
} | Sends a MAIL FROM command to indicate the sender.
@param string $from The "From:" address
@return bool If MAIL FROM command was accepted or not
@throws Exception\ExceptionNoHelo | entailment |
public function rcpt($to)
{
// need to have issued MAIL FROM first
if (!$this->state['mail']) {
$this->statusManager->setStatus($this->users,new Domain($this->domain),0,'Need MAIL FROM before RCPT TO');
throw new Exception\ExceptionNoMailFrom('Need MAIL FROM before RCPT TO');
}
$expectedCodes = array(
$this->config['responseCodes']['SMTP_GENERIC_SUCCESS'],
$this->config['responseCodes']['SMTP_USER_NOT_LOCAL']
);
if ($this->greyListedConsideredValid) {
$expectedCodes = array_merge($expectedCodes, $this->greyListed);
}
// issue RCPT TO, 5 minute timeout
try {
$this->send('RCPT TO:<' . $to . '>');
// process the response
try {
$response = $this->expect($expectedCodes, $this->config['commandTimeouts']['rcpt']);
$this->state['rcpt'] = true;
$isValid = 1;
$this->statusManager->updateStatus($to, array(
'result' => $isValid,
'info' => "OK: {$response}"
));
} catch (Exception\ExceptionUnexpectedResponse $e) {
$this->statusManager->setStatus($this->users, new Domain($this->domain), 0, 'UnexpectedResponse: ' . $e->getMessage());
$isValid = 0;
}
} catch (Exception\ExceptionSmtpValidatorEmail $e) {
$this->statusManager->setStatus($this->users, new Domain($this->domain), 0, 'Sending RCPT TO failed: ' . $e->getMessage());
$isValid = 0;
}
return $isValid;
} | Sends a RCPT TO command to indicate a recipient.
@param string $to Recipient's email address
@return bool Is the recipient accepted
@throws Exception\ExceptionNoMailFrom | entailment |
public function rset()
{
$this->send('RSET');
// MS ESMTP doesn't follow RFC according to ZF tracker, see [ZF-1377]
$expected = array(
$this->config['responseCodes']['SMTP_GENERIC_SUCCESS'],
$this->config['responseCodes']['SMTP_CONNECT_SUCCESS'],
// hotmail returns this o_O
$this->config['responseCodes']['SMTP_TRANSACTION_FAILED']
);
$this->expect($expected, $this->config['commandTimeouts']['rset']);
$this->state['mail'] = false;
$this->state['rcpt'] = false;
} | Sends a RSET command and resets our internal state.
@return void | entailment |
public function quit()
{
// although RFC says QUIT can be issued at any time, we won't
if ($this->state['helo']) {
try {
$this->send('QUIT');
$this->expect($this->config['responseCodes']['SMTP_QUIT_SUCCESS'], $this->config['commandTimeouts']['quit']);
} catch (Exception\ExceptionUnexpectedResponse $e) {}
}
} | Sends a QUIT command.
@return void | entailment |
public function send($cmd)
{
// must be connected
if (!$this->isConnect()) {
$this->statusManager->setStatus($this->users,new Domain($this->domain),0,'No connection');
return false;
}
$result = false;
// write the cmd to the connection stream
try {
if ($this->validationOptions['debug'] === true) {
$this->debug[] = ["timestamp" => microtime(true), "message" => "send> {$cmd}"];
}
$result = fwrite($this->socket, $cmd . self::CRLF);
} catch (\Exception $e) {
// did the send work?
if ($result === false) {
$this->statusManager->setStatus($this->users,new Domain($this->domain),0,'Send failed on: '. $this->host );
return $result;
}
}
return $result;
} | Sends a command to the remote host.
@param string $cmd The cmd to send
@return int|bool Number of bytes written to the stream
@throws Exception\ExceptionNoConnection
@throws Exception\ExceptionSendFailed | entailment |
public function recv($timeout = null)
{
// timeout specified?
if ($timeout !== null) {
stream_set_timeout($this->socket, $timeout);
}
// retrieve response
$line = fgets($this->socket, 1024);
if ($this->validationOptions['debug'] === true) {
$this->debug[] = ["timestamp" => microtime(true), "message" => "received> {$line}"];
}
// have we timed out?
$info = stream_get_meta_data($this->socket);
if (!empty($info['timed_out'])) {
throw new Exception\ExceptionTimeout('Timed out in recv');
}
// did we actually receive anything?
if ($line === false) {
throw new Exception\ExceptionNoResponse('No response in recv');
}
return $line;
} | Receives a response line from the remote host.
@param int $timeout Timeout in seconds
@return string
@throws Exception\ExceptionNoConnection
@throws Exception\ExceptionTimeout
@throws Exception\ExceptionNoResponse | entailment |
public function expect($codes, $timeout = null)
{
if (!is_array($codes)) {
$codes = (array)$codes;
}
$code = null;
$text = $line = '';
try {
$text = $line = $this->recv($timeout);
while (preg_match("/^[0-9]+-/", $line)) {
$line = $this->recv($timeout);
$text .= $line;
}
sscanf($line, '%d%s', $code, $text);
if ($code === null || !in_array($code, $codes)) {
throw new Exception\ExceptionUnexpectedResponse($line);
}
} catch (Exception\ExceptionNoResponse $e) {
// no response in expect() probably means that the
// remote server forcibly closed the connection so
// lets clean up on our end as well?
$this->disconnect(false);
} catch (Exception\ExceptionTimeout $e) {
$this->disconnect(false);
}
return $line;
} | Receives lines from the remote host and looks for expected response codes.
@param string|array $codes A list of one or more expected response codes
@param int $timeout The timeout for this individual command, if any
@return string The last text message received
@throws Exception\ExceptionUnexpectedResponse | entailment |
public function disconnect($quit = true)
{
if ($quit) {
$this->quit();
}
if ($this->isConnect()) {
fclose($this->socket);
}
$this->host = null;
$this->resetState();
} | Disconnects the currently connected MTA.
@param bool $quit Issue QUIT before closing the socket on our end.
@return void | entailment |
private function resetState()
{
$this->state['helo'] = false;
$this->state['mail'] = false;
$this->state['rcpt'] = false;
} | Resets internal state flags to defaults | entailment |
protected function buildOptions(): array
{
if (is_string($this->options)) {
$this->loadRemoteOptions($this->options);
}
if ($this->options instanceof \Closure) {
$this->options = $this->options->call($this->filter, $this->filter->getValue());
}
if ($this->options instanceof Arrayable) {
$this->options = $this->options->toArray();
}
if (empty($this->script)) {
$placeholder = trans('admin.choose');
$this->script = <<<SCRIPT
$(".{$this->getElementClass()}").select2({
placeholder: "$placeholder"
});
SCRIPT;
}
Admin::script($this->script);
return is_array($this->options) ? $this->options : [];
} | Build options.
@return array | entailment |
public function render()
{
$this->script = "$('{$this->getElementClassSelector()}').iCheck({radioClass:'iradio_minimal-blue'});";
return parent::render()->with(['options' => $this->options, 'inline' => $this->inline]);
} | {@inheritdoc} | entailment |
private function memberMentions($message)
{
$filteredMessage = $message['content'];
foreach ($message['mentions'] as $mention) {
$filteredMessage = str_replace('<@'.$mention['id'].'>', '@'.$mention['username'], $filteredMessage);
}
return $filteredMessage;
} | /*
Thanks @Vinlock | entailment |
public function sendData($data)
{
$endpoint = $this->endpoint;
if ($this->getTestMode()) {
$endpoint .= '?test=true';
}
$httpResponse = $this->httpClient->request('GET', $endpoint);
return $this->response = new FetchIssuersResponse($this, $this->parseXmlResponse($httpResponse));
} | {@inheritdoc} | entailment |
public function removeIDFilterIfNeeded()
{
if (!$this->useIdFilter && !$this->idFilterRemoved) {
array_shift($this->filters);
$this->idFilterRemoved = true;
}
} | Remove ID filter if needed. | entailment |
public function chunk(callable $callback, $count = 100)
{
return $this->model->addConditions($this->conditions())->chunk($callback, $count);
} | @param callable $callback
@param int $count
@return bool | entailment |
protected function urlWithoutFilters()
{
$columns = [];
/** @var Filter\AbstractFilter $filter * */
foreach ($this->filters as $filter) {
$columns[] = $filter->getColumn();
}
/** @var \Illuminate\Http\Request $request * */
$request = Request::instance();
$query = $request->query();
array_forget($query, $columns);
$question = '/' === $request->getBaseUrl().$request->getPathInfo() ? '/?' : '?';
return count($request->query()) > 0
? $request->url().$question.http_build_query($query)
: $request->fullUrl();
} | Get url without filter queryString.
@return string | entailment |
public function parse()
{
$parts = explode('@', $this->getEmail());
$domain = array_pop($parts);
$user = implode('@', $parts);
return array($user, $domain);
} | Parses an email string into respective user and domain parts and
returns those as an array.
@return array ['user', 'domain'] | entailment |
public function add($title, BatchAction $abstract)
{
$id = $this->actions->count();
$abstract->setId($id);
$this->actions->push(compact('id', 'title', 'abstract'));
return $this;
} | Add a batch action.
@param string $title
@param BatchAction $abstract
@return $this | entailment |
protected function setUpScripts()
{
Admin::script($this->script());
foreach ($this->actions as $action) {
$abstract = $action['abstract'];
$abstract->setResource($this->grid->resource());
Admin::script($abstract->script());
}
} | Setup scripts of batch actions. | entailment |
public function edit($guildId, $options = [])
{
$image = new Image();
$guild = $this->show($guildId);
$json['name'] = isset($options['name']) ? $options['name'] : $guild['name'];
$json['region'] = isset($options['region']) ? $options['region'] : $guild['region'];
$json['icon'] = isset($options['icon']) ? $image->encodeImage($options['icon']) : $guild['icon'];
$json['afk_channel_id'] = isset($options['afk_channel_id']) ? $options['afk_channel_id'] : $guild['afk_channel_id'];
return $this->request('PATCH', 'guilds/' . $guildId, [
'json' => $json
]);
} | /*
Edit a guild.
@param string $guildId Required
@param array $options [
@property string $name
@property string $region
@property file|url $icon
@property string $afk_channel_id
]
@return array | entailment |
public function getOutdatedPackages(array $excluded = [])
{
// Get all installed and required packages.
$installed = $this->composer->getInstalledPackages();
$required = $this->composer->getRequiredPackages();
$outdated = [];
// Get the installed version number of the required packages.
$packages = array_intersect_key($installed, $required);
foreach ($packages as $package) {
$name = $package['name'];
$version = Version::normalize($package['version']);
$prettyVersion = $required[$name]['version'];
$devDependency = $package['devDependency'];
if (in_array($name, $excluded)) {
continue;
}
$package = new Package($name, $version, $prettyVersion, $devDependency);
if ($package->isOutdated()) {
$outdated[] = $package;
}
}
return $outdated;
} | Get outdated packages with their current and latest version.
@param array $excluded
@return array | entailment |
public function getValidator(array $input)
{
if (!array_key_exists($this->column, $input)) {
return false;
}
$input = array_only($input, $this->column);
$form = $this->buildNestedForm($this->column, $this->builder);
$rules = $attributes = [];
/* @var Field $field */
foreach ($form->fields() as $field) {
if (!$fieldRules = $field->getRules()) {
continue;
}
$column = $field->column();
if (is_array($column)) {
foreach ($column as $key => $name) {
$rules[$name.$key] = $fieldRules;
}
$this->resetInputKey($input, $column);
} else {
$rules[$column] = $fieldRules;
}
$attributes = array_merge(
$attributes,
$this->formatValidationAttribute($input, $field->label(), $column)
);
}
array_forget($rules, NestedForm::REMOVE_FLAG_NAME);
if (empty($rules)) {
return false;
}
$newRules = [];
foreach ($rules as $column => $rule) {
foreach (array_keys($input[$this->column]) as $key) {
$newRules["{$this->column}.$key.$column"] = $rule;
}
}
return Validator::make($input, $newRules, $this->validationMessages, $attributes);
} | Get validator for this field.
@param array $input
@return bool|Validator | entailment |
protected function resetInputKey(array &$input, array $column)
{
/**
* flip the column name array set.
*
* for example, for the DateRange, the column like as below
*
* ["start" => "created_at", "end" => "updated_at"]
*
* to:
*
* [ "created_at" => "start", "updated_at" => "end" ]
*/
$column = array_flip($column);
/**
* $this->column is the inputs array's node name, default is the relation name.
*
* So... $input[$this->column] is the data of this column's inputs data
*
* in the HasMany relation, has many data/field set, $set is field set in the below
*/
foreach ($input[$this->column] as $index => $set) {
/*
* foreach the field set to find the corresponding $column
*/
foreach ($set as $name => $value) {
/*
* if doesn't have column name, continue to the next loop
*/
if (!array_key_exists($name, $column)) {
continue;
}
/**
* example: $newKey = created_atstart.
*
* Σ( ° △ °|||)︴
*
* I don't know why a form need range input? Only can imagine is for range search....
*/
$newKey = $name.$column[$name];
/*
* set new key
*/
array_set($input, "{$this->column}.$index.$newKey", $value);
/*
* forget the old key and value
*/
array_forget($input, "{$this->column}.$index.$name");
}
}
} | Reset input key for validation.
@param array $input
@param array $column $column is the column name array set | entailment |
protected function buildNestedForm($column, \Closure $builder, $key = null)
{
$form = new Form\NestedForm($column, $key);
$form->setForm($this->form);
call_user_func($builder, $form);
$form->hidden($this->getKeyName());
$form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
return $form;
} | Build a Nested form.
@param string $column
@param \Closure $builder
@param null $key
@return NestedForm | entailment |
public function render()
{
// specify a view to render.
$this->view = $this->views[$this->viewMode];
list($template, $script) = $this->buildNestedForm($this->column, $this->builder)
->getTemplateHtmlAndScript();
$this->setupScript($script);
return parent::render()->with([
'forms' => $this->buildRelatedForms(),
'template' => $template,
'relationName' => $this->relationName,
]);
} | Render the `HasMany` field.
@throws \Exception
@return \Illuminate\View\View | entailment |
public static function add( $panel_id, $args ) {
$panel = static::_panel( $panel_id, $args );
static::$panels[ $panel->get_id() ] = $panel;
return $panel;
} | Add Panel
@param string $panel_id
@param array $args
@return Panel | entailment |
protected function validate(array $data)
{
$validator = Validator::make($data, $this->rules);
if ($validator->fails()) {
throw new FormValidationException(trans('dashboard::dashboard.errors.form.validation'), $validator);
}
} | Validate the form submission.
@param array $data
@throws FormValidationException | entailment |
public function render(string $view, array $data = [], $layout = null): string
{
$output = $this->fetch($view, $data);
// False - will disable use layout file
if ($layout === false) {
return $output;
}
return $this->renderContent($output, $data, $layout);
} | Render a view, if layout file is setting, will use it.
throws RuntimeException if view file does not exist
@param string $view
@param array $data extract data to view, cannot contain view as a key
@param string|null|false $layout Override default layout file
@return string
@throws \Throwable | entailment |
public function handle(Request $request, \Closure $next, ...$args)
{
if (!Admin::user() || !empty($args)) {
return $next($request);
}
if ($this->checkRoutePermission($request)) {
return $next($request);
}
if (!Admin::user()->allPermissions()->first(function ($permission) use ($request) {
return $permission->shouldPassThrough($request);
})) {
Checker::error();
}
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param array $args
@return mixed | entailment |
protected function collectFields(\Closure $content)
{
call_user_func($content, $this->form);
$all = $this->form->builder()->fields();
$fields = $all->slice($this->offset);
$this->offset = $all->count();
return $fields;
} | Collect fields under current tab.
@param \Closure $content
@return Collection | entailment |
public function render_content() {
?>
<?php if ( ! empty( $this->label ) ) : ?>
<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
<?php endif; ?>
<?php if ( ! empty( $this->description ) ) : ?>
<span class="description customize-control-description"><?php echo esc_html( $this->description ); ?></span>
<?php endif; ?>
<?php if ( ! empty( $this->content ) ) : ?>
<div class="content customize-control-content">
<?php echo wp_kses_post( $this->content ); ?>
</div>
<?php endif; ?>
<?php
} | Render the control's content
@return void | entailment |
protected function getOptions(array $options): array
{
$options['format'] = array_get($options, 'format', $this->format);
$options['locale'] = array_get($options, 'locale', config('app.locale'));
return $options;
} | @param array $options
@return mixed | entailment |
public function execute(InputInterface $input, OutputInterface $output)
{
$excluded = [];
if ($input->getOption('exclude')) {
$excluded = explode(',', $input->getOption('exclude'));
}
$io = new OutputStyle($input, $output);
$composerPath = $this->getComposerPathFromInput($input);
$ladder = new Ladder($composerPath);
$packages = $ladder->getOutdatedPackages($excluded);
$io->newLine();
$statusCode = 0;
if (!count($packages)) {
$io->writeln('All dependencies match the latest package versions <fg=green>:)</>');
$io->newLine();
return $statusCode;
}
$outdated = [];
$upgradable = [];
foreach ($packages as $package) {
$diff = $io->versionDiff($package->getVersion(), $package->getLatestVersion());
if ($package->isUpgradable()) {
$upgradable[] = [$package->getName(), $package->getVersion(), '→', $diff];
} else {
$outdated[] = [$package->getName(), $package->getVersion(), '→', $diff];
}
}
if (count($outdated) && !$input->getOption('upgradable')) {
$statusCode = 1;
$io->columns($outdated);
$io->newLine();
}
if (count($upgradable) && !$input->getOption('outdated')) {
$statusCode = 1;
$io->writeln('The following dependencies are satisfied by their declared version constraint, but the installed versions are behind. You can install the latest versions without modifying your composer.json file by using <fg=blue>composer update</>.');
$io->newLine();
$io->columns($upgradable);
$io->newLine();
}
return $statusCode;
} | Execute the command.
@param \Symfony\Component\Console\Input\InputInterface $input
@param \Symfony\Component\Console\Output\OutputInterface $output
@return int | entailment |
public function connect()
{
$this->log->debug("connect");
$host = $this->ipv4_address_for_host($this->host, $this->port);
if(!$host)
{
return FALSE;
}
// NOTE: This timeout doesn't apply to DNS, but does apply to the actual connecting
$this->socket = @stream_socket_client("tcp://{$host}:{$this->port}", $errno, $errorMessage, self::CONNECT_TIMEOUT);
$this->log->debug("connect after stream_socket_client, stream_socket_get_name: " . stream_socket_get_name($this->socket, TRUE));
stream_set_timeout($this->socket, self::SEND_REPLY_TIMEOUT, 0);
if(!$this->is_connected())
{
$this->log->error("Connection error $errno : $errorMessage");
$this->disconnect(); // TODO: delay retry?
return FALSE;
}
$hostname = gethostname();
$pid = getmypid();
$runtime = phpversion();
$platform = preg_replace('/\s+/', '_', php_uname());
$hello_and_auth_cmd =
"hello version php/instrumental_agent/" . self::VERSION . " " .
"hostname $hostname " .
"pid $pid " .
"runtime $runtime " .
"platform $platform\n" .
"authenticate $this->api_key\n";
// $this->log->debug("Sleeping. Enable packet loss to test.");
// sleep(10);
// $this->log->debug("Resuming.");
// NOTE: dropping packets didn't appear to affect sending
$this->socket_send($hello_and_auth_cmd);
$this->log->debug("connect fgets");
// NOTE: dropping packets did affect fgets, and SEND_REPLY_TIMEOUT did apply
$line = fgets($this->socket, 1024);
$this->log->debug("connect $line");
if($line != "ok\n")
{
$this->log->error("Sending hello failed.");
$this->disconnect(); // TODO: delay retry?
return FALSE;
}
$this->log->debug("connect fgets");
$line = fgets($this->socket, 1024);
$this->log->debug("connect $line");
if($line != "ok\n")
{
$this->log->error("Authentication failed with key $this->api_key Please check your configuration." );
$this->disconnect(); // TODO: delay retry?
return FALSE;
}
return TRUE;
} | TODO: Make private functions private | entailment |
public function select($options = [])
{
$source = [];
foreach ($options as $key => $value) {
$source[] = [
'value' => $key,
'text' => $value,
];
}
$this->addOptions(['source' => $source]);
} | Select type editable.
@param array $options | entailment |
public function data($data)
{
if ($data instanceof Arrayable) {
$data = $data->toArray();
}
$this->data = $data;
} | @param $data
@deprecated | entailment |
public function display($callback = null)
{
if ($callback instanceof \Closure) {
$callback->call($this, $this);
}
$actions = $this->prepends;
if ($this->allowEdit) {
array_push($actions, $this->editAction());
}
if ($this->allowDelete) {
array_push($actions, $this->deleteAction());
}
$actions = array_merge($actions, $this->appends);
return implode('', $actions);
} | {@inheritdoc} | entailment |
public function fill($data)
{
$this->value = array_get($data, $this->column);
if (is_string($this->value)) {
$this->value = explode(',', $this->value);
}
$this->value = array_filter((array) $this->value);
} | {@inheritdoc} | entailment |
public function prepare($value)
{
if (is_array($value) && !Arr::isAssoc($value)) {
$value = implode(',', array_filter($value));
}
return $value;
} | {@inheritdoc} | entailment |
public function value($value = null)
{
if (is_null($value)) {
return empty($this->value) ? ($this->getDefault() ?? []) : $this->value;
}
$this->value = $value;
return $this;
} | Get or set value for this field.
@param mixed $value
@return $this|array|mixed | entailment |
public function sendMessage()
{
$message = new \CodeMonkeysRu\GCM\Message();
call_user_func_array(array($message, 'bulkSet'), func_get_args());
return $this->send($message);
} | Send message to GCM without explicitly created message
@param string[] $registrationIds
@param array|null $data
@param string|null $collapseKey
@throws \CodeMonkeysRu\GCM\Exception
@return \CodeMonkeysRu\GCM\Response | entailment |
public function send(Message $message)
{
if (!$this->serverApiKey) {
throw new Exception("Server API Key not set", Exception::ILLEGAL_API_KEY);
}
//GCM response: Number of messages on bulk (1001) exceeds maximum allowed (1000)
if (count($message->getRegistrationIds()) > 1000) {
throw new Exception(
"Malformed request: Registration Ids exceed the GCM imposed limit of 1000",
Exception::MALFORMED_REQUEST
);
}
$rawData = $this->formMessageData($message);
$this->validatePayloadSize($rawData, 'data', 4096);
$this->validatePayloadSize($rawData, 'notification', 2048);
$data = json_encode($rawData);
$headers = array(
'Authorization: key='.$this->serverApiKey,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->gcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($this->caInfoPath !== false) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_CAINFO, $this->caInfoPath);
} else {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$resultBody = curl_exec($ch);
$resultHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
switch ($resultHttpCode) {
case "200":
//All fine. Continue response processing.
break;
case "400":
throw new Exception('Malformed request. '.$resultBody, Exception::MALFORMED_REQUEST);
break;
case "401":
throw new Exception('Authentication Error. '.$resultBody, Exception::AUTHENTICATION_ERROR);
break;
default:
//TODO: Retry-after
throw new Exception("Unknown error. ".$resultBody, Exception::UNKNOWN_ERROR);
break;
}
return new Response($message, $resultBody);
} | Send message to GCM
@param \CodeMonkeysRu\GCM\Message $message
@throws \CodeMonkeysRu\GCM\Exception
@return \CodeMonkeysRu\GCM\Response | entailment |
private function formMessageData(Message $message)
{
$data = array(
'registration_ids' => $message->getRegistrationIds(),
);
$dataFields = array(
'registration_ids' => 'getRegistrationIds',
'collapse_key' => 'getCollapseKey',
'data' => 'getData',
'notification' => 'getNotification',
'delay_while_idle' => 'getDelayWhileIdle',
'time_to_live' => 'getTtl',
'restricted_package_name' => 'getRestrictedPackageName',
'dry_run' => 'getDryRun',
'content_available' => 'getContentAvailable',
'priority' => 'getPriority',
);
foreach ($dataFields as $fieldName => $getter) {
if ($message->$getter() != null) {
$data[$fieldName] = $message->$getter();
}
}
return $data;
} | Form raw message data for sending to GCM
@param \CodeMonkeysRu\GCM\Message $message
@return array | entailment |
private function validatePayloadSize(array $rawData, $fieldName, $maxSize)
{
if (!isset($rawData[$fieldName])) {
return;
}
if (strlen(json_encode($rawData[$fieldName])) > $maxSize) {
throw new Exception(
ucfirst($fieldName)." payload is to big (max {$maxSize} bytes)",
Exception::MALFORMED_REQUEST
);
}
} | Validate size of json representation of passed payload
@param array $rawData
@param string $fieldName
@param int $maxSize
@throws \CodeMonkeysRu\GCM\Exception
@return void | entailment |
public function add(array $emails)
{
if(!empty ($emails) ){
foreach ($emails as $key => $values) {
$this->set($key, $values);
}
}
} | Adds new container the current container set.
@param array $emails An array of container | entailment |
public function get($key, $default = null, $first = true)
{
if(!is_string($key) && !is_int($key)){
throw new \InvalidArgumentException('$key expected to be string or integer, got: '.gettype($key));
}
if (!array_key_exists($key, $this->container)) {
if (null === $default) {
return $first ? null : array();
}
return $first ? $default : array($default);
}
if ($first) {
return count($this->container[$key]) ? $this->container[$key][0] : $default;
}
return $this->container[$key];
} | Returns a email value by name.
@param string $key The email name
@param mixed $default The default value
@param Boolean $first Whether to return the first value or all email values
@return string|array The first email value if $first is true, an array of values otherwise | entailment |
public function set($key, $values, $replace = true)
{
if(!is_string($key) && !is_int($key)){
throw new \InvalidArgumentException('$key expected to be string, got:'.gettype($key));
}
if( !is_string($values) && !is_array($values) ){
throw new \InvalidArgumentException('$key expected to be string or array, got: '.gettype($key));
}
$values = array_values((array)$values);
if (true === $replace || !isset($this->container[$key])) {
$this->container[$key] = $values;
} else {
$this->container[$key] = array_merge($this->container[$key], $values);
}
} | Sets a email values.
@param string|int $key The key
@param string|array $values The value or an array of values
@param Boolean $replace Whether to replace the actual value or not (true by default) | entailment |
public function getValidator(array $input)
{
if (!array_key_exists($this->column, $input)) {
return false;
}
$input = array_only($input, $this->column);
$rules = $attributes = [];
/** @var Field $field */
foreach ($this->buildEmbeddedForm()->fields() as $field) {
if (!$fieldRules = $field->getRules()) {
continue;
}
$column = $field->column();
/*
*
* For single column field format rules to:
* [
* 'extra.name' => 'required'
* 'extra.email' => 'required'
* ]
*
* For multiple column field with rules like 'required':
* 'extra' => [
* 'start' => 'start_at'
* 'end' => 'end_at',
* ]
*
* format rules to:
* [
* 'extra.start_atstart' => 'required'
* 'extra.end_atend' => 'required'
* ]
*/
if (is_array($column)) {
foreach ($column as $key => $name) {
$rules["{$this->column}.$name$key"] = $fieldRules;
}
$this->resetInputKey($input, $column);
} else {
$rules["{$this->column}.$column"] = $fieldRules;
}
/**
* For single column field format attributes to:
* [
* 'extra.name' => $label
* 'extra.email' => $label
* ].
*
* For multiple column field with rules like 'required':
* 'extra' => [
* 'start' => 'start_at'
* 'end' => 'end_at',
* ]
*
* format rules to:
* [
* 'extra.start_atstart' => "$label[start_at]"
* 'extra.end_atend' => "$label[end_at]"
* ]
*/
$attributes = array_merge(
$attributes,
$this->formatValidationAttribute($input, $field->label(), $column)
);
}
if (empty($rules)) {
return false;
}
return Validator::make($input, $rules, $this->validationMessages, $attributes);
} | {@inheritdoc} | entailment |
public function resetInputKey(array &$input, array $column)
{
$column = array_flip($column);
foreach ($input[$this->column] as $key => $value) {
if (!array_key_exists($key, $column)) {
continue;
}
$newKey = $key.$column[$key];
/*
* set new key
*/
array_set($input, "{$this->column}.$newKey", $value);
/*
* forget the old key and value
*/
array_forget($input, "{$this->column}.$key");
}
} | Reset input key for validation.
@param array $input
@param array $column $column is the column name array set | entailment |
public function getEntries($domain)
{
$hosts = array();
$weight = array();
getmxrr($domain, $hosts, $weight);
// sort MX priorities
foreach ($hosts as $k => $host) {
$this->mxs[$host] = $weight[$k];
}
asort($this->mxs);
// add the hostname with 0 weight (RFC 2821)
$this->mxs[$domain] = 0;
return $this->mxs;
} | Queries the DNS server for domain MX entries
@param string $domain The domain MX entries
@return array MX hosts and their weights | entailment |
public function edit($channelId, $name = null, $position = null, $topic = null)
{
$channel = $this->show($channelId);
$json['name'] = is_null($name) ? $channel['name'] : $name;
$json['position'] = is_null($position) ? $channel['position'] : $position;
$json['topic'] = is_null($topic) ? $channel['topic'] : $topic;
return $this->request('PATCH', 'channels/' . $channelId, [
'json' => $json
]);
} | Edit a channel.
@param string $channelId Required
@param string $name Required
@param int $position
@param string $topic
@return array | entailment |
public function handle(Request $request, Closure $next, $roles)
{
$accessDenied = true;
if (!$user = $this->auth->getActiveUser()) {
Flash::error(trans('dashboard::dashboard.flash.access_denied'));
return redirect()->route('auth.login');
}
if (!is_array($roles)) {
$roles = [$roles];
}
foreach ($roles as $role) {
if (!$role = $this->role->getBySlug($role)) {
continue;
}
if ($user->inRole($role)) {
$accessDenied = false;
}
}
if ($accessDenied) {
Flash::error(trans('dashboard::dashboard.flash.access_denied'));
// Redirect back to the previous page where request was made.
return redirect()->back();
}
return $next($request);
} | Check if user belongs to the specified role.
@param Request $request
@param Closure $next
@param string|array $roles
@return \Illuminate\Http\RedirectResponse | entailment |
public function handle(Request $request, Closure $next, $permissions)
{
$accessDenied = true;
if (!$user = $this->auth->getActiveUser()) {
Flash::error(trans('dashboard::dashboard.flash.access_denied'));
return redirect()->back();
}
if (!is_array($permissions)) {
$permissions = [$permissions];
}
foreach ($permissions as $permission) {
if ($user->hasAccess($permission)) {
$accessDenied = false;
}
}
if ($accessDenied) {
Flash::error(trans('dashboard::dashboard.flash.access_denied'));
return redirect()->back();
}
return $next($request);
} | Check if user has permission.
@param Request $request
@param Closure $next
@param string|array $permissions
@return \Illuminate\Http\RedirectResponse | entailment |
public function render()
{
if (!$this->grid->allowExport()) {
return '';
}
$this->setUpScripts();
$export = trans('admin.export');
$all = trans('admin.all');
$currentPage = trans('admin.current_page');
$selectedRows = trans('admin.selected_rows');
$page = request('page', 1);
return <<<EOT
<div class="btn-group pull-right" style="margin-right: 10px">
<a class="btn btn-sm btn-twitter"><i class="fa fa-download"></i> {$export}</a>
<button type="button" class="btn btn-sm btn-twitter dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li><a href="{$this->grid->exportUrl('all')}" target="_blank">{$all}</a></li>
<li><a href="{$this->grid->exportUrl('page', $page)}" target="_blank">{$currentPage}</a></li>
<li><a href="{$this->grid->exportUrl('selected', '__rows__')}" target="_blank" class='export-selected'>{$selectedRows}</a></li>
</ul>
</div>
EOT;
} | Render Export button.
@return string | entailment |
public function condition($inputs)
{
$value = array_get($inputs, $this->column);
if (is_array($value)) {
$value = array_filter($value);
}
if (is_null($value) || empty($value)) {
return;
}
$this->value = $value;
return $this->buildCondition($this->column, 'ilike', "%{$this->value}%");
} | Get condition of this filter.
@param array $inputs
@return array|mixed|void | entailment |
public function setOriginal($data, $relatedKeyName)
{
if (empty($data)) {
return $this;
}
foreach ($data as $value) {
/*
* like $this->original[30] = [ id = 30, .....]
*/
$this->original[$value[$relatedKeyName]] = $value;
}
return $this;
} | Set original values for fields.
@param array $data
@param string $relatedKeyName
@return $this | entailment |
public function options($options = [])
{
// remote options
if (is_string($options)) {
return $this->loadRemoteOptions(...func_get_args());
}
if ($options instanceof Arrayable) {
$options = $options->toArray();
}
if (is_callable($options)) {
$this->options = $options;
} else {
$this->options = (array) $options;
}
return $this;
} | Set options.
@param array|callable|string $options
@return $this|mixed | entailment |
protected function loadRemoteOptions($url, $parameters = [], $options = [])
{
$ajaxOptions = [
'url' => $url.'?'.http_build_query($parameters),
];
$ajaxOptions = json_encode(array_merge($ajaxOptions, $options));
$this->script = <<<EOT
$.ajax($ajaxOptions).done(function(data) {
$("{$this->getElementClassSelector()}").select2({data: data});
});
EOT;
return $this;
} | Load options from remote.
@param string $url
@param array $parameters
@param array $options
@return $this | entailment |
protected function databaseSetup()
{
$this->output->writeln(<<<STEP
<fg=yellow>
*-----------------------------------------------*
| |
| Configure Database |
| This package uses MySQL Only |
| |
*-----------------------------------------------*
</fg=yellow>
STEP
);
$host = $this->anticipate('Please enter the database host',
['localhost']);
$name = $this->anticipate('Please enter the database name',
['homestead']);
$user = $this->anticipate('Please enter the database user',
['homestead']);
$pass = $this->databaseSetupPassword();
$headers = [
'Setting',
'Value',
];
$data = [
['Host', $host],
['Name', $name],
['User', $user],
['Password', $pass],
];
$this->table($headers, $data);
if (!$this->confirm('Is the database info correct?')) {
$this->databaseSetup();
}
$this->database = [
'host' => $host,
'name' => $name,
'user' => $user,
'pass' => $pass,
];
$this->info('Database configuration saved.');
} | Setup the database credentials.
@return void | entailment |
protected function databaseSetupPassword()
{
$pass = $this->secret('Please enter the database password');
$passConfirm = $this->secret('Please confirm the database password');
if ($pass != $passConfirm) {
$this->error('[ERROR] Database passwords do not match. Please retry.');
$this->databaseSetupPassword();
}
return $pass;
} | Setup the database credentials password.
@return string | entailment |
protected function userSetup()
{
$this->output->writeln(<<<STEP
<fg=yellow>
*-----------------------------------------------*
| |
| Configure Default User |
| |
*-----------------------------------------------*
</fg=yellow>
STEP
);
$first = $this->ask('Please enter the user first name');
$last = $this->ask('Please enter the user last name');
$email = $this->ask('Please enter the user email');
$pass = $this->userSetupPassword();
$headers = [
'Setting',
'Value'
];
$data = [
['First Name', $first],
['Last Name', $last],
['Email', $email],
['Password', $pass],
];
$this->table($headers, $data);
if (!$this->confirm('Is the user information correct?')) {
$this->userSetup();
}
$this->user = [
'first' => $first,
'last' => $last,
'email' => $email,
'pass' => $pass,
];
$this->info('User configuration saved.');
} | Setup the user credentials.
@return void | entailment |
protected function userSetupPassword()
{
$pass = $this->secret('Please enter the user password');
$passConfirm = $this->secret('Please confirm the user password');
if ($pass != $passConfirm) {
$this->error('[ERROR] Passwords do not match.');
$this->userSetupPassword();
}
return $pass;
} | Setup the user credentials password.
@return string | entailment |
protected function setupEnvFile()
{
$env = __DIR__ . '/stubs/env.stub';
$config = $this->database;
// Update the env stub file with actual credentials.
$contents = str_replace(
array_map(function ($key) {
return '{{' . $key . '}}';
}, array_keys($config)),
array_values($config),
$this->laravel['files']->get($env)
);
// Generate a key
$contents = str_replace('{{key}}', Str::random(32), $contents);
// Check if we can actually write the environment file.
if ($this->laravel['files']->put(($envFile = $this->laravel['path.base'] . '/.env'),
$contents) === false
) {
throw new \RuntimeException("Could not write env file to [$envFile].");
}
// Reload env file
$this->laravel['Illuminate\Foundation\Bootstrap\DetectEnvironment']->bootstrap($this->laravel);
// Reload config
$this->laravel['Illuminate\Foundation\Bootstrap\LoadConfiguration']->bootstrap($this->laravel);
} | Setup ENV file with database credentials.
@return void | entailment |
protected function triggerPublish()
{
$this->info('Starting publishing vendor assets.');
$this->call('vendor:publish');
$this->info('Publishing vendor assets finished.');
// Reload config
$this->laravel['Illuminate\Foundation\Bootstrap\LoadConfiguration']->bootstrap($this->laravel);
} | Run vendor:publish to publish vendor assets.
@return void | entailment |
protected function createDefaultUser()
{
// Get the user configuration data.
$config = $this->user;
// Create default permission.
$this->permissionRepository->create([
'name' => 'Administrator (Full Access)',
'slug' => 'admin',
], false);
// Create default role.
$this->roleRepository->create([
'name' => 'Registered',
'slug' => 'registered',
], false);
// Create the admin role.
$role = $this->roleRepository->create([
'name' => 'Administrator',
'slug' => 'administrator',
'permissions' => [
'admin' => true,
],
], false);
// Create the user.
$user = $this->authRepository->registerAndActivate([
'email' => array_get($config, 'email'),
'first_name' => array_get($config, 'first'),
'last_name' => array_get($config, 'last'),
'password' => array_get($config, 'pass'),
'role' => 'administrator',
], false);
// Attach user to admin role.
$role->users()
->attach($user);
} | Create default Group and User
@return void | entailment |
protected function setupSeedStubs()
{
// Get the user configuration data.
$config = $this->user;
$user = __DIR__ . '/stubs/UserTableSeeder.stub';
$role = __DIR__ . '/stubs/RoleTableSeeder.stub';
$permission = __DIR__ . '/stubs/PermissionTableSeeder.stub';
// Update the UserTableSeeder stub file with actual credentials.
$userContents = str_replace(
array_map(function ($key) {
return '{{' . $key . '}}';
}, array_keys($config)),
array_values($config),
$this->laravel['files']->get($user)
);
// Get the contents of the RoleTableSeeder stub file.
$roleContents = $this->laravel['files']->get($role);
// Get the contents of the PermissionTableSeeder stub file.
$permissionContents = $this->laravel['files']->get($permission);
// Check if we can actually write the UserTableSeeder file.
if ($this->laravel['files']->put(($userFile = $this->laravel['path.database'] . '/seeds/UserTableSeeder.php'),
$userContents) === false
) {
throw new \RuntimeException("Could not write env file to [$userFile].");
}
// Check if we can actually write the RoleTableSeeder file.
if ($this->laravel['files']->put(($roleFile = $this->laravel['path.database'] . '/seeds/RoleTableSeeder.php'),
$roleContents) === false
) {
throw new \RuntimeException("Could not write env file to [$roleFile].");
}
// Check if we can actually write the PermissionTableSeeder file.
if ($this->laravel['files']->put(($permissionFile = $this->laravel['path.database'] . '/seeds/PermissionTableSeeder.php'),
$permissionContents) === false
) {
throw new \RuntimeException("Could not write env file to [$permissionFile].");
}
} | Setup stub files for seeders.
@return void | entailment |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.