sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function xml()
{
if (strtoupper($this->encoding) !== 'ISO-8859-1') {
return false;
}
try {
$converted = utf8_encode($this->string);
} catch (\Exception $e) {
return false;
}
return $converted;
} | xml
@link http://php.net/manual/en/function.utf8-encode.php
@return string|false | entailment |
public function mbstring($fromOverride = null)
{
try {
$converted = mb_convert_encoding($this->string, self::ENCODING, $fromOverride === null ? $this->encoding : $fromOverride);
} catch (\Exception $e) {
return false;
}
return $converted;
} | mbstring
@link http://php.net/manual/en/function.mb-convert-encoding.php
@param array|string|null $fromOverride
@return string|false | entailment |
public function callback($errno, $errstr, $errfile = '', $errline = 0, $errcontext = [])
{
$this->log[(string)microtime(true)] = [
'no' => $errno,
'str' => $errstr,
'file' => $errfile,
'line' => $errline,
'context' => $errcontext,
];
return $this->handle();
} | Callback
@param int $errno
@param string $errstr
@param string $errfile
@param int $errline
@param array $errcontext
@return bool | entailment |
public function read() {
$data = get_option( $this->name, [] );
$this->data = is_array( $data ) ? $data : [];
} | Read data from storage.
@return void | entailment |
public function save() {
if ( empty( $this->data ) ) {
return delete_option( $this->name );
}
$updated = update_option( $this->name, $this->data, $this->autoload );
// Reload the current data.
$this->read();
return $updated;
} | Save data to the storage.
@return bool | entailment |
public function getRoles(IdentityInterface $identity)
{
$identityHash = spl_object_hash($identity);
if (isset($this->cache[$identityHash])) {
return $this->cache[$identityHash];
}
$roles = new ArrayCollection();
foreach ($identity->getAuthorizationRoles() as $role) {
$childRoles = $this->getChildRoles($role);
$roles->add($role);
foreach ($childRoles as $childRole) {
if (!$roles->contains($childRole)) {
$roles->add($childRole);
}
}
}
return $this->cache[$identityHash] = $roles;
} | {@inheritdoc} | entailment |
public function prepare_new_row() {
$this->field = [];
$this->setup_fields();
$values = $this->get_value();
Dependency::check( $this->fields,
isset( $values[ $this->index ] ) ? (array) $values[ $this->index ] : []
);
} | Setup group for a new row.
@return void | entailment |
protected function setup_fields() {
foreach ( $this->prop( 'fields' ) as $args ) {
$field = $this->builder
->get_field( $args, $this )
->set_option( 'context', $this->args( 'context' ) )
->initialize();
if ( ! $field->check_capabilities() ) {
continue;
}
if ( 'hidden' === $args['type'] ) {
$this->builder->add_hidden_field( $args, $this );
continue;
}
$this->fields[ $field->get_id() ] = $field;
}
} | Setup field in the group.
@return void | entailment |
public function value( $key = '' ) {
$value = $this->get_value();
// For old systax support.
if ( $key && is_array( $value ) ) {
return array_key_exists( $key, $value ) ? $value[ $key ] : null;
}
return $value;
} | {@inheritdoc} | entailment |
public function get_default() {
if ( is_null( $this->args['default'] ) && ! is_callable( $this->args['default_cb'] ) ) {
return null;
}
return parent::get_default();
} | {@inheritdoc} | entailment |
public function escaped_value( $func = null, $meta_value = null ) {
return parent::escaped_value( $func ?: [ Utils::class, 'esc_value' ], $meta_value );
} | {@inheritdoc} | entailment |
protected function get_new_field( $field_args, $field_group = null ) {
return new static( $this->form->get_config(), $this->get_default_args( $field_args, $field_group ) );
} | {@inheritdoc} | entailment |
public function display( $field, $value, $builder ) {
?>
<div class="button-group">
<?php foreach ( (array) $field->options() as $key => $label ) : ?>
<?php
echo $builder->input( [ // @WPCS: XSS OK.
'type' => 'radio',
'id' => $builder->_id( '_' . $key ),
'value' => $key,
// 'checked' => $key === $value ? 'checked' : null,
'desc' => '',
'style' => 'display: none',
] );
?>
<label class="button suru-tooltip-target" for="<?php echo esc_attr( $builder->_input_id( '_' . $key ) ); ?>" title="<?php echo esc_attr( $label ); ?>">
<span><?php echo esc_html( $label ); ?></span>
</label>
<?php endforeach ?>
</div>
<?php
} | {@inheritdoc} | entailment |
public function parse($source)
{
$resolver = new RefResolver();
if ($this->connection !== null) {
$resolver->addResolver('schema', new Resolver($this->connection));
}
$parser = new JsonSchema(null, $resolver);
$schema = $parser->parse($source);
return Service\Schema::serializeCache($schema);
} | Parses and resolves the json schema source and returns the object
presentation of the schema
@param string $source
@return string | entailment |
public function setCredentials($username, $password)
{
$this->username = $username;
$this->password = $password;
$this->token = '';
$this->accessToken = '';
return $this;
} | Set username and password for authentication
Tokens will be cleared
@param string $username
@param string $password
@return PhonegapBuildApi | entailment |
public function setToken($token)
{
$this->token = $token;
$this->username = '';
$this->password = '';
$this->accessToken = '';
return $this;
} | Set simple token for authentication
Username + password and access token will be cleared
@param string $token
@return PhonegapBuildApi | entailment |
public function setAccessToken($accessToken)
{
$this->accessToken = $accessToken;
$this->username = '';
$this->password = '';
$this->token = '';
return $this;
} | Set access token for OAuth2 authentication
Username + password and simple token will be cleared
@param string $accessToken
@return PhonegapBuildApi | entailment |
public function createApplication($options = array())
{
// duplicating the default values from API documentation
$defaults = array(
'title' => 'Phonegap Application',
'package' => 'com.phonegap.www',
'version' => '0.0.1',
'description' => '',
'debug' => false,
// don't set defaults for keys, as it will throw an error
// if you want to set keys just pass them as options
// 'keys' => array(),
'private' => true,
'phonegap_version' => '3.1.0',
'hydrates' => false,
);
$options = array_merge($defaults, $options);
return $this->request('apps', 'post', $options);
} | Create application
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_post_https_build_phonegap_com_api_v1_apps
@param array $options - additional options, see details in API docs
@return mixed: array on success | false on fail | entailment |
public function createApplicationFromRepo($source, $options = array())
{
$options = array_merge($options, array(
'create_method' => 'remote_repo',
'repo' => $source,
));
return $this->createApplication($options);
} | Create application using GitHub repository
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_post_https_build_phonegap_com_api_v1_apps
@param string $source - GitHub repository
@param array $options - additional options, see details in API docs
@return mixed: array on success | false on fail | entailment |
public function createApplicationFromFile($source, $options = array())
{
$options = array_merge($options, array(
'create_method' => 'file',
'file' => $this->file($source),
));
return $this->createApplication($options);
} | Create application from file
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_post_https_build_phonegap_com_api_v1_apps
@param string $source - file path
@param array $options - additional options, see details in API docs
@return mixed: array on success | false on fail | entailment |
public function updateApplicationFromRepo($applicationId, $options = array())
{
$options = array_merge($options, array(
'pull' => true,
));
return $this->updateApplication($applicationId, $options);
} | Update application from GitHub repository
No need to pass repository as it was set when application had been created
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_put_https_build_phonegap_com_api_v1_apps_id
@param mixed: int | string $applicationId
@param array $options - additional options, see details in API docs
@return mixed: array on success | false on fail | entailment |
public function updateApplicationFromFile($applicationId, $source, $options = array())
{
$options = array_merge($options, array(
'file' => $this->file($source),
));
return $this->updateApplication($applicationId, $options);
} | Update application from file
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_put_https_build_phonegap_com_api_v1_apps_id
@param mixed: int | string $applicationId
@param string $source - file path
@param array $options - additional options, see details in API docs
@return mixed: array on success | false on fail | entailment |
public function updateApplicationIcon($applicationId, $source)
{
$options['icon'] = $this->file($source);
return $this->request(array('apps', $applicationId, 'icon'), 'post', $options);
} | Update application icon
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_post_https_build_phonegap_com_api_v1_apps_id_icon
@param mixed: int | string $applicationId
@param string $source - png icon file path
@return mixed: array on success | false on fail | entailment |
public function buildApplication($applicationId, $platforms = array())
{
$options = array();
if (! empty($platforms)) {
if (! is_array($platforms)) {
$platforms = array($platforms);
}
$options['platforms'] = $platforms;
}
return $this->request(array('apps', $applicationId, 'build'), 'post', $options);
} | Start building application
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_post_https_build_phonegap_com_api_v1_apps_id_build
@param mixed: int | string $applicationId
@param array | string $platforms - platform name ('android', 'ios', ...')
@return mixed: array on success | false on fail | entailment |
public function addCollaborator($applicationId, $options = array())
{
$defaults = array(
'email' => '',
'role' => self::ROLE_TESTER, // self::ROLE_DEV
);
$options = array_merge($defaults, $options);
return $this->request(array('apps', $applicationId, 'collaborators'), 'post', $options);
} | Add collaborator
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_post_https_build_phonegap_com_api_v1_apps_id_collaborators
@param mixed: int | string $applicationId
@param array $options - additional options, see details in API docs
@return mixed: array on success | false on fail | entailment |
public function updateCollaborator($applicationId, $collaboratorId, $options = array())
{
$defaults = array(
'role' => self::ROLE_TESTER, // self::ROLE_DEV
);
$options = array_merge($defaults, $options);
return $this->request(array('apps', $applicationId, 'collaborators', $collaboratorId), 'put', $options);
} | Update collaborator
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_put_https_build_phonegap_com_api_v1_apps_id_collaborators_id
@param mixed: int | string $applicationId
@param mixed: int | string $collaboratorId
@param array $options- additional options, see details in API docs
@return mixed: array on success | false on fail | entailment |
public function addKeyAndroid($title, $keystore, $options = array())
{
$defaults = array(
'title' => $title,
'keystore' => $this->file($keystore),
// 'alias' => 'release',
// 'key_pw' => '',
// 'keystore_pw' => '',
);
$options = array_merge($defaults, $options);
return $this->addKeyPlatform(self::ANDROID, $options);
} | Add key for android
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_post_https_build_phonegap_com_api_v1_keys_platform
@param string $title - key title
@param string $keystore - keystore file
@param array $options - additional options, see details in API docs
@return mixed: array on success | false on fail | entailment |
public function addKeyIos($title, $cert, $profile, $options = array())
{
$defaults = array(
'title' => $title,
'cert' => $this->file($cert),
'profile' => $this->file($profile),
// 'password' => '',
);
$options = array_merge($defaults, $options);
return $this->addKeyPlatform(self::IOS, $options);
} | Add key for ios
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_post_https_build_phonegap_com_api_v1_keys_platform
@param string $title - key title
@param string $cert - p12 certificate file
@param string $profile - mobileprovision file
@param array $options - additional options, see details in API docs
@return mixed: array on success | false on fail | entailment |
public function updateKeyIos($keyId, $password)
{
$options['password'] = $password;
return $this->updateKeyPlatform(self::IOS, $keyId, $options);
} | Update / unlock key for ios
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_put_https_build_phonegap_com_api_v1_keys_platform
@param mixed: int | string $keyId
@param string $password - key password
@return mixed: array on success | false on fail | entailment |
public function updateKeyAndroid($keyId, $keyPw, $keystorePw)
{
$options = array(
'key_pw' => $keyPw,
'keystore_pw' => $keystorePw,
);
return $this->updateKeyPlatform(self::ANDROID, $keyId, $options);
} | Update / unlock key for android
@link http://docs.build.phonegap.com/en_US/developer_api_write.md.html#_put_https_build_phonegap_com_api_v1_keys_platform
@param mixed: int | string $keyId
@param string $keyPw - key password
@param string $keystorePw - keystore password
@return mixed: array on success | false on fail | entailment |
protected function assocToString($array, $keyValueSeparator = ' - ', $pairSeparator = '; ')
{
if (! is_array($array)) {
return print_r($array, true);
}
foreach ($array as $key => &$value) {
$value = $key . $keyValueSeparator . $value;
}
return implode($pairSeparator, $array);
} | Represent associative array as string
@param array $array
@param string $keyValueSeparator
@param string $pairSeparator
@return string | entailment |
protected function request($uri, $method = 'get', $options = array())
{
$this->clear();
if (! in_array(strtolower($method), $this->methods)) {
return $this->setError('Unknown request method: ' . $method);
}
$isAuthorized = $this->accessToken || $this->token ||
($this->username && $this->password);
if (! $isAuthorized) {
return $this->setError('Please provide token or username and password');
}
// if uri is passed as array, create uri string from uri parts
if (is_array($uri)) {
$uri = implode('/', $uri);
}
// api request url
$url = $this->endpoint . $uri;
$handle = curl_init();
if ($this->accessToken) {
// Access token is used in OAuth2 flow
$url .= '?access_token=' . $this->accessToken;
} else if ($this->token) {
// Auth token is taken from PG account
$url .= '?auth_token=' . $this->token;
} else {
// if using username and password - pass them as curl option
curl_setopt($handle, CURLOPT_USERPWD, $this->username . ':' . $this->password);
}
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, strtoupper($method));
curl_setopt($handle, CURLOPT_HTTPHEADER, array(
'Content-type: multipart/form-data;',
));
// if request has additional options - add them to request
if (! empty($options)) {
// extract files, pass them separately
$files = array();
foreach ($options as $key => $value) {
if (! empty($value) && ! is_array($value) && $value[0] === '@') {
$files[$key] = $this->toCurlFile($value);
unset($options[$key]);
}
}
$data = $files;
if (! empty($options)) {
// original API requires data to be in json format
$data = array_merge($data, array(
'data' => json_encode($options),
));
}
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
}
$response = curl_exec($handle);
if (curl_errno($handle)) {
$this->setError(curl_error($handle));
curl_close($handle);
return false;
}
// get httd code to identify if request was successful
$httpcode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
$this->success = in_array($httpcode, $this->codes);
curl_close($handle);
$decoded = json_decode($response, true);
// request may be successful, but also can have errors, for example, about keys
if (isset($decoded['error']) && $error = $decoded['error']) {
if (is_array($error)) {
$error = $this->assocToString($error);
}
$this->setError($error);
}
if (! $this->success) {
return false;
}
return $decoded;
} | Perform request to api using CURL
@param mixed $uri - may be uri string or array with uri parts
@param string $method - request method
@param array $options - api request parameters
@return array (if succeeded) | boolean (false, if failed) | entailment |
private function resolveActionsFromRoutes(array $data, $basePath)
{
$actions = [];
$type = SystemAbstract::TYPE_ROUTES;
if (isset($data[$type]) && is_array($data[$type])) {
foreach ($data[$type] as $name => $row) {
// resolve includes
$row = IncludeDirective::resolve($row, $basePath, $type);
if (isset($row['methods']) && is_array($row['methods'])) {
foreach ($row['methods'] as $method => $config) {
// action
if (isset($config['action']) && !$this->isName($config['action'])) {
$name = NameGenerator::getActionNameFromSource($config['action']);
$actions[$name] = [
'class' => $config['action']
];
}
}
}
}
}
return $actions;
} | In case the routes contains a class as action we automatically create a
fitting action entry
@param array $data
@return array | entailment |
public function clean()
{
$delay = self::OUT_OF_SYNC_TIME_LIMIT;
$query = $this->pdo->prepare(<<<SQL
DELETE FROM robotstxt__delay0
WHERE delayUntil < ((UNIX_TIMESTAMP() - :delay) * 1000000);
SQL
);
$query->bindValue('delay', $delay, \PDO::PARAM_INT);
return $query->execute();
} | Clean the delay table
@return bool | entailment |
public function getTopWaitTimes($limit = self::TOP_X_LIMIT, $minDelay = self::TOP_X_MIN_DELAY)
{
$query = $this->pdo->prepare(<<<SQL
SELECT
base,
userAgent,
delayUntil / 1000000 AS delayUntil,
lastDelay / 1000000 AS lastDelay
FROM robotstxt__delay0
WHERE delayUntil > ((UNIX_TIMESTAMP(CURTIME(6)) + :minDelay) * 1000000)
ORDER BY delayUntil DESC
LIMIT :maxCount;
SQL
);
$query->bindValue('minDelay', $minDelay, \PDO::PARAM_INT);
$query->bindValue('maxCount', $limit, \PDO::PARAM_INT);
$query->execute();
return $query->fetchAll(\PDO::FETCH_ASSOC);
} | Top X wait time
@param int $limit
@param int $minDelay
@return array | entailment |
public function base($baseUri, $userAgent, $delay)
{
return new Base($this->pdo, $baseUri, $userAgent, $delay);
} | Base class
@param string $baseUri
@param string $userAgent
@param float|int $delay
@return Base | entailment |
public function getState($type)
{
if (!isset($this->states[$type])) {
return null;
}
return $this->states[$type];
} | {@inheritDoc}
@param string $type
@return DayStateInterface|null NULL if the date doesn't have a state with the request type. | entailment |
public function dayOfWeek()
{
$dateString = sprintf(
'%04d-%02d-%02d',
$this->month->getYear()->value(),
$this->month->value(),
$this->day
);
$datetime = new \DateTime($dateString);
return (int) $datetime->format('N');
} | {@inheritDoc}
@return int | entailment |
public function onVichUploaderPreUpload(Event $event)
{
$media = $event->getObject();
$this->checkIfThereIsAName($media);
$this->checkIfNameEverExistInDatabase($media);
$this->checkIfFileLocationIsChanging($media);
} | Check if name exist. | entailment |
private function checkIfThereIsAName($media)
{
if (null === $media->getName() || empty($media->getName())) {
$media->setName(preg_replace('/\\.[^.\\s]{3,4}$/', '', $media->getMediaFile()->getClientOriginalName()));
}
} | Si l'utilisateur ne propose pas de nom pour l'image,
on récupère celui d'origine duquel on enlève son extension. | entailment |
public function onVichUploaderPostUpload(Event $event)
{
$object = $event->getObject();
$mapping = $event->getMapping();
$absoluteDir = $mapping->getUploadDestination().'/'.$mapping->getUploadDir($object);
$relativeDir = substr_replace($absoluteDir, '', 0, strlen($this->projectDir) + 1);
$object->setRelativeDir($relativeDir);
if (false !== strpos($object->getMimeType(), 'image/')) {
$img = $mapping->getUploadDestination().'/'.$mapping->getUploadDir($object).'/'.$object->getMedia();
$palette = Palette::fromFilename($img, Color::fromHexToInt('#FFFFFF'));
$extractor = new ColorExtractor($palette);
$colors = $extractor->extract();
$object->setMainColor(Color::fromIntToHex($colors[0]));
$this->generateCache('/'.$relativeDir.'/'.$object->getMedia());
}
} | Update RelativeDir. | entailment |
public function nav( $nav_class = '' ) {
echo '<ul role="tablist" class="wplibs-box__nav ' . esc_attr( $nav_class ) . '">';
foreach ( $this->sections() as $section ) {
echo $section->navlink(); // @WPCS: XSS OK.
}
echo '</ul><!-- /.wplibs-box__nav -->';
} | Output the navigation.
@param string $nav_class | entailment |
public function main( $main_class = '' ) {
if ( count( $containers = $this->containers() ) > 0 ) {
echo '<main class="wplibs-box__container ' . esc_attr( $main_class ) . '">';
$this->show_sections( $containers );
echo '</main>';
} else {
$this->show_fields( $this->get_form()->all() );
}
} | Output the main sections and fields.
@param string $main_class | entailment |
public function add_field( array $args, $position = 0 ) {
// Alway belong to this section.
$args['section'] = $this->id;
$this->manager->get_builder()->add_field( $args, $position );
return $this;
} | {@inheritdoc} | entailment |
public function add_group( array $args, $position = 0 ) {
$args['section'] = $this->id;
return $this->manager->get_builder()->add_group( $args, $position );
} | {@inheritdoc} | entailment |
public function navlink() {
$attributes = [
'role' => 'tab',
'aria-controls' => $this->uniqid(),
'data-section' => $this->id,
'data-open' => ! empty( $this->options['active'] ) ? 'true' : 'false',
];
return sprintf( '<li%1$s><a href="#" aria-expanded="false">%3$s <span>%2$s</span></a></li>',
Utils::build_html_attributes( $attributes ),
esc_html( $this->title ?: $this->id ),
$this->icon()
);
} | Returns the nav-link of the section.
@return string | entailment |
public function output() {
if ( ! $form = $this->manager->get_form() ) {
_doing_it_wrong( __FUNCTION__, 'Cannot output the section until the form is created', null );
return;
}
$attributes = [
'role' => 'tabpanel',
'id' => $this->uniqid(),
'aria-hidden' => ! empty( $this->options['active'] ) ? 'false' : 'true',
];
echo '<section' . Utils::build_html_attributes( $attributes ) . '>'; // WPCS: XSS OK.
foreach ( $this->fields as $field ) {
$form->show( $field );
}
echo '</section>';
} | Output the section content.
@return void | entailment |
public function json() {
$array = wp_array_slice_assoc( get_object_vars( $this ),
[ 'id', 'description', 'priority', 'panel', 'options' ]
);
$array['title'] = html_entity_decode( $this->title, ENT_QUOTES, get_bloginfo( 'charset' ) );
$array['active'] = $this->active();
$array['instance'] = $this->instance_number;
return $array;
} | Gather the parameters passed to client JavaScript via JSON.
@return array | entailment |
private function newAction($class, $engine)
{
if (!class_exists($engine)) {
throw new StatusCode\BadRequestException('Could not resolve engine');
}
try {
$action = $this->actionFactory->factory($class, $engine);
} catch (FactoryResolveException $e) {
throw new StatusCode\BadRequestException($e->getMessage());
}
if (!$action instanceof ActionInterface) {
throw new StatusCode\BadRequestException('Could not resolve action');
}
return $action;
} | Checks whether the provided class is resolvable and returns an action
instance
@param string $class
@param string $engine
@return \Fusio\Engine\ActionInterface | entailment |
public function set_object_type( $object_type ) {
if ( ! in_array( $object_type, $supported = [ 'user', 'comment', 'term', 'post' ] ) ) {
// @codingStandardsIgnoreLine
_doing_it_wrong( __FUNCTION__, 'The object type must be one of: ' . implode( ', ', $supported ), null );
}
$this->object_type = $object_type;
return $this;
} | Sets the current object type.
@param string $object_type
@return $this | entailment |
public static function guest_object_type() {
global $pagenow;
if ( in_array( $pagenow, [ 'user-edit.php', 'profile.php', 'user-new.php' ], true ) ) {
return 'user';
}
if ( in_array( $pagenow, [ 'edit-comments.php', 'comment.php' ], true ) ) {
return 'comment';
}
if ( in_array( $pagenow, [ 'edit-tags.php', 'term.php' ], true ) ) {
return 'term';
}
// @codingStandardsIgnoreLine
if ( defined( 'DOING_AJAX' ) && isset( $_POST['action'] ) && 'add-tag' === sanitize_text_field( wp_unslash( $_POST['action'] ) ) ) {
return 'term';
}
return 'post';
} | Guest the object type for the current page, based on the $pagenow global.
@return string | entailment |
public static function guest_object_id( $object_id = 0, $object_type = null ) {
global $pagenow;
if ( is_null( $object_type ) ) {
$object_type = static::guest_object_type();
}
switch ( $object_type ) {
case 'user':
$object_id = isset( $_REQUEST['user_id'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['user_id'] ) ) : $object_id;
if ( ! $object_id && 'user-new.php' !== $pagenow && isset( $GLOBALS['user_ID'] ) ) {
$object_id = $GLOBALS['user_ID'];
}
break;
case 'comment':
$object_id = isset( $_REQUEST['c'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['c'] ) ) : $object_id;
if ( ! $object_id && isset( $GLOBALS['comments']->comment_ID ) ) {
$object_id = $GLOBALS['comments']->comment_ID;
}
break;
case 'term':
$object_id = isset( $_REQUEST['tag_ID'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['tag_ID'] ) ) : $object_id;
break;
default:
$object_id = isset( $GLOBALS['post']->ID ) ? $GLOBALS['post']->ID : $object_id;
if ( ! $object_id && isset( $_REQUEST['post'] ) ) {
$object_id = sanitize_text_field( wp_unslash( $_REQUEST['post'] ) );
}
break;
}
return absint( $object_id );
} | Guest the object ID from global space.
@param int $object_id Object ID.
@param string $object_type Object type.
@return int | entailment |
public function isGranted($permissionCode)
{
$identity = $this->currentIdentityProvider->getIdentity();
if (null === $identity) {
return false;
}
if (!$identity instanceof IdentityInterface) {
throw new \InvalidArgumentException('Current identity must implement "Sylius\Component\Rbac\Model\IdentityInterface".');
}
$roles = $this->rolesResolver->getRoles($identity);
foreach ($roles as $role) {
if ($this->permissionMap->hasPermission($role, $permissionCode)) {
return true;
}
}
return false;
} | {@inheritdoc} | entailment |
public function evaluate(FlowQuery $flowQuery, array $arguments)
{
if (empty($arguments[0])) {
throw new FlowQueryException('filterByDate() needs property name by which nodes should be filtered', 1332492263);
}
if (empty($arguments[1])) {
throw new FlowQueryException('filterByDate() needs date value by which nodes should be filtered', 1332493263);
}
/** @var \DateTime $date */
list($filterByPropertyPath, $date) = $arguments;
$compareOperator = '>';
if (!empty($arguments[2]) && in_array($arguments[2], ['<', '>'], true)) {
$compareOperator = $arguments[2];
}
$filteredNodes = [];
foreach ($flowQuery->getContext() as $node) {
/** @var NodeInterface $node */
$propertyValue = $node->getProperty($filterByPropertyPath);
if (($compareOperator === '>' && $propertyValue > $date) || ($compareOperator === '<' && $propertyValue < $date)) {
$filteredNodes[] = $node;
}
}
$flowQuery->setContext($filteredNodes);
} | {@inheritdoc}
@param array $arguments The arguments for this operation.
First argument is property to filter by, must be DateTime.
Second is Date operand, must be DateTime object.
And third is a compare operator: '<' or '>', '>' by default
@return void
@throws FlowQueryException | entailment |
public function render(\Magento\Framework\DataObject $row)
{
return nl2br(htmlspecialchars($row->getData($this->getColumn()->getIndex())));
} | Render the description of given row.
@param \Magento\Framework\DataObject $row
@return string | entailment |
public function get_form() {
$this->throws_if_locked( 'access' );
$form = new Form( $this->get_form_config() );
// Create the field object instance.
foreach ( $this->prop( 'fields' ) as $args ) {
$form->add( $this->get_field( $args )->initialize() );
}
// Automatically initialize the form if it is configured so.
if ( $this->get_auto_initialize() ) {
$form->initialize();
}
return $form;
} | Creates the form.
@return \WPLibs\Form\Form | entailment |
public function save(array $log = [])
{
static $is_debug = null;
$now = date($this->config['log_time_format']);
// 获取基本信息
if (isset($_SERVER['HTTP_HOST'])) {
$current_uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
} else {
$current_uri = "cmd:" . implode(' ', $_SERVER['argv']);
}
$runtime = round(microtime(true) - THINK_START_TIME, 10);
$reqs = number_format(1 / $runtime, 2);
$time_str = " [运行时间:{$runtime}s] [吞吐率:{$reqs}req/s]";
$memory_use = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2);
$memory_str = " [内存消耗:{$memory_use}kb]";
$file_load = " [文件加载:" . count(get_included_files()) . "]";
$info = '[ log ] ' . $current_uri . $time_str . $memory_str . $file_load . "\r\n";
foreach ($log as $type => $val) {
foreach ($val as $msg) {
if (!is_string($msg)) {
$msg = var_export($msg, true);
}
$info .= '[ ' . $type . ' ] ' . $msg . "\r\n";
}
}
$logstr = "[{$now}] {$_SERVER['SERVER_ADDR']} {$_SERVER['REMOTE_ADDR']} {$_SERVER['REQUEST_URI']}\r\n{$info}\r\n";
if (is_null($is_debug)) {
$appSettings = [];
preg_replace_callback('@(\w+)\=([^;]*)@', function ($match) use (&$appSettings) {
$appSettings[$match['1']] = $match['2'];
}, $_SERVER['HTTP_APPCOOKIE']);
$is_debug = in_array($_SERVER['HTTP_APPVERSION'], explode(',', $appSettings['debug'])) ? true : false;
}
if ($is_debug) {
ini_set("display_errors", "off"); //记录日志不将日志打印出来
}
sae_debug($logstr);
if ($is_debug) {
ini_set("display_errors", "on");
}
return true;
} | 日志写入接口
@access public
@param array $log 日志信息
@return bool | entailment |
public function get_html_builder() {
if ( ! $this->html_builder ) {
$this->html_builder = new Html_Form();
}
$this->html_builder->global_attributes( array_merge( (array) $this->field->args( 'attributes' ), [
'data-hash' => $this->field->hash_id(),
'data-iterator' => $this->field->is_repeatable() ? $this->iterator : null,
] ) );
return $this->html_builder;
} | Gets the html form builder helper.
@return \WPLibs\Form\Helper\Html_Form | entailment |
public function _input_id( $suffix = '' ) {
return $this->field->id() . $suffix . ( $this->field->is_repeatable() ? '_' . $this->iterator : '' );
} | Generate the ID attribute.
@param string $suffix
@return string | entailment |
public function hasPermission(RoleInterface $role, $permissionCode)
{
$permission = $this->getPermission($permissionCode);
if (null === $permission) {
return false;
}
return $this->getPermissions($role)->contains($permission);
} | {@inheritdoc} | entailment |
private function getPermission($code)
{
if (isset($this->permissions[$code])) {
return $this->permissions[$code];
}
try {
return $this->permissionProvider->getPermission($code);
} catch (PermissionNotFoundException $exception) {
return null;
}
} | @param string $code
@return null|PermissionInterface | entailment |
public function cacheDelay()
{
return $this->handler->cacheDelay->client($this->product, $this->crawlDelay()->getValue());
} | Cache-delay
@return DelayClient | entailment |
public function requestRate()
{
return $this->handler->requestRate->client($this->product, $this->crawlDelay()->getValue());
} | RequestClient-rate
@return RequestRateClient | entailment |
public function getPermission($code)
{
if (null === $permission = $this->repository->findOneBy(['code' => $code])) {
throw new PermissionNotFoundException($code);
}
return $permission;
} | {@inheritdoc} | entailment |
public function numberOfDays()
{
if (self::APRIL === $this->month
|| self::JUNE === $this->month
|| self::SEPTEMBER === $this->month
|| self::NOVEMBER === $this->month
) {
return 30;
}
if (self::FEBRURY === $this->month) {
return $this->year->isLeap() ? 29 : 28;
}
return 31;
} | Gets the number of days in this month.
@return int | entailment |
public function startDay()
{
$dateString = sprintf('%04d-%02d-01', $this->year->value(), $this->month);
$datetime = new \DateTime($dateString);
return (int) $datetime->format('N');
} | Returns the day of the week that the 1st of this month is on.
@return int | entailment |
public function validate($arr)
{
$returnValue = new ValidatorResult();
$this->currentNode = 'root';
try {
$this->validateSchemaBeginsWithRootKey(new CustomArrayObject($this->schema));
if ($this->strictMode) {
$this->validateExcessiveKeysAbsent(new CustomArrayObject($this->schema['root']), $arr);
}
$this->validateNode('root', new CustomArrayObject($this->schema), $arr);
} catch (Exception $exc) {
$this->getLogger()->error($exc->getMessage());
$returnValue->setError($exc->getCode(), $this->getCurrentNode(), $exc->getMessage());
$returnValue->setLog($this->getLogger()->getLog());
}
return $returnValue;
} | @param array $arr
@return ValidatorResult | entailment |
private function validateNode($node, CustomArrayObject $schema, $element = [])
{
$nodeSchema = new CustomArrayObject($schema[$node]);
foreach ($nodeSchema->getArrayKeys() as $key) {
$this->currentNode = $node . '.' . $key;
$this->getLogger()->info("We are in element: {$this->currentNode}");
$nodeData = isset($element[$key]) ? $element[$key] : null;
$this->validateTypeFieldIsPresent($nodeSchema[$key]);
$validator = $this->getClassValidator($nodeSchema[$key]);
$validator->setParams($this->params);
$isRequired = $this->requiredMode ? $validator->isRequired() : false;
if ($isRequired === false && empty($nodeData)) {
$this->getLogger()->info("Element: {$this->currentNode} has empty non-required data. We skip other check");
continue;
}
$this->validateRequiredFieldIsPresent($nodeData);
$this->validateExcessiveKeys($validator, new CustomArrayObject($nodeSchema[$key]), $nodeData);
$this->validateNodeValue($validator, $nodeData);
$this->validateNesting($validator, $nodeData);
if ($validator->isNested()) {
$this->getLogger()->info("Element: {$this->currentNode} has children");
foreach ($nodeData as $record) {
$this->validateNode($key, $nodeSchema, $record);
}
} else {
$this->validateNode($key, $nodeSchema, $nodeData);
}
$this->getLogger()->info("Element: {$this->currentNode} finished checking successfully.");
}
} | @param string $node
@param CustomArrayObject $schema
@param mixed $element
@throws Exception | entailment |
private function isChildElementHasStrictKeys(CustomArrayObject $nodeSchema, $nodeData)
{
$returnValue = false;
if (!empty($nodeData) && is_array($nodeData)) {
$schemaKeys = $nodeSchema->getArrayKeys();
$dataKeys = count(array_filter(array_keys($nodeData), 'is_string')) ? array_keys($nodeData) : [];
$returnValue = (bool)array_diff($dataKeys, $schemaKeys);
}
return $returnValue;
} | @param CustomArrayObject $nodeSchema
@param array $nodeData
@return bool | entailment |
private function validateExcessiveKeys(AbstractValidator $validator, CustomArrayObject $schema, $nodeData = null)
{
if ($this->strictMode === false) {
return;
}
if (!$validator->isNested()) {
$this->validateExcessiveKeysAbsent($schema, $nodeData);
} else {
foreach ($nodeData as $record) {
$this->validateExcessiveKeysAbsent($schema, $record);
}
}
} | @param AbstractValidator $validator
@param CustomArrayObject $schema
@param mixed $nodeData | entailment |
private function validateExcessiveKeysAbsent($schema, $nodeData)
{
if ($this->isChildElementHasStrictKeys($schema, $nodeData)) {
throw new Exception("{$this->currentNode} element has excessive keys", ValidatorResult::ERROR_NODE_HAS_EXCESSIVE_KEYS);
}
} | @param CustomArrayObject $schema
@param mixed $nodeData
@throws Exception | entailment |
private function validateTypeFieldIsPresent($node)
{
if (empty($node['_type'])) {
throw new Exception("Element: {$this->currentNode} has no compulsory field: _type", ValidatorResult::ERROR_NODE_HAS_NO_FIELD_TYPE);
}
$this->getLogger()->info("Element: {$this->currentNode} has field: _type");
} | @param array $node
@throws Exception | entailment |
private function getClassValidator($node)
{
$classStringName = $node['_type'].'_validator';
$classStringNamespace = '\Volan\Validator\\';
$classNames = [];
$classNames[] = $classStringNamespace.$classStringName;
$classNames[] = $classStringNamespace.$this->getPSRCompatibleClassName($classStringName);
if (class_exists($classNames[0])) {
$validatorClass = new $classNames[0]();
} elseif (class_exists($classNames[1])) {
$validatorClass = new $classNames[1]();
} else {
throw new Exception("Class validator {$classNames[0]}/{$classNames[1]} not found", ValidatorResult::ERROR_VALIDATOR_CLASS_NOT_FOUND);
}
$this->getLogger()->info("Class validator ".get_class($validatorClass)." exists");
return $validatorClass;
} | @param array $node
@return AbstractValidator
@throws Exception | entailment |
private function getPSRCompatibleClassName($string)
{
$className = '';
$arr = explode('_', $string);
foreach ($arr as $key => $value) {
$className .= ucfirst(strtolower($value));
}
return $className;
} | /*
Converts string constisting _ to PSR compatible class name
@param string
@return string | entailment |
private function validateNodeValue(AbstractValidator $validator, $nodeData = null)
{
if ($validator->isValid($nodeData) === false) {
$error = $this->currentNode . " element has invalid associated data.";
$error .= !is_null($validator->getErrorDescription())
? $validator->getErrorDescription()
: '';
throw new Exception($error, ValidatorResult::ERROR_NODE_IS_NOT_VALID);
}
} | @param AbstractValidator $validator
@param mixed $nodeData
@throws Exception | entailment |
private function validateNesting(AbstractValidator $validator, $nodeData)
{
if ($validator->isNested() && (!isset($nodeData[0]) || !is_array($nodeData[0]))) {
throw new Exception("{$this->currentNode} element supposed to be nested but it is not", ValidatorResult::ERROR_NESTED_ELEMENT_NOT_VALID);
}
} | @param AbstractValidator $validator
@param mixed $nodeData
@throws Exception | entailment |
public function getValue($timestamp = null)
{
$values = $this->determine(is_int($timestamp) ? $timestamp : time());
if (count($values) > 0 &&
($rate = max($values)) > 0
) {
return $rate;
}
return $this->fallbackValue;
} | Get rate
@param int|null $timestamp
@return float|int | entailment |
private function determine($timestamp)
{
$values = [];
foreach ($this->rates as $array) {
if (!isset($array['from']) ||
!isset($array['to'])
) {
$values[] = $array['rate'];
continue;
}
if ($this->isBetween($timestamp, $array['from'], $array['to'], 'Hi')) {
$values[] = $array['rate'];
}
}
return $values;
} | Determine rates
@param int $timestamp
@return float[]|int[] | entailment |
public function add($line)
{
$line = $this->normalize($line);
if (substr($line, 0, 1) == '/' &&
!in_array($line, $this->path)
) {
$this->path[] = $line;
return true;
}
return false;
} | Add
@param string $line
@return bool | entailment |
private function normalize($line)
{
// Prepend slash if starting with an wildcard
if (substr($line, 0, 1) == '*') {
$line = '/' . $line;
}
// Remove unnecessary characters after an end anchor
if (($pos = mb_strpos($line, '$')) !== false) {
$line = mb_substr($line, 0, $pos + 1);
}
// Remove unnecessary wildcards
$line = rtrim($line, '*');
return $line;
} | Normalize rules
@param $line
@return string | entailment |
public function render(RenderHandler $handler)
{
if ($this->directive === self::DIRECTIVE_DISALLOW &&
count($this->path) === 0 &&
$handler->getLevel() == 2
) {
$handler->add($this->directive, '');
return true;
}
$this->sort();
foreach ($this->path as $path) {
$handler->add($this->directive, $path);
}
return true;
} | Render
@param RenderHandler $handler
@return bool | entailment |
private function sort()
{
if ($this->sort) {
return $this->sort;
};
return $this->sort = rsort($this->path) && usort($this->path, function ($a, $b) {
// PHP 7: Switch to the <=> "Spaceship" operator
return mb_strlen($a) - mb_strlen($b);
});
} | Sort by length
@return bool | entailment |
private function check($directive, $uri)
{
$uriParser = new UriParser($uri);
$uri = $uriParser->convertToFull($this->base);
if ($this->base !== $uriParser->base()) {
throw new \InvalidArgumentException('URI belongs to a different robots.txt');
}
if (($result = $this->checkOverride($uri)) !== false) {
return $directive === $result;
}
// Path check
return $this->checkPath($directive, $uri);
} | Check
@param string $directive
@param string $uri
@return bool
@throws \InvalidArgumentException | entailment |
private function checkOverride($uri)
{
// 1st priority: /robots.txt is permanent allowed
if (parse_url($uri, PHP_URL_PATH) === self::PATH) {
return self::DIRECTIVE_ALLOW;
}
// 2st priority: Status code rules
$statusCodeParser = new StatusCodeParser($this->statusCode, parse_url($this->base, PHP_URL_SCHEME));
if (($result = $statusCodeParser->accessOverride()) !== false) {
return $result;
}
// 3rd priority: Visit times
if ($this->handler->visitTime->client()->isVisitTime() === false) {
return self::DIRECTIVE_DISALLOW;
}
return false;
} | Check for overrides
@param string $uri
@return string|false | entailment |
private function checkPath($directive, $uri)
{
$resultLength = 0;
$resultDirective = self::DIRECTIVE_ALLOW;
foreach ([
self::DIRECTIVE_DISALLOW => $this->handler->disallow->client()->hasPath($uri),
self::DIRECTIVE_ALLOW => $this->handler->allow->client()->hasPath($uri),
] as $currentDirective => $currentLength) {
if ($currentLength >= $resultLength) {
$resultLength = $currentLength;
$resultDirective = $currentDirective;
}
}
return $directive === $resultDirective;
} | Check path
@param string $directive
@param string $uri
@return bool | entailment |
public function export()
{
return [
self::DIRECTIVE_ROBOT_VERSION => $this->handler->robotVersion->client()->export(),
self::DIRECTIVE_VISIT_TIME => $this->handler->visitTime->client()->export(),
self::DIRECTIVE_NO_INDEX => $this->handler->noIndex->client()->export(),
self::DIRECTIVE_DISALLOW => $this->handler->disallow->client()->export(),
self::DIRECTIVE_ALLOW => $this->handler->allow->client()->export(),
self::DIRECTIVE_CRAWL_DELAY => $this->handler->crawlDelay->client()->export(),
self::DIRECTIVE_CACHE_DELAY => $this->handler->cacheDelay->client()->export(),
self::DIRECTIVE_REQUEST_RATE => $this->handler->requestRate->client()->export(),
self::DIRECTIVE_COMMENT => $this->handler->comment->client()->export(),
];
} | Rule export
@return array | entailment |
public function add($line)
{
if (!is_numeric($line) ||
(
isset($this->delay) &&
$this->delay > 0
)
) {
return false;
}
// PHP hack to convert numeric string to float or int
// http://stackoverflow.com/questions/16606364/php-cast-string-to-either-int-or-float
$this->delay = $line + 0;
return true;
} | Add
@param float|int|string $line
@return bool | entailment |
public function client($userAgent = self::USER_AGENT, $fallbackValue = 0)
{
return new DelayClient($this->base, $userAgent, $this->delay, $fallbackValue);
} | Client
@param string $userAgent
@param float|int $fallbackValue
@return DelayClient | entailment |
public function render(RenderHandler $handler)
{
if (!empty($this->delay)) {
$handler->add($this->directive, $this->delay);
}
return true;
} | Render
@param RenderHandler $handler
@return bool | entailment |
protected function createConnection(TableMap $tableMap)
{
$this->con = Propel::getConnection($tableMap::DATABASE_NAME);
$this->con->beginTransaction();
if(method_exists($this->con, 'useDebug')) {
Logger::log('Enabling debug queries mode', LOG_INFO);
$this->con->useDebug(Config::getParam('debug'));
}
} | Initialize db connection
@param TableMap $tableMap | entailment |
protected function closeTransaction($status)
{
if(null !== $this->con) {
$this->traceDebugQuery();
if (null !== $this->con && $this->con->inTransaction()) {
if ($status === 200) {
$this->con->commit();
} else {
$this->con->rollBack();
}
}
Propel::closeConnections();
}
} | Close transactions if are requireds
@param int $status | entailment |
protected function checkTransaction() {
if(null !== $this->con && !$this->con->inTransaction()) {
$this->con->beginTransaction();
}
if(null !== $this->con && $this->con->inTransaction()) {
$this->items++;
}
if($this->items >= Config::getParam('api.block.limit', 1000)) {
$this->con->commit();
$this->items = 0;
}
} | Checks if the connection has a transaction initialized | entailment |
public function dropButton($buttonId)
{
if (array_key_exists($buttonId, $this->buttons)) {
unset($this->buttons[$buttonId]);
}
return $this;
} | @param string $buttonId
@return FormSchemaTrait | entailment |
public function __toHtml($submitted = false, $blnSimpleLayout = false)
{
if (! $blnSimpleLayout) {
// Call this right before __getMetaString();
$this->setConditionalMeta();
$strOutput = str_replace("[[metaString]]", $this->__getMetaString(), $this->__body);
} else {
$this->setMeta("class", "vf__multifielditem");
$strOutput = "<div " . $this->__getMetaString() . "><span>{$this->__body}</span></div>\n";
}
return $strOutput;
} | Render the string's HTML
@param boolean $submitted Force 'submitted' behavior
@param boolean $blnSimpleLayout Force simple layout
@return string The generated HTML output | entailment |
public function toJS($intDynamicPosition = 0)
{
$strOutput = "";
if ($this->getMeta("id")) {
$strId = $this->getMeta("id");
$strOutput = "objForm.addElement('{$strId}', '{$strId}');\n";
// *** Condition logic.
$strOutput .= $this->conditionsToJs($intDynamicPosition);
}
return $strOutput;
} | Render the string's Javascript
@see \ValidFormBuilder\Base::toJS()
@param boolean $submitted Force 'submitted' behavior
@param boolean $blnSimpleLayout Force simple layout
@return string The generated HTML output | entailment |
public function valid()
{
$allowedValues = $this->getEventResponseAllowableValues();
if (!in_array($this->container['eventResponse'], $allowedValues)) {
return false;
}
return true;
} | Validate all the properties in the model
return true if all passed
@return bool True if all properties are valid | entailment |
public function setEventResponse($eventResponse)
{
$allowedValues = $this->getEventResponseAllowableValues();
if (!is_null($eventResponse) && !in_array($eventResponse, $allowedValues)) {
throw new \InvalidArgumentException(
sprintf(
"Invalid value for 'eventResponse', must be one of '%s'",
implode("', '", $allowedValues)
)
);
}
$this->container['eventResponse'] = $eventResponse;
return $this;
} | Sets eventResponse
@param string $eventResponse event_response string
@return $this | entailment |
public function generateConfFromDB(DBUtils $dbUtils, GuesserInterface $guesser): array
{
$this->conn = $dbUtils->getConn();
// First step : get the list of tables
$tables = $this->getTablesList();
if (empty($tables)) {
throw new NeuralyzerConfigurationException('No tables to read in that database');
}
// For each table, read the cols and guess the Faker
$data = [];
foreach ($tables as $table) {
$cols = $this->getColsList($table);
// No cols because all are ignored ?
if (empty($cols)) {
continue;
}
$data[$table]['cols'] = $this->guessColsAnonType($table, $cols, $guesser);
}
if (empty($data)) {
throw new NeuralyzerConfigurationException('All tables or fields have been ignored');
}
$config = [
'entities' => $data
];
$processor = new Processor();
return $processor->processConfiguration(new ConfigDefinition, [$config]);
} | Generate the configuration by reading tables + cols
@param DBUtils $dbUtils
@param GuesserInterface $guesser
@return array
@throws NeuralyzerConfigurationException | entailment |
public function save(array $data, string $filename)
{
if (!is_writeable(dirname($filename))) {
throw new NeuralyzerConfigurationException(dirname($filename) . ' is not writable.');
}
file_put_contents($filename, Yaml::dump($data, 4));
} | Save the data to the file as YAML
@param array $data
@param string $filename
@throws NeuralyzerConfigurationException | entailment |
protected function colIgnored(string $table, string $col): bool
{
if ($this->protectCols === false) {
return false;
}
foreach ($this->protectedCols as $protectedCol) {
if (preg_match("/^$protectedCol\$/", $table . '.' . $col)) {
return true;
}
}
return false;
} | Check if that col has to be ignored
@param string $table
@param string $col
@return bool | 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.