repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
bradcornford/Googlmapper | src/Cornford/Googlmapper/Mapper.php | Mapper.renderJavascript | public function renderJavascript()
{
if (!$this->isEnabled()) {
return;
}
return $this->view->make('googlmapper::javascript')
->withView($this->view)
->withOptions($this->generateRenderOptions())
->render();
} | php | public function renderJavascript()
{
if (!$this->isEnabled()) {
return;
}
return $this->view->make('googlmapper::javascript')
->withView($this->view)
->withOptions($this->generateRenderOptions())
->render();
} | [
"public",
"function",
"renderJavascript",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isEnabled",
"(",
")",
")",
"{",
"return",
";",
"}",
"return",
"$",
"this",
"->",
"view",
"->",
"make",
"(",
"'googlmapper::javascript'",
")",
"->",
"withView",
... | Renders and returns Google Map javascript code.
@return string | [
"Renders",
"and",
"returns",
"Google",
"Map",
"javascript",
"code",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/Mapper.php#L52-L62 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/Mapper.php | Mapper.generateRenderOptions | protected function generateRenderOptions($item = -1)
{
$options = $this->getOptions();
foreach (($item > -1 ? [$this->getItem($item)] : $this->getItems()) as $model) {
foreach ($model->getOptions() as $key => $option) {
if (array_key_exists($key, $this->getOptions()) && $this->getOptions()[$key] !== $option) {
$options[$key] = $option;
}
}
}
return $options;
} | php | protected function generateRenderOptions($item = -1)
{
$options = $this->getOptions();
foreach (($item > -1 ? [$this->getItem($item)] : $this->getItems()) as $model) {
foreach ($model->getOptions() as $key => $option) {
if (array_key_exists($key, $this->getOptions()) && $this->getOptions()[$key] !== $option) {
$options[$key] = $option;
}
}
}
return $options;
} | [
"protected",
"function",
"generateRenderOptions",
"(",
"$",
"item",
"=",
"-",
"1",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"getOptions",
"(",
")",
";",
"foreach",
"(",
"(",
"$",
"item",
">",
"-",
"1",
"?",
"[",
"$",
"this",
"->",
"getItem... | Generates the render options for Google Map.
@param integer $item
@return string | [
"Generates",
"the",
"render",
"options",
"for",
"Google",
"Map",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/Mapper.php#L71-L84 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/Mapper.php | Mapper.searchLocation | protected function searchLocation($location)
{
$request = file_get_contents(
sprintf(
'https://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false&key=%s',
urlencode($location),
$this->getKey()
)
);
return json_decode($request);
} | php | protected function searchLocation($location)
{
$request = file_get_contents(
sprintf(
'https://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false&key=%s',
urlencode($location),
$this->getKey()
)
);
return json_decode($request);
} | [
"protected",
"function",
"searchLocation",
"(",
"$",
"location",
")",
"{",
"$",
"request",
"=",
"file_get_contents",
"(",
"sprintf",
"(",
"'https://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false&key=%s'",
",",
"urlencode",
"(",
"$",
"location",
")",
","... | Search for a location against Google Maps Api.
@param string $location
@return mixed | [
"Search",
"for",
"a",
"location",
"against",
"Google",
"Maps",
"Api",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/Mapper.php#L93-L104 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/Mapper.php | Mapper.map | public function map($latitude, $longitude, array $options = [])
{
$parameters = array_replace_recursive(
$this->getOptions(),
[
'latitude' => $latitude,
'longitude' => $longitude,
'map' => 'map_' . count($this->getItems())
],
$options
);
$item = new Map($parameters);
$this->addItem($item);
return $this;
} | php | public function map($latitude, $longitude, array $options = [])
{
$parameters = array_replace_recursive(
$this->getOptions(),
[
'latitude' => $latitude,
'longitude' => $longitude,
'map' => 'map_' . count($this->getItems())
],
$options
);
$item = new Map($parameters);
$this->addItem($item);
return $this;
} | [
"public",
"function",
"map",
"(",
"$",
"latitude",
",",
"$",
"longitude",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"parameters",
"=",
"array_replace_recursive",
"(",
"$",
"this",
"->",
"getOptions",
"(",
")",
",",
"[",
"'latitude'",
... | Add a new map.
@param float $latitude
@param float $longitude
@param array $options
@return self | [
"Add",
"a",
"new",
"map",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/Mapper.php#L205-L221 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/Mapper.php | Mapper.streetview | public function streetview($latitude, $longitude, $heading, $pitch, array $options = [])
{
$parameters = array_replace_recursive(
$this->getOptions(),
[
'latitude' => $latitude,
'longitude' => $longitude,
'heading' => $heading,
'pitch' => $pitch,
'map' => 'map_' . count($this->getItems())
],
$options
);
$item = new Streetview($parameters);
$this->addItem($item);
return $this;
} | php | public function streetview($latitude, $longitude, $heading, $pitch, array $options = [])
{
$parameters = array_replace_recursive(
$this->getOptions(),
[
'latitude' => $latitude,
'longitude' => $longitude,
'heading' => $heading,
'pitch' => $pitch,
'map' => 'map_' . count($this->getItems())
],
$options
);
$item = new Streetview($parameters);
$this->addItem($item);
return $this;
} | [
"public",
"function",
"streetview",
"(",
"$",
"latitude",
",",
"$",
"longitude",
",",
"$",
"heading",
",",
"$",
"pitch",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"parameters",
"=",
"array_replace_recursive",
"(",
"$",
"this",
"->",
"... | Add a new street view map.
@param float $latitude
@param float $longitude
@param integer $heading
@param integer $pitch
@param array $options
@return self | [
"Add",
"a",
"new",
"street",
"view",
"map",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/Mapper.php#L234-L252 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/Mapper.php | Mapper.marker | public function marker($latitude, $longitude, array $options = [])
{
$items = $this->getItems();
if (empty($items)) {
throw new MapperInstanceException('No map found to add a marker to.');
}
$item = end($items);
$parameters = $this->getOptions();
$options = array_replace_recursive(
['markers' => $parameters['markers']],
$item->getOptions()['markers'],
$options
);
$item->marker($latitude, $longitude, $options);
return $this;
} | php | public function marker($latitude, $longitude, array $options = [])
{
$items = $this->getItems();
if (empty($items)) {
throw new MapperInstanceException('No map found to add a marker to.');
}
$item = end($items);
$parameters = $this->getOptions();
$options = array_replace_recursive(
['markers' => $parameters['markers']],
$item->getOptions()['markers'],
$options
);
$item->marker($latitude, $longitude, $options);
return $this;
} | [
"public",
"function",
"marker",
"(",
"$",
"latitude",
",",
"$",
"longitude",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"items",
"=",
"$",
"this",
"->",
"getItems",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"items",
")",
")",
... | Add a new map marker.
@param float $latitude
@param float $longitude
@param array $options
@throws MapperException
@return self | [
"Add",
"a",
"new",
"map",
"marker",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/Mapper.php#L265-L283 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/Mapper.php | Mapper.polyline | public function polyline(array $coordinates = [], array $options = [])
{
$items = $this->getItems();
if (empty($items)) {
throw new MapperInstanceException('No map found to add a polyline to.');
}
$defaults = [
'coordinates' => $coordinates,
'geodesic' => false,
'strokeColor' => '#FF0000',
'strokeOpacity' => 0.8,
'strokeWeight' => 2,
'editable' => false
];
$item = end($items);
$options = array_replace_recursive(
$defaults,
$options
);
$item->shape('polyline', $coordinates, $options);
return $this;
} | php | public function polyline(array $coordinates = [], array $options = [])
{
$items = $this->getItems();
if (empty($items)) {
throw new MapperInstanceException('No map found to add a polyline to.');
}
$defaults = [
'coordinates' => $coordinates,
'geodesic' => false,
'strokeColor' => '#FF0000',
'strokeOpacity' => 0.8,
'strokeWeight' => 2,
'editable' => false
];
$item = end($items);
$options = array_replace_recursive(
$defaults,
$options
);
$item->shape('polyline', $coordinates, $options);
return $this;
} | [
"public",
"function",
"polyline",
"(",
"array",
"$",
"coordinates",
"=",
"[",
"]",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"items",
"=",
"$",
"this",
"->",
"getItems",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"items",
")",... | Add a new map polyline.
@param array $coordinates
@param array $options
@throws MapperException
@return self | [
"Add",
"a",
"new",
"map",
"polyline",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/Mapper.php#L330-L356 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/Models/Location.php | Location.map | public function map(array $options = [])
{
return self::$mapper->map($this->getLatitude(), $this->getLongitude(), $options);
} | php | public function map(array $options = [])
{
return self::$mapper->map($this->getLatitude(), $this->getLongitude(), $options);
} | [
"public",
"function",
"map",
"(",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"self",
"::",
"$",
"mapper",
"->",
"map",
"(",
"$",
"this",
"->",
"getLatitude",
"(",
")",
",",
"$",
"this",
"->",
"getLongitude",
"(",
")",
",",
"$",
"... | Create a new map from location.
@param array $options
@return Mapper | [
"Create",
"a",
"new",
"map",
"from",
"location",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/Models/Location.php#L268-L271 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/Models/Location.php | Location.streetview | public function streetview($heading, $pitch, array $options = [])
{
return self::$mapper->streetview($this->getLatitude(), $this->getLongitude(), $heading, $pitch, $options);
} | php | public function streetview($heading, $pitch, array $options = [])
{
return self::$mapper->streetview($this->getLatitude(), $this->getLongitude(), $heading, $pitch, $options);
} | [
"public",
"function",
"streetview",
"(",
"$",
"heading",
",",
"$",
"pitch",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"self",
"::",
"$",
"mapper",
"->",
"streetview",
"(",
"$",
"this",
"->",
"getLatitude",
"(",
")",
",",
"$",
... | Create a new street view map from location.
@param integer $heading
@param integer $pitch
@param array $options
@return Mapper | [
"Create",
"a",
"new",
"street",
"view",
"map",
"from",
"location",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/Models/Location.php#L282-L285 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/Models/Map.php | Map.marker | public function marker($latitude, $longitude, array $options = [])
{
$parameters = [
'latitude' => $latitude,
'longitude' => $longitude,
];
$parameters = array_replace_recursive(
$this->options,
$parameters,
$options
);
$this->markers[] = new Marker($parameters);
} | php | public function marker($latitude, $longitude, array $options = [])
{
$parameters = [
'latitude' => $latitude,
'longitude' => $longitude,
];
$parameters = array_replace_recursive(
$this->options,
$parameters,
$options
);
$this->markers[] = new Marker($parameters);
} | [
"public",
"function",
"marker",
"(",
"$",
"latitude",
",",
"$",
"longitude",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"parameters",
"=",
"[",
"'latitude'",
"=>",
"$",
"latitude",
",",
"'longitude'",
"=>",
"$",
"longitude",
",",
"]",
... | Add a map marker to the markers bag.
@param float $latitude
@param float $longitude
@param array $options
@return void | [
"Add",
"a",
"map",
"marker",
"to",
"the",
"markers",
"bag",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/Models/Map.php#L52-L66 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/Models/Map.php | Map.shape | public function shape($type, $coordinates, array $options = [])
{
$parameters = [
'coordinates' => $coordinates
];
$parameters = array_replace_recursive(
$this->options,
$parameters,
$options
);
switch ($type) {
case 'polyline':
$this->shapes[] = new Polyline($parameters);
break;
case 'polygon':
$this->shapes[] = new Polygon($parameters);
break;
case 'rectangle':
$this->shapes[] = new Rectangle($parameters);
break;
case 'circle':
$this->shapes[] = new Circle($parameters);
break;
}
} | php | public function shape($type, $coordinates, array $options = [])
{
$parameters = [
'coordinates' => $coordinates
];
$parameters = array_replace_recursive(
$this->options,
$parameters,
$options
);
switch ($type) {
case 'polyline':
$this->shapes[] = new Polyline($parameters);
break;
case 'polygon':
$this->shapes[] = new Polygon($parameters);
break;
case 'rectangle':
$this->shapes[] = new Rectangle($parameters);
break;
case 'circle':
$this->shapes[] = new Circle($parameters);
break;
}
} | [
"public",
"function",
"shape",
"(",
"$",
"type",
",",
"$",
"coordinates",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"parameters",
"=",
"[",
"'coordinates'",
"=>",
"$",
"coordinates",
"]",
";",
"$",
"parameters",
"=",
"array_replace_recu... | Add a map shape to the shapes bag.
@param string $type
@param array $coordinates
@param array $options
@return void | [
"Add",
"a",
"map",
"shape",
"to",
"the",
"shapes",
"bag",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/Models/Map.php#L77-L104 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/MapperBase.php | MapperBase.setRegion | public function setRegion($value)
{
if (!is_string($value)) {
throw new MapperArgumentException('Invalid map region.');
}
if (!in_array($value, $this->regions)) {
throw new MapperArgumentException('Region is required in ISO 3166-1 code format.');
}
$this->region = $value;
} | php | public function setRegion($value)
{
if (!is_string($value)) {
throw new MapperArgumentException('Invalid map region.');
}
if (!in_array($value, $this->regions)) {
throw new MapperArgumentException('Region is required in ISO 3166-1 code format.');
}
$this->region = $value;
} | [
"public",
"function",
"setRegion",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"throw",
"new",
"MapperArgumentException",
"(",
"'Invalid map region.'",
")",
";",
"}",
"if",
"(",
"!",
"in_array",
"(",
"$",
... | Set the Google Maps region.
@param string $value
@throws MapperArgumentException
@return void | [
"Set",
"the",
"Google",
"Maps",
"region",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/MapperBase.php#L856-L867 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/MapperBase.php | MapperBase.setLanguage | public function setLanguage($value)
{
if (!is_string($value)) {
throw new MapperArgumentException('Invalid map language.');
}
if (!in_array($value, $this->languages)) {
throw new MapperArgumentException('Language is required in ISO 639-1 code format.');
}
$this->language = $value;
} | php | public function setLanguage($value)
{
if (!is_string($value)) {
throw new MapperArgumentException('Invalid map language.');
}
if (!in_array($value, $this->languages)) {
throw new MapperArgumentException('Language is required in ISO 639-1 code format.');
}
$this->language = $value;
} | [
"public",
"function",
"setLanguage",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"throw",
"new",
"MapperArgumentException",
"(",
"'Invalid map language.'",
")",
";",
"}",
"if",
"(",
"!",
"in_array",
"(",
"$... | Set the Google Maps language.
@param string $value
@throws MapperArgumentException
@return void | [
"Set",
"the",
"Google",
"Maps",
"language",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/MapperBase.php#L888-L899 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/MapperBase.php | MapperBase.setZoom | public function setZoom($value)
{
if (!is_numeric($value)) {
throw new MapperArgumentException('Zoom level must be an integer.');
}
if ($value < 1 || $value > 20) {
throw new MapperArgumentException('A zoom level must be between 1 and 20.');
}
$this->zoom = $value;
} | php | public function setZoom($value)
{
if (!is_numeric($value)) {
throw new MapperArgumentException('Zoom level must be an integer.');
}
if ($value < 1 || $value > 20) {
throw new MapperArgumentException('A zoom level must be between 1 and 20.');
}
$this->zoom = $value;
} | [
"public",
"function",
"setZoom",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"value",
")",
")",
"{",
"throw",
"new",
"MapperArgumentException",
"(",
"'Zoom level must be an integer.'",
")",
";",
"}",
"if",
"(",
"$",
"value",
"<",
... | Set map zoom level.
@param integer $value
@throws MapperArgumentException
@return void | [
"Set",
"map",
"zoom",
"level",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/MapperBase.php#L1160-L1171 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/MapperBase.php | MapperBase.setType | public function setType($value)
{
if (!in_array($value, $this->types)) {
throw new MapperArgumentException('Invalid map type.');
}
$this->type = $value;
} | php | public function setType($value)
{
if (!in_array($value, $this->types)) {
throw new MapperArgumentException('Invalid map type.');
}
$this->type = $value;
} | [
"public",
"function",
"setType",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"value",
",",
"$",
"this",
"->",
"types",
")",
")",
"{",
"throw",
"new",
"MapperArgumentException",
"(",
"'Invalid map type.'",
")",
";",
"}",
"$",
"thi... | Set map type.
@param string $value
@throws MapperArgumentException
@return void | [
"Set",
"map",
"type",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/MapperBase.php#L1388-L1395 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/MapperBase.php | MapperBase.setAnimation | public function setAnimation($value)
{
if (!in_array($value, $this->animations)) {
throw new MapperArgumentException('Invalid map marker animation.');
}
$this->animation = $value;
} | php | public function setAnimation($value)
{
if (!in_array($value, $this->animations)) {
throw new MapperArgumentException('Invalid map marker animation.');
}
$this->animation = $value;
} | [
"public",
"function",
"setAnimation",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"value",
",",
"$",
"this",
"->",
"animations",
")",
")",
"{",
"throw",
"new",
"MapperArgumentException",
"(",
"'Invalid map marker animation.'",
")",
";"... | Set map marker animation.
@param string $value
@throws MapperArgumentException
@return void | [
"Set",
"map",
"marker",
"animation",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/MapperBase.php#L1500-L1507 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/MapperBase.php | MapperBase.setClustersZoom | public function setClustersZoom($value)
{
if (!is_integer($value) && !is_null($value)) {
throw new MapperArgumentException('Invalid map clusters zoom setting.');
}
$this->clustersZoom = $value;
} | php | public function setClustersZoom($value)
{
if (!is_integer($value) && !is_null($value)) {
throw new MapperArgumentException('Invalid map clusters zoom setting.');
}
$this->clustersZoom = $value;
} | [
"public",
"function",
"setClustersZoom",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_integer",
"(",
"$",
"value",
")",
"&&",
"!",
"is_null",
"(",
"$",
"value",
")",
")",
"{",
"throw",
"new",
"MapperArgumentException",
"(",
"'Invalid map clusters zoom se... | Set map cluster zoom.
@param integer|null $value
@throws MapperArgumentException
@return void | [
"Set",
"map",
"cluster",
"zoom",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/MapperBase.php#L1632-L1639 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/MapperBase.php | MapperBase.getOptions | protected function getOptions()
{
return [
'key' => $this->getKey(),
'version' => $this->version,
'region' => $this->getRegion(),
'language' => $this->getLanguage(),
'async' => $this->getAsync(),
'marker' => $this->getMarker(),
'center' => $this->getCenter(),
'locate' => $this->getLocate(),
'zoom' => $this->getZoom(),
'scrollWheelZoom' => $this->getScrollWheelZoom(),
'fullscreenControl' => $this->getFullscreenControl(),
'zoomControl' => $this->getZoomControl(),
'scaleControl' => $this->getScaleControl(),
'streetViewControl' => $this->getStreetViewControl(),
'rotateControl' => $this->getRotateControl(),
'mapTypeControl' => $this->getMapTypeControl(),
'type' => $this->getType(),
'heading' => $this->getHeading(),
'tilt' => $this->getTilt(),
'ui' => $this->getUi(),
'overlay' => '',
'markers' => [
'title' => '',
'label' => '',
'content' => '',
'icon' => $this->getIcon(),
'place' => '',
'animation' => $this->getAnimation(),
'symbol' => '',
],
'cluster' => $this->getCluster(),
'clusters' => [
'icon' => $this->getClustersIcon(),
'grid' => $this->getClustersGrid(),
'zoom' => $this->getClustersZoom(),
'center' => $this->getClustersCenter(),
'size' => $this->getClustersSize()
],
];
} | php | protected function getOptions()
{
return [
'key' => $this->getKey(),
'version' => $this->version,
'region' => $this->getRegion(),
'language' => $this->getLanguage(),
'async' => $this->getAsync(),
'marker' => $this->getMarker(),
'center' => $this->getCenter(),
'locate' => $this->getLocate(),
'zoom' => $this->getZoom(),
'scrollWheelZoom' => $this->getScrollWheelZoom(),
'fullscreenControl' => $this->getFullscreenControl(),
'zoomControl' => $this->getZoomControl(),
'scaleControl' => $this->getScaleControl(),
'streetViewControl' => $this->getStreetViewControl(),
'rotateControl' => $this->getRotateControl(),
'mapTypeControl' => $this->getMapTypeControl(),
'type' => $this->getType(),
'heading' => $this->getHeading(),
'tilt' => $this->getTilt(),
'ui' => $this->getUi(),
'overlay' => '',
'markers' => [
'title' => '',
'label' => '',
'content' => '',
'icon' => $this->getIcon(),
'place' => '',
'animation' => $this->getAnimation(),
'symbol' => '',
],
'cluster' => $this->getCluster(),
'clusters' => [
'icon' => $this->getClustersIcon(),
'grid' => $this->getClustersGrid(),
'zoom' => $this->getClustersZoom(),
'center' => $this->getClustersCenter(),
'size' => $this->getClustersSize()
],
];
} | [
"protected",
"function",
"getOptions",
"(",
")",
"{",
"return",
"[",
"'key'",
"=>",
"$",
"this",
"->",
"getKey",
"(",
")",
",",
"'version'",
"=>",
"$",
"this",
"->",
"version",
",",
"'region'",
"=>",
"$",
"this",
"->",
"getRegion",
"(",
")",
",",
"'l... | Get mapper options.
@return array | [
"Get",
"mapper",
"options",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/MapperBase.php#L1712-L1754 | train |
bradcornford/Googlmapper | src/Cornford/Googlmapper/MapperBase.php | MapperBase.getItem | public function getItem($item)
{
return isset($this->items[$item]) ? $this->items[$item] : false;
} | php | public function getItem($item)
{
return isset($this->items[$item]) ? $this->items[$item] : false;
} | [
"public",
"function",
"getItem",
"(",
"$",
"item",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"items",
"[",
"$",
"item",
"]",
")",
"?",
"$",
"this",
"->",
"items",
"[",
"$",
"item",
"]",
":",
"false",
";",
"}"
] | Get a mapping item by reference.
@param integer $item
@return array|boolean | [
"Get",
"a",
"mapping",
"item",
"by",
"reference",
"."
] | 785e8c11b13abd4247acce55b4394307575ff622 | https://github.com/bradcornford/Googlmapper/blob/785e8c11b13abd4247acce55b4394307575ff622/src/Cornford/Googlmapper/MapperBase.php#L1797-L1800 | train |
Ocramius/ProxyManager | src/ProxyManager/ProxyGenerator/LazyLoadingGhostGenerator.php | LazyLoadingGhostGenerator.getAbstractProxiedMethods | private function getAbstractProxiedMethods(ReflectionClass $originalClass) : array
{
return array_map(
static function (ReflectionMethod $method) : ProxyManagerMethodGenerator {
$generated = ProxyManagerMethodGenerator::fromReflectionWithoutBodyAndDocBlock(
new MethodReflection($method->getDeclaringClass()->getName(), $method->getName())
);
$generated->setAbstract(false);
return $generated;
},
ProxiedMethodsFilter::getAbstractProxiedMethods($originalClass)
);
} | php | private function getAbstractProxiedMethods(ReflectionClass $originalClass) : array
{
return array_map(
static function (ReflectionMethod $method) : ProxyManagerMethodGenerator {
$generated = ProxyManagerMethodGenerator::fromReflectionWithoutBodyAndDocBlock(
new MethodReflection($method->getDeclaringClass()->getName(), $method->getName())
);
$generated->setAbstract(false);
return $generated;
},
ProxiedMethodsFilter::getAbstractProxiedMethods($originalClass)
);
} | [
"private",
"function",
"getAbstractProxiedMethods",
"(",
"ReflectionClass",
"$",
"originalClass",
")",
":",
"array",
"{",
"return",
"array_map",
"(",
"static",
"function",
"(",
"ReflectionMethod",
"$",
"method",
")",
":",
"ProxyManagerMethodGenerator",
"{",
"$",
"ge... | Retrieves all abstract methods to be proxied
@return MethodGenerator[] | [
"Retrieves",
"all",
"abstract",
"methods",
"to",
"be",
"proxied"
] | ba2d3a0bfe72ada4ecae1e1d1167e4b90dd3639a | https://github.com/Ocramius/ProxyManager/blob/ba2d3a0bfe72ada4ecae1e1d1167e4b90dd3639a/src/ProxyManager/ProxyGenerator/LazyLoadingGhostGenerator.php#L134-L148 | train |
Ocramius/ProxyManager | src/ProxyManager/ProxyGenerator/Util/PublicScopeSimulator.php | PublicScopeSimulator.getUndefinedPropertyNotice | private static function getUndefinedPropertyNotice(string $operationType, string $nameParameter) : string
{
if ($operationType !== self::OPERATION_GET) {
return '';
}
return ' $backtrace = debug_backtrace(false);' . "\n"
. ' trigger_error(' . "\n"
. ' sprintf(' . "\n"
. ' \'Undefined property: %s::$%s in %s on line %s\',' . "\n"
. ' get_parent_class($this),' . "\n"
. ' $' . $nameParameter . ',' . "\n"
. ' $backtrace[0][\'file\'],' . "\n"
. ' $backtrace[0][\'line\']' . "\n"
. ' ),' . "\n"
. ' \E_USER_NOTICE' . "\n"
. ' );' . "\n";
} | php | private static function getUndefinedPropertyNotice(string $operationType, string $nameParameter) : string
{
if ($operationType !== self::OPERATION_GET) {
return '';
}
return ' $backtrace = debug_backtrace(false);' . "\n"
. ' trigger_error(' . "\n"
. ' sprintf(' . "\n"
. ' \'Undefined property: %s::$%s in %s on line %s\',' . "\n"
. ' get_parent_class($this),' . "\n"
. ' $' . $nameParameter . ',' . "\n"
. ' $backtrace[0][\'file\'],' . "\n"
. ' $backtrace[0][\'line\']' . "\n"
. ' ),' . "\n"
. ' \E_USER_NOTICE' . "\n"
. ' );' . "\n";
} | [
"private",
"static",
"function",
"getUndefinedPropertyNotice",
"(",
"string",
"$",
"operationType",
",",
"string",
"$",
"nameParameter",
")",
":",
"string",
"{",
"if",
"(",
"$",
"operationType",
"!==",
"self",
"::",
"OPERATION_GET",
")",
"{",
"return",
"''",
"... | This will generate code that triggers a notice if access is attempted on a non-existing property | [
"This",
"will",
"generate",
"code",
"that",
"triggers",
"a",
"notice",
"if",
"access",
"is",
"attempted",
"on",
"a",
"non",
"-",
"existing",
"property"
] | ba2d3a0bfe72ada4ecae1e1d1167e4b90dd3639a | https://github.com/Ocramius/ProxyManager/blob/ba2d3a0bfe72ada4ecae1e1d1167e4b90dd3639a/src/ProxyManager/ProxyGenerator/Util/PublicScopeSimulator.php#L75-L92 | train |
Ocramius/ProxyManager | src/ProxyManager/ProxyGenerator/Util/PublicScopeSimulator.php | PublicScopeSimulator.getByRefReturnValue | private static function getByRefReturnValue(string $operationType) : string
{
return $operationType === self::OPERATION_GET || $operationType === self::OPERATION_SET ? '& ' : '';
} | php | private static function getByRefReturnValue(string $operationType) : string
{
return $operationType === self::OPERATION_GET || $operationType === self::OPERATION_SET ? '& ' : '';
} | [
"private",
"static",
"function",
"getByRefReturnValue",
"(",
"string",
"$",
"operationType",
")",
":",
"string",
"{",
"return",
"$",
"operationType",
"===",
"self",
"::",
"OPERATION_GET",
"||",
"$",
"operationType",
"===",
"self",
"::",
"OPERATION_SET",
"?",
"'&... | Defines whether the given operation produces a reference.
Note: if the object is a wrapper, the wrapped instance is accessed directly. If the object
is a ghost or the proxy has no wrapper, then an instance of the parent class is created via
on-the-fly unserialization | [
"Defines",
"whether",
"the",
"given",
"operation",
"produces",
"a",
"reference",
"."
] | ba2d3a0bfe72ada4ecae1e1d1167e4b90dd3639a | https://github.com/Ocramius/ProxyManager/blob/ba2d3a0bfe72ada4ecae1e1d1167e4b90dd3639a/src/ProxyManager/ProxyGenerator/Util/PublicScopeSimulator.php#L101-L104 | train |
Ocramius/ProxyManager | src/ProxyManager/ProxyGenerator/Util/ProxiedMethodsFilter.php | ProxiedMethodsFilter.methodCannotBeProxied | private static function methodCannotBeProxied(ReflectionMethod $method) : bool
{
return $method->isConstructor() || $method->isFinal() || $method->isStatic();
} | php | private static function methodCannotBeProxied(ReflectionMethod $method) : bool
{
return $method->isConstructor() || $method->isFinal() || $method->isStatic();
} | [
"private",
"static",
"function",
"methodCannotBeProxied",
"(",
"ReflectionMethod",
"$",
"method",
")",
":",
"bool",
"{",
"return",
"$",
"method",
"->",
"isConstructor",
"(",
")",
"||",
"$",
"method",
"->",
"isFinal",
"(",
")",
"||",
"$",
"method",
"->",
"i... | Checks whether the method cannot be proxied | [
"Checks",
"whether",
"the",
"method",
"cannot",
"be",
"proxied"
] | ba2d3a0bfe72ada4ecae1e1d1167e4b90dd3639a | https://github.com/Ocramius/ProxyManager/blob/ba2d3a0bfe72ada4ecae1e1d1167e4b90dd3639a/src/ProxyManager/ProxyGenerator/Util/ProxiedMethodsFilter.php#L76-L79 | train |
Ocramius/ProxyManager | src/ProxyManager/Generator/Util/IdentifierSuffixer.php | IdentifierSuffixer.getIdentifier | public static function getIdentifier(string $name) : string
{
static $salt;
$salt = $salt ?? $salt = self::loadBaseHashSalt();
$suffix = substr(sha1($name . $salt), 0, 5);
if (! preg_match(self::VALID_IDENTIFIER_FORMAT, $name)) {
return self::DEFAULT_IDENTIFIER . $suffix;
}
return $name . $suffix;
} | php | public static function getIdentifier(string $name) : string
{
static $salt;
$salt = $salt ?? $salt = self::loadBaseHashSalt();
$suffix = substr(sha1($name . $salt), 0, 5);
if (! preg_match(self::VALID_IDENTIFIER_FORMAT, $name)) {
return self::DEFAULT_IDENTIFIER . $suffix;
}
return $name . $suffix;
} | [
"public",
"static",
"function",
"getIdentifier",
"(",
"string",
"$",
"name",
")",
":",
"string",
"{",
"static",
"$",
"salt",
";",
"$",
"salt",
"=",
"$",
"salt",
"??",
"$",
"salt",
"=",
"self",
"::",
"loadBaseHashSalt",
"(",
")",
";",
"$",
"suffix",
"... | Generates a valid unique identifier from the given name,
with a suffix attached to it | [
"Generates",
"a",
"valid",
"unique",
"identifier",
"from",
"the",
"given",
"name",
"with",
"a",
"suffix",
"attached",
"to",
"it"
] | ba2d3a0bfe72ada4ecae1e1d1167e4b90dd3639a | https://github.com/Ocramius/ProxyManager/blob/ba2d3a0bfe72ada4ecae1e1d1167e4b90dd3639a/src/ProxyManager/Generator/Util/IdentifierSuffixer.php#L33-L45 | train |
composer/semver | src/Semver.php | Semver.satisfies | public static function satisfies($version, $constraints)
{
if (null === self::$versionParser) {
self::$versionParser = new VersionParser();
}
$versionParser = self::$versionParser;
$provider = new Constraint('==', $versionParser->normalize($version));
$constraints = $versionParser->parseConstraints($constraints);
return $constraints->matches($provider);
} | php | public static function satisfies($version, $constraints)
{
if (null === self::$versionParser) {
self::$versionParser = new VersionParser();
}
$versionParser = self::$versionParser;
$provider = new Constraint('==', $versionParser->normalize($version));
$constraints = $versionParser->parseConstraints($constraints);
return $constraints->matches($provider);
} | [
"public",
"static",
"function",
"satisfies",
"(",
"$",
"version",
",",
"$",
"constraints",
")",
"{",
"if",
"(",
"null",
"===",
"self",
"::",
"$",
"versionParser",
")",
"{",
"self",
"::",
"$",
"versionParser",
"=",
"new",
"VersionParser",
"(",
")",
";",
... | Determine if given version satisfies given constraints.
@param string $version
@param string $constraints
@return bool | [
"Determine",
"if",
"given",
"version",
"satisfies",
"given",
"constraints",
"."
] | 37e4db276f38376a63ea67e96b09571d74312779 | https://github.com/composer/semver/blob/37e4db276f38376a63ea67e96b09571d74312779/src/Semver.php#L32-L43 | train |
composer/semver | src/Semver.php | Semver.satisfiedBy | public static function satisfiedBy(array $versions, $constraints)
{
$versions = array_filter($versions, function ($version) use ($constraints) {
return Semver::satisfies($version, $constraints);
});
return array_values($versions);
} | php | public static function satisfiedBy(array $versions, $constraints)
{
$versions = array_filter($versions, function ($version) use ($constraints) {
return Semver::satisfies($version, $constraints);
});
return array_values($versions);
} | [
"public",
"static",
"function",
"satisfiedBy",
"(",
"array",
"$",
"versions",
",",
"$",
"constraints",
")",
"{",
"$",
"versions",
"=",
"array_filter",
"(",
"$",
"versions",
",",
"function",
"(",
"$",
"version",
")",
"use",
"(",
"$",
"constraints",
")",
"... | Return all versions that satisfy given constraints.
@param array $versions
@param string $constraints
@return array | [
"Return",
"all",
"versions",
"that",
"satisfy",
"given",
"constraints",
"."
] | 37e4db276f38376a63ea67e96b09571d74312779 | https://github.com/composer/semver/blob/37e4db276f38376a63ea67e96b09571d74312779/src/Semver.php#L53-L60 | train |
composer/semver | src/VersionParser.php | VersionParser.normalizeBranch | public function normalizeBranch($name)
{
$name = trim($name);
if (in_array($name, array('master', 'trunk', 'default'))) {
return $this->normalize($name);
}
if (preg_match('{^v?(\d++)(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?$}i', $name, $matches)) {
$version = '';
for ($i = 1; $i < 5; ++$i) {
$version .= isset($matches[$i]) ? str_replace(array('*', 'X'), 'x', $matches[$i]) : '.x';
}
return str_replace('x', '9999999', $version) . '-dev';
}
return 'dev-' . $name;
} | php | public function normalizeBranch($name)
{
$name = trim($name);
if (in_array($name, array('master', 'trunk', 'default'))) {
return $this->normalize($name);
}
if (preg_match('{^v?(\d++)(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?$}i', $name, $matches)) {
$version = '';
for ($i = 1; $i < 5; ++$i) {
$version .= isset($matches[$i]) ? str_replace(array('*', 'X'), 'x', $matches[$i]) : '.x';
}
return str_replace('x', '9999999', $version) . '-dev';
}
return 'dev-' . $name;
} | [
"public",
"function",
"normalizeBranch",
"(",
"$",
"name",
")",
"{",
"$",
"name",
"=",
"trim",
"(",
"$",
"name",
")",
";",
"if",
"(",
"in_array",
"(",
"$",
"name",
",",
"array",
"(",
"'master'",
",",
"'trunk'",
",",
"'default'",
")",
")",
")",
"{",... | Normalizes a branch name to be able to perform comparisons on it.
@param string $name
@return string | [
"Normalizes",
"a",
"branch",
"name",
"to",
"be",
"able",
"to",
"perform",
"comparisons",
"on",
"it",
"."
] | 37e4db276f38376a63ea67e96b09571d74312779 | https://github.com/composer/semver/blob/37e4db276f38376a63ea67e96b09571d74312779/src/VersionParser.php#L198-L216 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.getCacheStats | public static function getCacheStats()
{
return array(
'hits'=>self::$cache_hits,
'misses'=>self::$cache_misses,
'entries'=>count(self::$token_cache),
'size'=>strlen(serialize(self::$token_cache))
);
} | php | public static function getCacheStats()
{
return array(
'hits'=>self::$cache_hits,
'misses'=>self::$cache_misses,
'entries'=>count(self::$token_cache),
'size'=>strlen(serialize(self::$token_cache))
);
} | [
"public",
"static",
"function",
"getCacheStats",
"(",
")",
"{",
"return",
"array",
"(",
"'hits'",
"=>",
"self",
"::",
"$",
"cache_hits",
",",
"'misses'",
"=>",
"self",
"::",
"$",
"cache_misses",
",",
"'entries'",
"=>",
"count",
"(",
"self",
"::",
"$",
"t... | Get stats about the token cache
@return Array An array containing the keys 'hits', 'misses', 'entries', and 'size' in bytes | [
"Get",
"stats",
"about",
"the",
"token",
"cache"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L164-L172 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.init | protected static function init()
{
if (self::$init) return;
// Sort reserved word list from longest word to shortest, 3x faster than usort
$reservedMap = array_combine(self::$reserved, array_map('strlen', self::$reserved));
arsort($reservedMap);
self::$reserved = array_keys($reservedMap);
// Set up regular expressions
self::$regex_boundaries = '('.implode('|',array_map(array(__CLASS__, 'quote_regex'),self::$boundaries)).')';
self::$regex_reserved = '('.implode('|',array_map(array(__CLASS__, 'quote_regex'),self::$reserved)).')';
self::$regex_reserved_toplevel = str_replace(' ','\\s+','('.implode('|',array_map(array(__CLASS__, 'quote_regex'),self::$reserved_toplevel)).')');
self::$regex_reserved_newline = str_replace(' ','\\s+','('.implode('|',array_map(array(__CLASS__, 'quote_regex'),self::$reserved_newline)).')');
self::$regex_function = '('.implode('|',array_map(array(__CLASS__, 'quote_regex'),self::$functions)).')';
self::$init = true;
} | php | protected static function init()
{
if (self::$init) return;
// Sort reserved word list from longest word to shortest, 3x faster than usort
$reservedMap = array_combine(self::$reserved, array_map('strlen', self::$reserved));
arsort($reservedMap);
self::$reserved = array_keys($reservedMap);
// Set up regular expressions
self::$regex_boundaries = '('.implode('|',array_map(array(__CLASS__, 'quote_regex'),self::$boundaries)).')';
self::$regex_reserved = '('.implode('|',array_map(array(__CLASS__, 'quote_regex'),self::$reserved)).')';
self::$regex_reserved_toplevel = str_replace(' ','\\s+','('.implode('|',array_map(array(__CLASS__, 'quote_regex'),self::$reserved_toplevel)).')');
self::$regex_reserved_newline = str_replace(' ','\\s+','('.implode('|',array_map(array(__CLASS__, 'quote_regex'),self::$reserved_newline)).')');
self::$regex_function = '('.implode('|',array_map(array(__CLASS__, 'quote_regex'),self::$functions)).')';
self::$init = true;
} | [
"protected",
"static",
"function",
"init",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"init",
")",
"return",
";",
"// Sort reserved word list from longest word to shortest, 3x faster than usort",
"$",
"reservedMap",
"=",
"array_combine",
"(",
"self",
"::",
"$",
"r... | Stuff that only needs to be done once. Builds regular expressions and sorts the reserved words. | [
"Stuff",
"that",
"only",
"needs",
"to",
"be",
"done",
"once",
".",
"Builds",
"regular",
"expressions",
"and",
"sorts",
"the",
"reserved",
"words",
"."
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L177-L195 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.tokenize | protected static function tokenize($string)
{
self::init();
$tokens = array();
// Used for debugging if there is an error while tokenizing the string
$original_length = strlen($string);
// Used to make sure the string keeps shrinking on each iteration
$old_string_len = strlen($string) + 1;
$token = null;
$current_length = strlen($string);
// Keep processing the string until it is empty
while ($current_length) {
// If the string stopped shrinking, there was a problem
if ($old_string_len <= $current_length) {
$tokens[] = array(
self::TOKEN_VALUE=>$string,
self::TOKEN_TYPE=>self::TOKEN_TYPE_ERROR
);
return $tokens;
}
$old_string_len = $current_length;
// Determine if we can use caching
if ($current_length >= self::$max_cachekey_size) {
$cacheKey = substr($string,0,self::$max_cachekey_size);
} else {
$cacheKey = false;
}
// See if the token is already cached
if ($cacheKey && isset(self::$token_cache[$cacheKey])) {
// Retrieve from cache
$token = self::$token_cache[$cacheKey];
$token_length = strlen($token[self::TOKEN_VALUE]);
self::$cache_hits++;
} else {
// Get the next token and the token type
$token = self::getNextToken($string, $token);
$token_length = strlen($token[self::TOKEN_VALUE]);
self::$cache_misses++;
// If the token is shorter than the max length, store it in cache
if ($cacheKey && $token_length < self::$max_cachekey_size) {
self::$token_cache[$cacheKey] = $token;
}
}
$tokens[] = $token;
// Advance the string
$string = substr($string, $token_length);
$current_length -= $token_length;
}
return $tokens;
} | php | protected static function tokenize($string)
{
self::init();
$tokens = array();
// Used for debugging if there is an error while tokenizing the string
$original_length = strlen($string);
// Used to make sure the string keeps shrinking on each iteration
$old_string_len = strlen($string) + 1;
$token = null;
$current_length = strlen($string);
// Keep processing the string until it is empty
while ($current_length) {
// If the string stopped shrinking, there was a problem
if ($old_string_len <= $current_length) {
$tokens[] = array(
self::TOKEN_VALUE=>$string,
self::TOKEN_TYPE=>self::TOKEN_TYPE_ERROR
);
return $tokens;
}
$old_string_len = $current_length;
// Determine if we can use caching
if ($current_length >= self::$max_cachekey_size) {
$cacheKey = substr($string,0,self::$max_cachekey_size);
} else {
$cacheKey = false;
}
// See if the token is already cached
if ($cacheKey && isset(self::$token_cache[$cacheKey])) {
// Retrieve from cache
$token = self::$token_cache[$cacheKey];
$token_length = strlen($token[self::TOKEN_VALUE]);
self::$cache_hits++;
} else {
// Get the next token and the token type
$token = self::getNextToken($string, $token);
$token_length = strlen($token[self::TOKEN_VALUE]);
self::$cache_misses++;
// If the token is shorter than the max length, store it in cache
if ($cacheKey && $token_length < self::$max_cachekey_size) {
self::$token_cache[$cacheKey] = $token;
}
}
$tokens[] = $token;
// Advance the string
$string = substr($string, $token_length);
$current_length -= $token_length;
}
return $tokens;
} | [
"protected",
"static",
"function",
"tokenize",
"(",
"$",
"string",
")",
"{",
"self",
"::",
"init",
"(",
")",
";",
"$",
"tokens",
"=",
"array",
"(",
")",
";",
"// Used for debugging if there is an error while tokenizing the string",
"$",
"original_length",
"=",
"st... | Takes a SQL string and breaks it into tokens.
Each token is an associative array with type and value.
@param String $string The SQL string
@return Array An array of tokens. | [
"Takes",
"a",
"SQL",
"string",
"and",
"breaks",
"it",
"into",
"tokens",
".",
"Each",
"token",
"is",
"an",
"associative",
"array",
"with",
"type",
"and",
"value",
"."
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L356-L419 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.highlight | public static function highlight($string)
{
$tokens = self::tokenize($string);
$return = '';
foreach ($tokens as $token) {
$return .= self::highlightToken($token);
}
return self::output($return);
} | php | public static function highlight($string)
{
$tokens = self::tokenize($string);
$return = '';
foreach ($tokens as $token) {
$return .= self::highlightToken($token);
}
return self::output($return);
} | [
"public",
"static",
"function",
"highlight",
"(",
"$",
"string",
")",
"{",
"$",
"tokens",
"=",
"self",
"::",
"tokenize",
"(",
"$",
"string",
")",
";",
"$",
"return",
"=",
"''",
";",
"foreach",
"(",
"$",
"tokens",
"as",
"$",
"token",
")",
"{",
"$",
... | Add syntax highlighting to a SQL string
@param String $string The SQL string
@return String The SQL string with HTML styles applied | [
"Add",
"syntax",
"highlighting",
"to",
"a",
"SQL",
"string"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L730-L741 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.splitQuery | public static function splitQuery($string)
{
$queries = array();
$current_query = '';
$empty = true;
$tokens = self::tokenize($string);
foreach ($tokens as $token) {
// If this is a query separator
if ($token[self::TOKEN_VALUE] === ';') {
if (!$empty) {
$queries[] = $current_query.';';
}
$current_query = '';
$empty = true;
continue;
}
// If this is a non-empty character
if ($token[self::TOKEN_TYPE] !== self::TOKEN_TYPE_WHITESPACE && $token[self::TOKEN_TYPE] !== self::TOKEN_TYPE_COMMENT && $token[self::TOKEN_TYPE] !== self::TOKEN_TYPE_BLOCK_COMMENT) {
$empty = false;
}
$current_query .= $token[self::TOKEN_VALUE];
}
if (!$empty) {
$queries[] = trim($current_query);
}
return $queries;
} | php | public static function splitQuery($string)
{
$queries = array();
$current_query = '';
$empty = true;
$tokens = self::tokenize($string);
foreach ($tokens as $token) {
// If this is a query separator
if ($token[self::TOKEN_VALUE] === ';') {
if (!$empty) {
$queries[] = $current_query.';';
}
$current_query = '';
$empty = true;
continue;
}
// If this is a non-empty character
if ($token[self::TOKEN_TYPE] !== self::TOKEN_TYPE_WHITESPACE && $token[self::TOKEN_TYPE] !== self::TOKEN_TYPE_COMMENT && $token[self::TOKEN_TYPE] !== self::TOKEN_TYPE_BLOCK_COMMENT) {
$empty = false;
}
$current_query .= $token[self::TOKEN_VALUE];
}
if (!$empty) {
$queries[] = trim($current_query);
}
return $queries;
} | [
"public",
"static",
"function",
"splitQuery",
"(",
"$",
"string",
")",
"{",
"$",
"queries",
"=",
"array",
"(",
")",
";",
"$",
"current_query",
"=",
"''",
";",
"$",
"empty",
"=",
"true",
";",
"$",
"tokens",
"=",
"self",
"::",
"tokenize",
"(",
"$",
"... | Split a SQL string into multiple queries.
Uses ";" as a query delimiter.
@param String $string The SQL string
@return Array An array of individual query strings without trailing semicolons | [
"Split",
"a",
"SQL",
"string",
"into",
"multiple",
"queries",
".",
"Uses",
";",
"as",
"a",
"query",
"delimiter",
"."
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L751-L783 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.removeComments | public static function removeComments($string)
{
$result = '';
$tokens = self::tokenize($string);
foreach ($tokens as $token) {
// Skip comment tokens
if ($token[self::TOKEN_TYPE] === self::TOKEN_TYPE_COMMENT || $token[self::TOKEN_TYPE] === self::TOKEN_TYPE_BLOCK_COMMENT) {
continue;
}
$result .= $token[self::TOKEN_VALUE];
}
$result = self::format( $result,false);
return $result;
} | php | public static function removeComments($string)
{
$result = '';
$tokens = self::tokenize($string);
foreach ($tokens as $token) {
// Skip comment tokens
if ($token[self::TOKEN_TYPE] === self::TOKEN_TYPE_COMMENT || $token[self::TOKEN_TYPE] === self::TOKEN_TYPE_BLOCK_COMMENT) {
continue;
}
$result .= $token[self::TOKEN_VALUE];
}
$result = self::format( $result,false);
return $result;
} | [
"public",
"static",
"function",
"removeComments",
"(",
"$",
"string",
")",
"{",
"$",
"result",
"=",
"''",
";",
"$",
"tokens",
"=",
"self",
"::",
"tokenize",
"(",
"$",
"string",
")",
";",
"foreach",
"(",
"$",
"tokens",
"as",
"$",
"token",
")",
"{",
... | Remove all comments from a SQL string
@param String $string The SQL string
@return String The SQL string without comments | [
"Remove",
"all",
"comments",
"from",
"a",
"SQL",
"string"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L792-L809 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.compress | public static function compress($string)
{
$result = '';
$tokens = self::tokenize($string);
$whitespace = true;
foreach ($tokens as $token) {
// Skip comment tokens
if ($token[self::TOKEN_TYPE] === self::TOKEN_TYPE_COMMENT || $token[self::TOKEN_TYPE] === self::TOKEN_TYPE_BLOCK_COMMENT) {
continue;
}
// Remove extra whitespace in reserved words (e.g "OUTER JOIN" becomes "OUTER JOIN")
elseif ($token[self::TOKEN_TYPE] === self::TOKEN_TYPE_RESERVED || $token[self::TOKEN_TYPE] === self::TOKEN_TYPE_RESERVED_NEWLINE || $token[self::TOKEN_TYPE] === self::TOKEN_TYPE_RESERVED_TOPLEVEL) {
$token[self::TOKEN_VALUE] = preg_replace('/\s+/',' ',$token[self::TOKEN_VALUE]);
}
if ($token[self::TOKEN_TYPE] === self::TOKEN_TYPE_WHITESPACE) {
// If the last token was whitespace, don't add another one
if ($whitespace) {
continue;
} else {
$whitespace = true;
// Convert all whitespace to a single space
$token[self::TOKEN_VALUE] = ' ';
}
} else {
$whitespace = false;
}
$result .= $token[self::TOKEN_VALUE];
}
return rtrim($result);
} | php | public static function compress($string)
{
$result = '';
$tokens = self::tokenize($string);
$whitespace = true;
foreach ($tokens as $token) {
// Skip comment tokens
if ($token[self::TOKEN_TYPE] === self::TOKEN_TYPE_COMMENT || $token[self::TOKEN_TYPE] === self::TOKEN_TYPE_BLOCK_COMMENT) {
continue;
}
// Remove extra whitespace in reserved words (e.g "OUTER JOIN" becomes "OUTER JOIN")
elseif ($token[self::TOKEN_TYPE] === self::TOKEN_TYPE_RESERVED || $token[self::TOKEN_TYPE] === self::TOKEN_TYPE_RESERVED_NEWLINE || $token[self::TOKEN_TYPE] === self::TOKEN_TYPE_RESERVED_TOPLEVEL) {
$token[self::TOKEN_VALUE] = preg_replace('/\s+/',' ',$token[self::TOKEN_VALUE]);
}
if ($token[self::TOKEN_TYPE] === self::TOKEN_TYPE_WHITESPACE) {
// If the last token was whitespace, don't add another one
if ($whitespace) {
continue;
} else {
$whitespace = true;
// Convert all whitespace to a single space
$token[self::TOKEN_VALUE] = ' ';
}
} else {
$whitespace = false;
}
$result .= $token[self::TOKEN_VALUE];
}
return rtrim($result);
} | [
"public",
"static",
"function",
"compress",
"(",
"$",
"string",
")",
"{",
"$",
"result",
"=",
"''",
";",
"$",
"tokens",
"=",
"self",
"::",
"tokenize",
"(",
"$",
"string",
")",
";",
"$",
"whitespace",
"=",
"true",
";",
"foreach",
"(",
"$",
"tokens",
... | Compress a query by collapsing white space and removing comments
@param String $string The SQL string
@return String The SQL string without comments | [
"Compress",
"a",
"query",
"by",
"collapsing",
"white",
"space",
"and",
"removing",
"comments"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L818-L852 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.highlightToken | protected static function highlightToken($token)
{
$type = $token[self::TOKEN_TYPE];
if (self::is_cli()) {
$token = $token[self::TOKEN_VALUE];
} else {
if (defined('ENT_IGNORE')) {
$token = htmlentities($token[self::TOKEN_VALUE],ENT_COMPAT | ENT_IGNORE ,'UTF-8');
} else {
$token = htmlentities($token[self::TOKEN_VALUE],ENT_COMPAT,'UTF-8');
}
}
if ($type===self::TOKEN_TYPE_BOUNDARY) {
return self::highlightBoundary($token);
} elseif ($type===self::TOKEN_TYPE_WORD) {
return self::highlightWord($token);
} elseif ($type===self::TOKEN_TYPE_BACKTICK_QUOTE) {
return self::highlightBacktickQuote($token);
} elseif ($type===self::TOKEN_TYPE_QUOTE) {
return self::highlightQuote($token);
} elseif ($type===self::TOKEN_TYPE_RESERVED) {
return self::highlightReservedWord($token);
} elseif ($type===self::TOKEN_TYPE_RESERVED_TOPLEVEL) {
return self::highlightReservedWord($token);
} elseif ($type===self::TOKEN_TYPE_RESERVED_NEWLINE) {
return self::highlightReservedWord($token);
} elseif ($type===self::TOKEN_TYPE_NUMBER) {
return self::highlightNumber($token);
} elseif ($type===self::TOKEN_TYPE_VARIABLE) {
return self::highlightVariable($token);
} elseif ($type===self::TOKEN_TYPE_COMMENT || $type===self::TOKEN_TYPE_BLOCK_COMMENT) {
return self::highlightComment($token);
}
return $token;
} | php | protected static function highlightToken($token)
{
$type = $token[self::TOKEN_TYPE];
if (self::is_cli()) {
$token = $token[self::TOKEN_VALUE];
} else {
if (defined('ENT_IGNORE')) {
$token = htmlentities($token[self::TOKEN_VALUE],ENT_COMPAT | ENT_IGNORE ,'UTF-8');
} else {
$token = htmlentities($token[self::TOKEN_VALUE],ENT_COMPAT,'UTF-8');
}
}
if ($type===self::TOKEN_TYPE_BOUNDARY) {
return self::highlightBoundary($token);
} elseif ($type===self::TOKEN_TYPE_WORD) {
return self::highlightWord($token);
} elseif ($type===self::TOKEN_TYPE_BACKTICK_QUOTE) {
return self::highlightBacktickQuote($token);
} elseif ($type===self::TOKEN_TYPE_QUOTE) {
return self::highlightQuote($token);
} elseif ($type===self::TOKEN_TYPE_RESERVED) {
return self::highlightReservedWord($token);
} elseif ($type===self::TOKEN_TYPE_RESERVED_TOPLEVEL) {
return self::highlightReservedWord($token);
} elseif ($type===self::TOKEN_TYPE_RESERVED_NEWLINE) {
return self::highlightReservedWord($token);
} elseif ($type===self::TOKEN_TYPE_NUMBER) {
return self::highlightNumber($token);
} elseif ($type===self::TOKEN_TYPE_VARIABLE) {
return self::highlightVariable($token);
} elseif ($type===self::TOKEN_TYPE_COMMENT || $type===self::TOKEN_TYPE_BLOCK_COMMENT) {
return self::highlightComment($token);
}
return $token;
} | [
"protected",
"static",
"function",
"highlightToken",
"(",
"$",
"token",
")",
"{",
"$",
"type",
"=",
"$",
"token",
"[",
"self",
"::",
"TOKEN_TYPE",
"]",
";",
"if",
"(",
"self",
"::",
"is_cli",
"(",
")",
")",
"{",
"$",
"token",
"=",
"$",
"token",
"["... | Highlights a token depending on its type.
@param Array $token An associative array containing type and value.
@return String HTML code of the highlighted token. | [
"Highlights",
"a",
"token",
"depending",
"on",
"its",
"type",
"."
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L861-L898 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.highlightQuote | protected static function highlightQuote($value)
{
if (self::is_cli()) {
return self::$cli_quote . $value . "\x1b[0m";
} else {
return '<span ' . self::$quote_attributes . '>' . $value . '</span>';
}
} | php | protected static function highlightQuote($value)
{
if (self::is_cli()) {
return self::$cli_quote . $value . "\x1b[0m";
} else {
return '<span ' . self::$quote_attributes . '>' . $value . '</span>';
}
} | [
"protected",
"static",
"function",
"highlightQuote",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"self",
"::",
"is_cli",
"(",
")",
")",
"{",
"return",
"self",
"::",
"$",
"cli_quote",
".",
"$",
"value",
".",
"\"\\x1b[0m\"",
";",
"}",
"else",
"{",
"return",
... | Highlights a quoted string
@param String $value The token's value
@return String HTML code of the highlighted token. | [
"Highlights",
"a",
"quoted",
"string"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L907-L914 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.highlightBacktickQuote | protected static function highlightBacktickQuote($value)
{
if (self::is_cli()) {
return self::$cli_backtick_quote . $value . "\x1b[0m";
} else {
return '<span ' . self::$backtick_quote_attributes . '>' . $value . '</span>';
}
} | php | protected static function highlightBacktickQuote($value)
{
if (self::is_cli()) {
return self::$cli_backtick_quote . $value . "\x1b[0m";
} else {
return '<span ' . self::$backtick_quote_attributes . '>' . $value . '</span>';
}
} | [
"protected",
"static",
"function",
"highlightBacktickQuote",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"self",
"::",
"is_cli",
"(",
")",
")",
"{",
"return",
"self",
"::",
"$",
"cli_backtick_quote",
".",
"$",
"value",
".",
"\"\\x1b[0m\"",
";",
"}",
"else",
... | Highlights a backtick quoted string
@param String $value The token's value
@return String HTML code of the highlighted token. | [
"Highlights",
"a",
"backtick",
"quoted",
"string"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L923-L930 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.highlightReservedWord | protected static function highlightReservedWord($value)
{
if (self::is_cli()) {
return self::$cli_reserved . $value . "\x1b[0m";
} else {
return '<span ' . self::$reserved_attributes . '>' . $value . '</span>';
}
} | php | protected static function highlightReservedWord($value)
{
if (self::is_cli()) {
return self::$cli_reserved . $value . "\x1b[0m";
} else {
return '<span ' . self::$reserved_attributes . '>' . $value . '</span>';
}
} | [
"protected",
"static",
"function",
"highlightReservedWord",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"self",
"::",
"is_cli",
"(",
")",
")",
"{",
"return",
"self",
"::",
"$",
"cli_reserved",
".",
"$",
"value",
".",
"\"\\x1b[0m\"",
";",
"}",
"else",
"{",
... | Highlights a reserved word
@param String $value The token's value
@return String HTML code of the highlighted token. | [
"Highlights",
"a",
"reserved",
"word"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L939-L946 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.highlightBoundary | protected static function highlightBoundary($value)
{
if ($value==='(' || $value===')') return $value;
if (self::is_cli()) {
return self::$cli_boundary . $value . "\x1b[0m";
} else {
return '<span ' . self::$boundary_attributes . '>' . $value . '</span>';
}
} | php | protected static function highlightBoundary($value)
{
if ($value==='(' || $value===')') return $value;
if (self::is_cli()) {
return self::$cli_boundary . $value . "\x1b[0m";
} else {
return '<span ' . self::$boundary_attributes . '>' . $value . '</span>';
}
} | [
"protected",
"static",
"function",
"highlightBoundary",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"'('",
"||",
"$",
"value",
"===",
"')'",
")",
"return",
"$",
"value",
";",
"if",
"(",
"self",
"::",
"is_cli",
"(",
")",
")",
"{",
"... | Highlights a boundary token
@param String $value The token's value
@return String HTML code of the highlighted token. | [
"Highlights",
"a",
"boundary",
"token"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L955-L964 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.highlightNumber | protected static function highlightNumber($value)
{
if (self::is_cli()) {
return self::$cli_number . $value . "\x1b[0m";
} else {
return '<span ' . self::$number_attributes . '>' . $value . '</span>';
}
} | php | protected static function highlightNumber($value)
{
if (self::is_cli()) {
return self::$cli_number . $value . "\x1b[0m";
} else {
return '<span ' . self::$number_attributes . '>' . $value . '</span>';
}
} | [
"protected",
"static",
"function",
"highlightNumber",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"self",
"::",
"is_cli",
"(",
")",
")",
"{",
"return",
"self",
"::",
"$",
"cli_number",
".",
"$",
"value",
".",
"\"\\x1b[0m\"",
";",
"}",
"else",
"{",
"return"... | Highlights a number
@param String $value The token's value
@return String HTML code of the highlighted token. | [
"Highlights",
"a",
"number"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L973-L980 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.highlightError | protected static function highlightError($value)
{
if (self::is_cli()) {
return self::$cli_error . $value . "\x1b[0m";
} else {
return '<span ' . self::$error_attributes . '>' . $value . '</span>';
}
} | php | protected static function highlightError($value)
{
if (self::is_cli()) {
return self::$cli_error . $value . "\x1b[0m";
} else {
return '<span ' . self::$error_attributes . '>' . $value . '</span>';
}
} | [
"protected",
"static",
"function",
"highlightError",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"self",
"::",
"is_cli",
"(",
")",
")",
"{",
"return",
"self",
"::",
"$",
"cli_error",
".",
"$",
"value",
".",
"\"\\x1b[0m\"",
";",
"}",
"else",
"{",
"return",
... | Highlights an error
@param String $value The token's value
@return String HTML code of the highlighted token. | [
"Highlights",
"an",
"error"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L989-L996 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.highlightComment | protected static function highlightComment($value)
{
if (self::is_cli()) {
return self::$cli_comment . $value . "\x1b[0m";
} else {
return '<span ' . self::$comment_attributes . '>' . $value . '</span>';
}
} | php | protected static function highlightComment($value)
{
if (self::is_cli()) {
return self::$cli_comment . $value . "\x1b[0m";
} else {
return '<span ' . self::$comment_attributes . '>' . $value . '</span>';
}
} | [
"protected",
"static",
"function",
"highlightComment",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"self",
"::",
"is_cli",
"(",
")",
")",
"{",
"return",
"self",
"::",
"$",
"cli_comment",
".",
"$",
"value",
".",
"\"\\x1b[0m\"",
";",
"}",
"else",
"{",
"retur... | Highlights a comment
@param String $value The token's value
@return String HTML code of the highlighted token. | [
"Highlights",
"a",
"comment"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L1005-L1012 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.highlightWord | protected static function highlightWord($value)
{
if (self::is_cli()) {
return self::$cli_word . $value . "\x1b[0m";
} else {
return '<span ' . self::$word_attributes . '>' . $value . '</span>';
}
} | php | protected static function highlightWord($value)
{
if (self::is_cli()) {
return self::$cli_word . $value . "\x1b[0m";
} else {
return '<span ' . self::$word_attributes . '>' . $value . '</span>';
}
} | [
"protected",
"static",
"function",
"highlightWord",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"self",
"::",
"is_cli",
"(",
")",
")",
"{",
"return",
"self",
"::",
"$",
"cli_word",
".",
"$",
"value",
".",
"\"\\x1b[0m\"",
";",
"}",
"else",
"{",
"return",
... | Highlights a word token
@param String $value The token's value
@return String HTML code of the highlighted token. | [
"Highlights",
"a",
"word",
"token"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L1021-L1028 | train |
jdorn/sql-formatter | lib/SqlFormatter.php | SqlFormatter.highlightVariable | protected static function highlightVariable($value)
{
if (self::is_cli()) {
return self::$cli_variable . $value . "\x1b[0m";
} else {
return '<span ' . self::$variable_attributes . '>' . $value . '</span>';
}
} | php | protected static function highlightVariable($value)
{
if (self::is_cli()) {
return self::$cli_variable . $value . "\x1b[0m";
} else {
return '<span ' . self::$variable_attributes . '>' . $value . '</span>';
}
} | [
"protected",
"static",
"function",
"highlightVariable",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"self",
"::",
"is_cli",
"(",
")",
")",
"{",
"return",
"self",
"::",
"$",
"cli_variable",
".",
"$",
"value",
".",
"\"\\x1b[0m\"",
";",
"}",
"else",
"{",
"ret... | Highlights a variable token
@param String $value The token's value
@return String HTML code of the highlighted token. | [
"Highlights",
"a",
"variable",
"token"
] | 7ef9b85961956aa572413693e1194b60f50ab9ab | https://github.com/jdorn/sql-formatter/blob/7ef9b85961956aa572413693e1194b60f50ab9ab/lib/SqlFormatter.php#L1037-L1044 | train |
sensiolabs/security-checker | SensioLabs/Security/SecurityChecker.php | SecurityChecker.check | public function check($lock, $format = 'json', array $headers = [])
{
if (0 !== strpos($lock, 'data://text/plain;base64,')) {
if (is_dir($lock) && file_exists($lock.'/composer.lock')) {
$lock = $lock.'/composer.lock';
} elseif (preg_match('/composer\.json$/', $lock)) {
$lock = str_replace('composer.json', 'composer.lock', $lock);
}
if (!is_file($lock)) {
throw new RuntimeException('Lock file does not exist.');
}
}
return $this->crawler->check($lock, $format, $headers);
} | php | public function check($lock, $format = 'json', array $headers = [])
{
if (0 !== strpos($lock, 'data://text/plain;base64,')) {
if (is_dir($lock) && file_exists($lock.'/composer.lock')) {
$lock = $lock.'/composer.lock';
} elseif (preg_match('/composer\.json$/', $lock)) {
$lock = str_replace('composer.json', 'composer.lock', $lock);
}
if (!is_file($lock)) {
throw new RuntimeException('Lock file does not exist.');
}
}
return $this->crawler->check($lock, $format, $headers);
} | [
"public",
"function",
"check",
"(",
"$",
"lock",
",",
"$",
"format",
"=",
"'json'",
",",
"array",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"0",
"!==",
"strpos",
"(",
"$",
"lock",
",",
"'data://text/plain;base64,'",
")",
")",
"{",
"if",
"... | Checks a composer.lock file.
@param string $lock The path to the composer.lock file
@param string $format The format of the result
@param array $headers An array of headers to add for this specific HTTP request
@return Result
@throws RuntimeException When the lock file does not exist
@throws RuntimeException When the certificate can not be copied | [
"Checks",
"a",
"composer",
".",
"lock",
"file",
"."
] | 3de652566530d72e5515eeeafad6a3734956589a | https://github.com/sensiolabs/security-checker/blob/3de652566530d72e5515eeeafad6a3734956589a/SensioLabs/Security/SecurityChecker.php#L39-L54 | train |
sensiolabs/security-checker | SensioLabs/Security/Crawler.php | Crawler.check | public function check($lock, $format = 'json', array $headers = [])
{
list($headers, $body) = $this->doCheck($lock, $format, $headers);
if (!(preg_match('/X-Alerts: (\d+)/i', $headers, $matches) || 2 == \count($matches))) {
throw new RuntimeException('The web service did not return alerts count.');
}
return new Result((int) $matches[1], $body, $format);
} | php | public function check($lock, $format = 'json', array $headers = [])
{
list($headers, $body) = $this->doCheck($lock, $format, $headers);
if (!(preg_match('/X-Alerts: (\d+)/i', $headers, $matches) || 2 == \count($matches))) {
throw new RuntimeException('The web service did not return alerts count.');
}
return new Result((int) $matches[1], $body, $format);
} | [
"public",
"function",
"check",
"(",
"$",
"lock",
",",
"$",
"format",
"=",
"'json'",
",",
"array",
"$",
"headers",
"=",
"[",
"]",
")",
"{",
"list",
"(",
"$",
"headers",
",",
"$",
"body",
")",
"=",
"$",
"this",
"->",
"doCheck",
"(",
"$",
"lock",
... | Checks a Composer lock file.
@param string $lock The path to the composer.lock file or a string able to be opened via file_get_contents
@param string $format The format of the result
@param array $headers An array of headers to add for this specific HTTP request
@return Result | [
"Checks",
"a",
"Composer",
"lock",
"file",
"."
] | 3de652566530d72e5515eeeafad6a3734956589a | https://github.com/sensiolabs/security-checker/blob/3de652566530d72e5515eeeafad6a3734956589a/SensioLabs/Security/Crawler.php#L59-L68 | train |
craftcms/redactor | src/controllers/DefaultController.php | DefaultController.actionCanEdit | public function actionCanEdit(): Response
{
$this->requireAcceptsJson();
$this->requirePostRequest();
$assetId = Craft::$app->getRequest()->getRequiredBodyParam('assetId');
$asset = Asset::find()->id($assetId)->one();
if (!$asset) {
return $this->asJson([
'success' => false
]);
}
/** @var Volume $volume */
$volume = $asset->getVolume();
$user = Craft::$app->getUser()->getIdentity();
return $this->asJson([
'success' => (
$user->can('saveAssetInVolume:' . $volume->uid) &&
$user->can('deleteFilesAndFoldersInVolume:' . $volume->uid)
),
]);
} | php | public function actionCanEdit(): Response
{
$this->requireAcceptsJson();
$this->requirePostRequest();
$assetId = Craft::$app->getRequest()->getRequiredBodyParam('assetId');
$asset = Asset::find()->id($assetId)->one();
if (!$asset) {
return $this->asJson([
'success' => false
]);
}
/** @var Volume $volume */
$volume = $asset->getVolume();
$user = Craft::$app->getUser()->getIdentity();
return $this->asJson([
'success' => (
$user->can('saveAssetInVolume:' . $volume->uid) &&
$user->can('deleteFilesAndFoldersInVolume:' . $volume->uid)
),
]);
} | [
"public",
"function",
"actionCanEdit",
"(",
")",
":",
"Response",
"{",
"$",
"this",
"->",
"requireAcceptsJson",
"(",
")",
";",
"$",
"this",
"->",
"requirePostRequest",
"(",
")",
";",
"$",
"assetId",
"=",
"Craft",
"::",
"$",
"app",
"->",
"getRequest",
"("... | Check if user allowed to edit an Asset
@return Response
@throws \yii\base\InvalidConfigException
@throws \yii\web\BadRequestHttpException | [
"Check",
"if",
"user",
"allowed",
"to",
"edit",
"an",
"Asset"
] | 55ee76494f6332ba5709003d2082e51d56ae8b1a | https://github.com/craftcms/redactor/blob/55ee76494f6332ba5709003d2082e51d56ae8b1a/src/controllers/DefaultController.php#L31-L55 | train |
craftcms/redactor | src/Field.php | Field.registerRedactorPlugin | public static function registerRedactorPlugin(string $plugin)
{
if (isset(self::$_registeredPlugins[$plugin])) {
return;
}
$paths = self::redactorPluginPaths();
foreach ($paths as $registeredPath) {
foreach (["{$registeredPath}/{$plugin}", $registeredPath] as $path) {
if (file_exists("{$path}/{$plugin}.js")) {
$view = Craft::$app->getView();
$baseUrl = Craft::$app->getAssetManager()->getPublishedUrl($path, true);
$view->registerJsFile("{$baseUrl}/{$plugin}.js", [
'depends' => RedactorAsset::class
]);
// CSS file too?
if (file_exists("{$path}/{$plugin}.css")) {
$view->registerCssFile("{$baseUrl}/{$plugin}.css");
}
// Don't do this twice
self::$_registeredPlugins[$plugin] = true;
return;
}
}
}
throw new InvalidConfigException('Redactor plugin not found: '.$plugin);
} | php | public static function registerRedactorPlugin(string $plugin)
{
if (isset(self::$_registeredPlugins[$plugin])) {
return;
}
$paths = self::redactorPluginPaths();
foreach ($paths as $registeredPath) {
foreach (["{$registeredPath}/{$plugin}", $registeredPath] as $path) {
if (file_exists("{$path}/{$plugin}.js")) {
$view = Craft::$app->getView();
$baseUrl = Craft::$app->getAssetManager()->getPublishedUrl($path, true);
$view->registerJsFile("{$baseUrl}/{$plugin}.js", [
'depends' => RedactorAsset::class
]);
// CSS file too?
if (file_exists("{$path}/{$plugin}.css")) {
$view->registerCssFile("{$baseUrl}/{$plugin}.css");
}
// Don't do this twice
self::$_registeredPlugins[$plugin] = true;
return;
}
}
}
throw new InvalidConfigException('Redactor plugin not found: '.$plugin);
} | [
"public",
"static",
"function",
"registerRedactorPlugin",
"(",
"string",
"$",
"plugin",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"_registeredPlugins",
"[",
"$",
"plugin",
"]",
")",
")",
"{",
"return",
";",
"}",
"$",
"paths",
"=",
"self",
"... | Registers a Redactor plugin's JS & CSS files.
@param string $plugin
@return void
@throws InvalidConfigException if the plugin can't be found | [
"Registers",
"a",
"Redactor",
"plugin",
"s",
"JS",
"&",
"CSS",
"files",
"."
] | 55ee76494f6332ba5709003d2082e51d56ae8b1a | https://github.com/craftcms/redactor/blob/55ee76494f6332ba5709003d2082e51d56ae8b1a/src/Field.php#L189-L217 | train |
craftcms/redactor | src/Field.php | Field.redactorPluginPaths | public static function redactorPluginPaths(): array
{
if (self::$_pluginPaths !== null) {
return self::$_pluginPaths;
}
$event = new RegisterPluginPathsEvent([
'paths' => [
Craft::getAlias('@config/redactor/plugins'),
dirname(__DIR__).'/lib/redactor-plugins',
]
]);
Event::trigger(self::class, self::EVENT_REGISTER_PLUGIN_PATHS, $event);
return self::$_pluginPaths = $event->paths;
} | php | public static function redactorPluginPaths(): array
{
if (self::$_pluginPaths !== null) {
return self::$_pluginPaths;
}
$event = new RegisterPluginPathsEvent([
'paths' => [
Craft::getAlias('@config/redactor/plugins'),
dirname(__DIR__).'/lib/redactor-plugins',
]
]);
Event::trigger(self::class, self::EVENT_REGISTER_PLUGIN_PATHS, $event);
return self::$_pluginPaths = $event->paths;
} | [
"public",
"static",
"function",
"redactorPluginPaths",
"(",
")",
":",
"array",
"{",
"if",
"(",
"self",
"::",
"$",
"_pluginPaths",
"!==",
"null",
")",
"{",
"return",
"self",
"::",
"$",
"_pluginPaths",
";",
"}",
"$",
"event",
"=",
"new",
"RegisterPluginPaths... | Returns the registered Redactor plugin paths.
@return string[] | [
"Returns",
"the",
"registered",
"Redactor",
"plugin",
"paths",
"."
] | 55ee76494f6332ba5709003d2082e51d56ae8b1a | https://github.com/craftcms/redactor/blob/55ee76494f6332ba5709003d2082e51d56ae8b1a/src/Field.php#L224-L239 | train |
craftcms/redactor | src/Field.php | Field._getSectionSources | private function _getSectionSources(Element $element = null): array
{
$sources = [];
$sections = Craft::$app->getSections()->getAllSections();
$showSingles = false;
foreach ($sections as $section) {
if ($section->type === Section::TYPE_SINGLE) {
$showSingles = true;
} else if ($element) {
// Does the section have URLs in the same site as the element we're editing?
$sectionSiteSettings = $section->getSiteSettings();
if (isset($sectionSiteSettings[$element->siteId]) && $sectionSiteSettings[$element->siteId]->hasUrls) {
$sources[] = 'section:'.$section->uid;
}
}
}
if ($showSingles) {
array_unshift($sources, 'singles');
}
return $sources;
} | php | private function _getSectionSources(Element $element = null): array
{
$sources = [];
$sections = Craft::$app->getSections()->getAllSections();
$showSingles = false;
foreach ($sections as $section) {
if ($section->type === Section::TYPE_SINGLE) {
$showSingles = true;
} else if ($element) {
// Does the section have URLs in the same site as the element we're editing?
$sectionSiteSettings = $section->getSiteSettings();
if (isset($sectionSiteSettings[$element->siteId]) && $sectionSiteSettings[$element->siteId]->hasUrls) {
$sources[] = 'section:'.$section->uid;
}
}
}
if ($showSingles) {
array_unshift($sources, 'singles');
}
return $sources;
} | [
"private",
"function",
"_getSectionSources",
"(",
"Element",
"$",
"element",
"=",
"null",
")",
":",
"array",
"{",
"$",
"sources",
"=",
"[",
"]",
";",
"$",
"sections",
"=",
"Craft",
"::",
"$",
"app",
"->",
"getSections",
"(",
")",
"->",
"getAllSections",
... | Returns the available section sources.
@param Element|null $element The element the field is associated with, if there is one
@return array | [
"Returns",
"the",
"available",
"section",
"sources",
"."
] | 55ee76494f6332ba5709003d2082e51d56ae8b1a | https://github.com/craftcms/redactor/blob/55ee76494f6332ba5709003d2082e51d56ae8b1a/src/Field.php#L584-L607 | train |
craftcms/redactor | src/Field.php | Field._getCategorySources | private function _getCategorySources(Element $element = null): array
{
$sources = [];
if ($element) {
$categoryGroups = Craft::$app->getCategories()->getAllGroups();
foreach ($categoryGroups as $categoryGroup) {
// Does the category group have URLs in the same site as the element we're editing?
$categoryGroupSiteSettings = $categoryGroup->getSiteSettings();
if (isset($categoryGroupSiteSettings[$element->siteId]) && $categoryGroupSiteSettings[$element->siteId]->hasUrls) {
$sources[] = 'group:'.$categoryGroup->uid;
}
}
}
return $sources;
} | php | private function _getCategorySources(Element $element = null): array
{
$sources = [];
if ($element) {
$categoryGroups = Craft::$app->getCategories()->getAllGroups();
foreach ($categoryGroups as $categoryGroup) {
// Does the category group have URLs in the same site as the element we're editing?
$categoryGroupSiteSettings = $categoryGroup->getSiteSettings();
if (isset($categoryGroupSiteSettings[$element->siteId]) && $categoryGroupSiteSettings[$element->siteId]->hasUrls) {
$sources[] = 'group:'.$categoryGroup->uid;
}
}
}
return $sources;
} | [
"private",
"function",
"_getCategorySources",
"(",
"Element",
"$",
"element",
"=",
"null",
")",
":",
"array",
"{",
"$",
"sources",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"element",
")",
"{",
"$",
"categoryGroups",
"=",
"Craft",
"::",
"$",
"app",
"->",
"... | Returns the available category sources.
@param Element|null $element The element the field is associated with, if there is one
@return array | [
"Returns",
"the",
"available",
"category",
"sources",
"."
] | 55ee76494f6332ba5709003d2082e51d56ae8b1a | https://github.com/craftcms/redactor/blob/55ee76494f6332ba5709003d2082e51d56ae8b1a/src/Field.php#L615-L632 | train |
craftcms/redactor | src/Field.php | Field._getVolumeKeys | private function _getVolumeKeys(): array
{
if (!$this->availableVolumes) {
return [];
}
$criteria = ['parentId' => ':empty:'];
if ($this->availableVolumes !== '*') {
$criteria['volumeId'] = Db::idsByUids('{{%volumes}}', $this->availableVolumes);
}
$folders = Craft::$app->getAssets()->findFolders($criteria);
// Sort volumes in the same order as they are sorted in the CP
$sortedVolumeIds = Craft::$app->getVolumes()->getAllVolumeIds();
$sortedVolumeIds = array_flip($sortedVolumeIds);
$volumeKeys = [];
usort($folders, function($a, $b) use ($sortedVolumeIds) {
// In case Temporary volumes ever make an appearance in RTF modals, sort them to the end of the list.
$aOrder = $sortedVolumeIds[$a->volumeId] ?? PHP_INT_MAX;
$bOrder = $sortedVolumeIds[$b->volumeId] ?? PHP_INT_MAX;
return $aOrder - $bOrder;
});
foreach ($folders as $folder) {
$volumeKeys[] = 'folder:'.$folder->uid;
}
return $volumeKeys;
} | php | private function _getVolumeKeys(): array
{
if (!$this->availableVolumes) {
return [];
}
$criteria = ['parentId' => ':empty:'];
if ($this->availableVolumes !== '*') {
$criteria['volumeId'] = Db::idsByUids('{{%volumes}}', $this->availableVolumes);
}
$folders = Craft::$app->getAssets()->findFolders($criteria);
// Sort volumes in the same order as they are sorted in the CP
$sortedVolumeIds = Craft::$app->getVolumes()->getAllVolumeIds();
$sortedVolumeIds = array_flip($sortedVolumeIds);
$volumeKeys = [];
usort($folders, function($a, $b) use ($sortedVolumeIds) {
// In case Temporary volumes ever make an appearance in RTF modals, sort them to the end of the list.
$aOrder = $sortedVolumeIds[$a->volumeId] ?? PHP_INT_MAX;
$bOrder = $sortedVolumeIds[$b->volumeId] ?? PHP_INT_MAX;
return $aOrder - $bOrder;
});
foreach ($folders as $folder) {
$volumeKeys[] = 'folder:'.$folder->uid;
}
return $volumeKeys;
} | [
"private",
"function",
"_getVolumeKeys",
"(",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"availableVolumes",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"criteria",
"=",
"[",
"'parentId'",
"=>",
"':empty:'",
"]",
";",
"if",
"(",
"$",... | Returns the available volumes.
@return string[] | [
"Returns",
"the",
"available",
"volumes",
"."
] | 55ee76494f6332ba5709003d2082e51d56ae8b1a | https://github.com/craftcms/redactor/blob/55ee76494f6332ba5709003d2082e51d56ae8b1a/src/Field.php#L639-L672 | train |
craftcms/redactor | src/Field.php | Field._getTransforms | private function _getTransforms(): array
{
if (!$this->availableTransforms) {
return [];
}
$allTransforms = Craft::$app->getAssetTransforms()->getAllTransforms();
$transformList = [];
foreach ($allTransforms as $transform) {
if (!is_array($this->availableTransforms) || in_array($transform->uid, $this->availableTransforms, false)) {
$transformList[] = [
'handle' => Html::encode($transform->handle),
'name' => Html::encode($transform->name)
];
}
}
return $transformList;
} | php | private function _getTransforms(): array
{
if (!$this->availableTransforms) {
return [];
}
$allTransforms = Craft::$app->getAssetTransforms()->getAllTransforms();
$transformList = [];
foreach ($allTransforms as $transform) {
if (!is_array($this->availableTransforms) || in_array($transform->uid, $this->availableTransforms, false)) {
$transformList[] = [
'handle' => Html::encode($transform->handle),
'name' => Html::encode($transform->name)
];
}
}
return $transformList;
} | [
"private",
"function",
"_getTransforms",
"(",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"availableTransforms",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"allTransforms",
"=",
"Craft",
"::",
"$",
"app",
"->",
"getAssetTransforms",
"(",... | Get available transforms.
@return array | [
"Get",
"available",
"transforms",
"."
] | 55ee76494f6332ba5709003d2082e51d56ae8b1a | https://github.com/craftcms/redactor/blob/55ee76494f6332ba5709003d2082e51d56ae8b1a/src/Field.php#L679-L698 | train |
craftcms/redactor | src/Field.php | Field._getCustomConfigOptions | private function _getCustomConfigOptions(string $dir): array
{
$options = ['' => Craft::t('redactor', 'Default')];
$path = Craft::$app->getPath()->getConfigPath().DIRECTORY_SEPARATOR.$dir;
if (is_dir($path)) {
$files = FileHelper::findFiles($path, [
'only' => ['*.json'],
'recursive' => false
]);
foreach ($files as $file) {
$options[pathinfo($file, PATHINFO_BASENAME)] = pathinfo($file, PATHINFO_FILENAME);
}
}
return $options;
} | php | private function _getCustomConfigOptions(string $dir): array
{
$options = ['' => Craft::t('redactor', 'Default')];
$path = Craft::$app->getPath()->getConfigPath().DIRECTORY_SEPARATOR.$dir;
if (is_dir($path)) {
$files = FileHelper::findFiles($path, [
'only' => ['*.json'],
'recursive' => false
]);
foreach ($files as $file) {
$options[pathinfo($file, PATHINFO_BASENAME)] = pathinfo($file, PATHINFO_FILENAME);
}
}
return $options;
} | [
"private",
"function",
"_getCustomConfigOptions",
"(",
"string",
"$",
"dir",
")",
":",
"array",
"{",
"$",
"options",
"=",
"[",
"''",
"=>",
"Craft",
"::",
"t",
"(",
"'redactor'",
",",
"'Default'",
")",
"]",
";",
"$",
"path",
"=",
"Craft",
"::",
"$",
"... | Returns the available Redactor config options.
@param string $dir The directory name within the config/ folder to look for config files
@return array | [
"Returns",
"the",
"available",
"Redactor",
"config",
"options",
"."
] | 55ee76494f6332ba5709003d2082e51d56ae8b1a | https://github.com/craftcms/redactor/blob/55ee76494f6332ba5709003d2082e51d56ae8b1a/src/Field.php#L706-L723 | train |
craftcms/redactor | src/Field.php | Field._getConfig | private function _getConfig(string $dir, string $file = null)
{
if (!$file) {
return false;
}
$path = Craft::$app->getPath()->getConfigPath().DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.$file;
if (!is_file($path)) {
return false;
}
return Json::decode(file_get_contents($path));
} | php | private function _getConfig(string $dir, string $file = null)
{
if (!$file) {
return false;
}
$path = Craft::$app->getPath()->getConfigPath().DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.$file;
if (!is_file($path)) {
return false;
}
return Json::decode(file_get_contents($path));
} | [
"private",
"function",
"_getConfig",
"(",
"string",
"$",
"dir",
",",
"string",
"$",
"file",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"file",
")",
"{",
"return",
"false",
";",
"}",
"$",
"path",
"=",
"Craft",
"::",
"$",
"app",
"->",
"getPath",
"... | Returns a JSON-decoded config, if it exists.
@param string $dir The directory name within the config/ folder to look for the config file
@param string|null $file The filename to load
@return array|false The config, or false if the file doesn't exist | [
"Returns",
"a",
"JSON",
"-",
"decoded",
"config",
"if",
"it",
"exists",
"."
] | 55ee76494f6332ba5709003d2082e51d56ae8b1a | https://github.com/craftcms/redactor/blob/55ee76494f6332ba5709003d2082e51d56ae8b1a/src/Field.php#L732-L745 | train |
craftcms/redactor | src/Field.php | Field._allowedStyles | private function _allowedStyles(): array
{
$styles = [];
$plugins = array_flip($this->_getRedactorConfig()['plugins'] ?? []);
if (isset($plugins['alignment'])) {
$styles['text-align'] = true;
}
if (isset($plugins['fontcolor'])) {
$styles['color'] = true;
}
if (isset($plugins['fontfamily'])) {
$styles['font-family'] = true;
}
if (isset($plugins['fontsize'])) {
$styles['font-size'] = true;
}
return $styles;
} | php | private function _allowedStyles(): array
{
$styles = [];
$plugins = array_flip($this->_getRedactorConfig()['plugins'] ?? []);
if (isset($plugins['alignment'])) {
$styles['text-align'] = true;
}
if (isset($plugins['fontcolor'])) {
$styles['color'] = true;
}
if (isset($plugins['fontfamily'])) {
$styles['font-family'] = true;
}
if (isset($plugins['fontsize'])) {
$styles['font-size'] = true;
}
return $styles;
} | [
"private",
"function",
"_allowedStyles",
"(",
")",
":",
"array",
"{",
"$",
"styles",
"=",
"[",
"]",
";",
"$",
"plugins",
"=",
"array_flip",
"(",
"$",
"this",
"->",
"_getRedactorConfig",
"(",
")",
"[",
"'plugins'",
"]",
"??",
"[",
"]",
")",
";",
"if",... | Returns the allowed inline CSS styles, based on the plugins that are enabled.
@return string[] | [
"Returns",
"the",
"allowed",
"inline",
"CSS",
"styles",
"based",
"on",
"the",
"plugins",
"that",
"are",
"enabled",
"."
] | 55ee76494f6332ba5709003d2082e51d56ae8b1a | https://github.com/craftcms/redactor/blob/55ee76494f6332ba5709003d2082e51d56ae8b1a/src/Field.php#L781-L798 | train |
craftcms/redactor | src/FieldData.php | FieldData.getPages | public function getPages(): array
{
if ($this->_pages !== null) {
return $this->_pages;
}
$this->_pages = [];
$pages = explode('<!--pagebreak-->', (string)$this);
foreach ($pages as $page) {
$this->_pages[] = new \Twig_Markup($page, Craft::$app->charset);
}
return $this->_pages;
} | php | public function getPages(): array
{
if ($this->_pages !== null) {
return $this->_pages;
}
$this->_pages = [];
$pages = explode('<!--pagebreak-->', (string)$this);
foreach ($pages as $page) {
$this->_pages[] = new \Twig_Markup($page, Craft::$app->charset);
}
return $this->_pages;
} | [
"public",
"function",
"getPages",
"(",
")",
":",
"array",
"{",
"if",
"(",
"$",
"this",
"->",
"_pages",
"!==",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"_pages",
";",
"}",
"$",
"this",
"->",
"_pages",
"=",
"[",
"]",
";",
"$",
"pages",
"=",
... | Returns an array of the individual page contents.
@return \Twig_Markup[] | [
"Returns",
"an",
"array",
"of",
"the",
"individual",
"page",
"contents",
"."
] | 55ee76494f6332ba5709003d2082e51d56ae8b1a | https://github.com/craftcms/redactor/blob/55ee76494f6332ba5709003d2082e51d56ae8b1a/src/FieldData.php#L77-L91 | train |
craftcms/redactor | src/FieldData.php | FieldData.getPage | public function getPage(int $pageNumber)
{
$pages = $this->getPages();
if (isset($pages[$pageNumber - 1])) {
return $pages[$pageNumber - 1];
}
return null;
} | php | public function getPage(int $pageNumber)
{
$pages = $this->getPages();
if (isset($pages[$pageNumber - 1])) {
return $pages[$pageNumber - 1];
}
return null;
} | [
"public",
"function",
"getPage",
"(",
"int",
"$",
"pageNumber",
")",
"{",
"$",
"pages",
"=",
"$",
"this",
"->",
"getPages",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"pages",
"[",
"$",
"pageNumber",
"-",
"1",
"]",
")",
")",
"{",
"return",
"$",... | Returns a specific page.
@param int $pageNumber
@return string|null | [
"Returns",
"a",
"specific",
"page",
"."
] | 55ee76494f6332ba5709003d2082e51d56ae8b1a | https://github.com/craftcms/redactor/blob/55ee76494f6332ba5709003d2082e51d56ae8b1a/src/FieldData.php#L99-L108 | train |
nao-pon/flysystem-google-drive | example/GoogleUpload.php | GoogleUpload.create_folder | protected function create_folder()
{
$fileMetadata = new \Google_Service_Drive_DriveFile([
'name' => 'google_drive_folder_name',
'mimeType' => 'application/vnd.google-apps.folder',
]);
$folder = $this->service->files->create($fileMetadata, ['fields' => 'id']);
return $folder->id;
} | php | protected function create_folder()
{
$fileMetadata = new \Google_Service_Drive_DriveFile([
'name' => 'google_drive_folder_name',
'mimeType' => 'application/vnd.google-apps.folder',
]);
$folder = $this->service->files->create($fileMetadata, ['fields' => 'id']);
return $folder->id;
} | [
"protected",
"function",
"create_folder",
"(",
")",
"{",
"$",
"fileMetadata",
"=",
"new",
"\\",
"Google_Service_Drive_DriveFile",
"(",
"[",
"'name'",
"=>",
"'google_drive_folder_name'",
",",
"'mimeType'",
"=>",
"'application/vnd.google-apps.folder'",
",",
"]",
")",
";... | create folder in google drive.
@return [type] [description] | [
"create",
"folder",
"in",
"google",
"drive",
"."
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/example/GoogleUpload.php#L44-L54 | train |
nao-pon/flysystem-google-drive | example/GoogleUpload.php | GoogleUpload.remove_duplicated | protected function remove_duplicated($file)
{
$response = $this->service->files->listFiles([
'q' => "'$this->folder_id' in parents and name contains '$file' and trashed=false",
]);
foreach ($response->files as $found) {
return $this->service->files->delete($found->id);
}
} | php | protected function remove_duplicated($file)
{
$response = $this->service->files->listFiles([
'q' => "'$this->folder_id' in parents and name contains '$file' and trashed=false",
]);
foreach ($response->files as $found) {
return $this->service->files->delete($found->id);
}
} | [
"protected",
"function",
"remove_duplicated",
"(",
"$",
"file",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"service",
"->",
"files",
"->",
"listFiles",
"(",
"[",
"'q'",
"=>",
"\"'$this->folder_id' in parents and name contains '$file' and trashed=false\"",
",",... | remove duplicated files before adding new ones
again thats because google use 'id' not 'name'.
note that we cant search for files as bulk "a limitation in the drive Api it self"
so instead we call this method from a loop with all the files we want to remove
also note the some of the api methods are from the v2 even if we are using v3 in this example
google docs are often mis-guiding
https://developers.google.com/drive/v2/reference/
https://developers.google.com/drive/v3/web/search-parameters
@return [type] [description] | [
"remove",
"duplicated",
"files",
"before",
"adding",
"new",
"ones",
"again",
"thats",
"because",
"google",
"use",
"id",
"not",
"name",
"."
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/example/GoogleUpload.php#L70-L79 | train |
nao-pon/flysystem-google-drive | example/GoogleUpload.php | GoogleUpload.upload_files | public function upload_files()
{
$adapter = new GoogleDriveAdapter($this->service, Cache::get('folder_id'));
$filesystem = new Filesystem($adapter);
// here we are uploading files from local storage
// we first get all the files
$files = Storage::files();
// loop over the found files
foreach ($files as $file) {
// remove file from google drive in case we have something under the same name
// comment out if its okay to have files under the same name
$this->remove_duplicated($file);
// read the file content
$read = Storage::get($file);
// save to google drive
$filesystem->write($file, $read);
// remove the local file
Storage::delete($file);
}
} | php | public function upload_files()
{
$adapter = new GoogleDriveAdapter($this->service, Cache::get('folder_id'));
$filesystem = new Filesystem($adapter);
// here we are uploading files from local storage
// we first get all the files
$files = Storage::files();
// loop over the found files
foreach ($files as $file) {
// remove file from google drive in case we have something under the same name
// comment out if its okay to have files under the same name
$this->remove_duplicated($file);
// read the file content
$read = Storage::get($file);
// save to google drive
$filesystem->write($file, $read);
// remove the local file
Storage::delete($file);
}
} | [
"public",
"function",
"upload_files",
"(",
")",
"{",
"$",
"adapter",
"=",
"new",
"GoogleDriveAdapter",
"(",
"$",
"this",
"->",
"service",
",",
"Cache",
"::",
"get",
"(",
"'folder_id'",
")",
")",
";",
"$",
"filesystem",
"=",
"new",
"Filesystem",
"(",
"$",... | this is the only method u need to call from ur controller.
@param [type] $new_name [description]
@return [type] [description] | [
"this",
"is",
"the",
"only",
"method",
"u",
"need",
"to",
"call",
"from",
"ur",
"controller",
"."
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/example/GoogleUpload.php#L88-L110 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.getUrl | public function getUrl($path)
{
if ($this->publish($path)) {
$obj = $this->getFileObject($path);
if ($url = $obj->getWebContentLink()) {
return str_replace('export=download', 'export=media', $url);
}
if ($url = $obj->getWebViewLink()) {
return $url;
}
}
return false;
} | php | public function getUrl($path)
{
if ($this->publish($path)) {
$obj = $this->getFileObject($path);
if ($url = $obj->getWebContentLink()) {
return str_replace('export=download', 'export=media', $url);
}
if ($url = $obj->getWebViewLink()) {
return $url;
}
}
return false;
} | [
"public",
"function",
"getUrl",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"publish",
"(",
"$",
"path",
")",
")",
"{",
"$",
"obj",
"=",
"$",
"this",
"->",
"getFileObject",
"(",
"$",
"path",
")",
";",
"if",
"(",
"$",
"url",
"=",
... | Get contents parmanent URL
@param string $path
itemId path
@return string|false | [
"Get",
"contents",
"parmanent",
"URL"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L669-L681 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.hasDir | public function hasDir($path)
{
$meta = $this->getMetadata($path);
return ($meta && isset($meta['hasdir'])) ? $meta : [
'hasdir' => true
];
} | php | public function hasDir($path)
{
$meta = $this->getMetadata($path);
return ($meta && isset($meta['hasdir'])) ? $meta : [
'hasdir' => true
];
} | [
"public",
"function",
"hasDir",
"(",
"$",
"path",
")",
"{",
"$",
"meta",
"=",
"$",
"this",
"->",
"getMetadata",
"(",
"$",
"path",
")",
";",
"return",
"(",
"$",
"meta",
"&&",
"isset",
"(",
"$",
"meta",
"[",
"'hasdir'",
"]",
")",
")",
"?",
"$",
"... | Has child directory
@param string $path
itemId path
@return array | [
"Has",
"child",
"directory"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L691-L697 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.setHasDir | protected function setHasDir($targets, $object)
{
$service = $this->service;
$client = $service->getClient();
$gFiles = $service->files;
$opts = [
'pageSize' => 1
];
$paths = [];
$client->setUseBatch(true);
$batch = $service->createBatch();
$i = 0;
foreach ($targets as $id) {
$opts['q'] = sprintf('trashed = false and "%s" in parents and mimeType = "%s"', $id, self::DIRMIME);
$request = $gFiles->listFiles($this->applyDefaultParams($opts, 'files.list'));
$key = ++ $i;
$batch->add($request, (string) $key);
$paths['response-' . $key] = $id;
}
$results = $batch->execute();
foreach ($results as $key => $result) {
if ($result instanceof Google_Service_Drive_FileList) {
$object[$paths[$key]]['hasdir'] = $this->cacheHasDirs[$paths[$key]] = (bool) $result->getFiles();
}
}
$client->setUseBatch(false);
return $object;
} | php | protected function setHasDir($targets, $object)
{
$service = $this->service;
$client = $service->getClient();
$gFiles = $service->files;
$opts = [
'pageSize' => 1
];
$paths = [];
$client->setUseBatch(true);
$batch = $service->createBatch();
$i = 0;
foreach ($targets as $id) {
$opts['q'] = sprintf('trashed = false and "%s" in parents and mimeType = "%s"', $id, self::DIRMIME);
$request = $gFiles->listFiles($this->applyDefaultParams($opts, 'files.list'));
$key = ++ $i;
$batch->add($request, (string) $key);
$paths['response-' . $key] = $id;
}
$results = $batch->execute();
foreach ($results as $key => $result) {
if ($result instanceof Google_Service_Drive_FileList) {
$object[$paths[$key]]['hasdir'] = $this->cacheHasDirs[$paths[$key]] = (bool) $result->getFiles();
}
}
$client->setUseBatch(false);
return $object;
} | [
"protected",
"function",
"setHasDir",
"(",
"$",
"targets",
",",
"$",
"object",
")",
"{",
"$",
"service",
"=",
"$",
"this",
"->",
"service",
";",
"$",
"client",
"=",
"$",
"service",
"->",
"getClient",
"(",
")",
";",
"$",
"gFiles",
"=",
"$",
"service",... | Do cache cacheHasDirs with batch request
@param array $targets
[[path => id],...]
@return void | [
"Do",
"cache",
"cacheHasDirs",
"with",
"batch",
"request"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L707-L734 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.getRawVisibility | protected function getRawVisibility($path)
{
$file = $this->getFileObject($path);
$permissions = $file->getPermissions();
$visibility = AdapterInterface::VISIBILITY_PRIVATE;
foreach ($permissions as $permission) {
if ($permission->type === $this->publishPermission['type'] && $permission->role === $this->publishPermission['role']) {
$visibility = AdapterInterface::VISIBILITY_PUBLIC;
break;
}
}
return $visibility;
} | php | protected function getRawVisibility($path)
{
$file = $this->getFileObject($path);
$permissions = $file->getPermissions();
$visibility = AdapterInterface::VISIBILITY_PRIVATE;
foreach ($permissions as $permission) {
if ($permission->type === $this->publishPermission['type'] && $permission->role === $this->publishPermission['role']) {
$visibility = AdapterInterface::VISIBILITY_PUBLIC;
break;
}
}
return $visibility;
} | [
"protected",
"function",
"getRawVisibility",
"(",
"$",
"path",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"getFileObject",
"(",
"$",
"path",
")",
";",
"$",
"permissions",
"=",
"$",
"file",
"->",
"getPermissions",
"(",
")",
";",
"$",
"visibility",
"... | Get the object permissions presented as a visibility.
@param string $path
itemId path
@return string | [
"Get",
"the",
"object",
"permissions",
"presented",
"as",
"a",
"visibility",
"."
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L744-L756 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.publish | protected function publish($path)
{
if (($file = $this->getFileObject($path))) {
if ($this->getRawVisibility($path) === AdapterInterface::VISIBILITY_PUBLIC) {
return true;
}
try {
$permission = new Google_Service_Drive_Permission($this->publishPermission);
if ($this->service->permissions->create($file->getId(), $permission)) {
return true;
}
} catch (Exception $e) {
return false;
}
}
return false;
} | php | protected function publish($path)
{
if (($file = $this->getFileObject($path))) {
if ($this->getRawVisibility($path) === AdapterInterface::VISIBILITY_PUBLIC) {
return true;
}
try {
$permission = new Google_Service_Drive_Permission($this->publishPermission);
if ($this->service->permissions->create($file->getId(), $permission)) {
return true;
}
} catch (Exception $e) {
return false;
}
}
return false;
} | [
"protected",
"function",
"publish",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"(",
"$",
"file",
"=",
"$",
"this",
"->",
"getFileObject",
"(",
"$",
"path",
")",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getRawVisibility",
"(",
"$",
"path",
")",
"... | Publish specified path item
@param string $path
itemId path
@return bool | [
"Publish",
"specified",
"path",
"item"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L766-L783 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.unPublish | protected function unPublish($path)
{
if (($file = $this->getFileObject($path))) {
$permissions = $file->getPermissions();
try {
foreach ($permissions as $permission) {
if ($permission->type === 'anyone' && $permission->role === 'reader') {
$this->service->permissions->delete($file->getId(), $permission->getId());
}
}
return true;
} catch (Exception $e) {
return false;
}
}
return false;
} | php | protected function unPublish($path)
{
if (($file = $this->getFileObject($path))) {
$permissions = $file->getPermissions();
try {
foreach ($permissions as $permission) {
if ($permission->type === 'anyone' && $permission->role === 'reader') {
$this->service->permissions->delete($file->getId(), $permission->getId());
}
}
return true;
} catch (Exception $e) {
return false;
}
}
return false;
} | [
"protected",
"function",
"unPublish",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"(",
"$",
"file",
"=",
"$",
"this",
"->",
"getFileObject",
"(",
"$",
"path",
")",
")",
")",
"{",
"$",
"permissions",
"=",
"$",
"file",
"->",
"getPermissions",
"(",
")",
";... | Un-publish specified path item
@param string $path
itemId path
@return bool | [
"Un",
"-",
"publish",
"specified",
"path",
"item"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L793-L810 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.splitPath | protected function splitPath($path, $getParentId = true)
{
if ($path === '' || $path === '/') {
$fileName = $this->root;
$dirName = '';
} else {
$paths = explode('/', $path);
$fileName = array_pop($paths);
if ($getParentId) {
$dirName = $paths ? array_pop($paths) : '';
} else {
$dirName = join('/', $paths);
}
if ($dirName === '') {
$dirName = $this->root;
}
}
return [
$dirName,
$fileName
];
} | php | protected function splitPath($path, $getParentId = true)
{
if ($path === '' || $path === '/') {
$fileName = $this->root;
$dirName = '';
} else {
$paths = explode('/', $path);
$fileName = array_pop($paths);
if ($getParentId) {
$dirName = $paths ? array_pop($paths) : '';
} else {
$dirName = join('/', $paths);
}
if ($dirName === '') {
$dirName = $this->root;
}
}
return [
$dirName,
$fileName
];
} | [
"protected",
"function",
"splitPath",
"(",
"$",
"path",
",",
"$",
"getParentId",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"path",
"===",
"''",
"||",
"$",
"path",
"===",
"'/'",
")",
"{",
"$",
"fileName",
"=",
"$",
"this",
"->",
"root",
";",
"$",
"di... | Path splits to dirId, fileId or newName
@param string $path
@return array [ $dirId , $fileId|newName ] | [
"Path",
"splits",
"to",
"dirId",
"fileId",
"or",
"newName"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L819-L840 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.normaliseObject | protected function normaliseObject(Google_Service_Drive_DriveFile $object, $dirname)
{
$id = $object->getId();
$path_parts = $this->splitFileExtension($object->getName());
$result = ['name' => $object->getName()];
$result['type'] = $object->mimeType === self::DIRMIME ? 'dir' : 'file';
$result['path'] = ($dirname ? ($dirname . '/') : '') . $id;
$result['filename'] = $path_parts['filename'];
$result['extension'] = $path_parts['extension'];
$result['timestamp'] = strtotime($object->getModifiedTime());
if ($result['type'] === 'file') {
$result['mimetype'] = $object->mimeType;
$result['size'] = (int) $object->getSize();
}
if ($result['type'] === 'dir') {
$result['size'] = 0;
if ($this->useHasDir) {
$result['hasdir'] = isset($this->cacheHasDirs[$id]) ? $this->cacheHasDirs[$id] : false;
}
}
// attach additional fields
if ($this->additionalFields) {
foreach($this->additionalFields as $field) {
if (property_exists($object, $field)) {
$result[$field] = $object->$field;
}
}
}
return $result;
} | php | protected function normaliseObject(Google_Service_Drive_DriveFile $object, $dirname)
{
$id = $object->getId();
$path_parts = $this->splitFileExtension($object->getName());
$result = ['name' => $object->getName()];
$result['type'] = $object->mimeType === self::DIRMIME ? 'dir' : 'file';
$result['path'] = ($dirname ? ($dirname . '/') : '') . $id;
$result['filename'] = $path_parts['filename'];
$result['extension'] = $path_parts['extension'];
$result['timestamp'] = strtotime($object->getModifiedTime());
if ($result['type'] === 'file') {
$result['mimetype'] = $object->mimeType;
$result['size'] = (int) $object->getSize();
}
if ($result['type'] === 'dir') {
$result['size'] = 0;
if ($this->useHasDir) {
$result['hasdir'] = isset($this->cacheHasDirs[$id]) ? $this->cacheHasDirs[$id] : false;
}
}
// attach additional fields
if ($this->additionalFields) {
foreach($this->additionalFields as $field) {
if (property_exists($object, $field)) {
$result[$field] = $object->$field;
}
}
}
return $result;
} | [
"protected",
"function",
"normaliseObject",
"(",
"Google_Service_Drive_DriveFile",
"$",
"object",
",",
"$",
"dirname",
")",
"{",
"$",
"id",
"=",
"$",
"object",
"->",
"getId",
"(",
")",
";",
"$",
"path_parts",
"=",
"$",
"this",
"->",
"splitFileExtension",
"("... | Get normalised files array from Google_Service_Drive_DriveFile
@param Google_Service_Drive_DriveFile $object
@param String $dirname
Parent directory itemId path
@return array Normalised files array | [
"Get",
"normalised",
"files",
"array",
"from",
"Google_Service_Drive_DriveFile"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L870-L899 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.getItems | protected function getItems($dirname, $recursive = false, $maxResults = 0, $query = '')
{
list (, $itemId) = $this->splitPath($dirname);
$maxResults = min($maxResults, 1000);
$results = [];
$parameters = [
'pageSize' => $maxResults ?: 1000,
'fields' => $this->fetchfieldsList,
'spaces' => $this->spaces,
'q' => sprintf('trashed = false and "%s" in parents', $itemId)
];
if ($query) {
$parameters['q'] .= ' and (' . $query . ')';
}
$parameters = $this->applyDefaultParams($parameters, 'files.list');
$pageToken = NULL;
$gFiles = $this->service->files;
$this->cacheHasDirs[$itemId] = false;
$setHasDir = [];
do {
try {
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$fileObjs = $gFiles->listFiles($parameters);
if ($fileObjs instanceof Google_Service_Drive_FileList) {
foreach ($fileObjs as $obj) {
$id = $obj->getId();
$this->cacheFileObjects[$id] = $obj;
$result = $this->normaliseObject($obj, $dirname);
$results[$id] = $result;
if ($result['type'] === 'dir') {
if ($this->useHasDir) {
$setHasDir[$id] = $id;
}
if ($this->cacheHasDirs[$itemId] === false) {
$this->cacheHasDirs[$itemId] = true;
unset($setHasDir[$itemId]);
}
if ($recursive) {
$results = array_merge($results, $this->getItems($result['path'], true, $maxResults, $query));
}
}
}
$pageToken = $fileObjs->getNextPageToken();
} else {
$pageToken = NULL;
}
} catch (Exception $e) {
$pageToken = NULL;
}
} while ($pageToken && $maxResults === 0);
if ($setHasDir) {
$results = $this->setHasDir($setHasDir, $results);
}
return array_values($results);
} | php | protected function getItems($dirname, $recursive = false, $maxResults = 0, $query = '')
{
list (, $itemId) = $this->splitPath($dirname);
$maxResults = min($maxResults, 1000);
$results = [];
$parameters = [
'pageSize' => $maxResults ?: 1000,
'fields' => $this->fetchfieldsList,
'spaces' => $this->spaces,
'q' => sprintf('trashed = false and "%s" in parents', $itemId)
];
if ($query) {
$parameters['q'] .= ' and (' . $query . ')';
}
$parameters = $this->applyDefaultParams($parameters, 'files.list');
$pageToken = NULL;
$gFiles = $this->service->files;
$this->cacheHasDirs[$itemId] = false;
$setHasDir = [];
do {
try {
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$fileObjs = $gFiles->listFiles($parameters);
if ($fileObjs instanceof Google_Service_Drive_FileList) {
foreach ($fileObjs as $obj) {
$id = $obj->getId();
$this->cacheFileObjects[$id] = $obj;
$result = $this->normaliseObject($obj, $dirname);
$results[$id] = $result;
if ($result['type'] === 'dir') {
if ($this->useHasDir) {
$setHasDir[$id] = $id;
}
if ($this->cacheHasDirs[$itemId] === false) {
$this->cacheHasDirs[$itemId] = true;
unset($setHasDir[$itemId]);
}
if ($recursive) {
$results = array_merge($results, $this->getItems($result['path'], true, $maxResults, $query));
}
}
}
$pageToken = $fileObjs->getNextPageToken();
} else {
$pageToken = NULL;
}
} catch (Exception $e) {
$pageToken = NULL;
}
} while ($pageToken && $maxResults === 0);
if ($setHasDir) {
$results = $this->setHasDir($setHasDir, $results);
}
return array_values($results);
} | [
"protected",
"function",
"getItems",
"(",
"$",
"dirname",
",",
"$",
"recursive",
"=",
"false",
",",
"$",
"maxResults",
"=",
"0",
",",
"$",
"query",
"=",
"''",
")",
"{",
"list",
"(",
",",
"$",
"itemId",
")",
"=",
"$",
"this",
"->",
"splitPath",
"(",... | Get items array of target dirctory
@param string $dirname
itemId path
@param bool $recursive
@param number $maxResults
@param string $query
@return array Items array | [
"Get",
"items",
"array",
"of",
"target",
"dirctory"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L912-L971 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.getFileObject | protected function getFileObject($path, $checkDir = false)
{
list ($parentId, $itemId) = $this->splitPath($path, true);
if (isset($this->cacheFileObjects[$itemId])) {
return $this->cacheFileObjects[$itemId];
} else if (isset($this->cacheFileObjectsByName[$parentId . '/' . $itemId])) {
return $this->cacheFileObjectsByName[$parentId . '/' . $itemId];
}
$service = $this->service;
$client = $service->getClient();
$client->setUseBatch(true);
$batch = $service->createBatch();
$opts = [
'fields' => $this->fetchfieldsGet
];
$batch->add($this->service->files->get($itemId, $this->applyDefaultParams($opts, 'files.get')), 'obj');
if ($checkDir && $this->useHasDir) {
$batch->add($service->files->listFiles($this->applyDefaultParams([
'pageSize' => 1,
'q' => sprintf('trashed = false and "%s" in parents and mimeType = "%s"', $itemId, self::DIRMIME)
], 'files.list')), 'hasdir');
}
$results = array_values($batch->execute());
list ($fileObj, $hasdir) = array_pad($results, 2, null);
$client->setUseBatch(false);
if ($fileObj instanceof Google_Service_Drive_DriveFile) {
if ($hasdir && $fileObj->mimeType === self::DIRMIME) {
if ($hasdir instanceof Google_Service_Drive_FileList) {
$this->cacheHasDirs[$fileObj->getId()] = (bool) $hasdir->getFiles();
}
}
} else {
$fileObj = NULL;
}
$this->cacheFileObjects[$itemId] = $fileObj;
return $fileObj;
} | php | protected function getFileObject($path, $checkDir = false)
{
list ($parentId, $itemId) = $this->splitPath($path, true);
if (isset($this->cacheFileObjects[$itemId])) {
return $this->cacheFileObjects[$itemId];
} else if (isset($this->cacheFileObjectsByName[$parentId . '/' . $itemId])) {
return $this->cacheFileObjectsByName[$parentId . '/' . $itemId];
}
$service = $this->service;
$client = $service->getClient();
$client->setUseBatch(true);
$batch = $service->createBatch();
$opts = [
'fields' => $this->fetchfieldsGet
];
$batch->add($this->service->files->get($itemId, $this->applyDefaultParams($opts, 'files.get')), 'obj');
if ($checkDir && $this->useHasDir) {
$batch->add($service->files->listFiles($this->applyDefaultParams([
'pageSize' => 1,
'q' => sprintf('trashed = false and "%s" in parents and mimeType = "%s"', $itemId, self::DIRMIME)
], 'files.list')), 'hasdir');
}
$results = array_values($batch->execute());
list ($fileObj, $hasdir) = array_pad($results, 2, null);
$client->setUseBatch(false);
if ($fileObj instanceof Google_Service_Drive_DriveFile) {
if ($hasdir && $fileObj->mimeType === self::DIRMIME) {
if ($hasdir instanceof Google_Service_Drive_FileList) {
$this->cacheHasDirs[$fileObj->getId()] = (bool) $hasdir->getFiles();
}
}
} else {
$fileObj = NULL;
}
$this->cacheFileObjects[$itemId] = $fileObj;
return $fileObj;
} | [
"protected",
"function",
"getFileObject",
"(",
"$",
"path",
",",
"$",
"checkDir",
"=",
"false",
")",
"{",
"list",
"(",
"$",
"parentId",
",",
"$",
"itemId",
")",
"=",
"$",
"this",
"->",
"splitPath",
"(",
"$",
"path",
",",
"true",
")",
";",
"if",
"("... | Get file oblect Google_Service_Drive_DriveFile
@param string $path
itemId path
@param string $checkDir
do check hasdir
@return Google_Service_Drive_DriveFile|null | [
"Get",
"file",
"oblect",
"Google_Service_Drive_DriveFile"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L983-L1026 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.getDownloadUrl | protected function getDownloadUrl($file)
{
if (strpos($file->mimeType, 'application/vnd.google-apps') !== 0) {
return 'https://www.googleapis.com/drive/v3/files/' . $file->getId() . '?alt=media';
} else {
$mimeMap = $this->options['appsExportMap'];
if (isset($mimeMap[$file->getMimeType()])) {
$mime = $mimeMap[$file->getMimeType()];
} else {
$mime = $mimeMap['default'];
}
$mime = rawurlencode($mime);
return 'https://www.googleapis.com/drive/v3/files/' . $file->getId() . '/export?mimeType=' . $mime;
}
return false;
} | php | protected function getDownloadUrl($file)
{
if (strpos($file->mimeType, 'application/vnd.google-apps') !== 0) {
return 'https://www.googleapis.com/drive/v3/files/' . $file->getId() . '?alt=media';
} else {
$mimeMap = $this->options['appsExportMap'];
if (isset($mimeMap[$file->getMimeType()])) {
$mime = $mimeMap[$file->getMimeType()];
} else {
$mime = $mimeMap['default'];
}
$mime = rawurlencode($mime);
return 'https://www.googleapis.com/drive/v3/files/' . $file->getId() . '/export?mimeType=' . $mime;
}
return false;
} | [
"protected",
"function",
"getDownloadUrl",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"file",
"->",
"mimeType",
",",
"'application/vnd.google-apps'",
")",
"!==",
"0",
")",
"{",
"return",
"'https://www.googleapis.com/drive/v3/files/'",
".",
"$",
"... | Get download url
@param Google_Service_Drive_DriveFile $file
@return string|false | [
"Get",
"download",
"url"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L1035-L1052 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.detectChunkSizeBytes | protected function detectChunkSizeBytes()
{
// Max and default chunk size of 100MB
$chunkSizeBytes = 100 * 1024 * 1024;
$memoryLimit = $this->getIniBytes('memory_limit');
if ($memoryLimit > 0) {
$availableMemory = $memoryLimit - $this->getMemoryUsedBytes();
/*
* We need some breathing room, so we only take 1/4th of the available memory for use in chunking (the divide by 4 does this).
* The chunk size must be a multiple of 256KB(262144).
* An example of why we need the breathing room is detecting the mime type for a file that is just small enough to fit into one chunk.
* In this scenario, we send the entire file off as a string to have the mime type detected. Unfortunately, this leads to the entire
* file being loaded into memory again, separately from the copy we're holding.
*/
$chunkSizeBytes = max(262144, min($chunkSizeBytes, floor($availableMemory / 4 / 262144) * 262144));
}
return (int)$chunkSizeBytes;
} | php | protected function detectChunkSizeBytes()
{
// Max and default chunk size of 100MB
$chunkSizeBytes = 100 * 1024 * 1024;
$memoryLimit = $this->getIniBytes('memory_limit');
if ($memoryLimit > 0) {
$availableMemory = $memoryLimit - $this->getMemoryUsedBytes();
/*
* We need some breathing room, so we only take 1/4th of the available memory for use in chunking (the divide by 4 does this).
* The chunk size must be a multiple of 256KB(262144).
* An example of why we need the breathing room is detecting the mime type for a file that is just small enough to fit into one chunk.
* In this scenario, we send the entire file off as a string to have the mime type detected. Unfortunately, this leads to the entire
* file being loaded into memory again, separately from the copy we're holding.
*/
$chunkSizeBytes = max(262144, min($chunkSizeBytes, floor($availableMemory / 4 / 262144) * 262144));
}
return (int)$chunkSizeBytes;
} | [
"protected",
"function",
"detectChunkSizeBytes",
"(",
")",
"{",
"// Max and default chunk size of 100MB",
"$",
"chunkSizeBytes",
"=",
"100",
"*",
"1024",
"*",
"1024",
";",
"$",
"memoryLimit",
"=",
"$",
"this",
"->",
"getIniBytes",
"(",
"'memory_limit'",
")",
";",
... | Detect the largest chunk size that can be used for uploading a file
@return int | [
"Detect",
"the",
"largest",
"chunk",
"size",
"that",
"can",
"be",
"used",
"for",
"uploading",
"a",
"file"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L1105-L1123 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.normaliseUploadedFile | protected function normaliseUploadedFile($uploadedFile, $localPath, $visibility)
{
list ($parentId, $fileName) = $this->splitPath($localPath);
if (!($uploadedFile instanceof Google_Service_Drive_DriveFile)) {
return false;
}
$this->cacheFileObjects[$uploadedFile->getId()] = $uploadedFile;
if (! $this->getFileObject($localPath)) {
$this->cacheFileObjectsByName[$parentId . '/' . $fileName] = $uploadedFile;
}
$result = $this->normaliseObject($uploadedFile, Util::dirname($localPath));
if ($visibility && $this->setVisibility($localPath, $visibility)) {
$result['visibility'] = $visibility;
}
return $result;
} | php | protected function normaliseUploadedFile($uploadedFile, $localPath, $visibility)
{
list ($parentId, $fileName) = $this->splitPath($localPath);
if (!($uploadedFile instanceof Google_Service_Drive_DriveFile)) {
return false;
}
$this->cacheFileObjects[$uploadedFile->getId()] = $uploadedFile;
if (! $this->getFileObject($localPath)) {
$this->cacheFileObjectsByName[$parentId . '/' . $fileName] = $uploadedFile;
}
$result = $this->normaliseObject($uploadedFile, Util::dirname($localPath));
if ($visibility && $this->setVisibility($localPath, $visibility)) {
$result['visibility'] = $visibility;
}
return $result;
} | [
"protected",
"function",
"normaliseUploadedFile",
"(",
"$",
"uploadedFile",
",",
"$",
"localPath",
",",
"$",
"visibility",
")",
"{",
"list",
"(",
"$",
"parentId",
",",
"$",
"fileName",
")",
"=",
"$",
"this",
"->",
"splitPath",
"(",
"$",
"localPath",
")",
... | Normalise a Drive File that has been created
@param Google_Service_Drive_DriveFile $uploadedFile
@param string $localPath
@param string $visibility
@return array|bool | [
"Normalise",
"a",
"Drive",
"File",
"that",
"has",
"been",
"created"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L1133-L1152 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.uploadResourceToGoogleDrive | protected function uploadResourceToGoogleDrive($resource, $parentId, $fileName, $srcDriveFile, $mime)
{
$chunkSizeBytes = $this->detectChunkSizeBytes();
$fileSize = $this->getFileSizeBytes($resource);
if ($fileSize <= $chunkSizeBytes) {
// If the resource fits in a single chunk, we'll just upload it in a single request
return $this->uploadStringToGoogleDrive(stream_get_contents($resource), $parentId, $fileName, $srcDriveFile, $mime);
}
$client = $this->service->getClient();
// Call the API with the media upload, defer so it doesn't immediately return.
$client->setDefer(true);
$request = $this->ensureDriveFileExists('', $parentId, $fileName, $srcDriveFile, $mime);
$client->setDefer(false);
$media = $this->getMediaFileUpload($client, $request, $mime, $chunkSizeBytes);
$media->setFileSize($fileSize);
// Upload chunks until we run out of file to upload; $status will be false until the process is complete.
$status = false;
while (! $status && ! feof($resource)) {
$chunk = $this->readFileChunk($resource, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
// The final value of $status will be the data from the API for the object that has been uploaded.
return $status;
} | php | protected function uploadResourceToGoogleDrive($resource, $parentId, $fileName, $srcDriveFile, $mime)
{
$chunkSizeBytes = $this->detectChunkSizeBytes();
$fileSize = $this->getFileSizeBytes($resource);
if ($fileSize <= $chunkSizeBytes) {
// If the resource fits in a single chunk, we'll just upload it in a single request
return $this->uploadStringToGoogleDrive(stream_get_contents($resource), $parentId, $fileName, $srcDriveFile, $mime);
}
$client = $this->service->getClient();
// Call the API with the media upload, defer so it doesn't immediately return.
$client->setDefer(true);
$request = $this->ensureDriveFileExists('', $parentId, $fileName, $srcDriveFile, $mime);
$client->setDefer(false);
$media = $this->getMediaFileUpload($client, $request, $mime, $chunkSizeBytes);
$media->setFileSize($fileSize);
// Upload chunks until we run out of file to upload; $status will be false until the process is complete.
$status = false;
while (! $status && ! feof($resource)) {
$chunk = $this->readFileChunk($resource, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
// The final value of $status will be the data from the API for the object that has been uploaded.
return $status;
} | [
"protected",
"function",
"uploadResourceToGoogleDrive",
"(",
"$",
"resource",
",",
"$",
"parentId",
",",
"$",
"fileName",
",",
"$",
"srcDriveFile",
",",
"$",
"mime",
")",
"{",
"$",
"chunkSizeBytes",
"=",
"$",
"this",
"->",
"detectChunkSizeBytes",
"(",
")",
"... | Upload a PHP resource stream to Google Drive
@param resource $resource
@param string $parentId
@param string $fileName
@param string $mime
@return bool|Google_Service_Drive_DriveFile | [
"Upload",
"a",
"PHP",
"resource",
"stream",
"to",
"Google",
"Drive"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L1163-L1190 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.uploadStringToGoogleDrive | protected function uploadStringToGoogleDrive($contents, $parentId, $fileName, $srcDriveFile, $mime)
{
return $this->ensureDriveFileExists($contents, $parentId, $fileName, $srcDriveFile, $mime);
} | php | protected function uploadStringToGoogleDrive($contents, $parentId, $fileName, $srcDriveFile, $mime)
{
return $this->ensureDriveFileExists($contents, $parentId, $fileName, $srcDriveFile, $mime);
} | [
"protected",
"function",
"uploadStringToGoogleDrive",
"(",
"$",
"contents",
",",
"$",
"parentId",
",",
"$",
"fileName",
",",
"$",
"srcDriveFile",
",",
"$",
"mime",
")",
"{",
"return",
"$",
"this",
"->",
"ensureDriveFileExists",
"(",
"$",
"contents",
",",
"$"... | Upload a string to Google Drive
@param string $contents
@param string $parentId
@param string $fileName
@param string $mime
@return Google_Service_Drive_DriveFile | [
"Upload",
"a",
"string",
"to",
"Google",
"Drive"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L1201-L1204 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.ensureDriveFileExists | protected function ensureDriveFileExists($contents, $parentId, $fileName, $srcDriveFile, $mime)
{
if (! $mime) {
$mime = Util::guessMimeType($fileName, $contents);
}
$driveFile = new Google_Service_Drive_DriveFile();
$mode = 'update';
if (! $srcDriveFile) {
$mode = 'insert';
$driveFile->setName($fileName);
$driveFile->setParents([$parentId]);
}
$driveFile->setMimeType($mime);
$params = ['fields' => $this->fetchfieldsGet];
if ($contents) {
$params['data'] = $contents;
$params['uploadType'] = 'media';
}
if ($mode === 'insert') {
$retrievedDriveFile = $this->service->files->create($driveFile, $this->applyDefaultParams($params, 'files.create'));
} else {
$retrievedDriveFile = $this->service->files->update(
$srcDriveFile->getId(),
$driveFile,
$this->applyDefaultParams($params, 'files.update')
);
}
return $retrievedDriveFile;
} | php | protected function ensureDriveFileExists($contents, $parentId, $fileName, $srcDriveFile, $mime)
{
if (! $mime) {
$mime = Util::guessMimeType($fileName, $contents);
}
$driveFile = new Google_Service_Drive_DriveFile();
$mode = 'update';
if (! $srcDriveFile) {
$mode = 'insert';
$driveFile->setName($fileName);
$driveFile->setParents([$parentId]);
}
$driveFile->setMimeType($mime);
$params = ['fields' => $this->fetchfieldsGet];
if ($contents) {
$params['data'] = $contents;
$params['uploadType'] = 'media';
}
if ($mode === 'insert') {
$retrievedDriveFile = $this->service->files->create($driveFile, $this->applyDefaultParams($params, 'files.create'));
} else {
$retrievedDriveFile = $this->service->files->update(
$srcDriveFile->getId(),
$driveFile,
$this->applyDefaultParams($params, 'files.update')
);
}
return $retrievedDriveFile;
} | [
"protected",
"function",
"ensureDriveFileExists",
"(",
"$",
"contents",
",",
"$",
"parentId",
",",
"$",
"fileName",
",",
"$",
"srcDriveFile",
",",
"$",
"mime",
")",
"{",
"if",
"(",
"!",
"$",
"mime",
")",
"{",
"$",
"mime",
"=",
"Util",
"::",
"guessMimeT... | Ensure that a file exists on Google Drive by creating it if it doesn't exist or updating it if it does
@param string $contents
@param string $parentId
@param string $fileName
@param string $mime
@return Google_Service_Drive_DriveFile | [
"Ensure",
"that",
"a",
"file",
"exists",
"on",
"Google",
"Drive",
"by",
"creating",
"it",
"if",
"it",
"doesn",
"t",
"exist",
"or",
"updating",
"it",
"if",
"it",
"does"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L1215-L1248 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.getIniBytes | protected function getIniBytes($iniName = '', $val = '')
{
if ($iniName !== '') {
$val = ini_get($iniName);
if ($val === false) {
return 0;
}
}
$val = trim($val, "bB \t\n\r\0\x0B");
$last = strtolower($val[strlen($val) - 1]);
$val = (int)$val;
switch ($last) {
case 't':
$val *= 1024;
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
} | php | protected function getIniBytes($iniName = '', $val = '')
{
if ($iniName !== '') {
$val = ini_get($iniName);
if ($val === false) {
return 0;
}
}
$val = trim($val, "bB \t\n\r\0\x0B");
$last = strtolower($val[strlen($val) - 1]);
$val = (int)$val;
switch ($last) {
case 't':
$val *= 1024;
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
} | [
"protected",
"function",
"getIniBytes",
"(",
"$",
"iniName",
"=",
"''",
",",
"$",
"val",
"=",
"''",
")",
"{",
"if",
"(",
"$",
"iniName",
"!==",
"''",
")",
"{",
"$",
"val",
"=",
"ini_get",
"(",
"$",
"iniName",
")",
";",
"if",
"(",
"$",
"val",
"=... | Return bytes from php.ini value
@param string $iniName
@param string $val
@return number | [
"Return",
"bytes",
"from",
"php",
".",
"ini",
"value"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L1282-L1304 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.getMediaFileUpload | protected function getMediaFileUpload($client, $request, $mime, $chunkSizeBytes)
{
return new Google_Http_MediaFileUpload($client, $request, $mime, null, true, $chunkSizeBytes);
} | php | protected function getMediaFileUpload($client, $request, $mime, $chunkSizeBytes)
{
return new Google_Http_MediaFileUpload($client, $request, $mime, null, true, $chunkSizeBytes);
} | [
"protected",
"function",
"getMediaFileUpload",
"(",
"$",
"client",
",",
"$",
"request",
",",
"$",
"mime",
",",
"$",
"chunkSizeBytes",
")",
"{",
"return",
"new",
"Google_Http_MediaFileUpload",
"(",
"$",
"client",
",",
"$",
"request",
",",
"$",
"mime",
",",
... | Get a MediaFileUpload
@param $client
@param $request
@param $mime
@param $chunkSizeBytes
@return Google_Http_MediaFileUpload | [
"Get",
"a",
"MediaFileUpload"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L1338-L1341 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.applyDefaultParams | protected function applyDefaultParams($params, $cmdName)
{
if (isset($this->defaultParams[$cmdName]) && is_array($this->defaultParams[$cmdName])) {
return array_replace($this->defaultParams[$cmdName], $params);
} else {
return $params;
}
} | php | protected function applyDefaultParams($params, $cmdName)
{
if (isset($this->defaultParams[$cmdName]) && is_array($this->defaultParams[$cmdName])) {
return array_replace($this->defaultParams[$cmdName], $params);
} else {
return $params;
}
} | [
"protected",
"function",
"applyDefaultParams",
"(",
"$",
"params",
",",
"$",
"cmdName",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"defaultParams",
"[",
"$",
"cmdName",
"]",
")",
"&&",
"is_array",
"(",
"$",
"this",
"->",
"defaultParams",
"[",
... | Apply optional parameters for each command
@param array $params The parameters
@param string $cmdName The command name
@return array
@see https://developers.google.com/drive/v3/reference/files
@see \Google_Service_Drive_Resource_Files | [
"Apply",
"optional",
"parameters",
"for",
"each",
"command"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L1354-L1361 | train |
nao-pon/flysystem-google-drive | src/GoogleDriveAdapter.php | GoogleDriveAdapter.setTeamDriveId | public function setTeamDriveId($teamDriveId, $corpora = 'teamDrive')
{
$this->enableTeamDriveSupport();
$this->defaultParams = array_merge_recursive($this->defaultParams, [
'files.list' => [
'corpora' => $corpora,
'includeTeamDriveItems' => true,
'teamDriveId' => $teamDriveId
]
]);
if ($this->root === 'root') {
$this->setPathPrefix($teamDriveId);
$this->root = $teamDriveId;
}
} | php | public function setTeamDriveId($teamDriveId, $corpora = 'teamDrive')
{
$this->enableTeamDriveSupport();
$this->defaultParams = array_merge_recursive($this->defaultParams, [
'files.list' => [
'corpora' => $corpora,
'includeTeamDriveItems' => true,
'teamDriveId' => $teamDriveId
]
]);
if ($this->root === 'root') {
$this->setPathPrefix($teamDriveId);
$this->root = $teamDriveId;
}
} | [
"public",
"function",
"setTeamDriveId",
"(",
"$",
"teamDriveId",
",",
"$",
"corpora",
"=",
"'teamDrive'",
")",
"{",
"$",
"this",
"->",
"enableTeamDriveSupport",
"(",
")",
";",
"$",
"this",
"->",
"defaultParams",
"=",
"array_merge_recursive",
"(",
"$",
"this",
... | Selects Team Drive to operate by changing default parameters
@return void
@param string $teamDriveId Team Drive id
@param string $corpora Corpora value for files.list
@see https://developers.google.com/drive/v3/reference/files
@see https://developers.google.com/drive/v3/reference/files/list
@see \Google_Service_Drive_Resource_Files | [
"Selects",
"Team",
"Drive",
"to",
"operate",
"by",
"changing",
"default",
"parameters"
] | b99f4f8c1a344937984082a00f5bb33075c8410d | https://github.com/nao-pon/flysystem-google-drive/blob/b99f4f8c1a344937984082a00f5bb33075c8410d/src/GoogleDriveAdapter.php#L1395-L1410 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Filter.php | Filter.create | public static function create($filter = array())
{
if ($filter instanceof self) {
return $filter;
}
if (is_int($filter)) {
$filter = array('page' => $filter);
}
return new self($filter);
} | php | public static function create($filter = array())
{
if ($filter instanceof self) {
return $filter;
}
if (is_int($filter)) {
$filter = array('page' => $filter);
}
return new self($filter);
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"filter",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"$",
"filter",
"instanceof",
"self",
")",
"{",
"return",
"$",
"filter",
";",
"}",
"if",
"(",
"is_int",
"(",
"$",
"filter",
")",
")",
"{",
"... | Factory method, creates an instance of a filter.
Used to build URLs to collection endpoints.
@param array $filter
@return $this | [
"Factory",
"method",
"creates",
"an",
"instance",
"of",
"a",
"filter",
".",
"Used",
"to",
"build",
"URLs",
"to",
"collection",
"endpoints",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Filter.php#L18-L29 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.configure | public static function configure($settings)
{
if (isset($settings['client_id'])) {
self::configureOAuth($settings);
} else {
self::configureBasicAuth($settings);
}
} | php | public static function configure($settings)
{
if (isset($settings['client_id'])) {
self::configureOAuth($settings);
} else {
self::configureBasicAuth($settings);
}
} | [
"public",
"static",
"function",
"configure",
"(",
"$",
"settings",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"settings",
"[",
"'client_id'",
"]",
")",
")",
"{",
"self",
"::",
"configureOAuth",
"(",
"$",
"settings",
")",
";",
"}",
"else",
"{",
"self",
"... | Configure the API client with the required settings to access
the API for a store.
Accepts OAuth and (for now!) Basic Auth credentials
@param array $settings | [
"Configure",
"the",
"API",
"client",
"with",
"the",
"required",
"settings",
"to",
"access",
"the",
"API",
"for",
"a",
"store",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L77-L84 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.configureOAuth | public static function configureOAuth($settings)
{
if (!isset($settings['auth_token'])) {
throw new Exception("'auth_token' must be provided");
}
if (!isset($settings['store_hash'])) {
throw new Exception("'store_hash' must be provided");
}
self::$client_id = $settings['client_id'];
self::$auth_token = $settings['auth_token'];
self::$store_hash = $settings['store_hash'];
self::$client_secret = isset($settings['client_secret']) ? $settings['client_secret'] : null;
self::$api_path = self::$api_url . sprintf(self::$stores_prefix, self::$store_hash);
self::$connection = false;
} | php | public static function configureOAuth($settings)
{
if (!isset($settings['auth_token'])) {
throw new Exception("'auth_token' must be provided");
}
if (!isset($settings['store_hash'])) {
throw new Exception("'store_hash' must be provided");
}
self::$client_id = $settings['client_id'];
self::$auth_token = $settings['auth_token'];
self::$store_hash = $settings['store_hash'];
self::$client_secret = isset($settings['client_secret']) ? $settings['client_secret'] : null;
self::$api_path = self::$api_url . sprintf(self::$stores_prefix, self::$store_hash);
self::$connection = false;
} | [
"public",
"static",
"function",
"configureOAuth",
"(",
"$",
"settings",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"settings",
"[",
"'auth_token'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"'auth_token' must be provided\"",
")",
";",
"}",
... | Configure the API client with the required OAuth credentials.
Requires a settings array to be passed in with the following keys:
- client_id
- auth_token
- store_hash
@param array $settings
@throws \Exception | [
"Configure",
"the",
"API",
"client",
"with",
"the",
"required",
"OAuth",
"credentials",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L98-L116 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.configureBasicAuth | public static function configureBasicAuth(array $settings)
{
if (!isset($settings['store_url'])) {
throw new Exception("'store_url' must be provided");
}
if (!isset($settings['username'])) {
throw new Exception("'username' must be provided");
}
if (!isset($settings['api_key'])) {
throw new Exception("'api_key' must be provided");
}
self::$username = $settings['username'];
self::$api_key = $settings['api_key'];
self::$store_url = rtrim($settings['store_url'], '/');
self::$api_path = self::$store_url . self::$path_prefix;
self::$connection = false;
} | php | public static function configureBasicAuth(array $settings)
{
if (!isset($settings['store_url'])) {
throw new Exception("'store_url' must be provided");
}
if (!isset($settings['username'])) {
throw new Exception("'username' must be provided");
}
if (!isset($settings['api_key'])) {
throw new Exception("'api_key' must be provided");
}
self::$username = $settings['username'];
self::$api_key = $settings['api_key'];
self::$store_url = rtrim($settings['store_url'], '/');
self::$api_path = self::$store_url . self::$path_prefix;
self::$connection = false;
} | [
"public",
"static",
"function",
"configureBasicAuth",
"(",
"array",
"$",
"settings",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"settings",
"[",
"'store_url'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"'store_url' must be provided\"",
")",
"... | Configure the API client with the required credentials.
Requires a settings array to be passed in with the following keys:
- store_url
- username
- api_key
@param array $settings
@throws \Exception | [
"Configure",
"the",
"API",
"client",
"with",
"the",
"required",
"credentials",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L130-L149 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.connection | private static function connection()
{
if (!self::$connection) {
self::$connection = new Connection();
if (self::$client_id) {
self::$connection->authenticateOauth(self::$client_id, self::$auth_token);
} else {
self::$connection->authenticateBasic(self::$username, self::$api_key);
}
}
return self::$connection;
} | php | private static function connection()
{
if (!self::$connection) {
self::$connection = new Connection();
if (self::$client_id) {
self::$connection->authenticateOauth(self::$client_id, self::$auth_token);
} else {
self::$connection->authenticateBasic(self::$username, self::$api_key);
}
}
return self::$connection;
} | [
"private",
"static",
"function",
"connection",
"(",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"$",
"connection",
")",
"{",
"self",
"::",
"$",
"connection",
"=",
"new",
"Connection",
"(",
")",
";",
"if",
"(",
"self",
"::",
"$",
"client_id",
")",
"{",
... | Get an instance of the HTTP connection object. Initializes
the connection if it is not already active.
@return Connection | [
"Get",
"an",
"instance",
"of",
"the",
"HTTP",
"connection",
"object",
".",
"Initializes",
"the",
"connection",
"if",
"it",
"is",
"not",
"already",
"active",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L218-L230 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.getCollection | public static function getCollection($path, $resource = 'Resource')
{
$response = self::connection()->get(self::$api_path . $path);
return self::mapCollection($resource, $response);
} | php | public static function getCollection($path, $resource = 'Resource')
{
$response = self::connection()->get(self::$api_path . $path);
return self::mapCollection($resource, $response);
} | [
"public",
"static",
"function",
"getCollection",
"(",
"$",
"path",
",",
"$",
"resource",
"=",
"'Resource'",
")",
"{",
"$",
"response",
"=",
"self",
"::",
"connection",
"(",
")",
"->",
"get",
"(",
"self",
"::",
"$",
"api_path",
".",
"$",
"path",
")",
... | Get a collection result from the specified endpoint.
@param string $path api endpoint
@param string $resource resource class to map individual items
@return mixed array|string mapped collection or XML string if useXml is true | [
"Get",
"a",
"collection",
"result",
"from",
"the",
"specified",
"endpoint",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L259-L264 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.getResource | public static function getResource($path, $resource = 'Resource')
{
$response = self::connection()->get(self::$api_path . $path);
return self::mapResource($resource, $response);
} | php | public static function getResource($path, $resource = 'Resource')
{
$response = self::connection()->get(self::$api_path . $path);
return self::mapResource($resource, $response);
} | [
"public",
"static",
"function",
"getResource",
"(",
"$",
"path",
",",
"$",
"resource",
"=",
"'Resource'",
")",
"{",
"$",
"response",
"=",
"self",
"::",
"connection",
"(",
")",
"->",
"get",
"(",
"self",
"::",
"$",
"api_path",
".",
"$",
"path",
")",
";... | Get a resource entity from the specified endpoint.
@param string $path api endpoint
@param string $resource resource class to map individual items
@return mixed Resource|string resource object or XML string if useXml is true | [
"Get",
"a",
"resource",
"entity",
"from",
"the",
"specified",
"endpoint",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L273-L278 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.getCount | public static function getCount($path)
{
$response = self::connection()->get(self::$api_path . $path);
if ($response == false || is_string($response)) {
return $response;
}
return $response->count;
} | php | public static function getCount($path)
{
$response = self::connection()->get(self::$api_path . $path);
if ($response == false || is_string($response)) {
return $response;
}
return $response->count;
} | [
"public",
"static",
"function",
"getCount",
"(",
"$",
"path",
")",
"{",
"$",
"response",
"=",
"self",
"::",
"connection",
"(",
")",
"->",
"get",
"(",
"self",
"::",
"$",
"api_path",
".",
"$",
"path",
")",
";",
"if",
"(",
"$",
"response",
"==",
"fals... | Get a count value from the specified endpoint.
@param string $path api endpoint
@return mixed int|string count value or XML string if useXml is true | [
"Get",
"a",
"count",
"value",
"from",
"the",
"specified",
"endpoint",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L286-L295 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.createResource | public static function createResource($path, $object)
{
if (is_array($object)) {
$object = (object)$object;
}
return self::connection()->post(self::$api_path . $path, $object);
} | php | public static function createResource($path, $object)
{
if (is_array($object)) {
$object = (object)$object;
}
return self::connection()->post(self::$api_path . $path, $object);
} | [
"public",
"static",
"function",
"createResource",
"(",
"$",
"path",
",",
"$",
"object",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"object",
")",
")",
"{",
"$",
"object",
"=",
"(",
"object",
")",
"$",
"object",
";",
"}",
"return",
"self",
"::",
"co... | Send a post request to create a resource on the specified collection.
@param string $path api endpoint
@param mixed $object object or XML string to create
@return mixed | [
"Send",
"a",
"post",
"request",
"to",
"create",
"a",
"resource",
"on",
"the",
"specified",
"collection",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L304-L311 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.updateResource | public static function updateResource($path, $object)
{
if (is_array($object)) {
$object = (object)$object;
}
return self::connection()->put(self::$api_path . $path, $object);
} | php | public static function updateResource($path, $object)
{
if (is_array($object)) {
$object = (object)$object;
}
return self::connection()->put(self::$api_path . $path, $object);
} | [
"public",
"static",
"function",
"updateResource",
"(",
"$",
"path",
",",
"$",
"object",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"object",
")",
")",
"{",
"$",
"object",
"=",
"(",
"object",
")",
"$",
"object",
";",
"}",
"return",
"self",
"::",
"co... | Send a put request to update the specified resource.
@param string $path api endpoint
@param mixed $object object or XML string to update
@return mixed | [
"Send",
"a",
"put",
"request",
"to",
"update",
"the",
"specified",
"resource",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L320-L327 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.mapCollection | private static function mapCollection($resource, $object)
{
if ($object == false || is_string($object)) {
return $object;
}
$baseResource = __NAMESPACE__ . '\\' . $resource;
self::$resource = (class_exists($baseResource)) ? $baseResource : 'Bigcommerce\\Api\\Resources\\' . $resource;
return array_map(array('self', 'mapCollectionObject'), $object);
} | php | private static function mapCollection($resource, $object)
{
if ($object == false || is_string($object)) {
return $object;
}
$baseResource = __NAMESPACE__ . '\\' . $resource;
self::$resource = (class_exists($baseResource)) ? $baseResource : 'Bigcommerce\\Api\\Resources\\' . $resource;
return array_map(array('self', 'mapCollectionObject'), $object);
} | [
"private",
"static",
"function",
"mapCollection",
"(",
"$",
"resource",
",",
"$",
"object",
")",
"{",
"if",
"(",
"$",
"object",
"==",
"false",
"||",
"is_string",
"(",
"$",
"object",
")",
")",
"{",
"return",
"$",
"object",
";",
"}",
"$",
"baseResource",... | Internal method to wrap items in a collection to resource classes.
@param string $resource name of the resource class
@param array $object object collection
@return array | [
"Internal",
"method",
"to",
"wrap",
"items",
"in",
"a",
"collection",
"to",
"resource",
"classes",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L347-L357 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.mapResource | private static function mapResource($resource, $object)
{
if ($object == false || is_string($object)) {
return $object;
}
$baseResource = __NAMESPACE__ . '\\' . $resource;
$class = (class_exists($baseResource)) ? $baseResource : 'Bigcommerce\\Api\\Resources\\' . $resource;
return new $class($object);
} | php | private static function mapResource($resource, $object)
{
if ($object == false || is_string($object)) {
return $object;
}
$baseResource = __NAMESPACE__ . '\\' . $resource;
$class = (class_exists($baseResource)) ? $baseResource : 'Bigcommerce\\Api\\Resources\\' . $resource;
return new $class($object);
} | [
"private",
"static",
"function",
"mapResource",
"(",
"$",
"resource",
",",
"$",
"object",
")",
"{",
"if",
"(",
"$",
"object",
"==",
"false",
"||",
"is_string",
"(",
"$",
"object",
")",
")",
"{",
"return",
"$",
"object",
";",
"}",
"$",
"baseResource",
... | Map a single object to a resource class.
@param string $resource name of the resource class
@param \stdClass $object
@return Resource | [
"Map",
"a",
"single",
"object",
"to",
"a",
"resource",
"class",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L379-L388 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.getAuthToken | public static function getAuthToken($object)
{
$context = array_merge(array('grant_type' => 'authorization_code'), (array)$object);
$connection = new Connection();
return $connection->post(self::$login_url . '/oauth2/token', $context);
} | php | public static function getAuthToken($object)
{
$context = array_merge(array('grant_type' => 'authorization_code'), (array)$object);
$connection = new Connection();
return $connection->post(self::$login_url . '/oauth2/token', $context);
} | [
"public",
"static",
"function",
"getAuthToken",
"(",
"$",
"object",
")",
"{",
"$",
"context",
"=",
"array_merge",
"(",
"array",
"(",
"'grant_type'",
"=>",
"'authorization_code'",
")",
",",
"(",
"array",
")",
"$",
"object",
")",
";",
"$",
"connection",
"=",... | Swaps a temporary access code for a long expiry auth token.
@param \stdClass|array $object
@return \stdClass | [
"Swaps",
"a",
"temporary",
"access",
"code",
"for",
"a",
"long",
"expiry",
"auth",
"token",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L411-L417 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.getTime | public static function getTime()
{
$response = self::connection()->get(self::$api_path . '/time');
if ($response == false || is_string($response)) {
return $response;
}
return new \DateTime("@{$response->time}");
} | php | public static function getTime()
{
$response = self::connection()->get(self::$api_path . '/time');
if ($response == false || is_string($response)) {
return $response;
}
return new \DateTime("@{$response->time}");
} | [
"public",
"static",
"function",
"getTime",
"(",
")",
"{",
"$",
"response",
"=",
"self",
"::",
"connection",
"(",
")",
"->",
"get",
"(",
"self",
"::",
"$",
"api_path",
".",
"'/time'",
")",
";",
"if",
"(",
"$",
"response",
"==",
"false",
"||",
"is_stri... | Pings the time endpoint to test the connection to a store.
@return \DateTime | [
"Pings",
"the",
"time",
"endpoint",
"to",
"test",
"the",
"connection",
"to",
"a",
"store",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L456-L465 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.getProducts | public static function getProducts($filter = array())
{
$filter = Filter::create($filter);
return self::getCollection('/products' . $filter->toQuery(), 'Product');
} | php | public static function getProducts($filter = array())
{
$filter = Filter::create($filter);
return self::getCollection('/products' . $filter->toQuery(), 'Product');
} | [
"public",
"static",
"function",
"getProducts",
"(",
"$",
"filter",
"=",
"array",
"(",
")",
")",
"{",
"$",
"filter",
"=",
"Filter",
"::",
"create",
"(",
"$",
"filter",
")",
";",
"return",
"self",
"::",
"getCollection",
"(",
"'/products'",
".",
"$",
"fil... | Returns the default collection of products.
@param array $filter
@return mixed array|string list of products or XML string if useXml is true | [
"Returns",
"the",
"default",
"collection",
"of",
"products",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L473-L477 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.getProductsCount | public static function getProductsCount($filter = array())
{
$filter = Filter::create($filter);
return self::getCount('/products/count' . $filter->toQuery());
} | php | public static function getProductsCount($filter = array())
{
$filter = Filter::create($filter);
return self::getCount('/products/count' . $filter->toQuery());
} | [
"public",
"static",
"function",
"getProductsCount",
"(",
"$",
"filter",
"=",
"array",
"(",
")",
")",
"{",
"$",
"filter",
"=",
"Filter",
"::",
"create",
"(",
"$",
"filter",
")",
";",
"return",
"self",
"::",
"getCount",
"(",
"'/products/count'",
".",
"$",
... | Returns the total number of products in the collection.
@param array $filter
@return int|string number of products or XML string if useXml is true | [
"Returns",
"the",
"total",
"number",
"of",
"products",
"in",
"the",
"collection",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L566-L570 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.getOptions | public static function getOptions($filter = array())
{
$filter = Filter::create($filter);
return self::getCollection('/options' . $filter->toQuery(), 'Option');
} | php | public static function getOptions($filter = array())
{
$filter = Filter::create($filter);
return self::getCollection('/options' . $filter->toQuery(), 'Option');
} | [
"public",
"static",
"function",
"getOptions",
"(",
"$",
"filter",
"=",
"array",
"(",
")",
")",
"{",
"$",
"filter",
"=",
"Filter",
"::",
"create",
"(",
"$",
"filter",
")",
";",
"return",
"self",
"::",
"getCollection",
"(",
"'/options'",
".",
"$",
"filte... | Return the collection of options.
@param array $filter
@return array | [
"Return",
"the",
"collection",
"of",
"options",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L633-L637 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.getOptionValues | public static function getOptionValues($filter = array())
{
$filter = Filter::create($filter);
return self::getCollection('/options/values' . $filter->toQuery(), 'OptionValue');
} | php | public static function getOptionValues($filter = array())
{
$filter = Filter::create($filter);
return self::getCollection('/options/values' . $filter->toQuery(), 'OptionValue');
} | [
"public",
"static",
"function",
"getOptionValues",
"(",
"$",
"filter",
"=",
"array",
"(",
")",
")",
"{",
"$",
"filter",
"=",
"Filter",
"::",
"create",
"(",
"$",
"filter",
")",
";",
"return",
"self",
"::",
"getCollection",
"(",
"'/options/values'",
".",
"... | Return the collection of all option values.
@param array $filter
@return array | [
"Return",
"the",
"collection",
"of",
"all",
"option",
"values",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L711-L715 | train |
bigcommerce/bigcommerce-api-php | src/Bigcommerce/Api/Client.php | Client.getCategories | public static function getCategories($filter = array())
{
$filter = Filter::create($filter);
return self::getCollection('/categories' . $filter->toQuery(), 'Category');
} | php | public static function getCategories($filter = array())
{
$filter = Filter::create($filter);
return self::getCollection('/categories' . $filter->toQuery(), 'Category');
} | [
"public",
"static",
"function",
"getCategories",
"(",
"$",
"filter",
"=",
"array",
"(",
")",
")",
"{",
"$",
"filter",
"=",
"Filter",
"::",
"create",
"(",
"$",
"filter",
")",
";",
"return",
"self",
"::",
"getCollection",
"(",
"'/categories'",
".",
"$",
... | The collection of categories.
@param array $filter
@return array | [
"The",
"collection",
"of",
"categories",
"."
] | adcafe433271a6b42995ccf364a30856b0934941 | https://github.com/bigcommerce/bigcommerce-api-php/blob/adcafe433271a6b42995ccf364a30856b0934941/src/Bigcommerce/Api/Client.php#L723-L727 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.