Loading a block should be in theme context, because block visibility configured by theme, here is an example to how load system_breadcrumb_block
block in your active theme.
use Drupal\block\Entity\Block;
// Get block ids.
// This will return block ids by theme like the following
/* [
"bartik_breadcrumbs" => "bartik_breadcrumbs"
"seven_breadcrumbs" => "seven_breadcrumbs"
]
*/
$ids = \Drupal::entityQuery('block')
->condition('plugin', 'system_breadcrumb_block')
->execute();
// Get the active theme name.
$active_theme_name = \Drupal::service('theme.manager')
->getActiveTheme()
->getName();
$my_block_id = '';
foreach ($ids as $id) {
// Check the if the id start with theme name.
if (strpos($id, $active_theme_name) === 0) {
$my_block_id = $id;
}
}
// Load Block.
$block = Block::load($my_block_id);
// Get the block visibility array
// Something like
// [
// "user_role" => [
// "id" => "user_role",
// "roles" => [
// "administrator" => "administrator",
// ],
// ],
// ]
$visibility = $block->getVisibility();
$currentUser = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
/**
* TODO: Do your visibility check
*/
// Example to check if the user has the access by role
$has_access = FALSE;
if ($visibility['user_role']['roles']){
foreach ($visibility['user_role']['roles'] as $role => $name){
if ($currentUser->hasRole($role)){
$has_access = TRUE;
}
}
}
dpm($has_access);