sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function getTemporary() { // disable query logging $connection_name = Config::get('laravel-import-export::baseconf.connection_name'); DB::connection($connection_name)->disableQueryLog(); $temporary = TemporaryModel::whereRaw("1")->orderBy("id","DESC")->first(); if($temporary) { $this->csv_file = $temporary->file_object; return $this->csv_file; } return false; }
Get data from the temporary table @return Mixed $data @throws Exception
entailment
public function saveTemporary($csv_file = null, $temporary_model = null) { $csv_file = $csv_file ? $csv_file : $this->csv_file; if( $csv_file ) { $temporary_model = ($temporary_model) ? $temporary_model : new TemporaryModel(); $temporary_model->fill(array("file_object"=>$csv_file)); // disable query logging $connection_name = Config::get('laravel-import-export::baseconf.connection_name'); DB::connection($connection_name)->disableQueryLog(); return $temporary_model->save(); } else { return false; } }
Put data in the temporary table @return Boolean $success @throws Exception
entailment
public function updateHeaders(CsvFile $csv_file, array $columns, $table_name) { $this->csv_file = $csv_file ? $csv_file : $this->csv_file; foreach($this->csv_file as $csv_line) { $this->updateHeader($csv_line, $columns, $table_name); } }
Update headers of the csv_file @param CsvFile $csv_line @param Array $columns $key=column name, $value=column index @param Sring $table_name name of the table @throws UnalignedArrayException
entailment
protected function updateHeader(CsvLine $csv_line, array $columns, $table_name) { $model_attributes = $csv_line->getAttributes(); $new_attributes = array(); foreach($columns as $key_column => $column) { if( isset($model_attributes[$key_column]) ) { // append data to new attributes $new_attributes = array_merge($new_attributes,array($column => $model_attributes[$key_column])); unset($model_attributes[$key_column]); } else { throw new UnalignedArrayException; } } // update data $csv_line->resetAttributes(); foreach($new_attributes as $key_attribute => $attribute) { $csv_line->forceSetAttribute($key_attribute,$attribute); } $table = array("table" => $table_name); $csv_line->setConfig( $table ); return true; }
Update headers of the csv_line @param CsvLine $csv_line @param Array $columns $key=column name, $value=column index @param Sring $table_name name of the table @return Boolean @throws UnalignedArrayException
entailment
public function openFromCsv(array $config, CsvFileBuilder $builder = null) { $builder = $builder ? $builder : new CsvFileBuilder(); $builder->setConfigModel($config["model"]); $builder->setConfigFileParse($config["file_parse"]); $builder->setConfig($config["builder"]); $builder->buildFromCsv(); $this->csv_file = $builder->getCsvFile(); if( ! count($this->csv_file)) throw new NoDataException(); return $this->getCsvFile(); }
This method build the CsvFile from a csv file @param $config 'model' for RunTimeModel 'file' for ParseCsv 'builder' for CsvFileBuilder @throws FileNotFoundException @throws InvalidArgumentException @throws NoDataException @throws UnalignedArrayException @throws DomainException @return CsvFile
entailment
public function openFromDb(array $config, DbFileBuilder $builder = null) { $builder = $builder ? $builder : new DbFileBuilder(); $builder->setConfig($config); $builder->build(); $this->csv_file = $builder->getCsvFile(); return $this->getCsvFile(); }
Build the csvFile from Db @throws Exception @throws PDOException @return CsvFile
entailment
public function getMaxLength($csv_file = null) { $csv_file = $csv_file ? $csv_file : $this->csv_file; $sizes = array(0); if( ! $csv_file ) { throw new NoDataException(); } foreach($csv_file as $line) { $sizes[]=count($line->getElements() ); } return max($sizes); }
Get the max lenght of a csv_line @return Integer
entailment
public function getCsvString($separator, CsvFile $csv_file = null) { $csv_file = $csv_file ? $csv_file : $this->csv_file; $csv = ''; if( ! isset($csv_file) ) { throw new NoDataException; } else { foreach($csv_file as $key => $csv_line) { if($key == 0) { $csv.=$csv_line->getCsvHeader($separator); } $csv.=$csv_line->getCsvString($separator); } } return $csv; }
Create the csv string rappresenting the CsvFile @return String $csv @throws NoDataException
entailment
public function run(callable $confirmationCallback = null, $migrationId = null, $loadFromFile = false) { if ($this->logger) { $this->service->setLogger($this->logger); } // Выбрать миграцию if ($migrationId) { if ($next = $this->service->getDbRepository()->findById($migrationId)) { } else { $this->error("<error>Migration with ID={$migrationId} not found!</error>"); return; } } else { $next = $this->service->getDbRepository()->findLast(); } if (empty($next)) { $this->alert('<error>Nothing to rollback</error>'); return; } $title = 'Rollback: ' . $next->getName(); if ($this->optForce) { $this->error("<error>{$title}</error>"); // Запросить подтверждение } elseif ($confirmationCallback && !$confirmationCallback($title)) { return; } $this->service->down($next, $loadFromFile); $this->info('Done'); }
Run @param callable|null $confirmationCallback - Спросить подтверждение у пользователя перед запуском каждой миграции функция должна вернуть true/false принимает $migrationTitle @param int $migrationId - ID конкретной миграции, которую надо накатить @param bool $loadFromFile - Загрузить текст миграции из файла вместо БД
entailment
public function pack($object) : ?PackedObject { $uow = $this->em->getUnitOfWork(); if (! $uow->isInIdentityMap($object)) { return null; } $identity = $uow->getEntityIdentifier($object); $count = count($identity); if ($count === 0) { return null; } if ($count === 1) { $identity = reset($identity); } return new PackedObject($this->getClass($object), $identity); }
{@inheritdoc}
entailment
public function unpack(PackedObject $packedObject) { $class = $packedObject->getClass(); if ($this->em->getMetadataFactory()->isTransient($class)) { return null; } return $this->em->getReference($class, $packedObject->getData()); }
{@inheritdoc}
entailment
public function buildFromCsv(CsvLine $csv_line_base = null) { $this->csv_line_base = $csv_line_base ? $csv_line_base : new CsvLine; $this->csv_parser->setConfig($this->config_file_parse); $this->csv_line_base->setConfig($this->config_model); $this->updateCsvHeader(); // Csv loop while ( ($csv_line_array = $this->csv_parser->parseCsvFile()) != false ) { if( count($csv_line_array) && (! ( (count($csv_line_array) == 1) && is_null($csv_line_array[0]) ) ) ) { // create csv_line $csv_line = clone $this->csv_line_base; $csv_line->forceSetAttributes($csv_line_array); $this->appendLine($csv_line); } } }
This method build the CsvFile from a csv file @throws FileNotFoundException @throws InvalidArgumentException @throws UnalignedArrayException @throws DomainException
entailment
protected function updateCsvHeader() { if( $this->config['first_line_headers'] ) { $csv_line_array = $this->csv_parser->parseCsvFile(); $this->csv_file->setCsvHeader($csv_line_array); } }
Update the csv header with first row of the file if "first_line_headers" is enabled
entailment
public function match(Request $request) : ?RouteMatch { $path = $request->getPath(); foreach ($this->prefixes as $prefix) { if (strpos($path, $prefix) === 0) { return $this->route->match($request); } } return null; }
{@inheritdoc}
entailment
protected function generateIdentifier() { if ($this->identifier === null) { ++self::$nextIdentifier; self::$nextIdentifier &= 0xFFFF; $this->identifier = self::$nextIdentifier; } return $this->identifier; }
Returns the identifier or generates a new one. @return int
entailment
public function setIdentifier($value) { if ($value !== null && ($value < 0 || $value > 0xFFFF)) { throw new \InvalidArgumentException( sprintf( 'Expected an identifier between 0x0000 and 0xFFFF but got %x', $value ) ); } $this->identifier = $value; }
Sets the identifier. @param int|null $value @throws \InvalidArgumentException
entailment
public function approvedWithPending(): ActiveQuery { return $this->andWhere([$this->statusAttribute => [Status::APPROVED, Status::PENDING]]); }
Get a new active query object that includes approved and pending resources. @return ActiveQuery
entailment
public function process(Request $request, Handler $handler): Response { try { $symfonyRequest = (new HttpFoundationFactory()) ->createRequest($request); $this->router->getContext()->fromRequest($symfonyRequest); $route = $this->router ->matchRequest($symfonyRequest); } catch (MethodNotAllowedException $e) { $allows = implode(', ', $e->getAllowedMethods()); return $this->createResponse(405, $e->getMessage()) ->withHeader('Allow', $allows); } catch (NoConfigurationException $e) { return $this->createResponse(500, $e->getMessage()); } catch (ResourceNotFoundException $e) { return $this->createResponse(404, $e->getMessage()); } foreach ($route as $key => $value) { $request = $request->withAttribute($key, $value); } return $handler->handle($request); }
Process a request and return a response.
entailment
public function channel($channel) { if (!isset($channel['link'])) { $channel['link'] = '/'; } if (!isset($channel['title'])) { $channel['title'] = ''; } if (!isset($channel['description'])) { $channel['description'] = ''; } $channel = $this->_prepareOutput($channel); return $channel; }
Prepares the channel and sets default values. @param array $channel @return array Channel
entailment
public function render($view = null, $layout = null) { if (isset($this->viewVars['_serialize'])) { return $this->_serialize($this->viewVars['_serialize']); } if ($view !== false && $this->_getViewFileName($view)) { return parent::render($view, false); } }
Render a RSS view. Uses the special '_serialize' parameter to convert a set of view variables into a XML response. Makes generating simple XML responses very easy. You can omit the '_serialize' parameter, and use a normal view + layout as well. @param string|null $view The view being rendered. @param string|null $layout The layout being rendered. @return string The rendered view.
entailment
protected function _serialize($serialize) { $rootNode = isset($this->viewVars['_rootNode']) ? $this->viewVars['_rootNode'] : 'channel'; if (is_array($serialize)) { $data = [$rootNode => []]; foreach ($serialize as $alias => $key) { if (is_numeric($alias)) { $alias = $key; } $data[$rootNode][$alias] = $this->viewVars[$key]; } } else { $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null; if (is_array($data) && Hash::numeric(array_keys($data))) { $data = [$rootNode => [$serialize => $data]]; } } $defaults = ['document' => [], 'channel' => [], 'items' => []]; $data += $defaults; if (!empty($data['document']['namespace'])) { foreach ($data['document']['namespace'] as $prefix => $url) { $this->setNamespace($prefix, $url); } } $channel = $this->channel($data['channel']); if (!empty($channel['image']) && empty($channel['image']['title'])) { $channel['image']['title'] = $channel['title']; } foreach ($data['items'] as $item) { $channel['item'][] = $this->_prepareOutput($item); } $array = [ 'rss' => [ '@version' => $this->version, 'channel' => $channel, ] ]; $namespaces = []; foreach ($this->_usedNamespaces as $usedNamespacePrefix) { if (!isset($this->_namespaces[$usedNamespacePrefix])) { throw new RuntimeException(sprintf('The prefix %s is not specified.', $usedNamespacePrefix)); } $namespaces['xmlns:' . $usedNamespacePrefix] = $this->_namespaces[$usedNamespacePrefix]; } $array['rss'] += $namespaces; $options = []; if (Configure::read('debug')) { $options['pretty'] = true; } $output = Xml::fromArray($array, $options)->asXML(); $output = $this->_replaceCdata($output); return $output; }
Serialize view vars. @param string|array $serialize The viewVars that need to be serialized. @return string The serialized data @throws \RuntimeException When the prefix is not specified
entailment
protected function _prepareOutput($item) { foreach ($item as $key => $val) { $prefix = null; // The cast prevents a PHP bug for switch case and false positives with integers $bareKey = (string)$key; // Detect namespaces if (strpos($key, ':') !== false) { list($prefix, $bareKey) = explode(':', $key, 2); if (strpos($prefix, '@') !== false) { $prefix = substr($prefix, 1); } if (!in_array($prefix, $this->_usedNamespaces)) { $this->_usedNamespaces[] = $prefix; } } $attrib = null; switch ($bareKey) { case 'encoded': $val = $this->_newCdata($val); break; case 'pubDate': $val = $this->time($val); break; case 'category': if (is_array($val) && isset($val['domain'])) { $attrib['@domain'] = $val['domain']; $attrib['@'] = isset($val['content']) ? $val['content'] : $attrib['@domain']; $val = $attrib; } elseif (is_array($val) && !empty($val[0])) { $categories = []; foreach ($val as $category) { $attrib = []; if (is_array($category) && isset($category['domain'])) { $attrib['@domain'] = $category['domain']; $attrib['@'] = isset($val['content']) ? $val['content'] : $attrib['@domain']; $category = $attrib; } $categories[] = $category; } $val = $categories; } break; case 'link': case 'url': case 'guid': case 'comments': if (is_array($val) && isset($val['@href'])) { $attrib = $val; $attrib['@href'] = Router::url($val['@href'], true); if ($prefix === 'atom') { $attrib['@rel'] = 'self'; $attrib['@type'] = 'application/rss+xml'; } $val = $attrib; } elseif (is_array($val) && isset($val['url'])) { if (!isset($val['@isPermalink']) || $val['@isPermalink'] !== 'false') { $val['url'] = Router::url($val['url'], true); } if ($bareKey === 'guid') { $val['@'] = $val['url']; unset($val['url']); } } else { $val = Router::url($val, true); } break; case 'source': if (is_array($val) && isset($val['url'])) { $attrib['@url'] = Router::url($val['url'], true); $attrib['@'] = isset($val['content']) ? $val['content'] : $attrib['@url']; } elseif (!is_array($val)) { $attrib['@url'] = Router::url($val, true); $attrib['@'] = $attrib['@url']; } $val = $attrib; break; case 'enclosure': if (isset($val['url']) && is_string($val['url']) && is_file(WWW_ROOT . $val['url']) && file_exists(WWW_ROOT . $val['url'])) { if (!isset($val['length']) && strpos($val['url'], '://') === false) { $val['length'] = sprintf('%u', filesize(WWW_ROOT . $val['url'])); } if (!isset($val['type']) && function_exists('mime_content_type')) { $val['type'] = mime_content_type(WWW_ROOT . $val['url']); } } $attrib['@url'] = Router::url($val['url'], true); $attrib['@length'] = $val['length']; $attrib['@type'] = $val['type']; $val = $attrib; break; default: //nothing } if (is_array($val)) { $val = $this->_prepareOutput($val); } $item[$key] = $val; } return $item; }
RssView::_prepareOutput() @param array $item @return array
entailment
protected function _newCdata($content) { $i = count($this->_cdata); $this->_cdata[$i] = $content; return '###CDATA-' . $i . '###'; }
RssView::_newCdata() @param string $content @return string
entailment
protected function _replaceCdata($content) { foreach ($this->_cdata as $n => $data) { $data = '<![CDATA[' . $data . ']]>'; $content = str_replace('###CDATA-' . $n . '###', $data, $content); } return $content; }
RssView::_replaceCdata() @param string $content @return string
entailment
public function match(Request $request) : ?RouteMatch { $path = $request->getPath(); $httpMethod = $request->getMethod(); foreach ($this->routes as $values) { [$regexp] = $values; if (preg_match($regexp, $path, $matches) === 1) { [, $httpMethods] = $values; if ($httpMethods && ! in_array($httpMethod, $httpMethods, true)) { continue; } [, , $className, $methodName, $classParameterNames, $methodParameterNames] = $values; $classParameters = []; $methodParameters = []; $index = 1; foreach ($classParameterNames as $name) { $classParameters[$name] = $matches[$index++]; } foreach ($methodParameterNames as $name) { $methodParameters[$name] = $matches[$index++]; } return RouteMatch::forMethod($className, $methodName, $classParameters, $methodParameters); } } return null; }
{@inheritdoc}
entailment
public function embed($parent, string $field, &$entity): bool { // In order to update the document if it exists inside the $parent $this->unembed($parent, $field, $entity); $fieldValue = $parent->$field; $fieldValue[] = $entity; $parent->$field = array_values($fieldValue); return true; }
Embeds the given $entity into $field of $parent. This method will also consider the _id of the $entity in order to update it if it is already present in $field. @param mixed $parent the object where the $entity will be embedded @param string $field name of the field of the object where the document will be embedded @param mixed $entity entity that will be embedded within $parent @return bool Success
entailment
public function unembed($parent, string $field, &$entity): bool { $fieldValue = (array) $parent->$field; $id = $this->getId($entity); foreach ($fieldValue as $key => $document) { if ($id == $this->getId($document)) { unset($fieldValue[$key]); } } $parent->$field = array_values($fieldValue); return true; }
Removes the given $entity from $field of $parent. This method will consider the _id of the $entity in order to remove it. @param mixed $parent the object where the $entity will be removed @param string $field name of the field of the object where the document is @param mixed $entity entity that will be removed from $parent @return bool Success
entailment
public function attach($parent, string $field, &$entity): bool { $fieldValue = (array) $parent->$field; $newId = $this->getId($entity); foreach ($fieldValue as $id) { if ($id == $newId) { return true; } } $fieldValue[] = $newId; $parent->$field = $fieldValue; return true; }
Attach a new _id reference into $field of $parent. @param mixed $parent the object where $entity will be referenced @param string $field the field where the _id reference of $entity will be stored @param object|array $entity the object that is being attached @return bool Success
entailment
public function detach($parent, string $field, &$entity): bool { $fieldValue = (array) $parent->$field; $newId = $this->getId($entity); foreach ($fieldValue as $key => $id) { if ($id == $newId) { unset($fieldValue[$key]); } } $parent->$field = array_values($fieldValue); return true; }
Removes an _id reference from $field of $parent. @param mixed $parent the object where $entity reference will be removed @param string $field the field where the _id reference of $entity is stored @param mixed $entity the object being detached or its _id @return bool Success
entailment
protected function getId(&$object) { if (is_array($object)) { if (isset($object['_id']) && $object['_id']) { return $object['_id']; } return $object['_id'] = new ObjectId(); } if (is_object($object) && !$object instanceof ObjectId) { if (isset($object->_id) && $object->_id) { return $object->_id; } return $object->_id = new ObjectId(); } return $object; }
Gets the _id of the given object or array. If there is no _id in it a new _id will be generated and set on the object (while still returning it). @param mixed $object the object|array that the _id will be retrieved from @return ObjectId|mixed
entailment
public static function forMethod(string $class, string $method, array $classParameters = [], array $methodParameters = []) : RouteMatch { try { $controller = new \ReflectionMethod($class, $method); } catch (\ReflectionException $e) { throw RoutingException::invalidControllerClassMethod($e, $class, $method); } return new RouteMatch($controller, $classParameters, $methodParameters); }
Returns a RouteMatch for the given class and method. @param string $class @param string $method @param array $classParameters @param array $methodParameters @return RouteMatch The route match. @throws RoutingException If the class or method does not exist.
entailment
public static function forFunction($function, array $functionParameters = []) : RouteMatch { try { $controller = new \ReflectionFunction($function); } catch (\ReflectionException $e) { throw RoutingException::invalidControllerFunction($e, $function); } return new self($controller, [], $functionParameters); }
Returns a RouteMatch for the given function or closure. @param string|\Closure $function @param array $functionParameters @return RouteMatch The route match. @throws RoutingException If the function is invalid.
entailment
public function withClassParameters(array $parameters) : RouteMatch { $routeMatch = clone $this; $routeMatch->classParameters = $parameters + $this->classParameters; return $routeMatch; }
Returns a copy of this RouteMatch, with additional class parameters. Parameters with the same name will override current parameters. This RouteMatch instance is immutable, and unaffected by this method call. @param array $parameters An associative array of class parameters. @return RouteMatch
entailment
public function withFunctionParameters(array $parameters) : RouteMatch { $routeMatch = clone $this; $routeMatch->functionParameters = $parameters + $this->functionParameters; return $routeMatch; }
Returns a copy of this RouteMatch, with additional function parameters. Parameters with the same name will override current parameters. This RouteMatch instance is immutable, and unaffected by this method call. @param array $parameters An associative array of function parameters. @return RouteMatch
entailment
protected function printFormNew(){ $str = parent::printFormNew(); $str .= "<div class=\"row\">". "<div class=\"col-md-12\">". "<h3>Step1: Upload file</h3>". // "<span class=\"glyphicon glyphicon-upload pull-right icon-medium\"></span>". Form::open(array( 'url' => $this->getProcessUrl(), 'files' => true , 'role' => 'form')). "<div class=\"form-group\">". Form::label('file_csv', 'Select file to upload (CSV only for now) *'). Form::file('file_csv'). "</div>". "<div class=\"form-group\">". Form::label('separator','Type of separator: '). Form::select('separator' , array( ','=>'comma ,' , ';'=>'semicolon ;' ) , ',', array("class" => "form-control") ). "</div>". "<div class=\"form-group\">". Form::label('max_lines','Max number of lines to show in preview: '). Form::select('max_lines' , array('10'=>'10', '50'=>'50', '100'=>'100', '150'=>'150') , '10', array("class"=> "form-control") ). "</div>". "<div class=\"form-group checkbox\">". "<label>". Form::checkbox('headers','1',false). "Check if first line contains headers". "</label>". "</div>". "<div class=\"form-group checkbox\">". "<label>". Form::checkbox('create_table','1',false). "Check if want to create table schema (Warning: will overwrite table data)". "</label>". "</div>". "<div class=\"form-group\">". Form::submit('Load' , array('class'=>'btn btn-success')). Form::close(). "</div>". // form-group "</div>". // col "</div>". // row "<hr/>"; return $str; }
Return the form that needs to be processed
entailment
public function processForm(array $input = null, $validator = null, $csv_handler = null) { if($input) { $this->form_input = $input; } else { $this->fillFormInput(); } $validator = ($validator) ? $validator : new ValidatorFormInputModel($this); $csv_handler = ($csv_handler) ? $csv_handler : new CsvFileHandler(); if ( $validator->validateInput() && $this->checkInputCsv() ) { // process data $config = $this->getConfigFromInput(); $success = true; // big try catch to set errors try { $csv_file = $csv_handler->openFromCsv($config); } catch(FileNotFoundException $e) { $this->appendError("NotFound", "File not found." ); $success = false; } catch(InvalidArgumentException $e) { $this->appendError("InvalidArgument", "Invalid argument." ); $success = false; } catch(DomainException $e) { $this->appendError("Domain", "Invalid temporary data." ); $success = false; } catch(UnalignedArrayException $e) { $this->appendError("UnalignedArray", "Unaligned data." ); $success = false; } catch(NoDataException $e) { $this->appendError("NoData", "No data found in the file." ); $success = false; } // save temporary if($success) { $saved = false; try { $saved = $csv_handler->saveTemporary(); } catch( Exception $e) { $this->appendError("SaveTemporary" , "Cannot save temporary data: check database access configuration." ); } if($saved) { $this->is_executed = true; // add if want to create table to session $exchange_data = array( "max_lines" => $this->form_input['max_lines'], "create_table" => $this->form_input['create_table'] ); // save data for next state Session::put($this->exchange_key,$exchange_data); } } } return $this->getIsExecuted(); }
Process the form @return Boolean $is_executed if the state is executed successfully
entailment
protected function getConfigFromInput() { $config_file_parse['separator'] = $this->form_input['separator']; $config_file_parse['file_path'] = $this->form_input['file_csv']->getRealPath(); $config["file_parse"] = $config_file_parse; $config_builder['first_line_headers'] = ( $this->form_input['headers'] != '' ); $config["builder"] = $config_builder; $config_model = array(); $config["model"] = $config_model; return $config; }
get the config from form input
entailment
public function convertToString($source) { if (is_object($source)) { if ($source instanceof NamedInterface) { return $source->getName(); } elseif (method_exists($source, '__toString')) { return (string) $source; } else { return get_class($source); } } elseif (is_scalar($source) || is_null($source)) { return (string) $source; } else { return gettype($source); } }
@param mixed $source @return string
entailment
public function convertToObjectRequest($query) { $factory = new RequestFactory(); $request = $factory->create($query['api']); if (isset($query['parameters'])) { try { $request = Utils::setter($request, $query['parameters']); } catch (NavitiaCreationException $e) { $alias = array('parameters' => $query['parameters']); $request = Utils::setter($request, $alias); } } return $request; }
{@inheritDoc}
entailment
private function assertValidClientID($value, $fromPacket) { if (strlen($value) > 23) { $this->throwException( sprintf( 'Expected client id shorter than 24 bytes but got "%s".', $value ), $fromPacket ); } if ($value !== '' && !ctype_alnum($value)) { $this->throwException( sprintf( 'Expected a client id containing characters 0-9, a-z or A-Z but got "%s".', $value ), $fromPacket ); } }
Asserts that a client id is shorter than 24 bytes and only contains characters 0-9, a-z or A-Z. @param string $value @param bool $fromPacket @throws MalformedPacketException @throws \InvalidArgumentException
entailment
public function getAttribute(string $key) { $inAttributes = array_key_exists($key, $this->attributes); if ($inAttributes) { return $this->attributes[$key]; } elseif ('attributes' == $key) { return $this->attributes; } }
Get an attribute from the model. @param string $key the attribute to be accessed @return mixed
entailment
public function fill(array $input, bool $force = false) { foreach ($input as $key => $value) { if ($force) { $this->setAttribute($key, $value); continue; } if ((empty($this->fillable) || in_array($key, $this->fillable)) && !in_array($key, $this->guarded)) { $this->setAttribute($key, $value); } } }
Set the model attributes using an array. @param array $input the data that will be used to fill the attributes @param bool $force force fill
entailment
protected function hasMutatorMethod($key, $prefix) { $method = $this->buildMutatorMethod($key, $prefix); return method_exists($this, $method); }
Verify if model has a mutator method defined. @param mixed $key attribute name @param mixed $prefix method prefix to be used @return bool
entailment
protected function calculcateScore(TransitionInterface $transition) { $score = 0; if ($transition->getEventName()) { $score += 2; } if ($transition->getConditionName()) { ++$score; } return $score; }
@param TransitionInterface $transition @return int
entailment
public static function create(Container $container = null) : Application { if ($container !== null) { $valueResolver = $container->getValueResolver(); $injectionPolicy = $container->getInjectionPolicy(); } else { $valueResolver = new DefaultValueResolver(); $injectionPolicy = new InjectionPolicy\NullPolicy(); } return new Application($valueResolver, $injectionPolicy); }
Creates an application. If a dependency injection container is provided, it is used to automatically inject dependencies in controllers. @param Container|null $container @return Application
entailment
public function run() : void { $request = Request::getCurrent(); $response = $this->handle($request); $response->send(); }
Runs the application. @return void
entailment
public function handle(Request $request) : Response { try { return $this->handleRequest($request); } catch (HttpException $e) { return $this->handleHttpException($e, $request); } catch (\Throwable $e) { return $this->handleUncaughtException($e, $request); } }
@param \Brick\Http\Request $request @return \Brick\Http\Response
entailment
private function handleHttpException(HttpException $exception, Request $request) : Response { $response = new Response(); $response->setContent($exception); $response->setStatusCode($exception->getStatusCode()); $response->setHeaders($exception->getHeaders()); $response->setHeader('Content-Type', 'text/plain'); $event = new ExceptionCaughtEvent($exception, $request, $response); $this->eventDispatcher->dispatch(ExceptionCaughtEvent::class, $event); return $response; }
Converts an HttpException to a Response. @param \Brick\Http\Exception\HttpException $exception @param \Brick\Http\Request $request @return \Brick\Http\Response
entailment
private function handleUncaughtException(\Throwable $exception, Request $request) : Response { $httpException = new HttpInternalServerErrorException('Uncaught exception', $exception); return $this->handleHttpException($httpException, $request); }
Wraps an uncaught exception in an HttpInternalServerErrorException, and converts it to a Response. @param \Throwable $exception @param \Brick\Http\Request $request @return \Brick\Http\Response
entailment
private function handleRequest(Request $request) : Response { $event = new IncomingRequestEvent($request); $this->eventDispatcher->dispatch(IncomingRequestEvent::class, $event); $match = $this->route($request); $event = new RouteMatchedEvent($request, $match); $this->eventDispatcher->dispatch(RouteMatchedEvent::class, $event); $controllerReflection = $match->getControllerReflection(); $instance = null; $this->valueResolver->setRequest($request); if ($controllerReflection instanceof \ReflectionMethod) { $className = $controllerReflection->getDeclaringClass()->getName(); $instance = $this->injector->instantiate($className, $match->getClassParameters()); $callable = $controllerReflection->getClosure($instance); } elseif ($controllerReflection instanceof \ReflectionFunction) { $callable = $controllerReflection->getClosure(); } else { throw new \UnexpectedValueException('Unknown controller reflection type.'); } $event = new ControllerReadyEvent($request, $match, $instance); $event->addParameters($match->getFunctionParameters()); $this->eventDispatcher->dispatch(ControllerReadyEvent::class, $event); $response = $event->getResponse(); if ($response === null) { try { $result = $this->injector->invoke($callable, $event->getParameters()); if ($result instanceof Response) { $response = $result; } else { $event = new NonResponseResultEvent($request, $match, $instance, $result); $this->eventDispatcher->dispatch(NonResponseResultEvent::class, $event); $response = $event->getResponse(); if ($response === null) { throw $this->invalidReturnValue('controller', Response::class, $result); } } } catch (HttpException $e) { $response = $this->handleHttpException($e, $request); } finally { $event = new ControllerInvocatedEvent($request, $match, $instance); $this->eventDispatcher->dispatch(ControllerInvocatedEvent::class, $event); } } $event = new ResponseReceivedEvent($request, $response, $match, $instance); $this->eventDispatcher->dispatch(ResponseReceivedEvent::class, $event); return $response; }
@param \Brick\Http\Request $request The request to handle. @return \Brick\Http\Response The generated response. @throws \Brick\Http\Exception\HttpException If a route throws such an exception, or no route matches the request. @throws \UnexpectedValueException If a route or controller returned an invalid value.
entailment
private function route(Request $request) : RouteMatch { foreach ($this->routes as $route) { try { $match = $route->match($request); } catch (RoutingException $e) { throw new HttpNotFoundException($e->getMessage(), $e); } if ($match !== null) { if ($match instanceof RouteMatch) { return $match; } throw $this->invalidReturnValue('route', Route::class . ' or NULL', $match); } } throw new HttpNotFoundException('No route matches the request.'); }
Routes the given Request. @param Request $request The request. @return RouteMatch The route match. @throws HttpNotFoundException If no route matches the request. @throws \UnexpectedValueException If a route returns an invalid value.
entailment
private function invalidReturnValue(string $what, string $expected, $actual) : \UnexpectedValueException { $message = 'Invalid return value from %s: expected %s, got %s.'; $actual = is_object($actual) ? get_class($actual) : gettype($actual); return new \UnexpectedValueException(sprintf($message, $what, $expected, $actual)); }
@param string $what The name of the expected resource. @param string $expected The expected return value type. @param mixed $actual The actual return value. @return \UnexpectedValueException
entailment
public static function nameCase($string = '', array $options = []) { if ($string == '') return $string; self::$options = array_merge(self::$options, $options); // Do not do anything if string is mixed and lazy option is true. if (self::$options['lazy'] && self::skipMixed($string)) return $string; // Capitalize $string = self::capitalize($string); $string = self::updateIrish($string); // Fixes for "son (daughter) of" etc foreach (self::$replacements as $pattern => $replacement) { $string = mb_ereg_replace($pattern, $replacement, $string); } $string = self::updateRoman($string); $string = self::fixConjunction($string); return $string; }
Main function for NameCase. @param string $string @param array $options @return string
entailment
private static function capitalize($string) { $string = mb_strtolower($string); $string = mb_ereg_replace_callback('\b\w', function ($matches) { return mb_strtoupper($matches[0]); }, $string); // Lowercase 's $string = mb_ereg_replace_callback('\'\w\b', function ($matches) { return mb_strtolower($matches[0]); }, $string); return $string; }
Capitalize first letters. @param string $string @return string
entailment
private static function skipMixed($string) { $firstLetterLower = $string[0] == mb_strtolower($string[0]); $allLowerOrUpper = (mb_strtolower($string) == $string || mb_strtoupper($string) == $string); return ! ($firstLetterLower || $allLowerOrUpper); }
Skip if string is mixed case. @param string $string @return bool
entailment
private static function updateIrish($string) { if ( ! self::$options['irish']) return $string; if (mb_ereg_match('.*?\bMac[A-Za-z]{2,}[^aciozj]\b', $string) || mb_ereg_match('.*?\bMc', $string)) { $string = self::updateMac($string); } return mb_ereg_replace('Macmurdo', 'MacMurdo', $string); }
Update for Irish names. @param string $string @return string
entailment
private static function fixConjunction($string) { if ( ! self::$options['spanish']) return $string; foreach (self::$conjunctions as $conjunction) { $string = mb_ereg_replace('\b' . $conjunction . '\b', mb_strtolower($conjunction), $string); } return $string; }
Fix Spanish conjunctions. @param string $string @return string
entailment
private static function updateMac($string) { $string = mb_ereg_replace_callback('\b(Ma?c)([A-Za-z]+)', function ($matches) { return $matches[1] . mb_strtoupper(mb_substr($matches[2], 0, 1)) . mb_substr($matches[2], 1); }, $string); // Now fix "Mac" exceptions foreach (self::$exceptions as $pattern => $replacement) { $string = mb_ereg_replace($pattern, $replacement, $string); } return $string; }
Updates irish Mac & Mc. @param string $string @return string
entailment
public function send(TransactionInterface $transaction) { return $this->requestFactory->create( static::transformRequest($transaction), [], $this->httpClient, $this->loop )->then(function (ResponseInterface $response) { return \React\Promise\resolve(static::transformResponse($response)); }); }
@param TransactionInterface $transaction @return \React\Promise\Promise
entailment
public function has(string $key) : bool { return $this->session->has($this->getKey($key)); }
{@inheritdoc}
entailment
public function set(string $key, $value) : void { $this->session->set($this->getKey($key), $value); }
{@inheritdoc}
entailment
public function remove(string $key) : void { $this->session->remove($this->getKey($key)); }
{@inheritdoc}
entailment
public function reduce( $tolerance ) { $this->points = $this->_reduce($this->points, (double)$tolerance); return $this->points; }
Public visible method to reduce points. @param mixed $tolerance Defined threshold to reduce by @return array Reduced set of points
entailment
private function _reduce( $points, $tolerance ) { $distanceMax = $index = 0; // Can't user $this->lastkey, as this is a reclusive method. $pointsEnd = key(array_slice($points, -1, 1, true)); for ( $i = 1; $i < $pointsEnd; $i++ ) { $distance = $this->shortestDistanceToSegment( $points[$i], $points[0], $points[$pointsEnd] ); if ( $distance > $distanceMax ) { $index = $i; $distanceMax = $distance; } } if ( $distanceMax > $tolerance ) { $firstHalf = $this->_reduce( array_slice($points, 0, $index+1), $tolerance ); $secondHalf = $this->_reduce( array_slice($points, $index), $tolerance ); array_shift($secondHalf); $points = array_merge($firstHalf, $secondHalf); } else { $points = array($points[0], $points[$pointsEnd]); } return $points; }
Reduce points with Ramer-Douglas-Peucker algorithm. @param array $points Finite set of points @param mixed $tolerance Defined threshold to reduce by @return array Reduced set of points
entailment
public function reduce( $tolerance, $lookAhead=null ) { if ($lookAhead) { $this->lookAhead = (int)$lookAhead; } $key = 0; $endPoint = min($this->lookAhead, $this->lastKey()); do { if ( $key + 1 == $endPoint ) { if ( $endPoint != $this->lastKey() ) { $key = $endPoint; $endPoint = min($endPoint + $this->lookAhead, $this->lastKey()); } else { /* Ignore */ } } else { $maxIndex = $key + 1; $d = $this->shortestDistanceToSegment( $this->points[$maxIndex], $this->points[$key], $this->points[$endPoint] ); $maxD = $d; for ( $i = $maxIndex + 1; $i < $endPoint; $i++ ) { $d = $this->shortestDistanceToSegment( $this->points[$i], $this->points[$key], $this->points[$endPoint] ); if ( $d > $maxD ) { $maxD = $d; $maxIndex = $i; } } if ( $maxD > $tolerance ) { $endPoint--; } else { for ( $i = $key + 1; $i < $endPoint; $i++ ) { unset($this->points[$i]); } $key = $endPoint; $endPoint = min($endPoint + $this->lookAhead, $this->lastKey()); } } } while ( $key < $this->lastKey(-2) || $endPoint != $this->lastKey() ); return $this->reindex(); }
Reduce points with Lang algorithm. @param mixed $tolerance Defines threshold to reduce by. @param integer $lookAhead Defines the segment size per iteration. @return array Reduced set of points @updated v1.2.0 Introduced `lookAhead` concept to allow user to control performance & accuracy.
entailment
public function resetState() { parent::resetState(); // clean temporary db $table_name = Config::get('laravel-import-export::baseconf.table_prefix'); $connection_name = Config::get('laravel-import-export::baseconf.connection_name'); DB::connection($connection_name)->table($table_name)->truncate(); }
Reset the session_array state
entailment
public function initializeState() { if (Session::has($this->session_key)) { $this->setStateArray( Session::get($this->session_key) ); } else { $this->resetState(); } return $this->getStateArray(); }
Initialize starting import state from session
entailment
public function resetState() { // clean states $this->setStateArray( new StateArray() ); $state_array = $this->getStateArray(); $state_array->append( new $this->initial_state ); Session::put($this->session_key,$state_array); }
Reset the session_array state
entailment
public function setContent($layout) { $content = ''; $state_array = $this->getStateArray(); foreach($state_array as $state_key => $state) { $content.=$state->getForm(); } $layout->content = $content; }
Fill layout content with forms
entailment
public function processForm() { $current_state = $this->getCurrent(); $executed_process = $current_state->processForm(); // set next state $executed_next_state = $this->setNextState($current_state,$executed_process); // return success return ( $executed_process && $executed_next_state ); }
Process the current form @return $executed if success @throws ClassNotFoundException
entailment
protected function setNextState($current_state, $executed) { try { $next_state = $current_state->getNextState(); } catch(ClassNotFoundException $e) { Session::put('Errors', new MessageBag( array("Class" => "Class not found") ) ); return false; } if($executed) { // append next state $this->append($next_state); } else { // replace current state $this->replaceCurrent($next_state); } return true; }
Set the next state @return Boolean $success
entailment
public function replaceCurrent($value) { $key = $this->getLastKey(); if($key >= 0) { $this->getStateArray()->offsetSet($key,$value); } else { throw new NoDataException; } }
Replace the current state
entailment
private function copy($variable, bool $pack, array & $visited = [], int $level = 0) { if (is_object($variable)) { $hash = spl_object_hash($variable); if (isset($visited[$hash])) { return $visited[$hash]; } if ($pack) { $packedObject = $this->objectPacker->pack($variable); if ($packedObject !== null) { return $visited[$hash] = $packedObject; } } elseif ($variable instanceof PackedObject) { $object = $this->objectPacker->unpack($variable); if ($object === null) { throw new \RuntimeException('No object packer available for ' . $variable->getClass()); } if ($object !== null) { return $visited[$hash] = $object; } } $class = new \ReflectionClass($variable); $properties = $this->reflectionTools->getClassProperties($class); if (! $class->isUserDefined()) { if ($class->isCloneable()) { return $visited[$hash] = clone $variable; } return $visited[$hash] = $variable; } $visited[$hash] = $copy = $class->newInstanceWithoutConstructor(); foreach ($properties as $property) { $property->setAccessible(true); $value = $property->getValue($variable); $processed = $this->copy($value, $pack, $visited, $level + 1); $property->setValue($copy, $processed); } return $copy; } if (is_array($variable)) { foreach ($variable as & $value) { $value = $this->copy($value, $pack, $visited, $level + 1); } } return $variable; }
@param mixed $variable The variable to copy. @param bool $pack True to pack, false to unpack. @param array $visited The visited objects, for recursive calls. @param int $level The nesting level. @return mixed
entailment
public function validateInput() { $v = Validator::make ( $this->model->getFormInput() , $this->model->getRules() ); $success = true; if ( $v->fails() ) { $this->model->setErrors( $v->messages() ); $success = false; } return $success; }
Validate form_input with $rules @return Boolean
entailment
public function check(\ArrayAccess $keyvalue) { foreach ($this as $key => $value) { if (!($keyvalue->offsetExists($key) && ($keyvalue->offsetGet($key) === $value))) { return false; } } return true; }
@param \ArrayAccess $keyvalue @return bool
entailment
public function setVoter(\Symfony\Component\Security\Core\User\UserInterface $voter) { $this->voter = $voter; return $this; }
Set voter @param \Symfony\Component\Security\Core\User\UserInterface $voter @return VoteInterface
entailment
protected function checkAttributeAssignable($attribute): void { if (empty($this->assignable)) { return; } if (is_array($attribute)) { foreach ($attribute as $singleAttribute) { $this->checkAttributeAssignable($singleAttribute); } return; } if ( ! in_array($attribute, $this->assignable)) { throw new UnassignableAttributeException("Not allowed to assign value for '{$attribute}'"); } }
Checks whether attribute key(s) may be assigned values @param string|array $attribute array key name or array of key names @throws UnassignableAttributeException
entailment
protected function &getAttributeValue(string $key) { if (isset($this->attributes[$key])) { return $this->attributes[ $key ]; } $null = null; return $null; }
Get a plain attribute @param string $key @return mixed
entailment
public function setAttribute(string $key, $value): DataObjectInterface { $this->checkAttributeAssignable($key); $this->attributes[$key] = $value; return $this; }
Get attribute @param string $key @param mixed $value @return $this|DataObjectInterface
entailment
public function setAttributes(array $attributes): void { $this->checkAttributeAssignable(array_keys($attributes)); $this->setRawAttributes($attributes); }
Mass assignment of attributes @param array $attributes associative
entailment
public function __isset($key) { return (isset($this->attributes[$key]) && null !== $this->getAttributeValue($key)); }
Determine if an attribute exists on the model. @param string $key @return bool
entailment
public function toArray(): array { if ( ! count($this->attributes)) { return []; } // make this work recursively $array = []; foreach ($this->attributes as $key => $attribute) { if ($attribute instanceof Arrayable) { $attribute = $attribute->toArray(); } elseif (is_array($attribute)) { $attribute = $this->recursiveToArray($attribute); } $array[$key] = $attribute; } return $array; }
------------------------------------------------------------------------------
entailment
protected function recursiveToArray($item) { if (is_array($item)) { foreach ($item as &$subitem) { $subitem = $this->recursiveToArray($subitem); } unset($subitem); return $item; } if ($item instanceof Arrayable) { return $item->toArray(); } return $item; }
Recursively converts parameter to array @param mixed $item @return array|string
entailment
protected function arrayToObject(array $array) { $obj = (object) []; foreach ($array as $k => $v) { if (strlen($k)) { if (is_array($v)) { $obj->{$k} = $this->arrayToObject($v); } else { $obj->{$k} = $v; } } } return $obj; }
Warning: doesn't work with empty array keys! @param array $array @return object
entailment
public function offsetSet($offset, $value) { if ( ! $this->magicAssignment) { throw new UnassignableAttributeException("Not allowed to assign value by magic with array access"); } $this->checkAttributeAssignable($offset); $this->attributes[ $offset ] = $value; }
Set the value for a given offset. @param mixed $offset @param mixed $value @return void
entailment
public function getNested(?string $key, $default = null) { if (null === $key) { return $this; } if (isset($this->attributes[$key])) { return $this->getAttribute($key); } $keys = explode('.', $key); $part = $this->getAttribute( array_shift($keys) ); foreach ($keys as $index => $segment) { if ($part instanceof DataObjectInterface) { return $part->getNested(implode('.', array_slice($keys, $index)), $default); } if ( ! is_array($part) || ! array_key_exists($segment, $part)) { return value($default); } $part = $part[ $segment ]; } return $part; }
Returns nested content by dot notation, similar to Laravel's Arr::get() Works with nested arrays and data objects @param string|null $key dot-notation representation of keys, null to return self @param mixed $default default value to return if nothing found, may be a callback @return mixed
entailment
public function reduce( $tolerance ) { $this->_tolerance = $tolerance; $sentinelKey = 0; while ($sentinelKey < $this->count()-1) { $testKey = $sentinelKey + 1; while ( $sentinelKey < $this->count()-1 && $this->_isInTolerance($sentinelKey, $testKey) ) { unset($this->points[$testKey]); $testKey++; } $this->reindex(); $sentinelKey++; } return $this->reindex(); }
Remove points with a distance under a given tolerance. @param double $tolerance Maximum radial distance between points. @return array Reduced set of points
entailment
private function _isInTolerance($basePointIndex, $subjectPointIndex) { $radius = $this->distanceBetweenPoints( $this->points[$basePointIndex], $this->points[$subjectPointIndex] ); return $radius < $this->_tolerance; }
Helper method to ensure clean code. @param integer $basePointIndex Sentinel point index. @param integer $subjectPointIndex Test point index. @return bool True if subject point is under tolerance, false otherwise.
entailment
public function objectId($value = null) { if (null === $value) { return new ObjectId(); } if (is_string($value) && ObjectIdUtils::isObjectId($value)) { $value = new ObjectId($value); } return $value; }
Filters any field in the $fields that has it's value specified as a 'objectId'. It will wraps the $value, if any, into a ObjectId object. @param mixed $value value that may be converted to ObjectId @return ObjectId|mixed
entailment
public function sequence(int $value = null) { if ($value) { return $value; } return Ioc::make(SequenceService::class) ->getNextValue($this->collection ?: $this->entityClass); }
Prepares the field to have a sequence. If $value is zero or not defined a new auto-increment number will be "generated" for the collection of the schema. The sequence generation is done by the SequenceService. @param int|null $value value that will be evaluated @return int
entailment
public function createVote(RatingInterface $rating, UserInterface $voter) { $class = $this->getClass(); $vote = new $class; $vote->setRating($rating); $vote->setVoter($voter); $this->dispatcher->dispatch(DCSRatingEvents::VOTE_CREATE, new Event\VoteEvent($vote)); return $vote; }
Creates an empty vote instance @param RatingInterface $rating @param UserInterface $voter @return \DCS\RatingBundle\Model\VoteInterface
entailment
public function onDispatcherReady() { if ($this->dispatcher && $this->dispatcher->isReady()) { $context = $this->currentContext; $event = $this->currentEvent; $this->dispatcher = null; $this->currentContext = null; $this->currentEvent = null; $this->doCheckTransitions($context, $event); $this->mutex->releaseLock(); } }
is called after dispatcher was executed.
entailment
public function dispatchEvent(DispatcherInterface $dispatcher, $name, \ArrayAccess $context = null) { if ($this->dispatcher) { throw new \RuntimeException('Event dispatching is still running!'); } else { if ($this->currentState->hasEvent($name)) { $this->acquireLockOrThrowException(); $this->dispatcher = $dispatcher; if ($context) { $this->currentContext = $context; } else { $this->currentContext = new \ArrayIterator(array()); } $this->currentEvent = $this->currentState->getEvent($name); $dispatcher->dispatch($this->currentEvent, array($this->subject, $this->currentContext), new Callback(array($this, 'onDispatcherReady'))); } else { throw new WrongEventForStateException($this->currentState->getName(), $name); } } }
@param DispatcherInterface $dispatcher @param string $name @param \ArrayAccess $context @throws \RuntimeException
entailment
public function setPathFilter($path_filter) { if (empty($path_filter)) { $this->clearPathFilter(); } else { $this->path_filter = $path_filter.'/'; } return $this; }
Set Path Filter @param string $path_filter @return self
entailment
public function buildUrl($base) { $url = $base.self::getApiName().'/'; $parameters = http_build_query($this->getParams()); $region = $this->getRegion(). '/'; if (!is_null($region)) { $url .= $region; $path_filter = $this->getPathFilter(); if (!is_null($path_filter)) { $url .= $path_filter; } if ($parameters !== '') { $parameters = preg_replace( '/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '%5B%5D=', $parameters ); $url .= 'departures?'.$parameters; } } return rtrim($url, '/'); }
{@inheritDoc}
entailment
public function getIframeURL() { $info = $this->parseLink(); if (!$info) { return false; } $params = $this->Config()->get('service'); if ($this->Service == 'Vimeo') { $url = 'https://player.vimeo.com/video/' . $this->VideoID; if ($params && !empty($params[strtolower($this->Service)])) { $url .= '?' . http_build_query($params[strtolower($this->Service)], '', '&'); } return $url; } if ($this->Service == 'YouTube') { $url = 'https://www.youtube.com/embed/' . $this->VideoID; if ($params && !empty($params[strtolower($this->Service)])) { $url .= '?' . http_build_query($params[strtolower($this->Service)], '', '&'); } return $url; } }
Return the iframe URL @param Null @return String
entailment
public function iFrame($maxwidth = '100%', $height = '56%') { $url = $this->getIFrameURL(); if (!$url) { return false; } if (is_numeric($maxwidth)) { $maxwidth .= 'px'; } if (is_numeric($height)) { $height .= 'px'; } return $this->customise([ 'URL' => $url, 'MaxWidth' => $maxwidth, 'Height' => $height, ])->renderWith('Axllent\\FormFields\\Layout\\VideoIframe'); }
Return populated iframe template @param Varchar max width @param Varchar height in proportion @return String
entailment
public function getTitle() { if ($this->getService() == 'YouTube') { $data = $this->getCachedJsonResponse( 'https://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $this->VideoID . '&format=json' ); if ($data && !empty($data['title'])) { return $data['title']; } } if ($this->getService() == 'Vimeo') { $data = $this->getCachedJsonResponse( 'https://vimeo.com/api/v2/video/' . $this->VideoID . '.json' ); if ($data && !empty($data[0]) && !empty($data[0]['title'])) { return $data[0]['title']; } } }
Scrape Video information from hosting sites @param Null @return String
entailment
public function thumbnailURL($size = 'large') { if (!in_array($size, ['large', 'medium', 'small'])) { return false; } $info = $this->parseLink(); $service = $this->getService(); if (!$info || !$service) { return false; } if ($service == 'YouTube') { if ($size == 'large') { $img = 'hqdefault.jpg'; } elseif ($size == 'medium') { $img = 'mqdefault.jpg'; } else { $img = 'default.jpg'; } return 'https://i.ytimg.com/vi/' . $this->VideoID . '/' . $img; } if ($service == 'Vimeo') { $data = $this->getCachedJsonResponse( 'https://vimeo.com/api/v2/video/' . $this->VideoID . '.json' ); if (!$data) { return false; } if ($size == 'large' && (!empty($data[0]['thumbnail_large']))) { return $data[0]['thumbnail_large']; } elseif ($size == 'medium' && (!empty($data[0]['thumbnail_medium']))) { return $data[0]['thumbnail_medium']; } elseif (!empty($data[0]['thumbnail_small'])) { return $data[0]['thumbnail_small']; } } return false; }
Return thumbnail URL @param Null @return String
entailment
private function getCachedJsonResponse($url) { if (!class_exists('GuzzleHttp\Client')) { return false; } $cache_seconds = $this->config()->get('cache_seconds'); if (!is_numeric($cache_seconds)) { $cache_seconds = 604800; } $cache = Injector::inst()->get(CacheInterface::class . '.videoImgCache'); $key = md5($url); if (!$json = $cache->get($key)) { $client = new \GuzzleHttp\Client([ 'timeout' => 5, // seconds 'headers' => [ // Appear like a web browser 'User-Agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0', 'Accept-Language' => 'en-US,en;q=0.5', ], ]); try { $res = $client->request('GET', $url); $json = (string) $res->getBody(); } catch (\GuzzleHttp\Exception\RequestException $e) { return false; } $cache->set($key, $json, $cache_seconds); } $data = @json_decode($json, true); return (!empty($data)) ? $data : false; }
Return cached json response @param String url @return Array|null
entailment