sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function handleMaintenanceMode()
{
// Authorize logged in admins on the fly
if ($this->doesCurrentUserHaveAccess())
{
return true;
}
if (Craft::$app->request->isSiteRequest && $this->settings->maintenanceModeEnabled)
{
$requestingIp = $this->getRequestingIp();
$authorizedIps = $this->settings->maintenanceModeAuthorizedIps;
$maintenanceUrl = $this->settings->maintenanceModePageUrl;
if ($maintenanceUrl == Craft::$app->request->getUrl())
{
return true;
}
if (empty($authorizedIps))
{
$this->forceRedirect($maintenanceUrl);
}
if (is_array($authorizedIps) && count($authorizedIps))
{
if (in_array($requestingIp, $authorizedIps))
{
return true;
}
foreach ($authorizedIps as $authorizedIp)
{
$authorizedIp = str_replace('*', '', $authorizedIp);
if (stripos($requestingIp, $authorizedIp) === 0)
{
return true;
}
}
$this->forceRedirect($maintenanceUrl);
}
}
} | Restricts accessed based on authorizedIps
@return bool
@throws HttpException
@throws \yii\base\InvalidConfigException | entailment |
protected function doesCurrentUserHaveAccess()
{
// Admins have access by default
if (Craft::$app->user->getIsAdmin())
{
return true;
}
// User has the right permission
if (Craft::$app->user->checkPermission(Patrol::MAINTENANCE_MODE_BYPASS_PERMISSION))
{
return true;
}
return false;
} | Returns whether or not the current user has access during maintenance mode | entailment |
public function getRequestingIp()
{
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
return $_SERVER['HTTP_CF_CONNECTING_IP'];
}
elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
{
return isset($_SERVER['HTTP_X_FORWARDED_FOR']);
}
elseif (isset($_SERVER['HTTP_X_REAL_IP']))
{
return isset($_SERVER['HTTP_X_REAL_IP']);
}
else
{
return $_SERVER['REMOTE_ADDR'];
}
} | Ensures that we get the right IP address even if behind CloudFlare or most proxies
@return string | entailment |
protected function forceRedirect($redirectTo = '')
{
if (empty($redirectTo))
{
$this->runDefaultBehavior();
}
Craft::$app->response->redirect($redirectTo, $this->settings->redirectStatusCode);
} | @param string $redirectTo
@throws HttpException | entailment |
public function parseAuthorizedIps($ips)
{
$ips = trim($ips);
if (is_string($ips) && !empty($ips))
{
$ips = explode(PHP_EOL, $ips);
}
return $this->filterOutArrayValues(
$ips, function($val) {
return preg_match('/^[0-9\.\*]{5,15}$/i', $val);
}
);
} | Parses authorizedIps to ensure they are valid even when created from a string
@param array|string $ips
@return array | entailment |
protected function filterOutArrayValues($values = null, \Closure $filter = null, $preserveKeys = false)
{
$data = [];
if (is_array($values) && count($values))
{
foreach ($values as $key => $value)
{
$value = trim($value);
if (!empty($value))
{
if (is_callable($filter) && $filter($value))
{
$data[$key] = $value;
}
}
}
if (!$preserveKeys)
{
$data = array_values($data);
}
}
return $data;
} | Filters out array values by using a custom filter
@param array|string|null $values
@param callable|\Closure $filter
@param bool $preserveKeys
@return array | entailment |
public function parseRestrictedAreas($areas)
{
if (is_string($areas) && !empty($areas))
{
$areas = trim($areas);
$areas = explode(PHP_EOL, $areas);
}
return $this->filterOutArrayValues(
$areas,
function($val) {
$valid = preg_match('/^[\/\{\}a-z\_\-\?\=]{1,255}$/i', $val);
if (!$valid)
{
return false;
}
return true;
}
);
} | Parse restricted areas to ensure they are valid even when created from a string
@param array|string $areas
@return array | entailment |
public function addFunction($functionName, $callback, $timeout = null)
{
if (isset($this->functions[$functionName])) {
throw new \InvalidArgumentException("Function $functionName is already registered");
}
$this->functions[$functionName] = array('callback' => $callback);
if (null !== $timeout) {
$this->functions[$functionName]['timeout'] = $timeout;
}
return $this;
} | @param string $functionName
@param callback $callback
@param int $timeout
@throws \InvalidArgumentException
@return self | entailment |
public function unregister($functionName)
{
if (!isset($this->functions[$functionName])) {
throw new \InvalidArgumentException("Function $functionName is not registered");
}
unset($this->functions[$functionName]);
return $this;
} | @param string
@throws \InvalidArgumentException
@return self | entailment |
protected function doWork($socket)
{
Connection::send($socket, 'grab_job');
$resp = array('function' => 'noop');
while (count($resp) && $resp['function'] == 'noop') {
$resp = Connection::blockingRead($socket);
}
if (in_array($resp['function'], array('noop', 'no_job'))) {
return false;
}
if ($resp['function'] != 'job_assign') {
throw new Exception('Internal error - Job was not assigned after it was grabbed by this worker');
}
$name = $resp['data']['func'];
$handle = $resp['data']['handle'];
$arg = array();
if (isset($resp['data']['arg']) &&
Connection::stringLength($resp['data']['arg'])) {
$arg = json_decode($resp['data']['arg'], true);
if ($arg === null) {
$arg = $resp['data']['arg'];
}
}
try {
$this->callStartCallbacks($handle, $name, $arg);
$functionCallback = $this->functions[$name]['callback'];
$result = call_user_func($functionCallback, $arg);
if (!$result) {
$result = '';
}
$this->jobComplete($socket, $handle, $result);
$this->callCompleteCallbacks($handle, $name, $result);
} catch (JobException $e) {
$this->jobFail($socket, $handle);
$this->callFailCallbacks($handle, $name, $e);
}
// Force the job's destructor to run
$job = null;
return true;
} | Listen on the socket for work.
Sends the 'grab_job' command and then listens for either the 'noop' or
the 'no_job' command to come back. If the 'job_assign' comes down the
pipe then we run that job.
@param resource $socket The socket to work on
@throws \MHlavac\Gearman\Exception
@return bool Returns true if work was done, false if not
@see Net_Gearman_Connection::send() | entailment |
public function jobStatus($numerator, $denominator)
{
Connection::send($this->conn, 'work_status', array(
'handle' => $this->handle,
'numerator' => $numerator,
'denominator' => $denominator,
));
} | Update Gearman with your job's status.
@param int $numerator The numerator (e.g. 1)
@param int $denominator The denominator (e.g. 100)
@see MHlavac\Gearman\Connection::send() | entailment |
public function attachCallback($callback, $type = self::JOB_COMPLETE)
{
if (!is_callable($callback)) {
throw new Exception('Invalid callback specified');
}
if (!isset($this->callback[$type])) {
throw new Exception('Invalid callback type specified.');
}
$this->callback[$type][] = $callback;
} | @param callback $callback
@param int $type
@throws \MHlavac\Gearman\Exception When an invalid callback or type is specified. | entailment |
public function init()
{
parent::init();
self::$plugin = $this;
$this->_setPluginComponents();
$this->_setLogging();
$this->_registerCpRoutes();
$this->_registerEventHandlers();
} | ========================================================================= | entailment |
public function doNormal($functionName, $workload, $unique = null)
{
return $this->runSingleTaskSet($this->createSet($functionName, $workload, $unique));
} | Runs a single task and returns a string representation of the result.
@param string $functionName
@param string $workload
@param string $unique
@return string | entailment |
public function doHigh($functionName, $workload, $unique = null)
{
return $this->runSingleTaskSet($this->createSet($functionName, $workload, $unique, Task::JOB_HIGH));
} | Runs a single high priority task and returns a string representation of the result.
@param string $functionName
@param string $workload
@param string $unique
@return string | entailment |
public function doLow($functionName, $workload, $unique = null)
{
return $this->runSingleTaskSet($this->createSet($functionName, $workload, $unique, Task::JOB_LOW));
} | Runs a single low priority task and returns a string representation of the result.
@param string $functionName
@param string $workload
@param string $unique
@return string | entailment |
protected function runSingleTaskSet(Set $set)
{
$this->runSet($set);
$task = current($set->tasks);
return $task->result;
} | @param Set $set
@return string | entailment |
public function doBackground($functionName, $workload, $unique = null)
{
$set = $this->createSet($functionName, $workload, $unique, Task::JOB_BACKGROUND);
$this->runSet($set);
return current($set->tasks);
} | Runs a task in the background, returning a job handle which can be used
to get the status of the running task.
@param string $functionName
@param string $workload
@param string $unique
@return Task | entailment |
public function doHighBackground($functionName, $workload, $unique = null)
{
$set = $this->createSet($functionName, $workload, $unique, Task::JOB_HIGH_BACKGROUND);
$this->runSet($set);
return current($set->tasks);
} | Runs a task in the background, returning a job handle which can be used
to get the status of the running task.
@param string $functionName
@param string $workload
@param string $unique
@return Task | entailment |
public function doLowBackground($functionName, $workload, $unique = null)
{
$set = $this->createSet($functionName, $workload, $unique, Task::JOB_LOW_BACKGROUND);
$this->runSet($set);
return current($set->tasks);
} | Runs a task in the background, returning a job handle which can be used
to get the status of the running task.
@param string $functionName
@param string $workload
@param string $unique
@return Task | entailment |
public function doEpoch($functionName, $workload, $epoch, $unique = null)
{
$set = $this->createSet($functionName, $workload, $unique, Task::JOB_EPOCH, $epoch);
$this->runSet($set);
return current($set->tasks);
} | Schedule a background task, returning a job handle which can be used
to get the status of the running task.
@param string $functionName
@param string $workload
@param int $epoch
@param string $unique
@return Task | entailment |
private function createSet($functionName, $workload, $unique = null, $type = Task::JOB_NORMAL, $epoch = 0)
{
if (null === $unique) {
$unique = $this->generateUniqueId();
}
$task = new Task($functionName, $workload, $unique, $type, $epoch);
$task->type = $type;
$set = new Set();
$set->addTask($task);
return $set;
} | @param string $functionName
@param string $workload
@param string $unique
@param int $type Type of job to run task as
@param int $epoch Time of job to run at (unix timestamp)
@return Set | entailment |
protected function submitTask(Task $task)
{
switch ($task->type) {
case Task::JOB_LOW:
$type = 'submit_job_low';
break;
case Task::JOB_LOW_BACKGROUND:
$type = 'submit_job_low_bg';
break;
case Task::JOB_HIGH_BACKGROUND:
$type = 'submit_job_high_bg';
break;
case Task::JOB_BACKGROUND:
$type = 'submit_job_bg';
break;
case Task::JOB_EPOCH:
$type = 'submit_job_epoch';
break;
case Task::JOB_HIGH:
$type = 'submit_job_high';
break;
default:
$type = 'submit_job';
break;
}
$arg = $task->arg;
$params = array(
'func' => $task->func,
'uniq' => $task->uniq,
'arg' => $arg,
);
if ($task->type == Task::JOB_EPOCH) {
$params['epoch'] = $task->epoch;
}
$s = $this->getConnection();
Connection::send($s, $type, $params);
if (!is_array(Connection::$waiting[(int) $s])) {
Connection::$waiting[(int) $s] = array();
}
array_push(Connection::$waiting[(int) $s], $task);
} | Submit a task to Gearman.
@param Task $task Task to submit to Gearman
@see \MHlavac\Gearman\Task, \MHlavac\Gearman\Client::runSet() | entailment |
public function runSet(Set $set, $timeout = null)
{
foreach ($this->getServers() as $server) {
$conn = Connection::connect($server, $timeout);
if (!Connection::isConnected($conn)) {
unset($this->servers[$server]);
continue;
}
$this->conn[] = $conn;
}
$totalTasks = $set->tasksCount;
$taskKeys = array_keys($set->tasks);
$t = 0;
if ($timeout !== null) {
$socket_timeout = min(10, (int) $timeout);
} else {
$socket_timeout = 10;
}
while (!$set->finished()) {
if ($timeout !== null) {
if (empty($start)) {
$start = microtime(true);
} else {
$now = microtime(true);
if ($now - $start >= $timeout) {
break;
}
}
}
if ($t < $totalTasks) {
$k = $taskKeys[$t];
$this->submitTask($set->tasks[$k]);
if ($set->tasks[$k]->type == Task::JOB_BACKGROUND ||
$set->tasks[$k]->type == Task::JOB_HIGH_BACKGROUND ||
$set->tasks[$k]->type == Task::JOB_LOW_BACKGROUND ||
$set->tasks[$k]->type == Task::JOB_EPOCH) {
$set->tasks[$k]->finished = true;
--$set->tasksCount;
}
++$t;
}
$write = null;
$except = null;
$read = $this->conn;
socket_select($read, $write, $except, $socket_timeout);
foreach ($read as $socket) {
$resp = Connection::read($socket);
if (count($resp)) {
$this->handleResponse($resp, $socket, $set);
}
}
}
} | Run a set of tasks.
@param Set $set A set of tasks to run
@param int $timeout Time in seconds for the socket timeout. Max is 10 seconds
@see MHlavac\Gearman\Set, MHlavac\Gearman\Task | entailment |
protected function handleResponse($resp, $s, Set $tasks)
{
if (isset($resp['data']['handle']) &&
$resp['function'] != 'job_created') {
$task = $tasks->getTask($resp['data']['handle']);
}
switch ($resp['function']) {
case 'work_complete':
$tasks->tasksCount--;
$task->complete($resp['data']['result']);
break;
case 'work_status':
$n = (int) $resp['data']['numerator'];
$d = (int) $resp['data']['denominator'];
$task->status($n, $d);
break;
case 'work_fail':
$tasks->tasksCount--;
$task->fail();
break;
case 'job_created':
$task = array_shift(Connection::$waiting[(int) $s]);
$task->handle = $resp['data']['handle'];
if ($task->type == Task::JOB_BACKGROUND) {
$task->finished = true;
}
$tasks->handles[$task->handle] = $task->uniq;
break;
case 'error':
throw new Exception('An error occurred');
default:
throw new Exception(
'Invalid function ' . $resp['function']
);
}
} | Handle the response read in.
@param array $resp The raw array response
@param resource $s The socket
@param Set $tasks The tasks being ran
@throws \MHlavac\Gearman\Exception | entailment |
public function disconnect()
{
if (!is_array($this->conn) || !count($this->conn)) {
return;
}
foreach ($this->conn as $conn) {
Connection::close($conn);
}
} | Disconnect from Gearman. | entailment |
function it_provides_access_to_error_details(){
$this->getCode()->shouldBe( 400 );
$this->getErrorMessage()->shouldBeString();
$this->getErrorMessage()->shouldBe( 'BadRequestError: "Missing personalisation: name"' );
$this->getErrors()->shouldBeArray();
$this->getErrors()[0]->shouldBeArray();
$this->getErrors()[0]['error']->shouldBe('BadRequestError');
$this->getErrors()[0]['message']->shouldBe('Missing personalisation: name');
} | Test constructor variations | entailment |
public function sendSms( $phoneNumber, $templateId, array $personalisation = array(), $reference = '', $smsSenderId = NULL ){
return $this->httpPost(
self::PATH_NOTIFICATION_SEND_SMS,
$this->buildSmsPayload( 'sms', $phoneNumber, $templateId, $personalisation, $reference, $smsSenderId)
);
} | Send an SMS message.
@param string $phoneNumber
@param string $templateId
@param array $personalisation
@param string $reference
@return array | entailment |
public function sendEmail( $emailAddress, $templateId, array $personalisation = array(), $reference = '', $emailReplyToId = NULL ){
return $this->httpPost(
self::PATH_NOTIFICATION_SEND_EMAIL,
$this->buildEmailPayload( 'email', $emailAddress, $templateId, $personalisation, $reference, $emailReplyToId )
);
} | Send an Email message.
@param string $emailAddress
@param string $templateId
@param array $personalisation
@param string $reference
@return array | entailment |
public function sendLetter( $templateId, array $personalisation = array(), $reference = '' ){
$payload = $this->buildPayload( 'letter', '', $templateId, $personalisation, $reference );
return $this->httpPost(
self::PATH_NOTIFICATION_SEND_LETTER,
$payload
);
} | Send a Letter
@param string $templateId
@param array $personalisation
@param string $reference
@return array | entailment |
public function sendPrecompiledLetter( $reference, $pdf_data, $postage = NULL ){
$payload = [
'reference' => $reference,
'content' => base64_encode($pdf_data)
];
if ($postage != NULL) {
$payload['postage'] = $postage;
}
return $this->httpPost(
self::PATH_NOTIFICATION_SEND_LETTER,
$payload
);
} | Send a precompiled letter.
Example usage: sendPrecompiledLetter($templateId, $ref, file_get_contents(<PATH TO FILE>)))
@param string $templateId
@param string $reference
@param string $pdf_data
@return array | entailment |
public function getNotification( $notificationId ){
$path = sprintf( self::PATH_NOTIFICATION_LOOKUP, $notificationId );
return $this->httpGet( $path );
} | Returns details about the passed notification ID.
NULL is returned if no notification is found for the ID.
@param string $notificationId
@return array|null | entailment |
public function listNotifications( array $filters = array() ){
// Only allow the following filter keys.
$filters = array_intersect_key( $filters, array_flip([
'older_than',
'reference',
'status',
'template_type',
]));
return $this->httpGet( self::PATH_NOTIFICATION_LIST, $filters );
} | Returns a list of all notifications for the current Service ID.
Filter supports:
- older_than
- reference
- status
- template_type
@param array $filters
@return mixed|null | entailment |
public function listReceivedTexts( array $filters = array() ){
// Only allow the following filter keys.
$filters = array_intersect_key( $filters, array_flip([
'older_than'
]));
return $this->httpGet( self::PATH_RECEIVED_TEXT_LIST, $filters );
} | Returns a list of all received texts for the current Service ID.
Filter supports:
- older_than
@param array $filters
@return mixed|null | entailment |
public function getTemplate( $templateId ){
$path = sprintf( self::PATH_TEMPLATE_LOOKUP, $templateId );
return $this->httpGet( $path );
} | Get a template by ID.
@param string $templateId
@return array | entailment |
public function getTemplateVersion( $templateId, $version ){
$path = sprintf( self::PATH_TEMPLATE_VERSION_LOOKUP, $templateId, $version );
return $this->httpGet( $path );
} | Get a template by ID and version.
@param string $templateId
@param int $version
@return array | entailment |
public function listTemplates( $templateType = null ){
$queryParams = is_null( $templateType ) ? [] : [ 'type' => $templateType ];
return $this->httpGet( self::PATH_TEMPLATE_LIST, $queryParams );
} | Get all templates
Can pass in template_type to filter templates.
@param string $template_type
@return array | entailment |
public function previewTemplate( $templateId, $personalisation){
$path = sprintf( self::PATH_TEMPLATE_PREVIEW, $templateId );
$payload = [
'personalisation'=>$personalisation
];
return $this->httpPost( $path, $payload );
} | Get a preview of a template
@return array | entailment |
private function buildPayload( $type, $to, $templateId, array $personalisation, $reference ){
$payload = [
'template_id'=> $templateId
];
if ( $type == 'sms' ) {
$payload['phone_number'] = $to;
} else if ( $type == 'email' ) {
$payload['email_address'] = $to;
}
if ( count($personalisation) > 0 ) {
$payload['personalisation'] = $personalisation;
}
if ( isset($reference) && $reference != '' ) {
$payload['reference'] = $reference;
}
return $payload;
} | Generates the payload expected by the API.
@param string $type
@param string $to
@param string $templateId
@param array $personalisation
@param string $reference
@return array | entailment |
private function buildEmailPayload( $type, $to, $templateId, array $personalisation, $reference, $emailReplyToId = NULL ) {
$payload = $this->buildPayload( $type, $to, $templateId, $personalisation, $reference );
if ( isset($emailReplyToId) && $emailReplyToId != '' ) {
$payload['email_reply_to_id'] = $emailReplyToId;
}
return $payload;
} | Generates the payload expected by the API for email adding the optional items.
@param string $type
@param string $to
@param string $templateId
@param array $personalisation
@param string $reference
@param string $emailReplyToId
@return array | entailment |
private function buildSmsPayload( $type, $to, $templateId, array $personalisation, $reference, $smsSenderId = NULL ){
$payload = $this->buildPayload( $type, $to, $templateId, $personalisation, $reference );
if ( isset($smsSenderId) && $smsSenderId != '' ) {
$payload['sms_sender_id'] = $smsSenderId;
}
return $payload;
} | Generates the payload expected by the API for sms adding the optional items.
@param string $type
@param string $to
@param string $templateId
@param array $personalisation
@param string $reference
@param string $smsSenderId
@return array | entailment |
private function httpGet( $path, array $query = array() ){
$url = new Uri( $this->baseUrl . $path );
foreach( $query as $name => $value ){
$url = URI::withQueryValue($url, $name, $value );
}
//---
$request = new Request(
'GET',
$url,
$this->buildHeaders()
);
try {
$response = $this->getHttpClient()->sendRequest( $request );
} catch (\RuntimeException $e){
throw new Exception\NotifyException( $e->getMessage(), $e->getCode(), $e );
}
//---
switch( $response->getStatusCode() ){
case 200:
return $this->handleResponse( $response );
case 404:
return null;
default:
return $this->handleErrorResponse( $response );
}
} | Performs a GET against the Notify API.
@param string $path
@param array $query
@return array|null
@throw Exception\NotifyException | Exception\ApiException | Exception\UnexpectedValueException | entailment |
private function httpPost( $path, Array $payload ){
$url = new Uri( $this->baseUrl . $path );
$request = new Request(
'POST',
$url,
$this->buildHeaders(),
json_encode( $payload )
);
try {
$response = $this->getHttpClient()->sendRequest( $request );
} catch (\RuntimeException $e){
throw new Exception\NotifyException( $e->getMessage(), $e->getCode(), $e );
}
//---
switch( $response->getStatusCode() ){
case 200:
case 201:
return $this->handleResponse( $response );
default:
return $this->handleErrorResponse( $response );
}
} | Performs a POST against the Notify API.
@param string $path
@param array $payload
@return array
@throw Exception\NotifyException | Exception\ApiException | Exception\UnexpectedValueException | entailment |
protected function handleResponse( ResponseInterface $response ){
$body = json_decode($response->getBody(), true);
// The expected response should always be JSON, thus now an array.
if( !is_array($body) ){
throw new Exception\ApiException( 'Malformed JSON response from server', $response->getStatusCode(), $body, $response );
}
return $body;
} | Called with a response from the API when the response code was successful. i.e. 20X.
@param ResponseInterface $response
@return array
@throw Exception\ApiException | entailment |
protected function handleErrorResponse( ResponseInterface $response ){
$body = json_decode($response->getBody(), true);
$message = "HTTP:{$response->getStatusCode()}";
throw new Exception\ApiException( $message, $response->getStatusCode(), $body, $response );
} | Called with a response from the API when the response code was unsuccessful. i.e. not 20X.
@param ResponseInterface $response
@return null
@throw Exception\ApiException | entailment |
public function get10()
{
// Is it valid?
if ($this->isValid()) {
// Is it already an ISBN-10? If so, return as-is.
if (strlen($this->raw) == 10) {
return $this->raw;
} elseif (strlen($this->raw) == 13
&& substr($this->raw, 0, 3) == '978'
) {
// Is it a Bookland EAN? If so, we can convert to ISBN-10.
$start = substr($this->raw, 3, 9);
return $start . self::getISBN10CheckDigit($start);
}
}
// If we made it this far, conversion was not possible:
return false;
} | Get the ISBN in ISBN-10 format:
@return mixed ISBN, or false if invalid/incompatible. | entailment |
public function get13()
{
// Is it invalid?
if (!$this->isValid()) {
return false;
}
// Is it an ISBN-10? If so, convert to Bookland EAN:
if (strlen($this->raw) == 10) {
$start = '978' . substr($this->raw, 0, 9);
return $start . self::getISBN13CheckDigit($start);
}
// If we made it this far, it must already be an ISBN-13; return as-is.
return $this->raw;
} | Get the ISBN in ISBN-13 format:
@return mixed ISBN, or false if invalid/incompatible. | entailment |
public function isValid()
{
// If we haven't already checked validity, do so now and store the result:
if (null === $this->valid) {
$this->valid = self::isValidISBN10($this->raw)
|| self::isValidISBN13($this->raw);
}
return $this->valid;
} | Is the current ISBN valid in some format? (May be 10 or 13 digit).
@return boolean | entailment |
public static function getISBN10CheckDigit($isbn)
{
$sum = 0;
for ($x = 0; $x < strlen($isbn); $x++) {
$sum += intval(substr($isbn, $x, 1)) * (1 + $x);
}
$checkdigit = $sum % 11;
return $checkdigit == 10 ? 'X' : $checkdigit;
} | Given the first 9 digits of an ISBN-10, generate the check digit.
@param string $isbn The first 9 digits of an ISBN-10.
@return string The check digit. | entailment |
public static function isValidISBN10($isbn)
{
$isbn = self::normalizeISBN($isbn);
if (strlen($isbn) != 10) {
return false;
}
return substr($isbn, 9) == self::getISBN10CheckDigit(substr($isbn, 0, 9));
} | Is the provided ISBN-10 valid?
@param string $isbn The ISBN-10 to test.
@return boolean | entailment |
public static function getISBN13CheckDigit($isbn)
{
$sum = 0;
$weight = 1;
for ($x = 0; $x < strlen($isbn); $x++) {
$sum += intval(substr($isbn, $x, 1)) * $weight;
$weight = $weight == 1 ? 3 : 1;
}
$retval = 10 - ($sum % 10);
return $retval == 10 ? 0 : $retval;
} | Given the first 12 digits of an ISBN-13, generate the check digit.
@param string $isbn The first 12 digits of an ISBN-13.
@return string The check digit. | entailment |
public static function isValidISBN13($isbn)
{
$isbn = self::normalizeISBN($isbn);
if (strlen($isbn) != 13) {
return false;
}
return
substr($isbn, 12) == self::getISBN13CheckDigit(substr($isbn, 0, 12));
} | Is the provided ISBN-13 valid?
@param string $isbn The ISBN-13 to test.
@return boolean | entailment |
public function getLocation($ip, $asArray = true)
{
if ($this->useLocalDB) {
$ipDataArray = $this->fromDB($ip) + ['ip' => $ip];
} else {
$ipDataArray = $this->fromSite($ip) + ['ip' => $ip];
}
if ($asArray) {
return $ipDataArray;
}
return new IpData($ipDataArray);
} | Определение географического положения по IP-адресу.
@param string $ip
@param boolean $asArray
@return array|IpData ('ip', 'country', 'city', 'region', 'lat', 'lng') или false если ничего не найдено.
@throws Exception | entailment |
public function updateDB()
{
if (($fileName = $this->getArchive()) === false) {
throw new Exception('Ошибка загрузки архива.');
}
$zip = new \ZipArchive;
if ($zip->open($fileName) !== true) {
@unlink($fileName);
throw new Exception('Ошибка распаковки.');
}
$this->generateIpTable($zip);
$this->generateCityTables($zip);
$zip->close();
@unlink($fileName);
} | Метод создаёт или обновляет локальную базу IP-адресов.
@throws Exception | entailment |
protected function generateCityTables($zip)
{
$citiesArray = explode("\n", $zip->getFromName(self::ARCHIVE_CITIES_FILE));
array_pop($citiesArray); // пустая строка
$cities = [];
$uniqueRegions = [];
$regionId = 1;
foreach ($citiesArray as $city) {
$row = explode("\t", $city);
$regionName = iconv('WINDOWS-1251', 'UTF-8', $row[2]);
if (!isset($uniqueRegions[$regionName])) {
// новый регион
$uniqueRegions[$regionName] = $regionId++;
}
$cities[$row[0]][0] = $row[0]; // id
$cities[$row[0]][1] = iconv('WINDOWS-1251', 'UTF-8', $row[1]); // name
$cities[$row[0]][2] = $uniqueRegions[$regionName]; // region_id
$cities[$row[0]][3] = $row[4]; // latitude
$cities[$row[0]][4] = $row[5]; // longitude
}
// города
Yii::$app->{$this->db}->createCommand()->truncateTable(self::DB_CITY_TABLE_NAME)->execute();
Yii::$app->{$this->db}->createCommand()->batchInsert(
self::DB_CITY_TABLE_NAME,
['id', 'name', 'region_id', 'latitude', 'longitude'],
$cities
)->execute();
// регионы
$regions = [];
foreach ($uniqueRegions as $regionUniqName => $regionUniqId) {
$regions[] = [$regionUniqId, $regionUniqName];
}
Yii::$app->{$this->db}->createCommand()->truncateTable(self::DB_REGION_TABLE_NAME)->execute();
Yii::$app->{$this->db}->createCommand()->batchInsert(
self::DB_REGION_TABLE_NAME,
['id', 'name'],
$regions
)->execute();
} | Метод производит заполнение таблиц городов и регионов используя
данные из файла self::ARCHIVE_CITIES.
@param $zip \ZipArchive
@throws \yii\db\Exception | entailment |
protected function generateIpTable($zip)
{
$ipsArray = explode("\n", $zip->getFromName(self::ARCHIVE_IPS_FILE));
array_pop($ipsArray); // пустая строка
$i = 0;
$values = [];
Yii::$app->{$this->db}->createCommand()->truncateTable(self::DB_IP_TABLE_NAME)->execute();
foreach ($ipsArray as $ip) {
$row = explode("\t", $ip);
$values[++$i] = [$row[0], $row[1], $row[3], ($row[4] !== '-' ? $row[4] : 0)];
if ($i === self::DB_IP_INSERTING_ROWS) {
Yii::$app->{$this->db}->createCommand()->batchInsert(
self::DB_IP_TABLE_NAME,
['ip_begin', 'ip_end', 'country_code', 'city_id'],
$values
)->execute();
$i = 0;
$values = [];
continue;
}
}
// оставшиеся строки не вошедшие в пакеты
Yii::$app->{$this->db}->createCommand()->batchInsert(
self::DB_IP_TABLE_NAME,
['ip_begin', 'ip_end', 'country_code', 'city_id'],
$values
)->execute();
} | Метод производит заполнение таблиц IP-адресов используя
данные из файла self::ARCHIVE_IPS.
@param $zip \ZipArchive
@throws \yii\db\Exception | entailment |
protected function getArchive()
{
if (($fileData = $this->getRemoteContent(self::ARCHIVE_URL)) === false) {
return false;
}
$fileName = Yii::getAlias('@runtime') . DIRECTORY_SEPARATOR . substr(strrchr(self::ARCHIVE_URL, '/'), 1);
if (@file_put_contents($fileName, $fileData) !== false) {
return $fileName;
}
return false;
} | Метод загружает архив с данными с адреса self::ARCHIVE_URL.
@return boolean|string путь к загруженному файлу или false если файл загрузить не удалось.
@throws Exception | entailment |
protected function getRemoteContent($url)
{
$response = (new Client())
->createRequest()
->setMethod('GET')
->setUrl($url)
->send();
if (!$response->isOk) {
throw new Exception("URL {$url} doesn't exist");
}
return $response->content;
} | Метод возвращает содержимое документа полученного по указанному url.
@param string $url
@return string
@throws Exception | entailment |
public function settingsHtml()
{
Craft::$app->view->registerAssetBundle(PatrolPluginAssetBundle::class);
/**
* @var SettingsModel $settings
*/
$settings = $this->getSettings();
$variables = [
'plugin' => $this,
'settings' => $settings,
'settingsJson' => $settings->getJsonObject(),
];
$html = Craft::$app->view->renderTemplate('patrol/_settings', $variables);
return Template::raw($html);
} | Returns rendered settings UI as a twig markup object
@return \Twig_Markup
@throws \Twig_Error_Loader
@throws \yii\base\Exception
@throws \yii\base\InvalidConfigException | entailment |
private function getFieldsDataFromMetadata(ClassMetadataInfo $metadata)
{
$fieldsData = (array) $metadata->fieldMappings;
// Convert type to filter widget
foreach ($fieldsData as $fieldName => $data) {
$fieldsData[$fieldName]['fieldName'] = $fieldName;
$fieldsData[$fieldName]['filterWidget'] = $this->getFilterType($fieldsData[$fieldName]['type'], $fieldName);
}
return $fieldsData;
} | Returns an array of fields data (name and filter widget to use).
Fields can be both column fields and association fields.
@param ClassMetadataInfo $metadata
@return array $fields | entailment |
public function destroyAUX()
{
parent::destroyAUX();
$metaModel = $this->getMetaModel()->getTableName();
// Try to delete the column. If it does not exist as we can assume it has been deleted already then.
$tableColumns = $this->connection->getSchemaManager()->listTableColumns($metaModel);
if (($colName = $this->getColName()) && \array_key_exists($colName, $tableColumns)) {
$this->tableManipulator->dropColumn($metaModel, $colName);
}
if (\array_key_exists($colName . '__sort', $tableColumns)) {
$this->tableManipulator->dropColumn($metaModel, $colName . '__sort');
}
} | {@inheritdoc} | entailment |
public function initializeAUX()
{
parent::initializeAUX();
if ($colName = $this->getColName()) {
$tableName = $this->quoteReservedWord($this->getMetaModel()->getTableName());
$this->tableManipulator->createColumn($tableName, $this->quoteReservedWord($colName), 'blob NULL');
}
} | {@inheritdoc} | entailment |
public function searchFor($strPattern)
{
$subSelect = $this->connection->createQueryBuilder();
$subSelect
->select($this->quoteReservedWord('uuid'))
->from($this->quoteReservedWord('tl_files'))
->where($subSelect->expr()->like($this->quoteReservedWord('path'), ':value'));
$builder = $this->connection->createQueryBuilder();
$builder
->select($this->quoteReservedWord('id'))
->from($this->getMetaModel()->getTableName())
->where($builder->expr()->in($this->quoteReservedWord($this->getColName()), $subSelect->getSQL()))
->setParameter('value', \str_replace(['*', '?'], ['%', '_'], $strPattern));
return $builder->execute()->fetchAll(\PDO::FETCH_COLUMN);
} | {@inheritdoc} | entailment |
public function unsetDataFor($arrIds)
{
$builder = $this->connection->createQueryBuilder();
$builder
->update($this->quoteReservedWord($this->getMetaModel()->getTableName()))
->set($this->quoteReservedWord($this->getColName()), ':null')
->where($builder->expr()->in($this->quoteReservedWord('id'), ':values'))
->setParameter('values', $arrIds, Connection::PARAM_STR_ARRAY)
->setParameter('null', null);
if ($this->getMetaModel()->hasAttribute($this->getColName() . '__sort')) {
$builder->set($this->quoteReservedWord($this->getColName() . '__sort'), ':null');
}
$builder->execute();
} | {@inheritdoc} | entailment |
public function getDataFor($arrIds)
{
$builder = $this->connection->createQueryBuilder();
$idField = $this->quoteReservedWord('id');
$aliasFile = $this->quoteReservedWord('file');
$builder
->select($idField, ' ' . $this->quoteReservedWord($this->getColName()) . ' ' . $aliasFile)
->from($this->getMetaModel()->getTableName())
->where($builder->expr()->in($idField, ':values'))
->setParameter('values', $arrIds, Connection::PARAM_STR_ARRAY);
if ($hasSort = $this->getMetaModel()->hasAttribute($this->getColName() . '__sort')) {
$sortField = $this->quoteReservedWord($this->getColName() . '__sort');
$aliasFileSort = $this->quoteReservedWord('file_sort');
$builder->addSelect($sortField . ' ' . $aliasFileSort);
}
$query = $builder->execute();
$data = [];
while ($result = $query->fetch(\PDO::FETCH_OBJ)) {
$row = $this->toolboxFile->convertValuesToMetaModels($this->stringUtil->deserialize($result->file, true));
if ($hasSort) {
// The sort key be can remove in later version. The new sort key is bin_sorted.
$row['sort'] = $sorted = $this->stringUtil->deserialize($result->file_sort, true);
foreach ($this->toolboxFile->convertValuesToMetaModels($sorted) as $sortedKey => $sortedValue) {
$row[$sortedKey . '_sorted'] = $sortedValue;
}
if (isset($row['sort'])) {
// @codingStandardsIgnoreStart
@\trigger_error(
'The sort key from the attribute file is deprecated since 2.1 and where removed in 3.0' .
'Use the key bin_sorted',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
}
}
$data[$result->id] = $row;
}
return $data;
} | {@inheritdoc} | entailment |
public function setDataFor($arrValues)
{
$tableName = $this->getMetaModel()->getTableName();
$colName = $this->getColName();
foreach ($arrValues as $id => $value) {
if (null === $value) {
// The sort key be can remove in later version.
$value = ['bin' => [], 'value' => [], 'path' => [], 'sort' => null];
}
$files = ToolboxFile::convertValuesToDatabase($value);
// Check single file or multiple file.
if ($this->get('file_multiple')) {
$files = \serialize($files);
} else {
$files = $files[0];
}
$this->connection->update(
$this->quoteReservedWord($tableName),
[$this->quoteReservedWord($colName) => $files],
[$this->quoteReservedWord('id') => $id]
);
}
} | This method is called to store the data for certain items to the database.
@param mixed $arrValues The values to be stored into database. Mapping is item id=>value.
@return void | entailment |
public function serializeData($mixValues)
{
$data = ToolboxFile::convertValuesToDatabase($mixValues ?: ['bin' => [], 'value' => [], 'path' => []]);
// Check single file or multiple file.
if ($this->get('file_multiple')) {
return \serialize($data);
}
return $data[0];
} | Take the data from the system and serialize it for the database.
@param mixed $mixValues The data to serialize.
@return string An serialized array with binary data or a binary data. | entailment |
private function handleCustomFileTree(&$arrFieldDef)
{
if ($this->get('file_uploadFolder')) {
// Set root path of file chooser depending on contao version.
$file = null;
if ($this->validator->isUuid($this->get('file_uploadFolder'))) {
$file = $this->fileRepository->findByUuid($this->get('file_uploadFolder'));
}
// Check if we have a file.
if (null !== $file) {
$arrFieldDef['eval']['path'] = $file->path;
} else {
// Fallback.
$arrFieldDef['eval']['path'] = $this->get('file_uploadFolder');
}
}
if ($this->get('file_validFileTypes')) {
$arrFieldDef['eval']['extensions'] = $this->get('file_validFileTypes');
}
if ($this->get('file_filesOnly')) {
$arrFieldDef['eval']['filesOnly'] = true;
}
} | Manipulate the field definition for custom file trees.
@param array $arrFieldDef The field definition to manipulate.
@return void | entailment |
public function getFieldDefinition($arrOverrides = [])
{
$fieldDefinition = parent::getFieldDefinition($arrOverrides);
$fieldDefinition['inputType'] = 'fileTree';
$fieldDefinition['eval']['files'] = true;
$fieldDefinition['eval']['extensions'] = $this->config->get('allowedDownload');
$fieldDefinition['eval']['multiple'] = (bool) $this->get('file_multiple');
$widgetMode = $this->getOverrideValue('file_widgetMode', $arrOverrides);
if (('normal' !== $widgetMode)
&& ((bool) $this->get('file_multiple'))
) {
$fieldDefinition['eval']['orderField'] = $this->getColName() . '__sort';
}
$fieldDefinition['eval']['isDownloads'] = ('downloads' === $widgetMode);
$fieldDefinition['eval']['isGallery'] = ('gallery' === $widgetMode);
if ($this->get('file_multiple')) {
$fieldDefinition['eval']['fieldType'] = 'checkbox';
} else {
$fieldDefinition['eval']['fieldType'] = 'radio';
}
if ($this->get('file_customFiletree')) {
$this->handleCustomFileTree($fieldDefinition);
}
return $fieldDefinition;
} | {@inheritdoc} | entailment |
protected function prepareTemplate(Template $template, $rowData, $settings)
{
parent::prepareTemplate($template, $rowData, $settings);
// No data, nothing to do.
if (!$rowData[$this->getColName()]) {
return;
}
$toolbox = clone $this->toolboxFile;
$toolbox
->setBaseLanguage($this->getMetaModel()->getActiveLanguage())
->setFallbackLanguage($this->getMetaModel()->getFallbackLanguage())
->setLightboxId(
\sprintf(
'%s.%s.%s',
$this->getMetaModel()->getTableName(),
$settings->get('id'),
$rowData['id']
)
)
->setShowImages($settings->get('file_showImage'));
if ($this->get('file_validFileTypes')) {
$toolbox->setAcceptedExtensions($this->get('file_validFileTypes'));
}
if ($settings->get('file_imageSize')) {
$toolbox->setResizeImages($settings->get('file_imageSize'));
}
$value = $rowData[$this->getColName()];
if (isset($value['value'])) {
foreach ($value['value'] as $strFile) {
$toolbox->addPathById($strFile);
}
} elseif (\is_array($value)) {
foreach ($value as $strFile) {
$toolbox->addPathById($strFile);
}
} else {
$toolbox->addPathById($value);
}
$toolbox->resolveFiles();
$data = $toolbox->sortFiles($settings->get('file_sortBy'), ($value['bin_sorted'] ?? []));
$template->files = $data['files'];
$template->src = $data['source'];
} | {@inheritDoc} | entailment |
public function create($id, $args){
// Construct the payload, optionally with attachments
$payload = array(
"source_guid" => $args[0],
"text" => $args[1]
);
if ( !empty($args[2]) ) {
$payload = array_merge($payload, array("attachments" => array($args[2])));
}
$params = array(
'url' => '/groups/' . $id . '/messages',
'method' => 'POST',
'query' => array(),
'payload' =>
array( "message" => $payload )
);
return $this->request($params);
} | create: Create messages in a group.
@param string $id
@param array $args
source_guid required string — This is used for client-side deduplication.
text required string — This can be omitted if at least one attachment is present.
attachments optional array - include array of attachments to attach images, etc.
@return string $return | entailment |
public function attachCallback($callback, $type = self::TASK_COMPLETE)
{
if (!is_callable($callback)) {
throw new Exception('Invalid callback specified');
}
if (!in_array(
$type,
array(self::TASK_COMPLETE, self::TASK_FAIL, self::TASK_STATUS)
)) {
throw new Exception('Invalid callback type specified');
}
$this->callback[$type][] = $callback;
return $this;
} | Attach a callback to this task.
@param callback $callback A valid PHP callback
@param int $type Type of callback
@throws \MHlavac\Gearman\Exception When the callback is invalid.
@throws \MHlavac\Gearman\Exception When the callback's type is invalid.
@return $this | entailment |
public function complete($result)
{
$this->finished = true;
$this->result = $result;
if (!count($this->callback[self::TASK_COMPLETE])) {
return;
}
foreach ($this->callback[self::TASK_COMPLETE] as $callback) {
call_user_func($callback, $this->func, $this->handle, $result);
}
} | Run the complete callbacks.
Complete callbacks are passed the name of the job, the handle of the
job and the result of the job (in that order).
@param object $result JSON decoded result passed back
@see \MHlavac\Gearman\Task::attachCallback() | entailment |
public function fail()
{
$this->finished = true;
if (!count($this->callback[self::TASK_FAIL])) {
return;
}
foreach ($this->callback[self::TASK_FAIL] as $callback) {
call_user_func($callback, $this);
}
} | Run the failure callbacks.
Failure callbacks are passed the task object job that failed
@see \MHlavac\Gearman\Task::attachCallback() | entailment |
public function status($numerator, $denominator)
{
if (!count($this->callback[self::TASK_STATUS])) {
return;
}
foreach ($this->callback[self::TASK_STATUS] as $callback) {
call_user_func($callback,
$this->func,
$this->handle,
$numerator,
$denominator);
}
} | Run the status callbacks.
Status callbacks are passed the name of the job, handle of the job and
the numerator/denominator as the arguments (in that order).
@param int $numerator The numerator from the status
@param int $denominator The denominator from the status
@see \MHlavac\Gearman\Task::attachCallback() | entailment |
public function getText()
{
if (!$this->text) {
$this->text = '';
for ($i = 0; $i < $this->macLength; $i++) {
$this->text .= strtolower($this->macChars{rand(0, strlen($this->macChars) - 1)});
}
}
return $this->text;
} | Returns text
@return string | entailment |
public function getHash($text = null)
{
// inserting captcha record
$time = time() + $this->timeout;
$textHash = $this->getTextHash($text);
// if session is started - storing captcha info here
$session = $this->getSession();
if ($session->isSessionStarted()) {
$hash = oxUtilsObject::getInstance()->generateUID();
$hashArray = $session->getVariable('captchaHashes');
$hashArray[$hash] = array($textHash => $time);
$session->setVariable('captchaHashes', $hashArray);
} else {
$database = DatabaseProvider::getDb();
$query = "insert into oecaptcha (oxhash, oxtime) values (" .
$database->quote($textHash) . ", " . $database->quote($time) . ")";
$database->execute($query);
$hash = $database->getOne('select LAST_INSERT_ID()', false, false);
}
return $hash;
} | Returns text hash
@param string $text User supplie text
@return string | entailment |
public function getTextHash($text)
{
if (!$text) {
$text = $this->getText();
}
$text = strtolower($text);
return md5('ox' . $text);
} | Returns given string captcha hash
@param string $text string to hash
@return string | entailment |
public function getImageUrl()
{
$config = \OxidEsales\Eshop\Core\Registry::getConfig();
$url = $config->getCurrentShopUrl() . 'modules/oe/captcha/core/utils/verificationimg.php?e_mac=';
$key = $config->getConfigParam('oecaptchakey');
$key = $key ? $key : $config->getConfigParam('sConfigKey');
$encryptor = new \OxidEsales\Eshop\Core\Encryptor();
$url .= $encryptor->encrypt($this->getText(), $key);
return $url;
} | Returns url to CAPTCHA image generator.
@return string | entailment |
public function passCaptcha($displayError = true)
{
$return = true;
// spam spider prevention
$mac = $this->getConfig()->getRequestParameter('c_mac');
$macHash = $this->getConfig()->getRequestParameter('c_mach');
if (!$this->pass($mac, $macHash)) {
$return = false;
}
if (!$return && $displayError) {
// even if there is no exception, use this as a default display method
oxRegistry::get('oxUtilsView')->addErrorToDisplay('MESSAGE_WRONG_VERIFICATION_CODE');
}
return $return;
} | Check if captcha is passed.
@return bool | entailment |
protected function pass($mac, $macHash)
{
$time = time();
$hash = $this->getTextHash($mac);
$pass = $this->passFromSession($macHash, $hash, $time);
// if captcha info was NOT stored in session
if ($pass === null) {
$pass = $this->passFromDb((int) $macHash, $hash, $time);
}
return (bool) $pass;
} | Verifies captcha input vs supplied hash. Returns true on success.
@param string $mac User supplied text
@param string $macHash Generated hash
@return bool | entailment |
protected function passFromSession($macHash, $hash, $time)
{
$pass = null;
$session = $this->getSession();
if (($hashArray = $session->getVariable('captchaHashes'))) {
$pass = (isset($hashArray[$macHash][$hash]) && $hashArray[$macHash][$hash] >= $time) ? true : false;
unset($hashArray[$macHash]);
if (!empty($hashArray)) {
$session->setVariable('captchaHashes', $hashArray);
} else {
$session->deleteVariable('captchaHashes');
}
}
return $pass;
} | Checks for session captcha hash validity
@param string $macHash hash key
@param string $hash captcha hash
@param int $time check time
@return bool | entailment |
protected function passFromDb($macHash, $hash, $time)
{
$database = DatabaseProvider::getDb();
$where = "where oxid = " . $database->quote($macHash) . " and oxhash = " . $database->quote($hash);
$query = "select 1 from oecaptcha " . $where;
$pass = (bool) $database->getOne($query, false, false);
if ($pass) {
// cleanup
$query = "delete from oecaptcha " . $where;
$database->execute($query);
}
// garbage cleanup
$query = "delete from oecaptcha where oxtime < $time";
$database->execute($query);
return $pass;
} | Checks for DB captcha hash validity
@param int $macHash hash key
@param string $hash captcha hash
@param int $time check time
@return bool | entailment |
private function databaseConnect()
{
$dsn = 'mysql:host='.$this->db['host'].';port='.$this->db['port'].';dbname='.$this->db['name'];
$options = array(
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
\PDO::ATTR_PERSISTENT => true,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instance
try
{
$this->dbh = new \PDO($dsn, $this->db['user'], $this->db['password'], $options);
}
// Catch any errors
catch (\PDOException $e)
{
exit($e->getMessage());
}
} | Database connection link | entailment |
private function query($q, $fetchAll = true)
{
$stmt = $this->dbh->query($q);
if ($fetchAll === true)
{
return $stmt->fetchAll();
}
else
{
return $stmt->fetch();
}
} | Query fetcher
@param string $q Query
@param boolean $fetchAll fetchAll or fetch
@return object PDO | entailment |
public function setCompress($p)
{
if (in_array($p, $this->compressAvailable))
$this->compressFormat = $p;
return $this;
} | Set compress file format (default : null - no compress)
@param string $p Compress format available in $this->compressAvailable
@return object MySQLBackup | entailment |
public function addTable($table)
{
if (!in_array($table, $this->tables))
{
$this->tables[] = $table;
}
return $this;
} | Add table name to dump
@param string $table Table name to dump
@return object MySQLBackup | entailment |
public function addTables(array $tables)
{
if (is_array($tables) && count($tables) > 0)
{
foreach ($tables as $t)
{
$this->addTable($t);
}
}
return $this;
} | Dump selected tables
@param array $tables Tables to backup
@return object MySQLBackup | entailment |
public function addAllTables()
{
$result = $this->query('SHOW TABLES');
foreach ($result as $row)
{
$this->addTable($row[0]);
}
return $this;
} | Dump all tables
@return object MySQLBackup | entailment |
public function excludeTables(array $tables)
{
if (is_array($tables) && count($tables) > 0)
{
$this->excludedTables = $tables;
}
return $this;
} | Exclude tables
@return object MySQLBackup | entailment |
public function dump()
{
$return = '';
if (count($this->tables) == 0)
{
$this->addAllTables();
}
$return .= "--\n";
$return .= "-- Backup ".$this->db['name']." - ".date('Y-m-d H:i:s')."\n";
$return .= "--\n\n\n";
$return .= "SET FOREIGN_KEY_CHECKS=0;";
$return .= "\n\n\n";
if ($this->addCreateDatabaseIfNotExists === true)
{
$return .= "CREATE DATABASE IF NOT EXISTS `".$this->db['name']."`;\n";
$return .= "USE `".$this->db['name']."`;";
$return .= "\n\n\n";
}
foreach ($this->tables as $table)
{
// We skip excluded tables
if (in_array($table, $this->excludedTables))
continue;
$stmt = $this->dbh->query('SELECT * FROM `'.$table.'`');
$stmt->execute();
$num_fields = $stmt->columnCount();
$return .= "--\n";
$return .= "-- Table ".$table."\n";
$return .= "--\n\n";
// Dump structure ?
if ($this->dumpStructure === true)
{
// Add DROP TABLE ?
if ($this->addDropTable === true)
{
$return .= 'DROP TABLE IF EXISTS `'.$table.'`;';
$return .= "\n\n";
}
$create_table_q = $this->query('SHOW CREATE TABLE `'.$table.'`', false);
$create_table = $create_table_q[1];
// Add IF NOT EXISTS ?
if ($this->addIfNotExists === true)
{
$create_table = preg_replace('/^CREATE TABLE/', 'CREATE TABLE IF NOT EXISTS', $create_table);
}
$return .= $create_table.";\n\n";
}
// Dump datas ?
if ($this->dumpDatas === true)
{
$datas = $this->query('SELECT * FROM `'.$table.'`');
foreach ($datas as $row)
{
$return .= 'INSERT INTO `'.$table.'` VALUES(';
for ($i = 0; $i < $num_fields; $i++)
{
if (isset($row[$i]))
{
$row[$i] = addslashes($row[$i]);
$return .= '"'.$row[$i].'"';
}
else
{
$return .= '""';
}
if ($i < ($num_fields-1))
{
$return .= ', ';
}
}
$return .= ");\n";
}
}
$return .= "\n\n";
$return .= "-- --------------------------------------------------------";
$return .= "\n\n\n";
}
// Save content in file
file_put_contents($this->filename.'.'.$this->extension, $return);
// Zip the file ?
if (!is_null($this->compressFormat))
{
$this->compress();
}
// Download the file ?
if ($this->downloadFile === true)
{
$this->download();
}
// Delete the file ?
if ($this->deleteFile === true)
{
$this->delete();
}
} | Dump SQL database with selected tables | entailment |
private function download()
{
header('Content-disposition: attachment; filename="'.$this->filename.'.'.$this->extension.'"');
header('Content-type: application/octet-stream');
readfile($this->filename.'.'.$this->extension);
} | Download the dump file | entailment |
private function compress()
{
switch ($this->compressFormat)
{
case 'zip':
if (class_exists('\ZipArchive'))
{
$zip = new \ZipArchive;
if ($zip->open($this->filename.'.zip', \ZipArchive::CREATE) === true)
{
$zip->addFile($this->filename.'.'.$this->extension, basename($this->filename).'.'.$this->extension);
$zip->close();
// We delete the sql file
$this->delete();
// Changing file extension to zip
$this->extension = 'zip';
}
}
else
{
throw new \Exception('\ZipArchive object does not exists');
}
break;
case 'gz':
case 'gzip':
$content = file_get_contents($this->filename.'.'.$this->extension);
file_put_contents($this->filename.'.sql.gz', gzencode($content, 9));
// We delete the sql file
$this->delete();
// Changing file extension to gzip
$this->extension = 'sql.gz';
break;
}
} | Compress the file | entailment |
private function delete()
{
if (file_exists($this->filename.'.'.$this->extension))
{
unlink($this->filename.'.'.$this->extension);
}
} | Delete the file | entailment |
public function getDefaultTemplate()
{
list($default, $negated) = $this->getTemplateStrings();
$template = new ArrayTemplate([
'default' => $default,
'negated' => $negated,
]);
return $template->setTemplateVars([
'key' => $this->getKey(),
'value' => $this->getValue(),
'actualValue' => $this->getActualValue(),
]);
} | {@inheritdoc}
@return TemplateInterface | entailment |
protected function doMatch($actual)
{
$this->validateActual($actual);
if ($this->isDeep()) {
return $this->matchDeep($actual);
}
$actual = $this->actualToArray($actual);
return $this->matchArrayIndex($actual);
} | Matches if the actual value has a property, optionally matching
the expected value of that property. If the deep flag is set,
the matcher will use the ObjectPath utility to parse deep expressions.
@code
$this->doMatch('child->name->first', 'brian');
@endcode
@param mixed $actual
@return mixed | entailment |
protected function matchArrayIndex($actual)
{
if (isset($actual[$this->getKey()])) {
$this->assertion->setActual($actual[$this->getKey()]);
return $this->isExpected($actual[$this->getKey()]);
}
return false;
} | Match that an array index exists, and matches
the expected value if set.
@param $actual
@return bool | entailment |
protected function matchDeep($actual)
{
$path = new ObjectPath($actual);
$value = $path->get($this->getKey());
if ($value === null) {
return false;
}
$this->assertion->setActual($value->getPropertyValue());
return $this->isExpected($value->getPropertyValue());
} | Uses ObjectPath to parse an expression if the deep flag
is set.
@param $actual
@return bool | entailment |
protected function isExpected($value)
{
if ($expected = $this->getValue()) {
$this->setActualValue($value);
return $this->getActualValue() === $expected;
}
return true;
} | Check if the given value is expected.
@param $value
@return bool | entailment |
protected function getTemplateStrings()
{
$default = 'Expected {{actual}} to have a{{deep}}property {{key}}';
$negated = 'Expected {{actual}} to not have a{{deep}}property {{key}}';
if ($this->getValue() && $this->isActualValueSet()) {
$default = 'Expected {{actual}} to have a{{deep}}property {{key}} of {{value}}, but got {{actualValue}}';
$negated = 'Expected {{actual}} to not have a{{deep}}property {{key}} of {{value}}';
}
$deep = ' ';
if ($this->isDeep()) {
$deep = ' deep ';
}
return str_replace('{{deep}}', $deep, [$default, $negated]);
} | Returns the strings used in creating the template for the matcher.
@return array | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.