sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function up()
{
Schema::create('lfm_categories', function (Blueprint $table) {
$table->integer('id', true);
$table->integer('user_id')->nullable()->unsigned()->default(0);
$table->string('title')->nullable()->default(null);;
$table->longText('title_disc')->nullable()->default(null);
$table->text('description')->nullable()->default(null);
$table->string('parent_category_id',255)->nullable()->default(null);
$table->integer('created_by')->unsigned()->nullable()->default(null);
$table->timestamps();
$table->softDeletes();
});
} | Run the migrations.
@return void | entailment |
public function table($table)
{
$processor = $this->getPostProcessor();
$grammar = $this->getQueryGrammar();
$query = new CassandraBuilder($this, $grammar, $processor);
return $query->from($table);
} | @param string $table
@return CassandraBuilder | entailment |
public function select($query, $bindings = [], $useReadPdo = true)
{
$query .= ' ALLOW FILTERING';
return $this->statement($query, $bindings);
} | @param string $query
@param array $bindings
@param bool $useReadPdo
@return mixed | entailment |
public function insert($query, $bindings = [])
{
try {
$this->statement($query, $bindings);
return true;
} catch (\Exception $e) {
throw new InternalServerErrorException('Insert failed. ' . $e->getMessage());
}
} | Run an insert statement against the database.
@param string $query
@param array $bindings
@return bool
@throws InternalServerErrorException | entailment |
public function statement($query, $bindings = [])
{
if (!empty($bindings)) {
return $this->client->runQuery($query, ['arguments' => $bindings]);
} else {
return $this->client->runQuery($query);
}
} | Execute an SQL statement and return the boolean result.
@param string $query
@param array $bindings
@return bool | entailment |
public function validateMoney(MoneyInterface $money)
{
try {
$this->numberValidator->validateNumber($money->getAmount());
} catch (InvalidNumberException $exception) {
throw new InvalidAmountException(
'Invalid amount for money specified: ' . $money->getAmount(),
0,
$exception
);
}
if (!($this->math->isZero($money->getAmount()) && $money->getCurrency() === null)) {
if (!is_string($money->getCurrency())) {
throw new InvalidCurrencyException('Specified currency is not string');
} elseif (!in_array($money->getCurrency(), $this->informationProvider->getSupportedCurrencies())) {
throw new InvalidCurrencyException('Invalid currency specified: ' . $money->getCurrency());
}
}
} | @param MoneyInterface $money
@throws InvalidAmountException
@throws InvalidCurrencyException | entailment |
public function run(
Renamer $renamer,
Scaffolder $scaffolder
) {
$this->drawBanner();
$child = $this->askForChildConfirmation();
$replacements = $this->askForReplacements($child);
if (! $child) {
$preset = $this->askForPreset();
}
if ($this->askForConfirmation()) {
if (isset($preset) && $preset !== 'none') {
$scaffolder->build($preset);
}
$renamer->replace($replacements);
$this->climate->backgroundLightGreen('Done. Cheers!');
} else {
$this->climate->backgroundRed('Shaking abored.');
}
} | Run CLI logic.
@param \Tonik\CLI\Command\Shake $shake
@return void | entailment |
public function askForReplacements($child)
{
$replacements = [];
if ($child) {
$this->placeholders = array_merge($this->placeholders, $this->childPlaceholders);
}
foreach ($this->placeholders as $placeholder => $data) {
$input = $this->climate->input($data['message']);
$input->defaultTo($data['value']);
$replacements[$placeholder] = addslashes($input->prompt());
}
return $replacements;
} | Asks placeholders and saves answers.
@param boolean child
@return array | entailment |
public function askForPreset()
{
$input = $this->climate->input('<comment>Choose the front-end scaffolding</comment>');
$input->accept($this->presets, true);
return strtolower($input->prompt());
} | Asks for preset name which files will be generated.
@return string | entailment |
public function addWarning(\PHPUnit_Framework_Test $test, \PHPUnit_Framework_Warning $e, $time)
{
$this->writeWarning($test, $e, $time);
} | @param \PHPUnit_Framework_Test $test
@param \PHPUnit_Framework_Warning $e
@param float $time
@since Method available since Release 4.2.0 | entailment |
protected function writeError(\PHPUnit_Framework_Test $test, \Exception $e, $time)
{
$this->writeFailureOrError($test, $e, $time, 'error');
} | @param \PHPUnit_Framework_Test $test
@param \Exception $e
@param float $time
@since Method available since Release 2.17.0 | entailment |
protected function writeFailure(\PHPUnit_Framework_Test $test, \Exception $e, $time)
{
$this->writeFailureOrError($test, $e, $time, 'failure');
} | @param \PHPUnit_Framework_Test $test
@param \Exception $e
@param float $time
@since Method available since Release 2.17.0 | entailment |
protected function writeWarning(\PHPUnit_Framework_Test $test, \Exception $e, $time)
{
$this->writeFailureOrError($test, $e, $time, 'failure');
} | @param \PHPUnit_Framework_Test $test
@param \Exception $e
@param float $time
@since Method available since Release 4.2.0 | entailment |
public function addError(\PHPUnit_Framework_Test $test, \Exception $e, $time)
{
if (!$this->colors) {
parent::addError($test, $e, $time);
return;
}
$this->writeProgress(Coloring::magenta('E'));
$this->lastTestFailed = true;
} | An error occurred.
@param \PHPUnit_Framework_Test $test
@param \Exception $e
@param float $time | entailment |
public function addFailure(\PHPUnit_Framework_Test $test, \PHPUnit_Framework_AssertionFailedError $e, $time)
{
if (!$this->colors) {
parent::addFailure($test, $e, $time);
return;
}
$this->writeProgress(Coloring::red('F'));
$this->lastTestFailed = true;
} | A failure occurred.
@param \PHPUnit_Framework_Test $test
@param \PHPUnit_Framework_AssertionFailedError $e
@param float $time | entailment |
public function scaffold()
{
$this->updateDependencies([
'foundation-sites' => '^6.4.1',
'what-input' => '^4.1.3',
'motion-ui' => '^1.2.2',
]);
$this->updateConfig([
'foundation' => [
'./resources/assets/js/foundation.js',
'./resources/assets/sass/foundation.scss',
],
]);
$this->updateSass($this->name);
$this->updateJavascript($this->name);
$this->updateAssets($this->name);
} | Scaffold a Foundation boilerplate preset.
@return void | entailment |
public static function findFileAndLineOfFailureOrError(array $testClassSuperTypes, \Exception $e, \ReflectionClass $class)
{
if (in_array($class->getName(), $testClassSuperTypes)) {
return;
}
if ($e->getFile() == $class->getFileName()) {
return array($e->getFile(), $e->getLine());
}
foreach ($e->getTrace() as $trace) {
if (array_key_exists('file', $trace) && $trace['file'] == $class->getFileName()) {
return array($trace['file'], $trace['line']);
}
}
if (method_exists($class, 'getTraits')) {
foreach ($class->getTraits() as $trait) {
$ret = self::findFileAndLineOfFailureOrError($testClassSuperTypes, $e, $trait);
if (!is_null($ret)) {
return $ret;
}
}
}
return self::findFileAndLineOfFailureOrError($testClassSuperTypes, $e, $class->getParentClass());
} | @param array $testClassSuperTypes
@param \Exception $e
@param \ReflectionClass $class
@return array | entailment |
public static function buildFailureTrace(array $backtrace)
{
$failureTrace = '';
for ($i = 0, $count = count($backtrace); $i < $count; ++$i) {
if (!array_key_exists('file', $backtrace[$i])) {
continue;
}
$failureTrace .=
$backtrace[$i]['file'].
':'.
(array_key_exists('line', $backtrace[$i]) ? $backtrace[$i]['line']
: '?').
PHP_EOL;
}
return $failureTrace;
} | @param array $backtrace
@return string | entailment |
public function addObject( $contentObject, $commit = true )
{
// Indexing is not implemented in eZ Publish 5 legacy search engine
if ( $this->searchHandler instanceof LegacyHandler )
{
$searchEngine = new eZSearchEngine();
$searchEngine->addObject( $contentObject, $commit );
return true;
}
try
{
// If the method is called for restoring from trash we'll be inside a transaction,
// meaning created Location(s) will not be visible outside of it.
// We check that Content's Locations are visible from the new stack, if not Content
// will be registered for indexing.
foreach ( $contentObject->assignedNodes() as $node )
{
$this->persistenceHandler->locationHandler()->load(
$node->attribute( 'node_id' )
);
}
$content = $this->persistenceHandler->contentHandler()->load(
(int)$contentObject->attribute( 'id' ),
(int)$contentObject->attribute( 'current_version' )
);
}
catch ( NotFoundException $e )
{
$pendingAction = new eZPendingActions(
array(
'action' => 'index_object',
'created' => time(),
'param' => (int)$contentObject->attribute( 'id' )
)
);
$pendingAction->store();
return true;
}
$this->searchHandler->indexContent( $content );
if ( $commit )
{
$this->commit();
}
return true;
} | Adds object $contentObject to the search database.
@param \eZContentObject $contentObject Object to add to search engine
@param bool $commit Whether to commit after adding the object
@return bool True if the operation succeeded. | entailment |
public function removeObjectById( $contentObjectId, $commit = null )
{
if ( !isset( $commit ) && ( $this->iniConfig->variable( 'IndexOptions', 'DisableDeleteCommits' ) === 'true' ) )
{
$commit = false;
}
elseif ( !isset( $commit ) )
{
$commit = true;
}
// Indexing is not implemented in eZ Publish 5 legacy search engine
if ( $this->searchHandler instanceof LegacyHandler )
{
$searchEngine = new eZSearchEngine();
$searchEngine->removeObjectById( $contentObjectId, $commit );
return true;
}
$this->searchHandler->deleteContent( (int)$contentObjectId );
if ( $commit )
{
$this->commit();
}
return true;
} | Removes a content object by ID from the search database.
@since 5.0
@param int $contentObjectId The content object to remove by ID
@param bool $commit Whether to commit after removing the object
@return bool True if the operation succeeded | entailment |
public function search( $searchText, $params = array(), $searchTypes = array() )
{
$searchText = trim( $searchText );
if ( empty( $searchText ) )
{
return array(
'SearchResult' => array(),
'SearchCount' => 0,
'StopWordArray' => array()
);
}
$doFullText = true;
$query = new LocationQuery();
$criteria = array();
if ( isset( $params['SearchDate'] ) && (int)$params['SearchDate'] > 0 )
{
$currentTimestamp = time();
$dateSearchType = (int)$params['SearchDate'];
$fromTimestamp = 0;
if ( $dateSearchType === 1 )
{
// Last day
$fromTimestamp = $currentTimestamp - 86400;
}
else if ( $dateSearchType === 2 )
{
// Last week
$fromTimestamp = $currentTimestamp - ( 7 * 86400 );
}
else if ( $dateSearchType === 3 )
{
// Last month
$fromTimestamp = $currentTimestamp - ( 30 * 86400 );
}
else if ( $dateSearchType === 4 )
{
// Last three months
$fromTimestamp = $currentTimestamp - ( 3 * 30 * 86400 );
}
else if ( $dateSearchType === 5 )
{
// Last year
$fromTimestamp = $currentTimestamp - ( 365 * 86400 );
}
$criteria[] = new Criterion\DateMetadata(
Criterion\DateMetadata::CREATED,
Criterion\Operator::GTE,
$fromTimestamp
);
}
if ( isset( $params['SearchSectionID'] ) && (int)$params['SearchSectionID'] > 0 )
{
$criteria[] = new Criterion\SectionId( (int)$params['SearchSectionID'] );
}
if ( isset( $params['SearchContentClassID'] ) && !is_array( $params['SearchContentClassID'] ) && (int)$params['SearchContentClassID'] > 0 )
{
$criteria[] = new Criterion\ContentTypeId( (int)$params['SearchContentClassID'] );
if ( isset( $params['SearchContentClassAttributeID'] ) && (int)$params['SearchContentClassAttributeID'] > 0 )
{
$classAttribute = eZContentClassAttribute::fetch( $params['SearchContentClassAttributeID'] );
if ( $classAttribute instanceof eZContentClassAttribute )
{
$criteria[] = new Criterion\Field(
$classAttribute->attribute( 'identifier' ),
Criterion\Operator::LIKE,
$searchText
);
$doFullText = false;
}
}
}
else if ( isset( $params['SearchContentClassID'] ) && is_array( $params['SearchContentClassID'] ) )
{
$contentTypeIDs = array_map(
function ($contentClassID)
{
return (int)$contentClassID;
},
$params['SearchContentClassID']
);
$criteria[] = new Criterion\ContentTypeId( $contentTypeIDs );
}
if ( isset( $params['SearchSubTreeArray'] ) && !empty( $params['SearchSubTreeArray'] ) )
{
$subTreeArrayCriteria = array();
foreach ( $params['SearchSubTreeArray'] as $nodeId )
{
$node = eZContentObjectTreeNode::fetch( $nodeId );
$subTreeArrayCriteria[] = $node->attribute( 'path_string' );
}
$criteria[] = new Criterion\Subtree( $subTreeArrayCriteria );
}
if ( $doFullText )
{
$query->query = new Criterion\FullText( $searchText );
}
if ( !empty( $criteria ) )
{
$query->filter = new Criterion\LogicalAnd( $criteria );
}
$query->limit = isset( $params['SearchLimit'] ) ? (int)$params['SearchLimit'] : 10;
$query->offset = isset( $params['SearchOffset'] ) ? (int)$params['SearchOffset'] : 0;
$useLocationSearch = $this->iniConfig->variable( 'SearchSettings', 'UseLocationSearch' ) === 'true';
if ( $useLocationSearch )
{
$searchResult = $this->repository->getSearchService()->findLocations( $query );
}
else
{
$searchResult = $this->repository->getSearchService()->findContentInfo( $query );
}
$nodeIds = array();
foreach ( $searchResult->searchHits as $searchHit )
{
$nodeIds[] = $useLocationSearch ?
$searchHit->valueObject->id :
$searchHit->valueObject->mainLocationId;
}
$resultNodes = array();
if ( !empty( $nodeIds ) )
{
$resultNodes = eZContentObjectTreeNode::fetch( $nodeIds );
if ( $resultNodes instanceof eZContentObjectTreeNode )
{
$resultNodes = array( $resultNodes );
}
else if ( is_array( $resultNodes ) )
{
$nodeIds = array_flip( $nodeIds );
usort(
$resultNodes,
function ( eZContentObjectTreeNode $node1, eZContentObjectTreeNode $node2 ) use ( $nodeIds )
{
if ( $node1->attribute( 'node_id' ) === $node2->attribute( 'node_id' ) )
{
return 0;
}
return ( $nodeIds[$node1->attribute( 'node_id' )] < $nodeIds[$node2->attribute( 'node_id' )] ) ? -1 : 1;
}
);
}
}
return array(
'SearchResult' => $resultNodes,
'SearchCount' => $searchResult->totalCount,
'StopWordArray' => array()
);
} | Searches $searchText in the search database.
@param string $searchText Search term
@param array $params Search parameters
@param array $searchTypes Search types
@return array | entailment |
public function cleanup()
{
// Indexing is not implemented in eZ Publish 5 legacy search engine
if ( $this->searchHandler instanceof LegacyHandler )
{
$db = eZDB::instance();
$db->begin();
$db->query( "DELETE FROM ezsearch_word" );
$db->query( "DELETE FROM ezsearch_object_word_link" );
$db->commit();
}
else if ( method_exists( $this->searchHandler, 'purgeIndex' ) )
{
$this->searchHandler->purgeIndex();
}
} | Purges the index. | entailment |
public function updateNodeSection( $nodeID, $sectionID )
{
$contentObject = eZContentObject::fetchByNodeID( $nodeID );
eZContentOperationCollection::registerSearchObject( $contentObject->attribute( 'id' ) );
} | Update index when a new section is assigned to an object, through a node.
@param int $nodeID
@param int $sectionID | entailment |
public function updateNodeVisibility( $nodeID, $action )
{
$node = eZContentObjectTreeNode::fetch( $nodeID );
eZContentOperationCollection::registerSearchObject( $node->attribute( 'contentobject_id' ) );
$params = array(
'Depth' => 1,
'DepthOperator' => 'eq',
'Limitation' => array(),
'IgnoreVisibility' => true
);
if ( $node->subTreeCount( $params ) > 0 )
{
$pendingAction = new eZPendingActions(
array(
'action' => 'index_subtree',
'created' => time(),
'param' => $nodeID
)
);
$pendingAction->store();
}
} | Update index when node's visibility is modified.
If the node has children, they will be also re-indexed, but this action is deferred to ezfindexsubtree cronjob.
@param int $nodeID
@param string $action | entailment |
public function swapNode( $nodeID, $selectedNodeID, $nodeIdList = array() )
{
$contentObject1 = eZContentObject::fetchByNodeID( $nodeID );
$contentObject2 = eZContentObject::fetchByNodeID( $selectedNodeID );
eZContentOperationCollection::registerSearchObject( $contentObject1->attribute( 'id' ) );
eZContentOperationCollection::registerSearchObject( $contentObject2->attribute( 'id' ) );
} | Update search index when two nodes are swapped
@param int $nodeID
@param int $selectedNodeID
@param array $nodeIdList | entailment |
function isSearchPartIncomplete( $part )
{
if ( $this->searchHandler instanceof LegacyHandler )
{
$searchEngine = new eZSearchEngine();
return $searchEngine->isSearchPartIncomplete( $part );
}
return false;
} | Returns true if the search part is incomplete.
Used only by legacy search engine (eZSearchEngine class).
@param string $part
@return bool | entailment |
public function normalizeText( $text )
{
if ( $this->searchHandler instanceof LegacyHandler )
{
$searchEngine = new eZSearchEngine();
return $searchEngine->normalizeText( $text );
}
return $text;
} | Normalizes the text so that it is easily parsable
Used only by legacy search engine (eZSearchEngine class).
@param string $text
@return string | entailment |
protected function getSSLBuilder($config)
{
if (empty($config)) {
return null;
}
$ssl = \Cassandra::ssl();
$serverCert = array_get($config, 'server_cert_path');
$clientCert = array_get($config, 'client_cert_path');
$privateKey = array_get($config, 'private_key_path');
$passPhrase = array_get($config, 'key_pass_phrase');
if (!empty($serverCert) && !empty($clientCert)) {
if (empty($privateKey)) {
throw new InternalServerErrorException('No private key provider.');
}
return $ssl->withVerifyFlags(\Cassandra::VERIFY_PEER_CERT)
->withTrustedCerts($serverCert)
->withClientCert($clientCert)
->withPrivateKey($privateKey, $passPhrase)
->build();
} elseif (!empty($serverCert)) {
return $ssl->withVerifyFlags(\Cassandra::VERIFY_PEER_CERT)
->withTrustedCerts(getenv('SERVER_CERT'))
->build();
} elseif (true === boolval(array_get($config, 'ssl', array_get($config, 'tls', false)))) {
return $ssl->withVerifyFlags(\Cassandra::VERIFY_NONE)
->build();
} else {
return null;
}
} | Creates the SSL connection builder.
@param $config
@return \Cassandra\SSLOptions|null
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException | entailment |
public function listTables()
{
$tables = $this->keyspace->tables();
$out = [];
foreach ($tables as $table) {
$out[] = ['table_name' => $table->name()];
}
return $out;
} | Lists Cassandra table.
@return array | entailment |
public function executeStatement($statement, array $options = [])
{
if (!empty($options)) {
return $this->session->execute($statement, $options);
} else {
return $this->session->execute($statement);
}
} | @param \Cassandra\SimpleStatement $statement
@param array $options
@return \Cassandra\Rows | entailment |
public function runQuery($cql, array $options = [])
{
$pageInfo = $this->extractPaginationInfo($cql);
$statement = $this->prepareStatement($cql);
$rows = $this->executeStatement($statement, $options);
return static::rowsToArray($rows, $pageInfo);
} | @param string $cql
@param array $options
@return array | entailment |
protected function extractPaginationInfo(& $cql)
{
$words = explode(' ', $cql);
$limit = 0;
$offset = 0;
$limitKey = null;
foreach ($words as $key => $word) {
if ('limit' === strtolower($word) && is_numeric($words[$key + 1])) {
$limit = (int)$words[$key + 1];
$limitKey = $key + 1;
}
if ('offset' === strtolower($word) && is_numeric($words[$key + 1])) {
$offset = (int)$words[$key + 1];
//Take out offset from CQL. It is not supported.
unset($words[$key], $words[$key + 1]);
}
}
//Offset is not supported by CQL. Therefore need to modify limit based on offset.
//Adding offset to limit in order to fetch all available records.
$limit += $offset;
if ($limitKey !== null) {
$words[$limitKey] = $limit;
}
$cql = implode(' ', $words);
return ['limit' => $limit, 'offset' => $offset];
} | Extracts pagination info from CQL.
@param $cql
@return array | entailment |
public static function rowsToArray($rows, array $options = [])
{
$limit = array_get($options, 'limit', 0);
$offset = array_get($options, 'offset', 0);
$array = [];
if ($offset > 0) {
if ($limit > 0) {
for ($i = 0; ($i < $limit && $rows->offsetExists($offset + $i)); $i++) {
$array[] = $rows->offsetGet($offset + $i);
}
} else {
for ($i = 0; $rows->offsetExists($offset + $i); $i++) {
$array[] = $rows->offsetGet($offset + $i);
}
}
} else {
foreach ($rows as $row) {
$array[] = $row;
}
}
return $array;
} | @param \Cassandra\Rows $rows
@param array $options
@return array | entailment |
public function write($buffer)
{
$result = fwrite($this->fileHandle, $buffer, strlen($buffer));
if ($result === false) {
throw new \UnexpectedValueException(sprintf('Failed to write buffer into the file [ %s ].', $this->file));
}
} | @param string $buffer
@throws \UnexpectedValueException | entailment |
public function resolve($pathOrFile)
{
if (is_dir($pathOrFile)) {
$pathOrFile .= DIRECTORY_SEPARATOR . '.docheader';
}
if (! is_file($pathOrFile)) {
throw DocHeaderFileConfiguration::notFound($pathOrFile);
}
return $pathOrFile;
} | @param string $pathOrFile
@throws DocHeaderFileConfiguration
@return string | entailment |
private static function apply($text, $color)
{
if (!array_key_exists($color, self::$outputFormatterStyles)) {
self::$outputFormatterStyles[$color] = new OutputFormatterStyle($color);
}
return self::$outputFormatterStyles[$color]->apply($text);
} | @param string $text
@param string $color
@return string | entailment |
public static function get($key = null)
{
if ($key === null) {
return self::self()->getContainer()['settings'];
} else {
return self::self()->getContainer()['settings'][$key];
}
} | Get the settings value.
If $key = null, this function returns settings.
@param string|null $key
@return mixed | entailment |
public static function set($key, $value)
{
if (is_array($key)) {
$now = self::self()->getContainer()['settings'];
foreach ($key as $item) {
$now = $now[$item];
}
$now = $value;
} else {
$settings = self::self()->getContainer()['settings'];
$settings[$key] = $value;
}
} | Set the settings value.
When $key is an array, it will be viewed to a list of keys. <br>
For Example:
$key = ['a','b']; <br>
The function will set the value of $container->settions['a']['b'].
@param array|string $key
@param mixed $value | entailment |
protected function handleBootstrap($filename, $syntaxCheck = false)
{
try {
\PHPUnit_Util_Fileloader::checkAndLoad($filename, $syntaxCheck);
} catch (RuntimeException $e) {
\PHPUnit_TextUI_TestRunner::showError($e->getMessage());
}
} | Loads a bootstrap file.
@param string $filename
@param bool $syntaxCheck
@see \PHPUnit_TextUI_Command::handleBootstrap()
@since Method available since Release 2.16.0 | entailment |
protected function earlyConfigure(\PHPUnit_Util_Configuration $configuration)
{
$configuration->handlePHPConfiguration();
$phpunitConfiguration = $configuration->getPHPUnitConfiguration();
if (array_key_exists('bootstrap', $phpunitConfiguration)) {
if (array_key_exists('syntaxCheck', $phpunitConfiguration)) {
$this->handleBootstrap($phpunitConfiguration['bootstrap'], $phpunitConfiguration['syntaxCheck']);
} else {
$this->handleBootstrap($phpunitConfiguration['bootstrap']);
}
}
if (array_key_exists('colors', $phpunitConfiguration)) {
$this->terminal->setColor($phpunitConfiguration['colors']);
}
if (method_exists($configuration, 'getSeleniumBrowserConfiguration') && class_exists('PHPUnit_Extensions_SeleniumTestCase')) {
$seleniumBrowserConfiguration = $configuration->getSeleniumBrowserConfiguration();
if (count($seleniumBrowserConfiguration) > 0) {
\PHPUnit_Extensions_SeleniumTestCase::$browsers = $seleniumBrowserConfiguration;
}
}
} | @param \PHPUnit_Util_Configuration $configuration $configuration
@since Method available since Release 2.16.0 | entailment |
public static function invokeWith($level, \Closure $callable)
{
$oldLevel = error_reporting($level);
self::enableErrorToException($level);
try {
call_user_func($callable);
} catch (\Exception $e) {
self::disableErrorToException();
error_reporting($oldLevel);
throw $e;
}
self::disableErrorToException();
error_reporting($oldLevel);
} | @param int $level
@param \Closure $callable
@throws \Exception | entailment |
public static function errorToException($code, $message, $file, $line)
{
if (error_reporting() & $code) {
throw new \ErrorException($message, 0, $code, $file, $line);
}
} | @param int $code
@param string $message
@param string $file
@param int $line
@throws \ErrorException | entailment |
public function validateMoney(MoneyInterface $money)
{
$this->baseValidator->validateMoney($money);
$precision = $this->informationProvider->getDefaultPrecision($money->getCurrency());
if (!$this->math->isEqual($money->getAmount(), $this->math->round($money->getAmount(), $precision))) {
throw new InvalidAmountException(sprintf(
'Too specific amount (%s) for currency (%s) specified',
$money->getAmount(),
$money->getCurrency()
));
}
} | @param MoneyInterface $money
@throws InvalidAmountException
@throws InvalidCurrencyException | entailment |
public function send($method, $uri, array $options = [])
{
$this->calls[] = array('send', $method, $uri, $options);
return new Response();
} | /*
{@inheritdoc} | entailment |
public function purgeKey($service, $key, array $options = [])
{
$this->calls[] = array('purgeKey', $service, $key, $options);
return new Response();
} | /*
{@inheritdoc} | entailment |
public function getCall($num)
{
if (array_key_exists($num, $this->calls)) {
return $this->calls[$num];
}
return null;
} | @param $num
@return array|null | entailment |
public function addSeeder(AbstractPopulator $seeder)
{
$seeder->setPopulator($this);
$seeder->setDatabase($this->database);
$seeder->setFaker($this->faker);
$this->seeders[] = $seeder;
} | Add new seeder
@param AbstractPopulator $seeder | entailment |
public function canvasImageScale()
{
$imageOriginalWidth = imagesx($this->oImg);
$imageOriginalHeight = imagesy($this->oImg);
$scale = min($imageOriginalWidth / $this->options ['width'], $imageOriginalHeight / $this->options ['height']);
$this->options ['cropWidth'] = ceil($this->options ['width'] * $scale);
$this->options ['cropHeight'] = ceil($this->options ['height'] * $scale);
$this->options ['minScale'] = min($this->options ['maxScale'], max(1 / $scale, $this->options ['minScale']));
if ($this->options ['prescale'] !== false)
{
$this->preScale = 1 / $scale / $this->options ['minScale'];
if ($this->preScale < 1)
{
$this->canvasImageResample(ceil($imageOriginalWidth * $this->preScale), ceil($imageOriginalHeight * $this->preScale));
$this->options ['cropWidth'] = ceil($this->options ['cropWidth'] * $this->preScale);
$this->options ['cropHeight'] = ceil($this->options ['cropHeight'] * $this->preScale);
}
else
{
$this->preScale = 1;
}
}
return $this;
} | Scale the image before smartcrop analyse
@return \App\Helpers\Classes\SmartClass | entailment |
public function canvasImageResample($width, $height)
{
$oCanvas = imagecreatetruecolor($width, $height);
imagecopyresampled($oCanvas, $this->oImg, 0, 0, 0, 0, $width, $height, imagesx($this->oImg), imagesy($this->oImg));
$this->oImg = $oCanvas;
return $this;
} | Function for scale image
@param integer $width
@param integer $height
@return \App\Helpers\Classes\SmartClass | entailment |
public function analyse()
{
$result = [];
$w = $this->w = imagesx($this->oImg);
$h = $this->h = imagesy($this->oImg);
$this->od = new \SplFixedArray ($h * $w * 3);
$this->aSample = new \SplFixedArray ($h * $w);
for ($y = 0; $y < $h; $y++)
{
for ($x = 0; $x < $w; $x++)
{
$p = ($y) * $this->w * 3 + ($x) * 3;
$aRgb = $this->getRgbColorAt($x, $y);
$this->od [$p + 1] = $this->edgeDetect($x, $y, $w, $h);
$this->od [$p] = $this->skinDetect($aRgb [0], $aRgb [1], $aRgb [2], $this->sample($x, $y));
$this->od [$p + 2] = $this->saturationDetect($aRgb [0], $aRgb [1], $aRgb [2], $this->sample($x, $y));
}
}
$scoreOutput = $this->downSample($this->options ['scoreDownSample']);
$topScore = -INF;
$topCrop = null;
$crops = $this->generateCrops();
foreach ($crops as &$crop)
{
$crop ['score'] = $this->score($scoreOutput, $crop);
if ($crop ['score'] ['total'] > $topScore)
{
$topCrop = $crop;
$topScore = $crop ['score'] ['total'];
}
}
$result ['topCrop'] = $topCrop;
if ($this->options ['debug'] && $topCrop)
{
$result ['crops'] = $crops;
$result ['debugOutput'] = $scoreOutput;
$result ['debugOptions'] = $this->options;
$result ['debugTopCrop'] = array_merge([], $result ['topCrop']);
}
return $result;
} | Analyse the image, find out the optimal crop scheme
@return array | entailment |
public function generateCrops()
{
$w = imagesx($this->oImg);
$h = imagesy($this->oImg);
$results = [];
$minDimension = min($w, $h);
$cropWidth = empty ($this->options ['cropWidth']) ? $minDimension : $this->options ['cropWidth'];
$cropHeight = empty ($this->options ['cropHeight']) ? $minDimension : $this->options ['cropHeight'];
for ($scale = $this->options ['maxScale']; $scale >= $this->options ['minScale']; $scale -= $this->options ['scaleStep'])
{
for ($y = 0; $y + $cropHeight * $scale <= $h; $y += $this->options ['step'])
{
for ($x = 0; $x + $cropWidth * $scale <= $w; $x += $this->options ['step'])
{
$results [] = [
'x' => $x,
'y' => $y,
'width' => $cropWidth * $scale,
'height' => $cropHeight * $scale
];
}
}
}
return $results;
} | Generate crop schemes
@return array | entailment |
public function score($output, $crop)
{
$result = [
'detail' => 0,
'saturation' => 0,
'skin' => 0,
'boost' => 0,
'total' => 0
];
$downSample = $this->options ['scoreDownSample'];
$invDownSample = 1 / $downSample;
$outputHeightDownSample = floor($this->h / $downSample) * $downSample;
$outputWidthDownSample = floor($this->w / $downSample) * $downSample;
$outputWidth = floor($this->w / $downSample);
for ($y = 0; $y < $outputHeightDownSample; $y += $downSample)
{
for ($x = 0; $x < $outputWidthDownSample; $x += $downSample)
{
$i = $this->importance($crop, $x, $y);
$p = floor($y / $downSample) * $outputWidth * 4 + floor($x / $downSample) * 4;
$detail = $output [$p + 1] / 255;
$result ['skin'] += $output [$p] / 255 * ($detail + $this->options ['skinBias']) * $i;
$result ['saturation'] += $output [$p + 2] / 255 * ($detail + $this->options ['saturationBias']) * $i;
$result ['detail'] = $p;
}
}
$result ['total'] = ($result ['detail'] * $this->options ['detailWeight'] + $result ['skin'] * $this->options ['skinWeight'] + $result ['saturation'] * $this->options ['saturationWeight'] + $result ['boost'] * $this->options ['boostWeight']) / ($crop ['width'] * $crop ['height']);
return $result;
} | Score a crop scheme
@param array $output
@param array $crop
@return array | entailment |
public function crop($x, $y, $width, $height)
{
$oCanvas = imagecreatetruecolor($width, $height);
imagecopyresampled($oCanvas, $this->oImg, 0, 0, $x, $y, $width, $height, $width, $height);
$this->oImg = $oCanvas;
return $this;
} | Crop image
@param integer $x
@param integer $y
@param integer $width
@param integer $height
@return \App\Helpers\Classes\SmartClass | entailment |
public function up()
{
Schema::create('lfm_files', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('user_id')->nullable()->unsigned()->default(0);;
$table->integer('category_id');
$table->integer('file_mime_type_id')->unsigned();
$table->string('original_name', 255)->nullable()->default(null);
$table->string('extension', 255)->nullable()->default(null);
$table->string('mimeType', 255)->nullable()->default(null);
$table->longText('path')->nullable()->default(null);
$table->text('filename')->nullable()->default(null);
$table->string('file_md5' ,255)->nullable()->default(null);
$table->text('large_filename')->nullable()->default(null);
$table->enum('is_direct',['1',0])->nullable()->default(0);
$table->text('medium_filename')->nullable()->default(null);
$table->text('small_filename')->nullable()->default(null);
$table->integer('version')->nullable()->unsigned()->default(0);
$table->integer('large_version')->nullable()->unsigned()->default(0);
$table->integer('medium_version')->nullable()->unsigned()->default(0);
$table->integer('small_version')->nullable()->unsigned()->default(0);
$table->double('size')->nullable()->default(null);
$table->integer('large_size')->nullable()->unsigned()->default(0);
$table->integer('medium_size')->nullable()->unsigned()->default(0);
$table->integer('small_size')->nullable()->unsigned()->default(0);
$table->integer('created_by')->nullable()->unsigned()->nullable()->default(null);
$table->timestamps();
$table->softDeletes();
});
} | Run the migrations.
@return void | entailment |
protected function createJUnitXMLWriter()
{
$streamWriter = $this->createStreamWriter($this->junitXMLFile);
$utf8Converter = extension_loaded('mbstring') ? new UTF8Converter() : new NullUTF8Converter();
return $this->junitXMLRealtime ? new StreamJUnitXMLWriter($streamWriter, $utf8Converter) : new DOMJUnitXMLWriter($streamWriter, $utf8Converter);
} | @return \Stagehand\TestRunner\JUnitXMLWriter\JUnitXMLWriter
@since Method available since Release 3.3.0 | entailment |
public function swap(array $replacements)
{
foreach ($replacements as $from => $to) {
$this->replace($from, $this->normalize($to));
}
} | Inits renaming process.
@param array $replacements Values map to replace.
@return void | entailment |
protected function replace($from, $to)
{
if ($this->file->getExtension() === 'json') {
$from = addslashes($from);
}
file_put_contents(
$this->file->getRealPath(),
str_replace($from, $to, $this->file->getContents())
);
} | Replaces strings in file content.
@param string $from
@param string $to
@return void | entailment |
public function boot()
{
// the main router
$this->loadRoutesFrom(__DIR__.'/Routes/private_routes.php');
$this->loadRoutesFrom(__DIR__.'/Routes/public_routes.php');
// the main views folder
$this->loadViewsFrom(__DIR__ . '/Views', 'laravel_file_manager');
// the main migration folder for create sms_ir tables
// for publish the views into main app
$this->publishes([
__DIR__ . '/Views' => resource_path('views/vendor/laravel_file_manager'),
]);
//publish storage file
$this->publishes([
__DIR__ . '/Storage/SystemFiles' => \Storage::disk(config('laravel_file_manager.driver_disk'))->path(config('laravel_file_manager.main_storage_folder_name').'\System'),
]);
$this->publishes([
__DIR__ . '/Database/Migrations/' => database_path('migrations')
], 'migrations');
// for publish the assets files into main app
$this->publishes([
__DIR__.'/assets' => public_path('vendor/laravel_file_manager'),
], 'public');
// for publish the sms_ir config file to the main app config folder
$this->publishes([
__DIR__ . '/Config/LFM.php' => config_path('laravel_file_manager.php'),
]);
// publish language
$this->publishes([
__DIR__ . '/Lang/En/Filemanager.php' => resource_path('lang/en/filemanager.php'),
]);
$this->publishes([
__DIR__ . '/Lang/Fa/Filemanager.php' => resource_path('lang/fa/filemanager.php'),
]);
$this->publishes([
__DIR__ . '/Traits/lfmFillable.php' => app_path('Traits/lfmFillable.php'),
]);
} | Bootstrap the application services.
@return void | entailment |
public function register()
{
// set the main config file
$this->mergeConfigFrom(
__DIR__ . '/Config/LFM.php', 'laravel_file_manager'
);
// bind the LFMC Facade
$this->app->bind('LFMC', function () {
return new LFMC;
});
$this->app->bind('FileManager', function () {
return new Media;
});
} | Register the application services.
@return void | entailment |
public function addListener($listener, array $events = array())
{
if (!\is_object($listener))
{
throw new InvalidArgumentException('The given listener is not an object.');
}
// We deal with a closure.
if ($listener instanceof Closure)
{
if (empty($events))
{
throw new InvalidArgumentException('No event name(s) and priority specified for the Closure listener.');
}
foreach ($events as $name => $priority)
{
if (!isset($this->listeners[$name]))
{
$this->listeners[$name] = new ListenersPriorityQueue;
}
$this->listeners[$name]->add($listener, $priority);
}
return $this;
}
// We deal with a "normal" object.
$methods = get_class_methods($listener);
if (!empty($events))
{
$methods = array_intersect($methods, array_keys($events));
}
// @deprecated
$regex = $this->listenerFilter ?: '.*';
foreach ($methods as $event)
{
// @deprecated - this outer `if` is deprecated.
if (preg_match("#$regex#", $event))
{
// Retain this inner code after removal of the outer `if`.
if (!isset($this->listeners[$event]))
{
$this->listeners[$event] = new ListenersPriorityQueue;
}
$priority = isset($events[$event]) ? $events[$event] : Priority::NORMAL;
$this->listeners[$event]->add($listener, $priority);
}
}
return $this;
} | Add a listener to this dispatcher, only if not already registered to these events.
If no events are specified, it will be registered to all events matching it's methods name.
In the case of a closure, you must specify at least one event name.
@param object|Closure $listener The listener
@param array $events An associative array of event names as keys
and the corresponding listener priority as values.
@return Dispatcher This method is chainable.
@throws InvalidArgumentException
@since 1.0 | entailment |
public function clearListeners($event = null)
{
if ($event)
{
if ($event instanceof EventInterface)
{
$event = $event->getName();
}
if (isset($this->listeners[$event]))
{
unset($this->listeners[$event]);
}
}
else
{
$this->listeners = array();
}
return $this;
} | Clear the listeners in this dispatcher.
If an event is specified, the listeners will be cleared only for that event.
@param EventInterface|string $event The event object or name.
@return Dispatcher This method is chainable.
@since 1.0 | entailment |
public function init() {
//close csrf
Yii::$app->request->enableCsrfValidation = false;
//默认设置
// $this->php_path = dirname(__FILE__) . '/';
$this->php_path = $_SERVER['DOCUMENT_ROOT'] . '/';
$this->php_url = '/';
//根目录路径,可以指定绝对路径,比如 /var/www/attached/
$this->root_path = $this->php_path . 'upload/';
//根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
$this->root_url = $this->php_url . 'upload/';
//图片扩展名
// $ext_arr = ['gif', 'jpg', 'jpeg', 'png', 'bmp'],
//文件保存目录路径
$this->save_path = $this->php_path . 'upload/';
//文件保存目录URL
$this->save_url = $this->php_url . 'upload/';
//定义允许上传的文件扩展名
// $ext_arr = array(
// 'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
// 'flash' => array('swf', 'flv'),
// 'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
// 'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
// ),
//最大文件大小
$this->max_size = 1000000;
$this->save_path = realpath($this->save_path) . '/';
//load config file
parent::init();
} | public $save_path; | entailment |
public function handAction() {
//获得action 动作
$action = Yii::$app->request->get('action');
switch ($action) {
case 'fileManagerJson':
$this->fileManagerJsonAction();
break;
case 'uploadJson':
$this->UploadJosnAction();
break;
default:
break;
}
} | 处理动作 | entailment |
public function cmp_func($a, $b) {
global $order;
if ($a['is_dir'] && !$b['is_dir']) {
return -1;
} else if (!$a['is_dir'] && $b['is_dir']) {
return 1;
} else {
if ($order == 'size') {
if ($a['filesize'] > $b['filesize']) {
return 1;
} else if ($a['filesize'] < $b['filesize']) {
return -1;
} else {
return 0;
}
} else if ($order == 'type') {
return strcmp($a['filetype'], $b['filetype']);
} else {
return strcmp($a['filename'], $b['filename']);
}
}
} | 排序 | entailment |
public function create($amount, $currency)
{
$result = new Money($amount, $currency);
$this->validator->validateMoney($result);
return $result;
} | @param string $amount
@param string $currency
@return Money
@throws InvalidAmountException
@throws InvalidCurrencyException | entailment |
public function createFromCents($amountInCents, $currency)
{
return $this->create($this->math->div($amountInCents, '100'), $currency);
} | @param int $amountInCents
@param string $currency
@return Money
@throws InvalidAmountException
@throws InvalidCurrencyException | entailment |
public function convert($text)
{
$encoding = mb_detect_encoding($text);
if (!$encoding || $encoding == 'ASCII' || $encoding == 'UTF-8') {
return $text;
}
return mb_convert_encoding($text, 'UTF-8', $encoding);
} | @param string $text
@return string | entailment |
public function send($method, $uri, array $options = [])
{
// Prepend entrypoint if $uri is not absolute
if (0 !== strpos($uri, 'http')) {
$uri = $this->entryPoint . $uri;
}
return $this->adapter->send($method, $uri, $options);
} | /*
{@inheritdoc} | entailment |
public function purgeAll($service, array $options = [])
{
$url = '/service/' . urlencode($service) . '/purge_all';
return $this->send('POST', $url, $options);
} | /*
{@inheritdoc} | entailment |
public function purgeKey($service, $key, array $options = [])
{
$url = '/service/' . urlencode($service) . '/purge/' . $key;
return $this->send('POST', $url, $options);
} | /*
{@inheritdoc} | entailment |
public function update(IRow &$row, $data)
{
$oldValues = [];
if ($row instanceof ActiveRow) {
$oldValues = $row->toArray();
}
$res = $this->getTable()->wherePrimary($row->getPrimary())->update($data);
if (!$res) {
// if MySQL is set to return number of updated rows (default) instead of number of matched rows,
// we're halting the execution here and nothing is saved to the audit log.
return false;
}
if ($this->auditLogRepository) {
// filter internal columns
$data = $this->filterValues($this->excludeColumns((array)$data));
// filter unchanged columns
if (!empty($oldValues)) {
$oldValues = $this->filterValues($this->excludeColumns($oldValues));
$oldValues = array_intersect_key($oldValues, (array)$data);
$data = array_diff_assoc((array)$data, $oldValues); // get changed values
$oldValues = array_intersect_key($oldValues, (array)$data); // get rid of unchanged $oldValues
}
$data = [
'version' => '1',
'from' => $oldValues,
'to' => $data,
];
$this->pushAuditLog(AuditLogRepository::OPERATION_UPDATE, $row->getSignature(), $data);
}
$row = $this->getTable()->wherePrimary($row->getPrimary())->fetch();
return true;
} | Update updates provided record with given $data array and mutates the provided instance. Operation is logged
to audit log.
@param IRow $row
@param array $data values to update
@return bool
@throws \Exception | entailment |
public function delete(IRow &$row)
{
$res = $this->getTable()->wherePrimary($row->getPrimary())->delete();
$oldValues = [];
if ($row instanceof ActiveRow) {
$oldValues = $row->toArray();
}
if (!$res) {
return false;
}
if ($this->auditLogRepository) {
$from = $this->filterValues($this->excludeColumns($oldValues));
$data = [
'version' => '1',
'from' => $from,
'to' => [],
];
$this->pushAuditLog(AuditLogRepository::OPERATION_DELETE, $row->getSignature(), $data);
}
return true;
} | Delete deletes provided record from repository and mutates the provided instance. Operation is logged to audit log.
@param IRow $row
@return bool | entailment |
public function insert($data)
{
$row = $this->getTable()->insert($data);
if (!$row instanceof IRow) {
return $row;
}
if ($this->auditLogRepository) {
$to = $this->filterValues($this->excludeColumns((array)$data));
$data = [
'version' => '1',
'from' => [],
'to' => $to,
];
$this->pushAuditLog(AuditLogRepository::OPERATION_CREATE, $row->getSignature(), $data);
}
return $row;
} | Insert inserts data to the repository. If single IRow is returned, it attempts to log audit information.
@param $data
@return bool|int|IRow | entailment |
private function filterValues(array $values)
{
foreach ($values as $i => $field) {
if (is_bool($field)) {
$values[$i] = (int) $field;
} elseif ($field instanceof \DateTime) {
$values[$i] = $field->format('Y-m-d H:i:s');
} elseif (!is_scalar($field)) {
unset($values[$i]);
}
}
return $values;
} | filterValues removes non-scalar values from the array and formats any DateTime to DB string representation.
@param array $values
@return array | entailment |
public static function bind_manipulation_capture()
{
$current = DB::get_conn();
if (!$current || !$current->getConnector()->getSelectedDatabase() || @$current->isManipulationLoggingCapture) {
return;
} // If not yet set, or its already captured, just return
$type = get_class($current);
$sanitisedType = str_replace('\\', '_', $type);
$file = TEMP_FOLDER . "/.cache.CLC.$sanitisedType";
$dbClass = 'AuditLoggerManipulateCapture_' . $sanitisedType;
if (!is_file($file)) {
file_put_contents($file, "<?php
class $dbClass extends $type
{
public \$isManipulationLoggingCapture = true;
public function manipulate(\$manipulation)
{
\SilverStripe\Auditor\AuditHook::handle_manipulation(\$manipulation);
return parent::manipulate(\$manipulation);
}
}
");
}
require_once $file;
/** @var Database $captured */
$captured = new $dbClass();
$captured->setConnector($current->getConnector());
$captured->setQueryBuilder($current->getQueryBuilder());
$captured->setSchemaManager($current->getSchemaManager());
// The connection might have had it's name changed (like if we're currently in a test)
$captured->selectDatabase($current->getConnector()->getSelectedDatabase());
DB::set_conn($captured);
} | This will bind a new class dynamically so we can hook into manipulation
and capture it. It creates a new PHP file in the temp folder, then
loads it and sets it as the active DB class.
@deprecated 2.1...3.0 Please use ProxyDBExtension with the tractorcow/silverstripe-proxy-db module instead | entailment |
public function onAfterPublish(&$original)
{
$member = Security::getCurrentUser();
if (!$member || !$member->exists()) {
return false;
}
$effectiveViewerGroups = '';
if ($this->owner->CanViewType === 'OnlyTheseUsers') {
$originalViewerGroups = $original ? $original->ViewerGroups()->column('Title') : [];
$effectiveViewerGroups = implode(', ', $originalViewerGroups);
}
if (!$effectiveViewerGroups) {
$effectiveViewerGroups = $this->owner->CanViewType;
}
$effectiveEditorGroups = '';
if ($this->owner->CanEditType === 'OnlyTheseUsers') {
$originalEditorGroups = $original ? $original->EditorGroups()->column('Title') : [];
$effectiveEditorGroups = implode(', ', $originalEditorGroups);
}
if (!$effectiveEditorGroups) {
$effectiveEditorGroups = $this->owner->CanEditType;
}
$this->getAuditLogger()->info(sprintf(
'"%s" (ID: %s) published %s "%s" (ID: %s, Version: %s, ClassName: %s, Effective ViewerGroups: %s, '
. 'Effective EditorGroups: %s)',
$member->Email ?: $member->Title,
$member->ID,
$this->owner->singular_name(),
$this->owner->Title,
$this->owner->ID,
$this->owner->Version,
$this->owner->ClassName,
$effectiveViewerGroups,
$effectiveEditorGroups
));
} | Log a record being published. | entailment |
public function onAfterUnpublish()
{
$member = Security::getCurrentUser();
if (!$member || !$member->exists()) {
return false;
}
$this->getAuditLogger()->info(sprintf(
'"%s" (ID: %s) unpublished %s "%s" (ID: %s)',
$member->Email ?: $member->Title,
$member->ID,
$this->owner->singular_name(),
$this->owner->Title,
$this->owner->ID
));
} | Log a record being unpublished. | entailment |
public function afterMemberLoggedIn()
{
$this->getAuditLogger()->info(sprintf(
'"%s" (ID: %s) successfully logged in',
$this->owner->Email ?: $this->owner->Title,
$this->owner->ID
));
} | Log successful login attempts. | entailment |
public function authenticationFailed($data)
{
// LDAP authentication uses a "Login" POST field instead of Email.
$login = isset($data['Login'])
? $data['Login']
: (isset($data[Email::class]) ? $data[Email::class] : '');
if (empty($login)) {
return $this->getAuditLogger()->warning(
'Could not determine username/email of failed authentication. '.
'This could be due to login form not using Email or Login field for POST data.'
);
}
$this->getAuditLogger()->info(sprintf('Failed login attempt using email "%s"', $login));
} | Log failed login attempts. | entailment |
public function onAfterInit()
{
// Suppress errors if dev/build necessary
if (!Security::database_is_ready()) {
return false;
}
$currentMember = Security::getCurrentUser();
if (!$currentMember || !$currentMember->exists()) {
return false;
}
$statusCode = $this->owner->getResponse()->getStatusCode();
if (substr($statusCode, 0, 1) == '4') {
$this->logPermissionDenied($statusCode, $currentMember);
}
} | Log permission failures (where the status is set after init of page). | entailment |
public static function convertFormatToFormat($jalaliFormat, $georgianFormat, $timeString, $timezone = null)
{
// Normalize $timezone, take from static::date(...)
$timezone = ($timezone != null) ? $timezone : ((self::$timezone != null) ? self::$timezone : date_default_timezone_get());
if (is_string($timezone))
{
$timezone = new \DateTimeZone($timezone);
}
elseif (!$timezone instanceof \DateTimeZone)
{
throw new \RuntimeException('Provided timezone is not correct.');
}
// Convert to timestamp, then to Jalali
$datetime = \DateTime::createFromFormat($georgianFormat, $timeString, $timezone);
return static::date($jalaliFormat, $datetime->getTimestamp());
} | Convert a formatted string from Georgian Calendar to Jalali Calendar.
This will be useful to directly convert time strings coming from databases.
Example:
// Suppose this comes from database
$a = '2016-02-14 14:20:38';
$date = \jDateTime::convertFormatToFormat('Y-m-d H:i:s', 'Y-m-d H:i:s', $a);
// $date will now be '۱۳۹۴-۱۱-۲۵ ۱۴:۲۰:۳۸'
@author Vahid Fazlollahzade
@param string $jalaliFormat Return format. Same as static::date(...)
@param string $georgianFormat The format of $timeString. See php.net/date
@param string $timeString The time itself, formatted as $georgianFormat
@param null|\DateTimeZone|string $timezone The timezone. Same as static::date(...)
@return string | entailment |
public static function date($format, $stamp = false, $convert = null, $jalali = null, $timezone = null)
{
//Timestamp + Timezone
$stamp = ($stamp !== false) ? $stamp : time();
$timezone = ($timezone != null) ? $timezone : ((self::$timezone != null) ? self::$timezone : date_default_timezone_get());
$obj = new \DateTime('@' . $stamp, new \DateTimeZone($timezone));
$obj->setTimezone(new \DateTimeZone($timezone));
if ((self::$jalali === false && $jalali === null) || $jalali === false)
{
return $obj->format($format);
}
else
{
//Find what to replace
$chars = (preg_match_all('/([a-zA-Z]{1})/', $format, $chars)) ? $chars[0] : [];
//Intact Keys
$intact = ['B', 'h', 'H', 'g', 'G', 'i', 's', 'I', 'U', 'u', 'Z', 'O', 'P'];
$intact = self::filterArray($chars, $intact);
$intactValues = [];
foreach ($intact as $k => $v)
{
$intactValues[ $k ] = $obj->format($v);
}
//End Intact Keys
//Changed Keys
list($year, $month, $day) = [$obj->format('Y'), $obj->format('n'), $obj->format('j')];
list($jyear, $jmonth, $jday) = self::toJalali($year, $month, $day);
$keys = ['d', 'D', 'j', 'l', 'N', 'S', 'w', 'z', 'W', 'F', 'm', 'M', 'n', 't', 'L', 'o', 'Y', 'y', 'a', 'A', 'c', 'r', 'e', 'T'];
$keys = self::filterArray($chars, $keys, ['z']);
$values = [];
foreach ($keys as $k => $key)
{
$v = '';
switch ($key)
{
//Day
case 'd':
$v = sprintf('%02d', $jday);
break;
case 'D':
$v = self::getDayNames($obj->format('D'), true);
break;
case 'j':
$v = $jday;
break;
case 'l':
$v = self::getDayNames($obj->format('l'));
break;
case 'N':
$v = self::getDayNames($obj->format('l'), false, 1, true);
break;
case 'S':
$v = 'ام';
break;
case 'w':
$v = self::getDayNames($obj->format('l'), false, 1, true) - 1;
break;
case 'z':
if ($jmonth > 6)
{
$v = 186 + (($jmonth - 6 - 1) * 30) + $jday;
}
else
{
$v = (($jmonth - 1) * 31) + $jday;
}
self::$temp['z'] = $v;
break;
//Week
case 'W':
$v = is_int(self::$temp['z'] / 7) ? (self::$temp['z'] / 7) : intval(self::$temp['z'] / 7 + 1);
break;
//Month
case 'F':
$v = self::getMonthNames($jmonth);
break;
case 'm':
$v = sprintf('%02d', $jmonth);
break;
case 'M':
$v = self::getMonthNames($jmonth, true);
break;
case 'n':
$v = $jmonth;
break;
case 't':
if ($jmonth >= 1 && $jmonth <= 6)
{
$v = 31;
}
else
{
if ($jmonth >= 7 && $jmonth <= 11)
{
$v = 30;
}
else
{
if ($jmonth == 12 && $jyear % 4 == 3)
{
$v = 30;
}
else
{
if ($jmonth == 12 && $jyear % 4 != 3)
{
$v = 29;
}
}
}
}
break;
//Year
case 'L':
$tmpObj = new \DateTime('@' . (time() - 31536000));
$v = $tmpObj->format('L');
break;
case 'o':
case 'Y':
$v = $jyear;
break;
case 'y':
$v = $jyear % 100;
break;
//Time
case 'a':
$v = ($obj->format('a') == 'am') ? 'ق.ظ' : 'ب.ظ';
break;
case 'A':
$v = ($obj->format('A') == 'AM') ? 'قبل از ظهر' : 'بعد از ظهر';
break;
//Full Dates
case 'c':
$v = $jyear . '-' . sprintf('%02d', $jmonth) . '-' . sprintf('%02d', $jday) . 'T';
$v .= $obj->format('H') . ':' . $obj->format('i') . ':' . $obj->format('s') . $obj->format('P');
break;
case 'r':
$v = self::getDayNames($obj->format('D'), true) . ', ' . sprintf('%02d', $jday) . ' ' . self::getMonthNames($jmonth, true);
$v .= ' ' . $jyear . ' ' . $obj->format('H') . ':' . $obj->format('i') . ':' . $obj->format('s') . ' ' . $obj->format('P');
break;
//Timezone
case 'e':
$v = $obj->format('e');
break;
case 'T':
$v = $obj->format('T');
break;
}
$values[ $k ] = $v;
}
//End Changed Keys
//Merge
$keys = array_merge($intact, $keys);
$values = array_merge($intactValues, $values);
//Return
$ret = strtr($format, array_combine($keys, $values));
return ($convert === false || ($convert === null && self::$convert === false) || ($jalali === false || $jalali === null && self::$jalali === false)) ? $ret : self::convertNumbers($ret);
}
} | jDateTime::Date
Formats and returns given timestamp just like php's
built in date() function.
e.g:
$obj->date("Y-m-d H:i", time());
$obj->date("Y-m-d", time(), false, false, 'America/New_York');
@author Sallar Kaboli
@param $format string Acceps format string based on: php.net/date
@param $stamp int Unix Timestamp (Epoch Time)
@param $convert bool (Optional) forces convert action. pass null to use system default
@param $jalali bool (Optional) forces jalali conversion. pass null to use system default
@param $timezone string (Optional) forces a different timezone. pass null to use system default
@return string Formatted input | entailment |
public static function gDate($format, $stamp = false, $timezone = null)
{
return self::date($format, $stamp, false, false, $timezone);
} | jDateTime::gDate
Same as jDateTime::Date method
but this one works as a helper and returns Gregorian Date
in case someone doesn't like to pass all those false arguments
to Date method.
e.g. $obj->gDate("Y-m-d") //Outputs: 2011-05-05
$obj->date("Y-m-d", false, false, false); //Outputs: 2011-05-05
Both return the exact same result.
@author Sallar Kaboli
@param $format string Acceps format string based on: php.net/date
@param $stamp int Unix Timestamp (Epoch Time)
@param $timezone string (Optional) forces a different timezone. pass null to use system default
@return string Formatted input | entailment |
public static function getdate($timestamp = null)
{
if ($timestamp === null)
{
$timestamp = time();
}
if (is_string($timestamp))
{
if (ctype_digit($timestamp) || ($timestamp{0} == '-' && ctype_digit(substr($timestamp, 1))))
{
$timestamp = (int)$timestamp;
}
else
{
$timestamp = strtotime($timestamp);
}
}
$dateString = self::date("s|i|G|j|w|n|Y|z|l|F", $timestamp);
$dateArray = explode("|", $dateString);
$result = ["seconds" => $dateArray[0], "minutes" => $dateArray[1], "hours" => $dateArray[2], "mday" => $dateArray[3], "wday" => $dateArray[4], "mon" => $dateArray[5], "year" => $dateArray[6], "yday" => $dateArray[7], "weekday" => $dateArray[8], "month" => $dateArray[9], 0 => $timestamp];
return $result;
} | jDateTime::getdate
Like php built-in function, returns an associative array containing the date information of a timestamp, or the current local time if no timestamp is given. .
@author Meysam Pour Ganji
@param $timestamp int The timestamp that whould convert to date information array, if NULL passed, current timestamp will be processed.
@return An associative array of information related to the timestamp. For see elements of the returned associative array see {@link http://php.net/manual/en/function.getdate.php#refsect1-function.getdate-returnvalues}. | entailment |
private static function getDayNames($day, $shorten = false, $len = 1, $numeric = false)
{
$days = ['sat' => [1, 'شنبه'], 'sun' => [2, 'یکشنبه'], 'mon' => [3, 'دوشنبه'], 'tue' => [4, 'سه شنبه'], 'wed' => [5, 'چهارشنبه'], 'thu' => [6, 'پنجشنبه'], 'fri' => [7, 'جمعه']];
$day = substr(strtolower($day), 0, 3);
$day = $days[ $day ];
return ($numeric) ? $day[0] : (($shorten) ? self::substr($day[1], 0, $len) : $day[1]);
} | Returns correct names for week days | entailment |
private static function getMonthNames($month, $shorten = false, $len = 3)
{
// Convert
$months = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'];
$ret = $months[ $month - 1 ];
// Return
return ($shorten) ? self::substr($ret, 0, $len) : $ret;
} | Returns correct names for months | entailment |
private static function substr($str, $start, $len)
{
if (function_exists('mb_substr'))
{
return mb_substr($str, $start, $len, 'UTF-8');
}
else
{
return substr($str, $start, $len * 2);
}
} | Substring helper | entailment |
public static function toGregorian($j_y, $j_m, $j_d)
{
$g_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
$j_days_in_month = [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29];
$jy = $j_y - 979;
$jm = $j_m - 1;
$jd = $j_d - 1;
$j_day_no = 365 * $jy + self::div($jy, 33) * 8 + self::div($jy % 33 + 3, 4);
for ($i = 0; $i < $jm; ++$i) $j_day_no += $j_days_in_month[ $i ];
$j_day_no += $jd;
$g_day_no = $j_day_no + 79;
$gy = 1600 + 400 * self::div($g_day_no, 146097);
$g_day_no = $g_day_no % 146097;
$leap = true;
if ($g_day_no >= 36525)
{
$g_day_no--;
$gy += 100 * self::div($g_day_no, 36524);
$g_day_no = $g_day_no % 36524;
if ($g_day_no >= 365)
{
$g_day_no++;
}
else
{
$leap = false;
}
}
$gy += 4 * self::div($g_day_no, 1461);
$g_day_no %= 1461;
if ($g_day_no >= 366)
{
$leap = false;
$g_day_no--;
$gy += self::div($g_day_no, 365);
$g_day_no = $g_day_no % 365;
}
for ($i = 0; $g_day_no >= $g_days_in_month[ $i ] + ($i == 1 && $leap); $i++) $g_day_no -= $g_days_in_month[ $i ] + ($i == 1 && $leap);
$gm = $i + 1;
$gd = $g_day_no + 1;
return [$gy, $gm, $gd];
} | Jalali to Gregorian Conversion
Copyright (C) 2000 Roozbeh Pournader and Mohammad Toossi | entailment |
public function Gregorian_to_Jalali($gy, $gm, $gd, $mod = '')
{
$g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
$jy = ($gy <= 1600) ? 0 : 979;
$gy -= ($gy <= 1600) ? 621 : 1600;
$gy2 = ($gm > 2) ? ($gy + 1) : $gy;
$days = (365 * $gy) + ((int)(($gy2 + 3) / 4)) - ((int)(($gy2 + 99) / 100)) + ((int)(($gy2 + 399) / 400)) - 80 + $gd + $g_d_m[ $gm - 1 ];
$jy += 33 * ((int)($days / 12053));
$days %= 12053;
$jy += 4 * ((int)($days / 1461));
$days %= 1461;
$jy += (int)(($days - 1) / 365);
if ($days > 365)
{
$days = ($days - 1) % 365;
}
$jm = ($days < 186) ? 1 + (int)($days / 31) : 7 + (int)(($days - 186) / 30);
$jd = 1 + (($days < 186) ? ($days % 31) : (($days - 186) % 30));
return ($mod == '') ? [$jy, $jm, $jd] : $jy . $mod . $jm . $mod . $jd;
} | *-----------------------------------Begin--------------------------------*// | entailment |
public static function parseFromFormat($format, $date)
{
// reverse engineer date formats
$keys = [
'Y' => ['year', '\d{4}'],
'y' => ['year', '\d{2}'],
'm' => ['month', '\d{2}'],
'n' => ['month', '\d{1,2}'],
'M' => ['month', '[A-Z][a-z]{3}'],
'F' => ['month', '[A-Z][a-z]{2,8}'],
'd' => ['day', '\d{2}'],
'j' => ['day', '\d{1,2}'],
'D' => ['day', '[A-Z][a-z]{2}'],
'l' => ['day', '[A-Z][a-z]{6,9}'],
'u' => ['hour', '\d{1,6}'],
'h' => ['hour', '\d{2}'],
'H' => ['hour', '\d{2}'],
'g' => ['hour', '\d{1,2}'],
'G' => ['hour', '\d{1,2}'],
'i' => ['minute', '\d{2}'],
's' => ['second', '\d{2}'],
];
// convert format string to regex
$regex = '';
$chars = str_split($format);
foreach ($chars as $n => $char)
{
$lastChar = isset($chars[ $n - 1 ]) ? $chars[ $n - 1 ] : '';
$skipCurrent = '\\' == $lastChar;
if (!$skipCurrent && isset($keys[ $char ]))
{
$regex .= '(?P<' . $keys[ $char ][0] . '>' . $keys[ $char ][1] . ')';
}
else
{
if ('\\' == $char)
{
$regex .= $char;
}
else
{
$regex .= preg_quote($char);
}
}
}
$dt = [];
$dt['error_count'] = 0;
// now try to match it
if (preg_match('#^' . $regex . '$#', $date, $dt))
{
foreach ($dt as $k => $v)
{
if (is_int($k))
{
unset($dt[ $k ]);
}
}
if (!jDateTime::checkdate($dt['month'], $dt['day'], $dt['year'], false))
{
$dt['error_count'] = 1;
}
}
else
{
$dt['error_count'] = 1;
}
$dt['errors'] = [];
$dt['fraction'] = '';
$dt['warning_count'] = 0;
$dt['warnings'] = [];
$dt['is_localtime'] = 0;
$dt['zone_type'] = 0;
$dt['zone'] = 0;
$dt['is_dst'] = '';
if (strlen($dt['year']) == 2)
{
$now = jDate::forge('now');
$x = $now->format('Y') - $now->format('y');
$dt['year'] += $x;
}
$dt['year'] = isset($dt['year']) ? (int)$dt['year'] : 0;
$dt['month'] = isset($dt['month']) ? (int)$dt['month'] : 0;
$dt['day'] = isset($dt['day']) ? (int)$dt['day'] : 0;
$dt['hour'] = isset($dt['hour']) ? (int)$dt['hour'] : 0;
$dt['minute'] = isset($dt['minute']) ? (int)$dt['minute'] : 0;
$dt['second'] = isset($dt['second']) ? (int)$dt['second'] : 0;
$dt['just_time'] = $dt['hour'] * 360 + $dt['minute'] * 60 + $dt['second'];
return $dt;
} | *------------------------------ Date converter --------------------------*// | entailment |
private static function buildHtreeRow($width, callable $hasher)
{
$row = [];
if ($width === 2) {
$row[] = new TwoChildrenNode($hasher);
return $row;
}
if ($width === 3) {
$row[] = new TwoChildrenNode($hasher);
$row[] = new TwoChildrenNode($hasher);
$row[] = new OneChildDuplicateNode(new TwoChildrenNode($hasher));
$row[0]->data($row[1], $row[2]);
return $row;
}
$rowSize = (int) ceil($width / 2);
$odd = $width % 2;
for ($i = 0; $i < $rowSize; $i++) {
$row[] = new TwoChildrenNode($hasher);
}
if ($odd) {
$row[$rowSize - 1] = new OneChildDuplicateNode($row[$rowSize - 1]);
}
$parents = self::buildHtreeRow($rowSize, $hasher);
$treeRoot = array_shift($parents);
$pRowSize = count($parents);
array_unshift($row, $treeRoot);
if ($pRowSize === 0) {
$row[0]->data($row[1], $row[2]);
return $row;
}
$pOdd = $rowSize % 2;
foreach ($parents as $i => $parent) {
$index = ($i * 2) + 1;
if ($i + 1 === $pRowSize && $pOdd) {
$parent->data($row[$index]);
continue;
}
$parent->data($row[$index], $row[$index + 1]);
}
return $row;
} | Returns a tree of ITreeNode objects of width $width
@param int $width
@param callable $hasher
@todo This must be cleaned up, it is pretty terrible as it stands.
@return ITreeNode[]
The return is an array of ITreeNode nodes that represent all of the base
of the tree in order. Additionally, the 0 index on the array will be the
TOP of the tree generated. Having both the base nodes and the top node
is all you need for operating on a fixed tree.
For example, if you were to build a tree of size 8, you this would
return an array of 5 ITreeNodes. The 0 index being the top of this tree
(that you should be calling ->hash() on) and the next 4 indicies being
instances of TwoChildrenNode objects (each which has the ability to
accept two strings as data). | entailment |
protected function parseSelect($schema, $extras)
{
$fields = array_get($extras, ApiOptions::FIELDS);
if (empty($fields)) {
// minimally return id fields
$idFields = array_get($extras, ApiOptions::ID_FIELD);
if (empty($idFields)) {
$idFields = $schema->primaryKey;
}
$fields = $idFields;
}
$fields = static::fieldsToArray($fields);
$outArray = [];
if (empty($fields)) {
foreach ($schema->getColumns() as $fieldInfo) {
if ($fieldInfo->isAggregate) {
continue;
}
$out = $this->parseFieldForSelect($fieldInfo);
if (is_array($out)) {
$outArray = array_merge($outArray, $out);
} else {
$outArray[] = $out;
}
}
} else {
$related = array_get($extras, ApiOptions::RELATED);
$related = static::fieldsToArray($related);
if (!empty($related) || $schema->fetchRequiresRelations) {
// add any required relationship mapping fields
foreach ($schema->getRelations() as $relation) {
if ($relation->alwaysFetch || in_array($relation->getName(true), $related)) {
foreach ($relation->field as $relField) {
if ($fieldInfo = $schema->getColumn($relField)) {
$relationField = $fieldInfo->getName(true); // account for aliasing
if (false === array_search($relationField, $fields)) {
$fields[] = $relationField;
}
}
}
}
}
}
foreach ($fields as $field) {
if ($fieldInfo = $schema->getColumn($field, true)) {
$out = $this->parseFieldForSelect($fieldInfo);
if (is_array($out)) {
$outArray = array_merge($outArray, $out);
} else {
$outArray[] = $out;
}
} else {
throw new BadRequestException('Invalid field requested: ' . $field);
}
}
}
return $outArray;
} | @param TableSchema $schema
@param array|null $extras
@return array
@throws \DreamFactory\Core\Exceptions\BadRequestException
@throws \Exception | entailment |
protected function addToTransaction(
$record = null,
$id = null,
$extras = null,
$rollback = false,
$continue = false,
$single = false
) {
$dbConn = $this->parent->getConnection();
if ($rollback) {
// sql transaction really only for rollback scenario, not batching
if (0 >= $dbConn->transactionLevel()) {
$dbConn->beginTransaction();
}
}
$ssFilters = array_get($extras, 'ss_filters');
$updates = array_get($extras, 'updates');
$idFields = array_get($extras, 'id_fields');
$needToIterate = ($single || !$continue || (1 < count($this->tableIdsInfo)));
$related = array_get($extras, 'related');
$requireMore = array_get_bool($extras, 'require_more') || !empty($related);
$builder = $dbConn->table($this->transactionTableSchema->internalName);
$match = [];
if (!is_null($id)) {
if (is_array($id)) {
$match = $id;
foreach ($idFields as $name) {
$builder->where($name, array_get($id, $name));
}
} else {
$name = array_get($idFields, 0);
$match[$name] = $id;
$builder->where($name, $id);
}
}
$serverFilter = $this->buildQueryStringFromData($ssFilters);
if (!empty($serverFilter)) {
Session::replaceLookups($serverFilter);
$params = [];
$filterString = $this->parseFilterString($serverFilter, $params, $this->tableFieldsInfo);
$builder->whereRaw($filterString, $params);
}
$out = [];
switch ($this->getAction()) {
case Verbs::POST:
// need the id back in the record
if (!empty($match)) {
$record = array_merge($record, $match);
}
$parsed = $this->parseRecord($record, $this->tableFieldsInfo, $ssFilters);
if (empty($parsed)) {
throw new BadRequestException('No valid fields were found in record.');
}
if (!$builder->insert($parsed)) {
throw new InternalServerErrorException("Record insert failed.");
}
$idName = (isset($this->tableIdsInfo, $this->tableIdsInfo[0], $this->tableIdsInfo[0]->name))
? $this->tableIdsInfo[0]->name : null;
// take care to return auto created id values
if (is_string($id) && $idName &&
((0 === strcasecmp($id, 'uuid()')) || (0 === strcasecmp($id, 'now()')))
) {
if ($newId = array_get($parsed, $idName)) {
switch (get_class($newId)) {
case 'Cassandra\Uuid':
case 'Cassandra\Timeuuid': // construct( int $seconds )
$id = $newId->uuid();
break;
}
}
}
$out = (is_array($id)) ? $id : [$idName => $id];
// add via record, so batch processing can retrieve extras
if ($requireMore) {
parent::addToTransaction($id);
}
break;
case Verbs::PUT:
case Verbs::PATCH:
if (!empty($updates)) {
$record = $updates;
}
// remove id from record
$record = array_except($record, array_keys($match));
$parsed = $this->parseRecord($record, $this->tableFieldsInfo, $ssFilters, true);
if (!empty($parsed)) {
if (!empty($match) && $this->parent->upsertAllowed() && !$builder->exists()) {
if (!$builder->insert(array_merge($match, $parsed))) {
throw new InternalServerErrorException("Record upsert failed.");
}
} else {
$rows = $builder->update($parsed);
if (0 >= $rows) {
// could have just not updated anything, or could be bad id
if (empty($this->runQuery($this->transactionTable, $builder, $extras))) {
throw new NotFoundException("Record with identifier '" .
print_r($id, true) .
"' not found.");
}
}
}
}
if (!empty($relatedInfo)) {
// need the id back in the record
if (!empty($match)) {
$record = array_merge($record, $match);
}
}
$idName =
(isset($this->tableIdsInfo, $this->tableIdsInfo[0], $this->tableIdsInfo[0]->name))
? $this->tableIdsInfo[0]->name : null;
$out = (is_array($id)) ? $id : [$idName => $id];
// add via record, so batch processing can retrieve extras
if ($requireMore) {
parent::addToTransaction($id);
}
break;
case Verbs::DELETE:
if (!$needToIterate) {
return parent::addToTransaction(null, $id);
}
// add via record, so batch processing can retrieve extras
if ($requireMore) {
$result = $this->runQuery(
$this->transactionTable,
$builder,
$extras
);
if (empty($result)) {
// bail, we know it isn't there
throw new NotFoundException("Record with identifier '" . print_r($id, true) . "' not found.");
}
$out = $result[0];
}
if (1 > $builder->delete()) {
// wasn't anything there to delete
throw new NotFoundException("Record with identifier '" . print_r($id, true) . "' not found.");
}
if (empty($out)) {
$idName =
(isset($this->tableIdsInfo, $this->tableIdsInfo[0], $this->tableIdsInfo[0]->name))
? $this->tableIdsInfo[0]->name : null;
$out = (is_array($id)) ? $id : [$idName => $id];
}
break;
case Verbs::GET:
if (!$needToIterate) {
return parent::addToTransaction(null, $id);
}
$result = $this->runQuery($this->transactionTable, $builder, $extras);
if (empty($result)) {
throw new NotFoundException("Record with identifier '" . print_r($id, true) . "' not found.");
}
$out = $result[0];
break;
}
return $out;
} | {@inheritdoc} | entailment |
protected function commitTransaction($extras = null)
{
$dbConn = $this->parent->getConnection();
if (empty($this->batchRecords) && empty($this->batchIds)) {
if (0 < $dbConn->transactionLevel()) {
$dbConn->commit();
}
return null;
}
$updates = array_get($extras, 'updates');
$ssFilters = array_get($extras, 'ss_filters');
$related = array_get($extras, 'related');
$requireMore = array_get_bool($extras, 'require_more') || !empty($related);
$builder = $dbConn->table($this->transactionTableSchema->internalName);
/** @type ColumnSchema $idName */
$idName = (isset($this->tableIdsInfo, $this->tableIdsInfo[0])) ? $this->tableIdsInfo[0] : null;
if (empty($idName)) {
throw new BadRequestException('No valid identifier found for this table.');
}
if (!empty($this->batchRecords)) {
if (is_array($this->batchRecords[0])) {
$temp = [];
foreach ($this->batchRecords as $record) {
$temp[] = array_get($record, $idName->getName(true));
}
$builder->whereIn($idName->name, $temp);
} else {
$builder->whereIn($idName->name, $this->batchRecords);
}
} else {
$builder->whereIn($idName->name, $this->batchIds);
}
$serverFilter = $this->buildQueryStringFromData($ssFilters);
if (!empty($serverFilter)) {
Session::replaceLookups($serverFilter);
$params = [];
$filterString = $this->parseFilterString($serverFilter, $params, $this->tableFieldsInfo);
$builder->whereRaw($filterString, $params);
}
$out = [];
$action = $this->getAction();
if (!empty($this->batchRecords)) {
if (1 == count($this->tableIdsInfo)) {
// records are used to retrieve extras
// ids array are now more like records
$result = $this->runQuery($this->transactionTable, $builder, $extras);
if (empty($result)) {
throw new NotFoundException('No records were found using the given identifiers.');
}
$out = $result;
} else {
$out = $this->retrieveRecords($this->transactionTable, $this->batchRecords, $extras);
}
$this->batchRecords = [];
} elseif (!empty($this->batchIds)) {
switch ($action) {
case Verbs::PUT:
case Verbs::PATCH:
if (!empty($updates)) {
$parsed = $this->parseRecord($updates, $this->tableFieldsInfo, $ssFilters, true);
if (!empty($parsed)) {
$rows = $builder->update($parsed);
if (count($this->batchIds) !== $rows) {
throw new BadRequestException('Batch Error: Not all requested records could be updated.');
}
}
if ($requireMore) {
$result = $this->runQuery(
$this->transactionTable,
$builder,
$extras
);
$out = $result;
}
}
break;
case Verbs::DELETE:
$result = $this->runQuery(
$this->transactionTable,
$builder,
$extras
);
if (count($this->batchIds) !== count($result)) {
foreach ($this->batchIds as $index => $id) {
$found = false;
foreach ($result as $record) {
if ($id == array_get($record, $idName->getName(true))) {
$out[$index] = $record;
$found = true;
break;
}
}
if (!$found) {
$out[$index] = new NotFoundException("Record with identifier '" . print_r($id,
true) . "' not found.");
}
}
} else {
$out = $result;
}
$rows = $builder->delete();
if (count($this->batchIds) !== $rows) {
throw new BatchException($out, 'Batch Error: Not all requested records could be deleted.');
}
break;
case Verbs::GET:
$result = $this->runQuery(
$this->transactionTable,
$builder,
$extras
);
if (count($this->batchIds) !== count($result)) {
foreach ($this->batchIds as $index => $id) {
$found = false;
foreach ($result as $record) {
if ($id == array_get($record, $idName->getName(true))) {
$out[$index] = $record;
$found = true;
break;
}
}
if (!$found) {
$out[$index] = new NotFoundException("Record with identifier '" . print_r($id,
true) . "' not found.");
}
}
throw new BatchException($out, 'Batch Error: Not all requested records could be retrieved.');
}
$out = $result;
break;
default:
break;
}
if (empty($out)) {
$out = [];
foreach ($this->batchIds as $id) {
$out[] = [$idName->getName(true) => $id];
}
}
$this->batchIds = [];
}
if (0 < $dbConn->transactionLevel()) {
$dbConn->commit();
}
return $out;
} | {@inheritdoc} | entailment |
public static function findByPluginID($pluginID)
{
if (is_null(self::$plugins)) {
self::loadAllPlugins();
}
foreach (self::$plugins as $plugin) { /* @var $plugin \Stagehand\TestRunner\Core\Plugin\PluginInterface */
if (strtolower($plugin->getPluginID()) == strtolower($pluginID)) {
return $plugin;
}
}
} | @param string $pluginID
@return \Stagehand\TestRunner\Core\Plugin\PluginInterface | entailment |
public function replace(array $replacements)
{
foreach ($this->files() as $file) {
(new Replacer($file))->swap($replacements);
}
} | Process renaming in files content.
@param array $answers
@return void | entailment |
public function files()
{
$files = (new Finder)->files();
foreach ($this->ignoredFiles as $name) {
$files->notName($name);
}
foreach ($this->searchedFiles as $name) {
$files->name($name);
}
return $files->exclude($this->ignoredDirectories)->in($this->dir);
} | Finds files to rename.
@return array | entailment |
protected function findSuiteMethod(\ReflectionClass $testClass)
{
if ($testClass->hasMethod(\PHPUnit_Runner_BaseTestRunner::SUITE_METHODNAME)) {
$method = $testClass->getMethod(\PHPUnit_Runner_BaseTestRunner::SUITE_METHODNAME);
if ($method->isStatic()) {
return $method;
}
}
} | @param \ReflectionClass $testClass
@return \ReflectionMethod
@since Method available since Release 3.0.3 | entailment |
public function attachMenuItemToForeignModule(
string $foreignMenuLink,
MenuItem $internalMenuItem,
MenuItem $menuItem
) {
$foreignMenuItem = $this->getMenuItemByLink($foreignMenuLink);
if (!is_null($foreignMenuItem)) {
$foreignMenuItem->addChild($menuItem);
} else {
$internalMenuItem->addChild($menuItem);
$this->attachMenuItem($internalMenuItem);
}
} | Try to attach menu item to:
- foreign module menu (if exists, search is done by link)
- own module menu (if foreign module menu doesn't exist) | entailment |
public function getNamespace()
{
if (isset($this->properties[ 'namespace' ])) {
return $this->properties[ 'namespace' ];
}
$dir = $this->getRealPath();
$dirParts = explode('Widgets' . DIRECTORY_SEPARATOR, $dir);
$namespace = loader()->getDirNamespace(reset($dirParts)) . 'Widgets\\' . str_replace(['/', DIRECTORY_SEPARATOR],
'\\', end($dirParts));
return $namespace;
} | Widget::getNamespace
@return mixed|string | entailment |
Subsets and Splits