How to find a gutenberg block by blockName if blocks are nested (recursively) - advanced-custom-fields

I need to get some data from an ACF Gutenberg block, but it is nested in a nested block, so
<?php
$blocks = parse_blocks( $pid->post_content );
foreach ( $blocks as $block ) {
if ( $block['blockName'] === 'acf/your-block-name' ) {
//do something
}
}
is not working.

You need to create a recursive function. The code will look like:
<?php
$blocks = parse_blocks($pid->post_content);
foreach ($blocks as $block) {
$myAcfBlock = getMyAcfBlock($block);
if($myAcfBlock){
//do something
}
}
function getMyAcfBlock($blockObject)
{
if ($blockObject['blockName'] === 'acf/your-block-name') {
return $blockObject;
}
if (!empty($blockObject['innerBlocks'])) {
foreach ($blockObject['innerBlocks'] as $innerBlock) {
$innerBlockObject = getLandigFormBlock($innerBlock);
if ($innerBlockObject) {
return $innerBlockObject;
}
}
}
return false;
}

Related

Laravel modify collection value with another value of another collection

I have a json file like this,
{
"unique_id_001":{
"price_1":264000,
"price_2":2178000,
"price_3":3168000,
"price_6":1089000,
"price_7":3168000
},
"unique_id_002":{
"price_1":264000,
"price_2":2178000,
"price_3":3168000,
"price_6":1089000,
"price_7":3168000
},
"unique_id_003":{
"price_1":264000,
"price_2":2178000,
"price_3":3168000,
"price_6":1089000,
"price_7":3168000
}
}
I convert it to collection and want to set those price_x to another collection.
public static function getOldPrices()
{
$storagePath = storage_path(self::PATH);
$file = File::get($storagePath);
$data = json_decode($file, true);
$collection = \App\Price::hydrate($data);
$oldPrices = $collection->flatten();
return $oldPrices;
}
public static function all()
{
$prices = \App\Price::all();
$old_prices = self::getOldPrices();
foreach ($prices as $price) {
foreach ($old_prices as $old_price) { // is there another way so I can remove this loop?
if ($price->id === $old_price->id) {
$price->price_1 = $old_price->price_1;
$price->price_2 = $old_price->price_2;
$price->price_3 = $old_price->price_3;
$price->price_6 = $old_price->price_6;
$price->price_7 = $old_price->price_7;
}
}
}
return $prices;
}
This code is working and could change the value of each price in $prices. But I wonder if there is other ways, because I used two foreach loop in this code, and I think it is not good.
I got another way using map()
Here is my updated code
$prices = $prices->map(function ($price) use ($oldPrices) {
if ($oldPrice = $oldPrices->firstWhere('id', $price->id)) {
$price->price_1 = $oldPrice->price_1;
$price->price_2 = $oldPrice->price_2;
$price->price_3 = $oldPrice->price_3;
$price->price_6 = $oldPrice->price_6;
$price->price_7 = $oldPrice->price_7;
}
return $price;
});

Extract data from complex JSON in Flutter

I'm working in extract data from more complex JSON with unknown structure, its structure changes with operation ,
JSON sample link :http://afs-i.com/json.json
Kindly find my code here : http://afs-i.com/main.dart
Thanks in advance
Update:
I extracted the data using PHP code, you can find result here: http://afs-i.com/json.php
Kindly this is my PHP code:
$arraycars=array();
$y=json_decode($x);
// echo "<pre>";
// var_dump($y->tree[0]->children);
foreach ($y->tree[0]->children as $f) {
if(isset($f->vid)){
global $arraycars;
$arraycars[]=$f;
} elseif(isset($f->children)){
if(sizeof($f->children) > 0){
coolectcars($f->children);
}
}
}
function coolectcars($array){
// var_dump($array);
foreach ($array as $f) {
if(isset($f->vid)){
global $arraycars;
$arraycars[]=$f;
} elseif(isset($f->children)){
if(sizeof($f->children) > 0){
coolectcars($f->children);
}
}
}
}
echo json_encode($arraycars);
Update:2
I have problem now with null error for this code:
The error:
I/flutter ( 4264): NoSuchMethodError: The method 'forEach' was called on
null.
I/flutter ( 4264): Receiver: null
I/flutter ( 4264): Tried calling: forEach(Closure: (Children) => Null)
The code:
List<Children> cars = [];
Queue numQ = new Queue();
numQ.addAll(parsed["tree"][0]["children"]);
Iterator i = numQ.iterator;
while (i.moveNext()) {
// print("ddddddd ${i.current}");
if (i.current.containsKey("vid")) {
cars.add(new Children(
i.current['vid'], i.current['protocol'], i.current['datetime'],
i.current['gpss']));
} else {
Queue numQ = new Queue();
if (i.current["children"] != null) {
numQ.addAll(i.current["children"]);
// iterate(numQ);
List<Children> carse=[];
carse = iterate(numQ);
carse.forEach((data){
cars.add(data);
}) ;
}
}
}
cars.forEach((data) {
print(data.toString());
});
List<Children> iterate(Queue numQ) {
List<Children> cars=new List<Children>();
Iterator i = numQ.iterator;
while (i.moveNext()) {
print("ddddddd ${i.current}");
if (i.current.containsKey("vid")) {
cars.add(new Children(
i.current['vid'], i.current['protocol'], i.current['datetime'],
i.current['gpss']));
} else {
if (i.current["children"] != null) {
Queue numQ = new Queue();
numQ.addAll(i.current["children"]);
List<Children> carse=[];
carse = iterate(numQ);
carse.forEach((data){
cars.add(data);
}) ;
}
}
return cars;
}
}
I prefer using built_value to do json deserialization/ serialization. It's more elegant. You don't need to write down fromJson by yourself. built_value will generate deserializers / serializer for you. You can check built_value's github or this and this articles.
A good place for convert JSON to dart here
hats to reddit url
just copy your json into the textbox and generate, it will auto generate for you.
With this, you can call fromJson and feed it the json, then you can also get auto complete for it
eg: usage
final response =
await http.get('http://afs-i.com/json.json');
if (response.statusCode == 200) {
final Autogenerated respJson = Autogenerated.fromJson(json.decode(response.body));
print(respJson.tree[0].userId);
}
insert this import 'dart:convert';
into your widget file at top.
lets say you have your json in
var response
then
var jsonDecoded= json.decode(response);
now you can get name and user_id like this:
var user_id= jsonDecoded["tree"][0]["user_id"];
var name = jsonDecoded["tree"][0]["name"];
NOTE : I get these values from the first object (0 index). If you want values for each object , you can loop to get it.
The final answer i reach:
final parsed = json.decode(response.body);
List<Children> cars = [];
Queue numQ = new Queue();
numQ.addAll(parsed["tree"][0]["children"]);
Iterator i = numQ.iterator;
while (i.moveNext()) {
if (i.current.containsKey("vid")) {
cars.add(new Children(
i.current['vid'],
i.current['datetime'],
));
} else {
Queue numQ = new Queue();
if (i.current["children"].toString() != "[]") {
numQ.addAll(i.current["children"]);
List<Children> carse = [];
carse = iterate(numQ);
carse.forEach((data) {
cars.add(data);
});
}
}
}
List<Children> iterate(Queue numQ) {
List<Children> cars = new List<Children>();
Iterator i = numQ.iterator;
while (i.moveNext()) {
if (i.current.containsKey("vid")) {
if (i.current.containsKey("vid")) {
cars.add(new Children(
i.current['vid'],
i.current['datetime'],
));
}
} else {
if (i.current["children"].toString() != "[]") {
Queue numQ = new Queue();
if (i.current["children"].toString() != "[]") {
numQ.addAll(i.current["children"]);
List<Children> carse = [];
carse = iterate(numQ);
carse.forEach((data) {
cars.add(data);
});
}
}
}
return cars;
}

Yii2 show error when exception occurs

I have this code in my controller:
...
if (Model::validateMultiple($ttepk)) {
$transaction = \Yii::$app->db->beginTransaction();
try {
foreach ($ttepk as $ttep) {
$ttep->save(false);
if (!$ttep->assignPs()) {
throw new UserException('assignPs failed');
}
}
$transaction->commit();
return $this->redirect(['index']);
} catch (Exception $ex) {
$transaction->rollBack();
throw $ex;
}
}
...
in model:
...
public function assignPs() {
foreach (...) {
$ttepetk[...] = new Ttepet;
$ttepetk[...]->ttepId = $this->id;
... // set other attributes
}
}
if (Model::validateMultiple($ttepetk)) {
foreach ($ttepetk as $ttepet) {
$ttepet->save(false);
}
return true;
} else {
return false;
}
}
...
Everything is working fine (no inserts are happening if any of the models fail validation), except that I would like to see the exact error, exactly by which Ttep (each Ttep is a model) and by which Ttepet (Ttep:Ttepet = 1:N) has the error happened, and what was that. Now I see the Exeption page only, and I don't know how to make the errors visible. Please point me to the right direction. Thanks!
You could iterate on each single model validating one by one and getting the errors when occurs ...
if (Model::validateMultiple($ttepetk)) {
foreach ($ttepetk as $ttepet) {
$ttepet->save(false);
}
return true;
} else {
foreach($ttepetk as $model){
if ($model->validate()) {
// all inputs are valid
} else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}
}
return $errors;
}
you can get the errors this way
$myErrorResult = $ttep->assignPs();
if (!$myErrorResult) {
......

Retrieving array of Controllers/Actions

Is it possible in Yii2 to retrieve an array containing all controllers and actions for the whole application?
I finally ended up with:
protected function actionGetcontrollersandactions()
{
$controllerlist = [];
if ($handle = opendir('../controllers')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && substr($file, strrpos($file, '.') - 10) == 'Controller.php') {
$controllerlist[] = $file;
}
}
closedir($handle);
}
asort($controllerlist);
$fulllist = [];
foreach ($controllerlist as $controller):
$handle = fopen('../controllers/' . $controller, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if (preg_match('/public function action(.*?)\(/', $line, $display)):
if (strlen($display[1]) > 2):
$fulllist[substr($controller, 0, -4)][] = strtolower($display[1]);
endif;
endif;
}
}
fclose($handle);
endforeach;
return $fulllist;
}
I started with the answer from Andreas Hinderberger, and just fine tuned it. I ended up with something like this:
It uses FileHelper to get all the files recursively, which is useful if you are extending controllers from base classes. It also formats the controller-id/action-id using Inflector::camel2id so they will match your routes.
public function getAllControllerActions()
{
$controllers = \yii\helpers\FileHelper::findFiles(Yii::getAlias('#app/controllers'), ['recursive' => true]);
$actions = [];
foreach ($controllers as $controller) {
$contents = file_get_contents($controller);
$controllerId = Inflector::camel2id(substr(basename($controller), 0, -14));
preg_match_all('/public function action(\w+?)\(/', $contents, $result);
foreach ($result[1] as $action) {
$actionId = Inflector::camel2id($action);
$route = $controllerId . '/' . $actionId;
$actions[$route] = $route;
}
}
asort($actions);
return $actions;
}
As far as I know Yii 2 doesn't have any built-in methods to achieve this. You can only get the current controller and its action.
What's the purpose of it? If you really need this you can write such functionality by yourself.
To get all controllers you should search for a files ending with Conroller. And they can be located in different places of application. For example in nested folders, modules, nested modules, etc. So there is more than just one place for search.
To get all actions you should search for all methods prefixed with action in each controller.
Also don't forget about attached actions in controller actions() method. In framework they are usually ending with Action, take a look for example at rest actions. But no one forces you to name it like that, so there is possibility that some external actions can just have different naming convention (for example if you working in team and don't follow this convention).
And you probably need to exclude such folders as vendor.
So it's not trivial task, but possible with some inaccuracies. I just don't get it what's the point of that.
Follow example walk trought all modules and collect all modules controller actions (no tested):
<?php
$controllerDirs = [];
$controllerDirs[] = \Yii::getAlias('#app/controllers');
if ($commonControllerDir = \Yii::getAlias('#common/controllers', false)) {
$controllerDirs['common'] = $commonControllerDir;
}
foreach (\Yii::$app->modules as $moduleId => $module) {
/*
* get module base path
*/
if (method_exists($module, 'getBasePath')) {
$basePath = $module->getBasePath();
} else {
$reflector = new \ReflectionClass($module['class']);
$basePath = StringHelper::dirname($reflector->getFileName());
}
$basePath .= '/controllers';
$controllerDirs[$moduleId] = $basePath;
}
$actions = [];
foreach ($controllerDirs as $moduleId => $cDir) {
$actions[$moduleId][$cDir] = actionGetcontrollersandactions($cDir);
}
print_r($actions);
function actionGetcontrollersandactions($controllerDir) {
$controllerlist = [];
if ($handle = opendir($controllerDir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && substr($file, strrpos($file, '.') - 10) == 'Controller.php') {
$controllerlist[] = $file;
}
}
closedir($handle);
}
asort($controllerlist);
$fulllist = [];
foreach ($controllerlist as $controller):
$handle = fopen($controllerDir . '/' . $controller, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if (preg_match('/public function action(.*?)\(/', $line, $display)):
if (strlen($display[1]) > 2):
$fulllist[substr($controller, 0, -4)][] = strtolower($display[1]);
endif;
endif;
}
}
fclose($handle);
endforeach;
return $fulllist;
}

Hide mySQL error from invalid URL

I have a site with 300 articles stored in a mySQL database with the URL format of www.site.com/article1.html.
Most invalid URLs redirect succesfully to the main site. For example, www.site.com/article301 redirects to www.site.com, which is what I want.
But www.site.com/article301.html does not redirect anywhere. Instead it loads a blank article template and the following error at the top of the page:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home//public_html/site.com/functions.php on line 26
Line 26 and down reads
if(mysql_num_rows($result)>0) {
$row=mysql_fetch_array($result);
if(ENABLE_REWRITE == 1) $path=' » '.$row['name'].''.$path;
if(ENABLE_REWRITE == 0) $path=' » '.$row['name'].''.$path;
if($row['parent']==0) $f=1;
else $id=$row['parent'];
} else {
return ' - ';
}
}
return $path;
}
Any ideas how to fix this?
Here's the full code, as requested by King Skippus
<?php
/*function get_folders_path($id) {
$f=0;
$path='';
while($f==0)
{
$result=mysql_query("SELECT name, parent FROM categories WHERE id=$id");
if(mysql_num_rows($result)>0) {
$row=mysql_fetch_array($result);
$path=' » '.$row['name'].$path;
if($row['parent']==0) $f=1;
else $id=$row['parent'];
} else {
return ' - ';
}
}
return $path;
}*/
function get_folders_path($id) {
$f=0;
$path='';
while($f==0)
{
$result=mysql_query("SELECT * FROM categories WHERE id=$id");
if($result !== FALSE && mysql_num_rows($result)>0) {
$row=mysql_fetch_array($result);
if(ENABLE_REWRITE == 1) $path=' » '.$row['name'].''.$path;
if(ENABLE_REWRITE == 0) $path=' » '.$row['name'].''.$path;
if($row['parent']==0) $f=1;
else $id=$row['parent'];
} else {
return ' - ';
}
}
return $path;
}
function get_categories_tree($id) {
static $categs = array ();
static $level=0;
$level++;
$result=mysql_query("SELECT * FROM categories WHERE parent=$id");
while($row=mysql_fetch_array($result)) {
$categs[$row['id']][0] = $row['id'];
$categs[$row['id']][1] = '/'.$row['nameurl'];
$categs[$row['id']][2] = str_repeat(' ', $level-1);
$categs[$row['id']][3] = $row['name'];
get_categories_tree($row['id']);
}
$level--;
return $categs;
}
function get_cats($id) {
$categs = array ();
$result=mysql_query("SELECT * FROM categories WHERE parent=$id");
while($row=mysql_fetch_array($result)) {
$categs[$row['id']][0] = $row['id'];
$categs[$row['id']][1] = '/'.$row['nameurl'];
// $categs[$row['id']][2] = str_repeat(' ', $level-1);
$categs[$row['id']][3] = $row['name'];
}
return $categs;
}
/*function login() {
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
return false;
} else {
$result=mysql_query("SELECT * FROM users WHERE login='{$_SERVER['PHP_AUTH_USER']}' AND password='{$_SERVER['PHP_AUTH_PW']}'");
if(mysql_num_rows($result)>0) return true;
else {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
return false;
}
}
}*/
function login() {
if (!isset($_SESSION['AUTH_USER']) || !isset($_SESSION['AUTH_PASS'])) return false;
else {
$result=mysql_query("SELECT * FROM users WHERE login='{$_SESSION['AUTH_USER']}' AND password='{$_SESSION['AUTH_PASS']}'");
if(mysql_num_rows($result)>0) return true;
else return false;
}
}
function get_categories($id) {
static $categs = array ("0" => "[Top]");
static $level=0;
$level++;
$result=mysql_query("SELECT * FROM categories WHERE parent=$id");
while($row=mysql_fetch_array($result)) {
$categs[$row['id']] = str_repeat('| ', $level-1).'|___'.$row['name'];
get_categories($row['id']);
}
$level--;
return $categs;
}
function get_parent_name($id) {
if($id!=0) {
$result=mysql_query("SELECT name FROM categories WHERE id=$id");
if(mysql_num_rows($result)>0) {
$row=mysql_fetch_array($result);
return $row['name'];
}
else return '-';
}
else return 'Top';
}
function getcatname($id, $table)
{
$r=mysql_query("SELECT title FROM $table WHERE id='$id'");
if(mysql_num_rows($r)>0) {
$row=mysql_fetch_array($r);
return $row['title'];
}
else
return "-";
}
?>
Probably your query failed, and you have no error handling. Your basic bare-bones query sequence should be:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
If you assume the query succeeded and blindly use $result later, you tend to get the type of errors you do, as mysql_query will return a boolean FALSE when something goes boom. That FALSE is not a valid statement handle, so the subsequent num_rows/fetch calls will also go boom.
Never assume a query has succeeded. Even if your sql syntax is 100% perfect, there's far too many other reasons for failure to NOT check.
Try replacing
if(mysql_num_rows($result)>0) {
with
if($result === FALSE) {
header('Location: http://www.example.com/');
}
else if (mysql_num_rows($result)>0) {
// Query was valid, but no rows returned. Take appropriate action.
}
EDIT
For troubleshooting purposes, what does it display if you change the function to this instead? Please be aware that this will intentionally break your site, but it will provide data that is useful for troubleshooting.
function get_folders_path($id) {
$f=0;
$path='';
while($f==0)
{
$result=mysql_query("SELECT * FROM categories WHERE id=$id");
die(sprintf("Value of id: %s, MySQL Error: %s",
var_dump($id, true), var_dump(mysql_error($result), true)));
// Leave the rest of your function as-is, just insert the line above.